Skip to main content

aidaemon_memory/sqlite/
structured.rs

1use std::collections::HashMap;
2
3use chrono::{NaiveDate, Utc};
4use sqlx::{Row, Sqlite, Transaction};
5
6use super::*;
7use crate::records::{
8    Fact, PersonalAliasCandidate, PersonalEntityCandidate, PersonalFactCandidate,
9    PersonalMemoryWrite, PersonalMemoryWriteResult, PersonalRelationshipCandidate,
10};
11
12use crate::text::normalize_fact_value as words;
13
14fn token(value: &str) -> String {
15    words(value).replace(' ', "_")
16}
17
18/// A validity bound as stored: a blank one (extraction emits `""` for "no
19/// bound") is no bound. Stored as `""` it hid the row from every
20/// `valid_to IS NULL` read, so the fact never reached the prompt and the
21/// next identical write inserted a duplicate.
22fn period(value: &Option<String>) -> Option<&str> {
23    value
24        .as_deref()
25        .map(str::trim)
26        .filter(|bound| !bound.is_empty())
27}
28
29fn alias_value(value: &str, alias_type: &str) -> String {
30    if matches!(
31        token(alias_type).as_str(),
32        "username" | "handle" | "online_handle" | "account_name"
33    ) {
34        value.trim().trim_start_matches('@').to_lowercase()
35    } else {
36        words(value)
37    }
38}
39
40fn date_value(value: &str) -> Option<String> {
41    if let Ok(date) = NaiveDate::parse_from_str(value.trim(), "%Y-%m-%d") {
42        return Some(date.format("%Y-%m-%d").to_string());
43    }
44    let clean = value.trim().replace(',', "");
45    ["%b %e %Y", "%B %e %Y", "%b %d %Y", "%B %d %Y"]
46        .iter()
47        .find_map(|format| NaiveDate::parse_from_str(&clean, format).ok())
48        .map(|date| date.format("%Y-%m-%d").to_string())
49}
50
51fn predicate(value: &str) -> String {
52    match token(value).as_str() {
53        "birthday" | "date_of_birth" | "dob" => "birth_date".to_string(),
54        "current_residence" | "home" | "location" => "residence".to_string(),
55        "place_of_birth" => "birthplace".to_string(),
56        "favorite_name" | "preferred_first_name" => "preferred_name".to_string(),
57        "address_as" | "call_me" | "preferred_address" | "salutation" => "addressing".to_string(),
58        "avoid_names" | "rejected_name" | "rejected_names" | "do_not_call" => {
59            "rejected_alias".to_string()
60        }
61        other => other.to_string(),
62    }
63}
64
65fn alias_type(value: &str) -> String {
66    match token(value).as_str() {
67        "favorite_name" | "preferred" | "preferred_first_name" => "preferred_name".to_string(),
68        "online_nickname" | "online_username" => "online_handle".to_string(),
69        "legal_name" | "full_name" => "legal_name_variant".to_string(),
70        "avoid_names" | "rejected_name" | "rejected_names" | "do_not_call" => {
71            "rejected_alias".to_string()
72        }
73        other => other.to_string(),
74    }
75}
76
77fn entity_type(value: &str) -> String {
78    match token(value).as_str() {
79        kind @ ("person" | "organization" | "project" | "place" | "account") => kind.to_string(),
80        _ => "person".to_string(),
81    }
82}
83
84fn relation(value: &str) -> String {
85    match token(value).as_str() {
86        "parent" | "parent_of" | "father_of" | "mother_of" => "PARENT_OF".to_string(),
87        "child" | "child_of" | "daughter_of" | "son_of" => "CHILD_OF".to_string(),
88        "lives_with" | "cohabits_with" => "LIVES_WITH".to_string(),
89        "lives_in" | "resident_of" => "LIVES_IN".to_string(),
90        "uses_alias" => "USES_ALIAS".to_string(),
91        "uses_handle" => "USES_HANDLE".to_string(),
92        "has_account" => "HAS_ACCOUNT".to_string(),
93        other => other.to_ascii_uppercase(),
94    }
95}
96
97fn inverse(value: &str) -> Option<&'static str> {
98    match value {
99        "PARENT_OF" => Some("CHILD_OF"),
100        "CHILD_OF" => Some("PARENT_OF"),
101        "LIVES_WITH" => Some("LIVES_WITH"),
102        "PARTNER_OF" => Some("PARTNER_OF"),
103        "SPOUSE_OF" => Some("SPOUSE_OF"),
104        _ => None,
105    }
106}
107
108/// The person a legacy free-text name fact names. Kept text matching: these
109/// rows predate structured personal memory and carry no typed entities, so a
110/// compound value ("Alice and Jordan", "A & B") is the only sign it names
111/// two people, and such a value is left for review rather than guessed.
112fn legacy_person_name(value: &str) -> Option<(String, Vec<String>)> {
113    let mut display = value.trim().to_string();
114    if display.is_empty() || display.to_ascii_lowercase().contains(" and ") || display.contains('&')
115    {
116        return None;
117    }
118
119    let mut aliases = Vec::new();
120    if let Some(start) = display.find('"')
121        && let Some(relative_end) = display[start + 1..].find('"')
122    {
123        let end = start + 1 + relative_end;
124        let alias = display[start + 1..end].trim();
125        if !alias.is_empty() {
126            aliases.push(alias.to_string());
127        }
128        display.replace_range(start..=end, "");
129    }
130    if let (Some(start), Some(end)) = (display.find('('), display.rfind(')'))
131        && end > start
132    {
133        let note = display[start + 1..end].trim();
134        let lower = note.to_ascii_lowercase();
135        let alias = lower
136            .strip_prefix("nickname ")
137            .or_else(|| lower.strip_prefix("aka "))
138            .or_else(|| lower.strip_prefix("also known as "))
139            .map(|prefix_removed| {
140                let offset = note.len().saturating_sub(prefix_removed.len());
141                note[offset..].trim()
142            });
143        if let Some(alias) = alias.filter(|alias| !alias.is_empty()) {
144            aliases.push(alias.to_string());
145            display.replace_range(start..=end, "");
146        }
147    }
148    let canonical = display.split_whitespace().collect::<Vec<_>>().join(" ");
149    (!canonical.is_empty()).then_some((canonical, aliases))
150}
151
152/// The people a legacy free-text list names. Kept text matching for the
153/// same reason as [`legacy_person_name`]: rows from before structured
154/// memory, with no typed entities to read instead.
155fn split_legacy_people(value: &str) -> Vec<String> {
156    value
157        .replace(" & ", ",")
158        .split([',', ';'])
159        .flat_map(|part| part.split(" and "))
160        .map(str::trim)
161        .filter(|part| !part.is_empty())
162        .map(str::to_string)
163        .collect()
164}
165
166/// A value that carries nothing to store. An extraction pass that emits a
167/// placeholder for "absent" is not stating a value either. Kept text
168/// matching: extractor JSON has no typed "absent" marker, and these exact
169/// whole-value tokens are that protocol's placeholders, never prose.
170fn is_placeholder_value(value: &str) -> bool {
171    let value = value.trim();
172    value.is_empty()
173        || ["none", "null", "n/a", "unknown"]
174            .iter()
175            .any(|marker| value.eq_ignore_ascii_case(marker))
176}
177
178fn confidence(source: &str, direct: bool) -> f32 {
179    if direct {
180        1.0
181    } else if matches!(
182        source,
183        "legacy" | "consolidation" | "inferred" | "task_learning"
184    ) {
185        0.6
186    } else {
187        0.8
188    }
189}
190
191fn low_authority(source: &str) -> bool {
192    matches!(
193        source,
194        "legacy" | "consolidation" | "inferred" | "progressive" | "task_learning" | "derived"
195    )
196}
197
198fn normalized_fact(predicate: &str, value: &str) -> anyhow::Result<(String, &'static str)> {
199    if predicate == "birth_date" {
200        Ok((
201            date_value(value).ok_or_else(|| anyhow::anyhow!("unsupported date: {value}"))?,
202            "date",
203        ))
204    } else {
205        Ok((words(value), "text"))
206    }
207}
208
209/// Ends `ids` in `table` as retracted (the owner asked to forget them) and
210/// audits each one. Returns how many active rows it ended.
211async fn retract(
212    tx: &mut Transaction<'_, Sqlite>,
213    table: &str,
214    record_type: &str,
215    ids: &[i64],
216    source: &str,
217) -> anyhow::Result<u64> {
218    let now = Utc::now().to_rfc3339();
219    let mut retracted = 0;
220    for &id in ids {
221        let entity_column = match table {
222            "memory_entity_facts" => "subject_entity_id",
223            "memory_aliases" => "entity_id",
224            _ => "source_entity_id",
225        };
226        let sql = format!(
227            "UPDATE {table} SET status = 'retracted', valid_to = ?, updated_at = ?
228             WHERE id = ? AND status IN ('active', 'disputed') AND valid_to IS NULL
229             RETURNING {entity_column}"
230        );
231        let Some(entity_id) = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(&*sql))
232            .bind(&now)
233            .bind(&now)
234            .bind(id)
235            .fetch_optional(&mut **tx)
236            .await?
237        else {
238            continue;
239        };
240        retracted += 1;
241        audit(
242            tx,
243            "retract",
244            Some(entity_id),
245            record_type,
246            Some(id),
247            serde_json::json!({"status": "retracted"}),
248            source,
249            None,
250        )
251        .await?;
252    }
253    Ok(retracted)
254}
255
256#[allow(clippy::too_many_arguments)]
257async fn audit(
258    tx: &mut Transaction<'_, Sqlite>,
259    operation: &str,
260    entity_id: Option<i64>,
261    record_type: &str,
262    record_id: Option<i64>,
263    state: serde_json::Value,
264    source: &str,
265    provenance: Option<&str>,
266) -> anyhow::Result<()> {
267    sqlx::query(
268        "INSERT INTO memory_write_audit
269         (operation, entity_id, record_type, record_id, new_state_json, source, provenance, created_at)
270         VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
271    )
272    .bind(operation)
273    .bind(entity_id)
274    .bind(record_type)
275    .bind(record_id)
276    .bind(state.to_string())
277    .bind(source)
278    .bind(provenance)
279    .bind(Utc::now().to_rfc3339())
280    .execute(&mut **tx)
281    .await?;
282    Ok(())
283}
284
285async fn review(
286    tx: &mut Transaction<'_, Sqlite>,
287    kind: &str,
288    reference: &str,
289    candidates: &[i64],
290    payload: serde_json::Value,
291    source: &str,
292) -> anyhow::Result<()> {
293    let now = Utc::now().to_rfc3339();
294    sqlx::query(
295        "INSERT OR IGNORE INTO memory_resolution_reviews
296         (review_kind, normalized_reference, candidate_entity_ids_json, payload_json,
297          source, status, created_at, updated_at)
298         VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)",
299    )
300    .bind(kind)
301    .bind(reference)
302    .bind(serde_json::to_string(candidates)?)
303    .bind(payload.to_string())
304    .bind(source)
305    .bind(&now)
306    .bind(&now)
307    .execute(&mut **tx)
308    .await?;
309    Ok(())
310}
311
312async fn owner_entity(
313    tx: &mut Transaction<'_, Sqlite>,
314    candidate: &PersonalEntityCandidate,
315    source: &str,
316    privacy: &str,
317    channel: Option<&str>,
318    result: &mut PersonalMemoryWriteResult,
319) -> anyhow::Result<i64> {
320    let existing = sqlx::query(
321        "SELECT id, canonical_name FROM memory_entities
322         WHERE is_owner = 1 AND status = 'active' LIMIT 1",
323    )
324    .fetch_optional(&mut **tx)
325    .await?;
326    let id = if let Some(row) = existing {
327        row.get("id")
328    } else if let Some(id) = sqlx::query_scalar::<_, i64>(
329        "SELECT id FROM memory_entities
330         WHERE entity_type = 'person' AND canonical_name = 'owner'
331           AND status = 'active' LIMIT 1",
332    )
333    .fetch_optional(&mut **tx)
334    .await?
335    {
336        sqlx::query(
337            "UPDATE memory_entities SET is_owner = 1, privacy = ?,
338             channel_id = COALESCE(channel_id, ?), updated_at = ? WHERE id = ?",
339        )
340        .bind(privacy)
341        .bind(channel)
342        .bind(Utc::now().to_rfc3339())
343        .bind(id)
344        .execute(&mut **tx)
345        .await?;
346        id
347    } else {
348        let now = Utc::now().to_rfc3339();
349        let id = sqlx::query(
350            "INSERT INTO memory_entities
351             (entity_type, canonical_name, display_name, aliases_json, channel_id, privacy,
352              status, is_owner, created_at, updated_at)
353             VALUES ('person', 'owner', 'Owner', '[]', ?, ?, 'active', 1, ?, ?)",
354        )
355        .bind(channel)
356        .bind(privacy)
357        .bind(&now)
358        .bind(&now)
359        .execute(&mut **tx)
360        .await?
361        .last_insert_rowid();
362        result.created_entities += 1;
363        audit(
364            tx,
365            "create",
366            Some(id),
367            "entity",
368            Some(id),
369            serde_json::json!({"entity_type": "person", "canonical_name": "owner"}),
370            source,
371            None,
372        )
373        .await?;
374        id
375    };
376
377    let display = candidate.canonical_name.trim();
378    let canonical = words(display);
379    let source_can_confirm_owner = !matches!(
380        source,
381        "consolidation" | "inferred" | "progressive" | "task_learning" | "derived"
382    );
383    if candidate.canonical_name_confirmed
384        && source_can_confirm_owner
385        && !canonical.is_empty()
386        && canonical != "owner"
387    {
388        let current: String =
389            sqlx::query_scalar("SELECT canonical_name FROM memory_entities WHERE id = ?")
390                .bind(id)
391                .fetch_one(&mut **tx)
392                .await?;
393        if current != canonical {
394            let collision: Option<i64> = sqlx::query_scalar(
395                "SELECT id FROM memory_entities
396                 WHERE entity_type = 'person' AND canonical_name = ? AND id != ?
397                   AND status = 'active' LIMIT 1",
398            )
399            .bind(&canonical)
400            .bind(id)
401            .fetch_optional(&mut **tx)
402            .await?;
403            if let Some(collision_id) = collision {
404                review(
405                    tx,
406                    "owner_name_collision",
407                    &canonical,
408                    &[id, collision_id],
409                    serde_json::json!({}),
410                    source,
411                )
412                .await?;
413                result
414                    .unresolved
415                    .push("confirmed owner name matches another entity".to_string());
416            } else {
417                sqlx::query(
418                    "UPDATE memory_entities SET canonical_name = ?, display_name = ?,
419                     updated_at = ? WHERE id = ?",
420                )
421                .bind(&canonical)
422                .bind(display)
423                .bind(Utc::now().to_rfc3339())
424                .bind(id)
425                .execute(&mut **tx)
426                .await?;
427                result.updated_entities += 1;
428                audit(
429                    tx,
430                    "update",
431                    Some(id),
432                    "entity",
433                    Some(id),
434                    serde_json::json!({"canonical_name": canonical}),
435                    source,
436                    None,
437                )
438                .await?;
439            }
440        }
441    }
442    Ok(id)
443}
444
445async fn resolve_entity(
446    tx: &mut Transaction<'_, Sqlite>,
447    candidate: &PersonalEntityCandidate,
448    source: &str,
449    privacy: &str,
450    channel: Option<&str>,
451    result: &mut PersonalMemoryWriteResult,
452) -> anyhow::Result<Option<i64>> {
453    if candidate.local_id.eq_ignore_ascii_case("owner") {
454        return owner_entity(tx, candidate, source, privacy, channel, result)
455            .await
456            .map(Some);
457    }
458    let kind = entity_type(&candidate.entity_type);
459    let display = candidate.canonical_name.trim();
460    let canonical = words(display);
461    if canonical.is_empty() {
462        result
463            .unresolved
464            .push(format!("entity {} has no usable name", candidate.local_id));
465        return Ok(None);
466    }
467    let exact = sqlx::query(
468        "SELECT id, status, merged_into_entity_id FROM memory_entities
469         WHERE entity_type = ? AND canonical_name = ? LIMIT 1",
470    )
471    .bind(&kind)
472    .bind(&canonical)
473    .fetch_optional(&mut **tx)
474    .await?;
475    if let Some(row) = exact {
476        let id: i64 = row.get("id");
477        let status: String = row.get("status");
478        if status == "active" {
479            return Ok(Some(id));
480        }
481        if status == "merged"
482            && let Some(target_id) = row.get::<Option<i64>, _>("merged_into_entity_id")
483        {
484            let target_is_active: bool = sqlx::query_scalar(
485                "SELECT EXISTS(
486                         SELECT 1 FROM memory_entities WHERE id = ? AND status = 'active'
487                     )",
488            )
489            .bind(target_id)
490            .fetch_one(&mut **tx)
491            .await?;
492            if target_is_active {
493                return Ok(Some(target_id));
494            }
495        }
496        review(
497            tx,
498            "inactive_entity_reference",
499            &canonical,
500            &[id],
501            serde_json::json!({"local_id": candidate.local_id, "status": status}),
502            source,
503        )
504        .await?;
505        result
506            .unresolved
507            .push(format!("entity '{display}' exists but is not active"));
508        return Ok(None);
509    }
510    if candidate.is_reference {
511        let aliases: Vec<i64> = sqlx::query_scalar(
512            "SELECT DISTINCT a.entity_id FROM memory_aliases a
513             JOIN memory_entities e ON e.id = a.entity_id
514             WHERE a.normalized_value = ? AND a.status = 'active'
515               AND e.entity_type = ? AND e.status = 'active'",
516        )
517        .bind(&canonical)
518        .bind(&kind)
519        .fetch_all(&mut **tx)
520        .await?;
521        if aliases.len() == 1 {
522            return Ok(aliases.first().copied());
523        }
524        let kind_review = if aliases.is_empty() {
525            "unresolved_reference"
526        } else {
527            "ambiguous_alias"
528        };
529        review(
530            tx,
531            kind_review,
532            &canonical,
533            &aliases,
534            serde_json::json!({"local_id": candidate.local_id}),
535            source,
536        )
537        .await?;
538        result
539            .unresolved
540            .push(format!("unresolved entity reference '{display}'"));
541        return Ok(None);
542    }
543    let now = Utc::now().to_rfc3339();
544    let id = sqlx::query(
545        "INSERT INTO memory_entities
546         (entity_type, canonical_name, display_name, aliases_json, channel_id, privacy,
547          status, is_owner, created_at, updated_at)
548         VALUES (?, ?, ?, '[]', ?, ?, 'active', 0, ?, ?)",
549    )
550    .bind(&kind)
551    .bind(&canonical)
552    .bind(display)
553    .bind(channel)
554    .bind(privacy)
555    .bind(&now)
556    .bind(&now)
557    .execute(&mut **tx)
558    .await?
559    .last_insert_rowid();
560    result.created_entities += 1;
561    audit(
562        tx,
563        "create",
564        Some(id),
565        "entity",
566        Some(id),
567        serde_json::json!({"entity_type": kind, "canonical_name": canonical}),
568        source,
569        None,
570    )
571    .await?;
572    Ok(Some(id))
573}
574
575#[allow(clippy::too_many_arguments)]
576async fn write_alias(
577    tx: &mut Transaction<'_, Sqlite>,
578    entity_id: i64,
579    candidate: &PersonalAliasCandidate,
580    source: &str,
581    provenance: Option<&str>,
582    confidence: f32,
583    direct: bool,
584    privacy: &str,
585    channel: Option<&str>,
586    result: &mut PersonalMemoryWriteResult,
587) -> anyhow::Result<()> {
588    let kind = alias_type(&candidate.alias_type);
589    let normalized = alias_value(&candidate.value, &kind);
590    if normalized.is_empty() {
591        return Ok(());
592    }
593    let now = Utc::now().to_rfc3339();
594    if let Some((id, existing_source, existing_status, existing_valid_to)) =
595        sqlx::query_as::<_, (i64, String, String, Option<String>)>(
596            "SELECT id, source, status, valid_to FROM memory_aliases
597             WHERE entity_id = ? AND alias_type = ? AND normalized_value = ?",
598        )
599        .bind(entity_id)
600        .bind(&kind)
601        .bind(&normalized)
602        .fetch_optional(&mut **tx)
603        .await?
604    {
605        let was_inactive = existing_status != "active" || existing_valid_to.is_some();
606        if was_inactive {
607            // A retracted/forgotten alias can only be reactivated by a fresh,
608            // direct high-authority owner statement, never by derived/automated
609            // repetition, and never inherits the old row's authority.
610            if !direct || low_authority(source) {
611                return Ok(());
612            }
613            sqlx::query(
614                "UPDATE memory_aliases SET status = 'active', value = ?,
615                 confidence = ?, source = ?, provenance = ?,
616                 last_confirmed_at = ?, confirmed_at = ?,
617                 valid_to = NULL, updated_at = ? WHERE id = ?",
618            )
619            .bind(candidate.value.trim())
620            .bind(confidence)
621            .bind(source)
622            .bind(provenance)
623            .bind(&now)
624            .bind(&now)
625            .bind(&now)
626            .bind(id)
627            .execute(&mut **tx)
628            .await?;
629            result.confirmed_aliases += 1;
630            return Ok(());
631        }
632        let upgrade_source = super::facts::fact_source_rank(source)
633            >= super::facts::fact_source_rank(&existing_source);
634        let kept_source = if upgrade_source {
635            source
636        } else {
637            existing_source.as_str()
638        };
639        sqlx::query(
640            "UPDATE memory_aliases SET status = 'active', value = ?,
641             confidence = MAX(confidence, ?), source = ?,
642             provenance = CASE WHEN ? THEN COALESCE(?, provenance) ELSE COALESCE(provenance, ?) END,
643             last_confirmed_at = CASE WHEN ? THEN ? ELSE last_confirmed_at END,
644             confirmed_at = CASE WHEN ? THEN COALESCE(confirmed_at, ?) ELSE confirmed_at END,
645             valid_to = NULL,
646             updated_at = CASE WHEN ? THEN ? ELSE updated_at END WHERE id = ?",
647        )
648        .bind(candidate.value.trim())
649        .bind(confidence)
650        .bind(kept_source)
651        .bind(upgrade_source)
652        .bind(provenance)
653        .bind(provenance)
654        .bind(direct)
655        .bind(&now)
656        .bind(direct)
657        .bind(&now)
658        .bind(upgrade_source || direct)
659        .bind(&now)
660        .bind(id)
661        .execute(&mut **tx)
662        .await?;
663        result.confirmed_aliases += 1;
664        return Ok(());
665    }
666    if !direct || low_authority(source) {
667        // Consult durable owner tombstones so low-authority/derived writes
668        // cannot resurrect a deleted/folded owner alias value for the same
669        // owner-profile key family (without affecting other people's aliases).
670        let is_owner: bool = sqlx::query_scalar::<_, i64>(
671            "SELECT 1 FROM memory_entities WHERE id = ? AND is_owner = 1 LIMIT 1",
672        )
673        .bind(entity_id)
674        .fetch_optional(&mut **tx)
675        .await?
676        .is_some();
677        if is_owner {
678            let value_norm = crate::text::normalize_fact_value(candidate.value.trim());
679            let target_family = crate::text::owner_projection_family(&kind);
680            let tombstone_keys: Vec<String> = sqlx::query_scalar(
681                "SELECT canonical_key FROM memory_fact_tombstones
682                 WHERE normalized_value = ?
683                   AND reason IN ('deleted', 'folded')
684                   AND LOWER(category) IN ('user', 'personal', 'profile', 'preference')",
685            )
686            .bind(&value_norm)
687            .fetch_all(&mut **tx)
688            .await?;
689            if tombstone_keys
690                .iter()
691                .any(|k| crate::text::owner_projection_family(k) == target_family)
692            {
693                return Ok(());
694            }
695        }
696    }
697    let id = sqlx::query(
698        "INSERT INTO memory_aliases
699         (entity_id, alias_type, value, normalized_value, status, source, provenance,
700          confidence, channel_id, privacy, asserted_at, confirmed_at, last_confirmed_at,
701          created_at, updated_at)
702         VALUES (?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?,
703                 CASE WHEN ? THEN ? END, CASE WHEN ? THEN ? END, ?, ?)",
704    )
705    .bind(entity_id)
706    .bind(&kind)
707    .bind(candidate.value.trim())
708    .bind(&normalized)
709    .bind(source)
710    .bind(provenance)
711    .bind(confidence)
712    .bind(channel)
713    .bind(privacy)
714    .bind(&now)
715    .bind(direct)
716    .bind(&now)
717    .bind(direct)
718    .bind(&now)
719    .bind(&now)
720    .bind(&now)
721    .execute(&mut **tx)
722    .await?
723    .last_insert_rowid();
724    result.created_aliases += 1;
725    audit(
726        tx,
727        "create",
728        Some(entity_id),
729        "alias",
730        Some(id),
731        serde_json::json!({"alias_type": kind, "normalized_value": normalized}),
732        source,
733        provenance,
734    )
735    .await
736}
737
738#[allow(clippy::too_many_arguments)]
739async fn write_fact(
740    tx: &mut Transaction<'_, Sqlite>,
741    entity_id: i64,
742    candidate: &PersonalFactCandidate,
743    source: &str,
744    provenance: Option<&str>,
745    confidence: f32,
746    direct: bool,
747    correction: bool,
748    privacy: &str,
749    channel: Option<&str>,
750    result: &mut PersonalMemoryWriteResult,
751) -> anyhow::Result<()> {
752    let pred = predicate(&candidate.predicate);
753    if candidate.retract {
754        // A typed forget. Only the owner's own word forgets; an extraction
755        // pass asking to retract changes nothing.
756        if !direct || low_authority(source) {
757            return Ok(());
758        }
759        let ids: Vec<i64> = sqlx::query_scalar(
760            "SELECT id FROM memory_entity_facts
761             WHERE subject_entity_id = ? AND predicate = ?
762               AND status IN ('active', 'disputed') AND valid_to IS NULL",
763        )
764        .bind(entity_id)
765        .bind(&pred)
766        .fetch_all(&mut **tx)
767        .await?;
768        let retracted = retract(tx, "memory_entity_facts", "fact", &ids, source).await?;
769        result.superseded_facts += retracted as usize;
770        return Ok(());
771    }
772    // Nothing to store: an empty value, or an extraction pass's placeholder
773    // for "absent". The owner saying "none" ("allergies: none") is a value.
774    if candidate.value.trim().is_empty()
775        || ((!direct || low_authority(source)) && is_placeholder_value(&candidate.value))
776    {
777        return Ok(());
778    }
779    let (normalized, value_type) = normalized_fact(&pred, &candidate.value)?;
780    let display = candidate
781        .display_value
782        .as_deref()
783        .unwrap_or(candidate.value.trim());
784    let now = Utc::now().to_rfc3339();
785    if let Some((id, existing_source)) = sqlx::query_as::<_, (i64, String)>(
786        "SELECT id, source FROM memory_entity_facts
787         WHERE subject_entity_id = ? AND predicate = ? AND normalized_value = ?
788           AND status = 'active' AND valid_to IS NULL LIMIT 1",
789    )
790    .bind(entity_id)
791    .bind(&pred)
792    .bind(&normalized)
793    .fetch_optional(&mut **tx)
794    .await?
795    {
796        let upgrade_source = super::facts::fact_source_rank(source)
797            >= super::facts::fact_source_rank(&existing_source);
798        let kept_source = if upgrade_source {
799            source
800        } else {
801            existing_source.as_str()
802        };
803        sqlx::query(
804            "UPDATE memory_entity_facts SET display_value = ?, source = ?,
805             confidence = MAX(confidence, ?),
806             provenance = CASE WHEN ? THEN COALESCE(?, provenance) ELSE COALESCE(provenance, ?) END,
807             last_confirmed_at = CASE WHEN ? THEN ? ELSE last_confirmed_at END,
808             confirmed_at = CASE WHEN ? THEN COALESCE(confirmed_at, ?) ELSE confirmed_at END,
809             updated_at = CASE WHEN ? THEN ? ELSE updated_at END WHERE id = ?",
810        )
811        .bind(display)
812        .bind(kept_source)
813        .bind(confidence)
814        .bind(upgrade_source)
815        .bind(provenance)
816        .bind(provenance)
817        .bind(direct)
818        .bind(&now)
819        .bind(direct)
820        .bind(&now)
821        .bind(upgrade_source || direct)
822        .bind(&now)
823        .bind(id)
824        .execute(&mut **tx)
825        .await?;
826        result.confirmed_facts += 1;
827        return Ok(());
828    }
829    let active = sqlx::query(
830        "SELECT id, normalized_value, source, confidence FROM memory_entity_facts
831         WHERE subject_entity_id = ? AND predicate = ? AND status = 'active'
832           AND valid_to IS NULL ORDER BY confidence DESC, updated_at DESC LIMIT 1",
833    )
834    .bind(entity_id)
835    .bind(&pred)
836    .fetch_optional(&mut **tx)
837    .await?;
838    let mut supersedes = None;
839    if let Some(row) = active {
840        let old_id: i64 = row.get("id");
841        let old_source: String = row.get("source");
842        let old_confidence = row.get::<f64, _>("confidence") as f32;
843        // The owner is the authority on themselves: an owner statement made
844        // now (not one an extraction pass inferred) replaces the earlier one
845        // whether or not the writer flagged it as a correction. Parking it as
846        // disputed left the old value active with nobody to resolve it.
847        let owner_restates = direct && !low_authority(source);
848        if direct
849            && (owner_restates || correction || old_confidence < 0.9 || low_authority(&old_source))
850        {
851            sqlx::query(
852                "UPDATE memory_entity_facts SET status = 'superseded', valid_to = ?,
853                 updated_at = ? WHERE id = ?",
854            )
855            .bind(&now)
856            .bind(&now)
857            .bind(old_id)
858            .execute(&mut **tx)
859            .await?;
860            result.superseded_facts += 1;
861            supersedes = Some(old_id);
862            audit(
863                tx,
864                "supersede",
865                Some(entity_id),
866                "fact",
867                Some(old_id),
868                serde_json::json!({"replacement_value": normalized}),
869                source,
870                provenance,
871            )
872            .await?;
873        } else {
874            let disputed_id = sqlx::query(
875                "INSERT INTO memory_entity_facts
876                 (subject_entity_id, predicate, value_type, value, normalized_value,
877                  display_value, status, source, provenance, confidence, channel_id,
878                  privacy, asserted_at, confirmed_at, last_confirmed_at, valid_from,
879                  valid_to, created_at, updated_at)
880                 VALUES (?, ?, ?, ?, ?, ?, 'disputed', ?, ?, ?, ?, ?, ?,
881                         CASE WHEN ? THEN ? END, CASE WHEN ? THEN ? END, ?, ?, ?, ?)",
882            )
883            .bind(entity_id)
884            .bind(&pred)
885            .bind(value_type)
886            .bind(&normalized)
887            .bind(&normalized)
888            .bind(display)
889            .bind(source)
890            .bind(provenance)
891            .bind(confidence)
892            .bind(channel)
893            .bind(privacy)
894            .bind(&now)
895            .bind(direct)
896            .bind(&now)
897            .bind(direct)
898            .bind(&now)
899            .bind(period(&candidate.valid_from))
900            .bind(period(&candidate.valid_to))
901            .bind(&now)
902            .bind(&now)
903            .execute(&mut **tx)
904            .await?
905            .last_insert_rowid();
906            review(
907                tx,
908                "conflicting_fact",
909                &format!("{entity_id}:{pred}"),
910                &[entity_id],
911                serde_json::json!({"active_fact_id": old_id, "disputed_fact_id": disputed_id}),
912                source,
913            )
914            .await?;
915            result.disputed_facts += 1;
916            result
917                .unresolved
918                .push(format!("conflicting confirmed value for {pred}"));
919            return Ok(());
920        }
921    }
922    let id = sqlx::query(
923        "INSERT INTO memory_entity_facts
924         (subject_entity_id, predicate, value_type, value, normalized_value,
925          display_value, status, source, provenance, confidence, channel_id,
926          privacy, asserted_at, confirmed_at, last_confirmed_at, valid_from,
927          valid_to, supersedes_fact_id, created_at, updated_at)
928         VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?,
929                 CASE WHEN ? THEN ? END, CASE WHEN ? THEN ? END, ?, ?, ?, ?, ?)",
930    )
931    .bind(entity_id)
932    .bind(&pred)
933    .bind(value_type)
934    .bind(&normalized)
935    .bind(&normalized)
936    .bind(display)
937    .bind(source)
938    .bind(provenance)
939    .bind(confidence)
940    .bind(channel)
941    .bind(privacy)
942    .bind(&now)
943    .bind(direct)
944    .bind(&now)
945    .bind(direct)
946    .bind(&now)
947    .bind(period(&candidate.valid_from))
948    .bind(period(&candidate.valid_to))
949    .bind(supersedes)
950    .bind(&now)
951    .bind(&now)
952    .execute(&mut **tx)
953    .await?
954    .last_insert_rowid();
955    result.created_facts += 1;
956    audit(
957        tx,
958        "create",
959        Some(entity_id),
960        "fact",
961        Some(id),
962        serde_json::json!({"predicate": pred, "normalized_value": normalized}),
963        source,
964        provenance,
965    )
966    .await
967}
968
969#[allow(clippy::too_many_arguments)]
970async fn one_edge(
971    tx: &mut Transaction<'_, Sqlite>,
972    from: i64,
973    rel: &str,
974    to: i64,
975    source: &str,
976    provenance: Option<&str>,
977    confidence: f32,
978    direct: bool,
979    privacy: &str,
980    channel: Option<&str>,
981    valid_from: Option<&str>,
982    valid_to: Option<&str>,
983    result: &mut PersonalMemoryWriteResult,
984) -> anyhow::Result<i64> {
985    let now = Utc::now().to_rfc3339();
986    if let Some(id) = sqlx::query_scalar::<_, i64>(
987        "SELECT id FROM memory_relationships
988         WHERE source_entity_id = ? AND relationship_type = ? AND target_entity_id = ?
989           AND status = 'active' AND valid_to IS NULL LIMIT 1",
990    )
991    .bind(from)
992    .bind(rel)
993    .bind(to)
994    .fetch_optional(&mut **tx)
995    .await?
996    {
997        sqlx::query(
998            "UPDATE memory_relationships SET source = ?, confidence = MAX(confidence, ?),
999             provenance = COALESCE(?, provenance),
1000             last_confirmed_at = CASE WHEN ? THEN ? ELSE last_confirmed_at END,
1001             confirmed_at = CASE WHEN ? THEN COALESCE(confirmed_at, ?) ELSE confirmed_at END,
1002             updated_at = ? WHERE id = ?",
1003        )
1004        .bind(source)
1005        .bind(confidence)
1006        .bind(provenance)
1007        .bind(direct)
1008        .bind(&now)
1009        .bind(direct)
1010        .bind(&now)
1011        .bind(&now)
1012        .bind(id)
1013        .execute(&mut **tx)
1014        .await?;
1015        result.confirmed_relationships += 1;
1016        return Ok(id);
1017    }
1018    let id = sqlx::query(
1019        "INSERT INTO memory_relationships
1020         (source_entity_id, relationship_type, target_entity_id, status, source,
1021          provenance, confidence, channel_id, privacy, asserted_at, confirmed_at,
1022          last_confirmed_at, valid_from, valid_to, created_at, updated_at)
1023         VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?,
1024                 CASE WHEN ? THEN ? END, CASE WHEN ? THEN ? END, ?, ?, ?, ?)",
1025    )
1026    .bind(from)
1027    .bind(rel)
1028    .bind(to)
1029    .bind(source)
1030    .bind(provenance)
1031    .bind(confidence)
1032    .bind(channel)
1033    .bind(privacy)
1034    .bind(&now)
1035    .bind(direct)
1036    .bind(&now)
1037    .bind(direct)
1038    .bind(&now)
1039    .bind(valid_from)
1040    .bind(valid_to)
1041    .bind(&now)
1042    .bind(&now)
1043    .execute(&mut **tx)
1044    .await?
1045    .last_insert_rowid();
1046    result.created_relationships += 1;
1047    audit(
1048        tx,
1049        "create",
1050        Some(from),
1051        "relationship",
1052        Some(id),
1053        serde_json::json!({"relationship_type": rel, "target_entity_id": to}),
1054        source,
1055        provenance,
1056    )
1057    .await?;
1058    Ok(id)
1059}
1060
1061#[allow(clippy::too_many_arguments)]
1062async fn write_edge(
1063    tx: &mut Transaction<'_, Sqlite>,
1064    from: i64,
1065    to: i64,
1066    candidate: &PersonalRelationshipCandidate,
1067    source: &str,
1068    provenance: Option<&str>,
1069    confidence: f32,
1070    direct: bool,
1071    privacy: &str,
1072    channel: Option<&str>,
1073    result: &mut PersonalMemoryWriteResult,
1074) -> anyhow::Result<()> {
1075    if from == to {
1076        return Ok(());
1077    }
1078    let rel = relation(&candidate.relationship_type);
1079    let first = one_edge(
1080        tx,
1081        from,
1082        &rel,
1083        to,
1084        source,
1085        provenance,
1086        confidence,
1087        direct,
1088        privacy,
1089        channel,
1090        period(&candidate.valid_from),
1091        period(&candidate.valid_to),
1092        result,
1093    )
1094    .await?;
1095    if let Some(back_relation) = inverse(&rel) {
1096        let second = one_edge(
1097            tx,
1098            to,
1099            back_relation,
1100            from,
1101            source,
1102            provenance,
1103            confidence,
1104            direct,
1105            privacy,
1106            channel,
1107            period(&candidate.valid_from),
1108            period(&candidate.valid_to),
1109            result,
1110        )
1111        .await?;
1112        sqlx::query(
1113            "UPDATE memory_relationships SET inverse_relationship_id =
1114             CASE WHEN id = ? THEN ? ELSE ? END WHERE id IN (?, ?)",
1115        )
1116        .bind(first)
1117        .bind(second)
1118        .bind(first)
1119        .bind(first)
1120        .bind(second)
1121        .execute(&mut **tx)
1122        .await?;
1123    }
1124    Ok(())
1125}
1126
1127impl SqliteMemory {
1128    pub async fn reconcile_structured_personal_memory(
1129        &self,
1130        write: &PersonalMemoryWrite,
1131        source: &str,
1132        provenance: Option<&str>,
1133        channel: Option<&str>,
1134        privacy: FactPrivacy,
1135    ) -> anyhow::Result<PersonalMemoryWriteResult> {
1136        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1137        let mut result = PersonalMemoryWriteResult::default();
1138        let confidence = confidence(source, write.direct_user_statement);
1139        let privacy = privacy.to_string();
1140        let mut entities = HashMap::new();
1141        for candidate in &write.entities {
1142            if let Some(id) =
1143                resolve_entity(&mut tx, candidate, source, &privacy, channel, &mut result).await?
1144            {
1145                entities.insert(candidate.local_id.clone(), id);
1146            }
1147        }
1148        for candidate in &write.aliases {
1149            if let Some(&id) = entities.get(&candidate.entity_local_id) {
1150                write_alias(
1151                    &mut tx,
1152                    id,
1153                    candidate,
1154                    source,
1155                    provenance,
1156                    confidence,
1157                    write.direct_user_statement,
1158                    &privacy,
1159                    channel,
1160                    &mut result,
1161                )
1162                .await?;
1163            } else {
1164                result.unresolved.push(format!(
1165                    "alias '{}' has no resolved entity",
1166                    candidate.value
1167                ));
1168            }
1169        }
1170        for candidate in &write.facts {
1171            if let Some(&id) = entities.get(&candidate.subject_local_id) {
1172                write_fact(
1173                    &mut tx,
1174                    id,
1175                    candidate,
1176                    source,
1177                    provenance,
1178                    confidence,
1179                    write.direct_user_statement,
1180                    write.correction,
1181                    &privacy,
1182                    channel,
1183                    &mut result,
1184                )
1185                .await?;
1186            } else {
1187                result.unresolved.push(format!(
1188                    "fact '{}' has no resolved entity",
1189                    candidate.predicate
1190                ));
1191            }
1192        }
1193        for candidate in &write.relationships {
1194            if let (Some(&from), Some(&to)) = (
1195                entities.get(&candidate.source_local_id),
1196                entities.get(&candidate.target_local_id),
1197            ) {
1198                write_edge(
1199                    &mut tx,
1200                    from,
1201                    to,
1202                    candidate,
1203                    source,
1204                    provenance,
1205                    confidence,
1206                    write.direct_user_statement,
1207                    &privacy,
1208                    channel,
1209                    &mut result,
1210                )
1211                .await?;
1212            } else {
1213                result.unresolved.push(format!(
1214                    "relationship '{}' has an unresolved endpoint",
1215                    candidate.relationship_type
1216                ));
1217            }
1218        }
1219        tx.commit().await?;
1220        Ok(result)
1221    }
1222
1223    pub async fn canonical_personal_facts(&self) -> anyhow::Result<Vec<Fact>> {
1224        let rows = sqlx::query(
1225            "SELECT f.id, f.predicate, f.display_value, f.value, f.source, f.asserted_at,
1226                    f.updated_at, f.channel_id, f.privacy, e.display_name, e.is_owner
1227             FROM memory_entity_facts f
1228             JOIN memory_entities e ON e.id = f.subject_entity_id
1229             WHERE f.status = 'active' AND f.valid_to IS NULL AND e.status = 'active'
1230             ORDER BY f.updated_at DESC",
1231        )
1232        .fetch_all(&self.pool)
1233        .await?;
1234        let mut output = Vec::new();
1235        for row in rows {
1236            let asserted = crate::types::parse_ts(&row.get::<String, _>("asserted_at"))
1237                .ok_or_else(|| anyhow::anyhow!("unreadable asserted_at"))?;
1238            let updated = crate::types::parse_ts(&row.get::<String, _>("updated_at"))
1239                .ok_or_else(|| anyhow::anyhow!("unreadable updated_at"))?;
1240            let owner = row.get::<i64, _>("is_owner") != 0;
1241            let name: String = row.get("display_name");
1242            let pred: String = row.get("predicate");
1243            output.push(Fact {
1244                id: -1_000_000_000 - row.get::<i64, _>("id"),
1245                category: if owner { "user" } else { "people" }.to_string(),
1246                key: if owner {
1247                    pred
1248                } else {
1249                    format!("{name} · {pred}")
1250                },
1251                value: row
1252                    .get::<Option<String>, _>("display_value")
1253                    .unwrap_or_else(|| row.get("value")),
1254                source: format!("canonical:{}", row.get::<String, _>("source")),
1255                created_at: asserted,
1256                updated_at: updated,
1257                superseded_at: None,
1258                recall_count: 0,
1259                last_recalled_at: None,
1260                channel_id: row.get("channel_id"),
1261                privacy: FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
1262                first_seen_at: Some(asserted),
1263                source_excerpt: None,
1264            });
1265        }
1266        let aliases = sqlx::query(
1267            "SELECT a.id, a.alias_type, a.value, a.source, a.asserted_at, a.updated_at,
1268                    a.channel_id, a.privacy, e.display_name, e.is_owner
1269             FROM memory_aliases a JOIN memory_entities e ON e.id = a.entity_id
1270             WHERE a.status = 'active' AND a.valid_to IS NULL AND e.status = 'active'",
1271        )
1272        .fetch_all(&self.pool)
1273        .await?;
1274        for row in aliases {
1275            let asserted = crate::types::parse_ts(&row.get::<String, _>("asserted_at"))
1276                .ok_or_else(|| anyhow::anyhow!("unreadable asserted_at"))?;
1277            let updated = crate::types::parse_ts(&row.get::<String, _>("updated_at"))
1278                .ok_or_else(|| anyhow::anyhow!("unreadable updated_at"))?;
1279            let owner = row.get::<i64, _>("is_owner") != 0;
1280            let name: String = row.get("display_name");
1281            let kind: String = row.get("alias_type");
1282            output.push(Fact {
1283                id: -2_000_000_000 - row.get::<i64, _>("id"),
1284                category: if owner { "user" } else { "people" }.to_string(),
1285                key: if owner {
1286                    kind
1287                } else {
1288                    format!("{name} · {kind}")
1289                },
1290                value: row.get("value"),
1291                source: format!("canonical:{}", row.get::<String, _>("source")),
1292                created_at: asserted,
1293                updated_at: updated,
1294                superseded_at: None,
1295                recall_count: 0,
1296                last_recalled_at: None,
1297                channel_id: row.get("channel_id"),
1298                privacy: FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
1299                first_seen_at: Some(asserted),
1300                source_excerpt: None,
1301            });
1302        }
1303        let edges = sqlx::query(
1304            "SELECT r.id, r.relationship_type, r.source, r.asserted_at, r.updated_at,
1305                    r.channel_id, r.privacy, a.display_name source_name, b.display_name target_name
1306             FROM memory_relationships r
1307             JOIN memory_entities a ON a.id = r.source_entity_id
1308             JOIN memory_entities b ON b.id = r.target_entity_id
1309             WHERE r.status = 'active' AND r.valid_to IS NULL
1310               AND a.status = 'active' AND b.status = 'active'",
1311        )
1312        .fetch_all(&self.pool)
1313        .await?;
1314        for row in edges {
1315            let asserted = crate::types::parse_ts(&row.get::<String, _>("asserted_at"))
1316                .ok_or_else(|| anyhow::anyhow!("unreadable asserted_at"))?;
1317            let updated = crate::types::parse_ts(&row.get::<String, _>("updated_at"))
1318                .ok_or_else(|| anyhow::anyhow!("unreadable updated_at"))?;
1319            let rel: String = row.get("relationship_type");
1320            output.push(Fact {
1321                id: -3_000_000_000 - row.get::<i64, _>("id"),
1322                category: "relationships".to_string(),
1323                key: rel.clone(),
1324                value: format!(
1325                    "{} {} {}",
1326                    row.get::<String, _>("source_name"),
1327                    rel,
1328                    row.get::<String, _>("target_name")
1329                ),
1330                source: format!("canonical:{}", row.get::<String, _>("source")),
1331                created_at: asserted,
1332                updated_at: updated,
1333                superseded_at: None,
1334                recall_count: 0,
1335                last_recalled_at: None,
1336                channel_id: row.get("channel_id"),
1337                privacy: FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
1338                first_seen_at: Some(asserted),
1339                source_excerpt: None,
1340            });
1341        }
1342        Ok(output)
1343    }
1344
1345    /// Retracts the canonical record behind a projected id from
1346    /// [`Self::canonical_personal_facts`] (owner and people facts, aliases and
1347    /// relationship edges carry synthetic negative ids there). Returns whether
1348    /// an active record was retracted.
1349    pub async fn retract_canonical_projection(
1350        &self,
1351        projected_id: i64,
1352        source: &str,
1353    ) -> anyhow::Result<bool> {
1354        let (table, record_type, id) = match projected_id {
1355            id if id <= -3_000_000_000 => {
1356                ("memory_relationships", "relationship", -3_000_000_000 - id)
1357            }
1358            id if id <= -2_000_000_000 => ("memory_aliases", "alias", -2_000_000_000 - id),
1359            id if id <= -1_000_000_000 => ("memory_entity_facts", "fact", -1_000_000_000 - id),
1360            _ => return Ok(false),
1361        };
1362        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1363        let mut ids = vec![id];
1364        if record_type == "relationship" {
1365            // An edge is stored with its inverse; forgetting one forgets both.
1366            let inverse: Option<i64> = sqlx::query_scalar(
1367                "SELECT inverse_relationship_id FROM memory_relationships WHERE id = ?",
1368            )
1369            .bind(id)
1370            .fetch_optional(&mut *tx)
1371            .await?
1372            .flatten();
1373            ids.extend(inverse);
1374        }
1375        let retracted = retract(&mut tx, table, record_type, &ids, source).await?;
1376        tx.commit().await?;
1377        Ok(retracted > 0)
1378    }
1379
1380    /// Updates the value of an editable canonical projection (owner/people
1381    /// entity facts and aliases; relationships return `None`). Returns the
1382    /// refreshed projected `Fact` when updated.
1383    pub async fn update_canonical_projection(
1384        &self,
1385        projected_id: i64,
1386        new_value: &str,
1387        source: &str,
1388    ) -> anyhow::Result<Option<Fact>> {
1389        let trimmed = new_value.trim();
1390        if trimmed.is_empty() {
1391            return Ok(None);
1392        }
1393        let now = Utc::now().to_rfc3339();
1394        let mut result_projected_id = projected_id;
1395        if projected_id <= -3_000_000_000 {
1396            // Relationship edges are not edited as free text.
1397            return Ok(None);
1398        } else if projected_id <= -2_000_000_000 {
1399            let id = -2_000_000_000 - projected_id;
1400            let row = sqlx::query(
1401                "SELECT entity_id, alias_type FROM memory_aliases
1402                 WHERE id = ? AND status = 'active' AND valid_to IS NULL",
1403            )
1404            .bind(id)
1405            .fetch_optional(&self.pool)
1406            .await?;
1407            let Some(row) = row else {
1408                return Ok(None);
1409            };
1410            let entity_id: i64 = row.get("entity_id");
1411            let kind: String = row.get("alias_type");
1412            let normalized = alias_value(trimmed, &kind);
1413            if normalized.is_empty() {
1414                return Ok(None);
1415            }
1416            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1417            // Resolve UNIQUE(entity_id, alias_type, normalized_value) collisions
1418            // cleanly: remove an inactive duplicate before updating, or merge
1419            // into an already-active identical alias.
1420            if let Some((other_id, other_status)) = sqlx::query_as::<_, (i64, String)>(
1421                "SELECT id, status FROM memory_aliases
1422                 WHERE entity_id = ? AND alias_type = ? AND normalized_value = ? AND id != ?
1423                 LIMIT 1",
1424            )
1425            .bind(entity_id)
1426            .bind(&kind)
1427            .bind(&normalized)
1428            .bind(id)
1429            .fetch_optional(&mut *tx)
1430            .await?
1431            {
1432                if other_status == "active" {
1433                    retract(&mut tx, "memory_aliases", "alias", &[id], source).await?;
1434                    sqlx::query(
1435                        "UPDATE memory_aliases
1436                         SET value = ?, source = ?, confidence = 1.0,
1437                             confirmed_at = COALESCE(confirmed_at, ?), last_confirmed_at = ?,
1438                             updated_at = ?
1439                         WHERE id = ?",
1440                    )
1441                    .bind(trimmed)
1442                    .bind(source)
1443                    .bind(&now)
1444                    .bind(&now)
1445                    .bind(&now)
1446                    .bind(other_id)
1447                    .execute(&mut *tx)
1448                    .await?;
1449                    result_projected_id = -2_000_000_000 - other_id;
1450                    tx.commit().await?;
1451                    return Ok(self
1452                        .canonical_personal_facts()
1453                        .await?
1454                        .into_iter()
1455                        .find(|fact| fact.id == result_projected_id));
1456                } else {
1457                    sqlx::query("DELETE FROM memory_aliases WHERE id = ?")
1458                        .bind(other_id)
1459                        .execute(&mut *tx)
1460                        .await?;
1461                }
1462            }
1463            sqlx::query(
1464                "UPDATE memory_aliases
1465                 SET value = ?, normalized_value = ?, source = ?, confidence = 1.0,
1466                     confirmed_at = COALESCE(confirmed_at, ?), last_confirmed_at = ?,
1467                     updated_at = ?
1468                 WHERE id = ? AND status = 'active' AND valid_to IS NULL",
1469            )
1470            .bind(trimmed)
1471            .bind(&normalized)
1472            .bind(source)
1473            .bind(&now)
1474            .bind(&now)
1475            .bind(&now)
1476            .bind(id)
1477            .execute(&mut *tx)
1478            .await?;
1479            audit(
1480                &mut tx,
1481                "edit",
1482                Some(entity_id),
1483                "alias",
1484                Some(id),
1485                serde_json::json!({"value": trimmed, "normalized_value": normalized}),
1486                source,
1487                None,
1488            )
1489            .await?;
1490            tx.commit().await?;
1491        } else if projected_id <= -1_000_000_000 {
1492            let id = -1_000_000_000 - projected_id;
1493            let row = sqlx::query(
1494                "SELECT subject_entity_id, predicate FROM memory_entity_facts
1495                 WHERE id = ? AND status = 'active' AND valid_to IS NULL",
1496            )
1497            .bind(id)
1498            .fetch_optional(&self.pool)
1499            .await?;
1500            let Some(row) = row else {
1501                return Ok(None);
1502            };
1503            let entity_id: i64 = row.get("subject_entity_id");
1504            let pred: String = row.get("predicate");
1505            let (normalized, value_type) = normalized_fact(&pred, trimmed)?;
1506            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1507            if let Some(other_id) = sqlx::query_scalar::<_, i64>(
1508                "SELECT id FROM memory_entity_facts
1509                 WHERE subject_entity_id = ? AND predicate = ? AND normalized_value = ?
1510                   AND status = 'active' AND valid_to IS NULL AND id != ?
1511                 LIMIT 1",
1512            )
1513            .bind(entity_id)
1514            .bind(&pred)
1515            .bind(&normalized)
1516            .bind(id)
1517            .fetch_optional(&mut *tx)
1518            .await?
1519            {
1520                retract(&mut tx, "memory_entity_facts", "fact", &[id], source).await?;
1521                sqlx::query(
1522                    "UPDATE memory_entity_facts
1523                     SET display_value = ?, source = ?, confidence = 1.0,
1524                         confirmed_at = COALESCE(confirmed_at, ?), last_confirmed_at = ?,
1525                         updated_at = ?
1526                     WHERE id = ?",
1527                )
1528                .bind(trimmed)
1529                .bind(source)
1530                .bind(&now)
1531                .bind(&now)
1532                .bind(&now)
1533                .bind(other_id)
1534                .execute(&mut *tx)
1535                .await?;
1536                result_projected_id = -1_000_000_000 - other_id;
1537                tx.commit().await?;
1538                return Ok(self
1539                    .canonical_personal_facts()
1540                    .await?
1541                    .into_iter()
1542                    .find(|fact| fact.id == result_projected_id));
1543            }
1544            sqlx::query(
1545                "UPDATE memory_entity_facts
1546                 SET value_type = ?, value = ?, normalized_value = ?, display_value = ?,
1547                     source = ?, confidence = 1.0,
1548                     confirmed_at = COALESCE(confirmed_at, ?), last_confirmed_at = ?,
1549                     updated_at = ?
1550                 WHERE id = ? AND status = 'active' AND valid_to IS NULL",
1551            )
1552            .bind(value_type)
1553            .bind(&normalized)
1554            .bind(&normalized)
1555            .bind(trimmed)
1556            .bind(source)
1557            .bind(&now)
1558            .bind(&now)
1559            .bind(&now)
1560            .bind(id)
1561            .execute(&mut *tx)
1562            .await?;
1563            audit(
1564                &mut tx,
1565                "edit",
1566                Some(entity_id),
1567                "fact",
1568                Some(id),
1569                serde_json::json!({"display_value": trimmed, "normalized_value": normalized}),
1570                source,
1571                None,
1572            )
1573            .await?;
1574            tx.commit().await?;
1575        } else {
1576            return Ok(None);
1577        }
1578        Ok(self
1579            .canonical_personal_facts()
1580            .await?
1581            .into_iter()
1582            .find(|fact| fact.id == result_projected_id))
1583    }
1584
1585    /// Retracts the owner's canonical facts and aliases a profile key names
1586    /// (`residence`, `birthday`, `name`, ...): forgetting `[user] residence`
1587    /// must reach the store the owner block is rendered from, not only the
1588    /// legacy row. Returns whether anything was retracted.
1589    pub async fn retract_owner_profile_key(&self, key: &str, source: &str) -> anyhow::Result<bool> {
1590        let pred = predicate(key);
1591        let kind = match token(key).as_str() {
1592            "name" => "legal_name_variant".to_string(),
1593            "username" | "handle" | "online_handle" | "online_nickname" => {
1594                "online_handle".to_string()
1595            }
1596            other => alias_type(other),
1597        };
1598        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1599        let facts: Vec<i64> = sqlx::query_scalar(
1600            "SELECT f.id FROM memory_entity_facts f
1601             JOIN memory_entities e ON e.id = f.subject_entity_id
1602             WHERE e.is_owner = 1 AND f.predicate = ?
1603               AND f.status IN ('active', 'disputed') AND f.valid_to IS NULL",
1604        )
1605        .bind(&pred)
1606        .fetch_all(&mut *tx)
1607        .await?;
1608        let aliases: Vec<i64> = sqlx::query_scalar(
1609            "SELECT a.id FROM memory_aliases a
1610             JOIN memory_entities e ON e.id = a.entity_id
1611             WHERE e.is_owner = 1 AND a.alias_type = ?
1612               AND a.status = 'active' AND a.valid_to IS NULL",
1613        )
1614        .bind(&kind)
1615        .fetch_all(&mut *tx)
1616        .await?;
1617        let retracted = retract(&mut tx, "memory_entity_facts", "fact", &facts, source).await?
1618            + retract(&mut tx, "memory_aliases", "alias", &aliases, source).await?;
1619        tx.commit().await?;
1620        Ok(retracted > 0)
1621    }
1622
1623    /// Conservatively dual-writes only unambiguous owner-profile legacy keys.
1624    /// Relationship-shaped and compound-name facts stay untouched and pending.
1625    pub async fn backfill_structured_personal_memory(&self) -> anyhow::Result<usize> {
1626        // The legacy people table carries an explicit relationship field, so it
1627        // is safe to create separate entities and edges from those rows. We do
1628        // not infer relationships from names, co-residence, or notes.
1629        let people =
1630            sqlx::query("SELECT id, name, aliases_json, relationship FROM people ORDER BY id")
1631                .fetch_all(&self.pool)
1632                .await?;
1633        for person in people {
1634            let legacy_id: i64 = person.get("id");
1635            let name: String = person.get("name");
1636            let relationship: Option<String> = person.get("relationship");
1637            let relationship_key = relationship.as_deref().map(token);
1638            let local_id = format!("legacy_person_{legacy_id}");
1639            let is_owner = relationship_key.as_deref() == Some("owner");
1640            let mut write = PersonalMemoryWrite {
1641                entities: vec![
1642                    PersonalEntityCandidate {
1643                        local_id: "owner".to_string(),
1644                        entity_type: "person".to_string(),
1645                        canonical_name: if is_owner {
1646                            name.clone()
1647                        } else {
1648                            "Owner".to_string()
1649                        },
1650                        is_reference: false,
1651                        // A legacy people-row display name is often a preferred
1652                        // short name. Let an explicit profile `full_name` fact
1653                        // promote the canonical identity below.
1654                        canonical_name_confirmed: false,
1655                    },
1656                    PersonalEntityCandidate {
1657                        local_id: local_id.clone(),
1658                        entity_type: "person".to_string(),
1659                        canonical_name: name.clone(),
1660                        is_reference: false,
1661                        canonical_name_confirmed: true,
1662                    },
1663                ],
1664                ..Default::default()
1665            };
1666            if is_owner {
1667                write.entities.pop();
1668            } else {
1669                let aliases: Vec<String> =
1670                    serde_json::from_str(&person.get::<String, _>("aliases_json"))
1671                        .unwrap_or_default();
1672                write
1673                    .aliases
1674                    .extend(aliases.into_iter().map(|value| PersonalAliasCandidate {
1675                        entity_local_id: local_id.clone(),
1676                        value,
1677                        alias_type: "nickname".to_string(),
1678                    }));
1679                match relationship_key.as_deref() {
1680                    Some("father" | "mother" | "parent") => {
1681                        write.relationships.push(PersonalRelationshipCandidate {
1682                            source_local_id: local_id.clone(),
1683                            relationship_type: "PARENT_OF".to_string(),
1684                            target_local_id: "owner".to_string(),
1685                            valid_from: None,
1686                            valid_to: None,
1687                        });
1688                    }
1689                    Some("daughter" | "son" | "child") => {
1690                        write.relationships.push(PersonalRelationshipCandidate {
1691                            source_local_id: "owner".to_string(),
1692                            relationship_type: "PARENT_OF".to_string(),
1693                            target_local_id: local_id,
1694                            valid_from: None,
1695                            valid_to: None,
1696                        });
1697                    }
1698                    _ => {}
1699                }
1700            }
1701            self.reconcile_structured_personal_memory(
1702                &write,
1703                "legacy",
1704                Some("legacy people table"),
1705                None,
1706                FactPrivacy::Private,
1707            )
1708            .await?;
1709        }
1710
1711        // Explicit relationship-shaped legacy facts are safe to project when
1712        // the predicate itself names the relationship. Parent/partner facts
1713        // may create a person from a single unambiguous name; child references
1714        // only attach to an already-known canonical name or alias so nicknames
1715        // are never guessed into merges.
1716        let relationship_facts = sqlx::query(
1717            "SELECT f.id, f.key, f.value, f.source, f.channel_id, f.privacy, f.source_excerpt
1718             FROM facts f
1719             WHERE f.superseded_at IS NULL
1720               AND f.archived_at IS NULL
1721               AND lower(f.category) IN ('user', 'personal', 'profile', 'family')
1722               AND lower(f.key) IN (
1723                 'dad_name', 'father_name', 'mom_name', 'mother_name',
1724                 'partner_name', 'spouse_name', 'daughter_name', 'daughter_name_2',
1725                 'son_name', 'son_name_2', 'child_name', 'oldest_daughter_name',
1726                 'youngest_daughter_name', 'oldest_son_name', 'youngest_son_name',
1727                 'daughter_names', 'son_names', 'children_names',
1728                 'has_daughter', 'has_son', 'has_children'
1729               )
1730               AND NOT EXISTS (
1731                 SELECT 1 FROM memory_write_audit a
1732                 WHERE a.operation = 'legacy_relationship_backfill'
1733                   AND a.source_fact_id = f.id
1734               )
1735             ORDER BY f.id",
1736        )
1737        .fetch_all(&self.pool)
1738        .await?;
1739        for row in relationship_facts {
1740            let fact_id: i64 = row.get("id");
1741            let key = token(&row.get::<String, _>("key"));
1742            let value: String = row.get("value");
1743            let is_parent = matches!(
1744                key.as_str(),
1745                "dad_name" | "father_name" | "mom_name" | "mother_name"
1746            );
1747            let is_partner = matches!(key.as_str(), "partner_name" | "spouse_name");
1748            let is_plural_child = matches!(
1749                key.as_str(),
1750                "daughter_names"
1751                    | "son_names"
1752                    | "children_names"
1753                    | "has_daughter"
1754                    | "has_son"
1755                    | "has_children"
1756            );
1757            let names = if is_plural_child {
1758                split_legacy_people(&value)
1759            } else {
1760                vec![value.clone()]
1761            };
1762            let direct = matches!(
1763                row.get::<String, _>("source").as_str(),
1764                "agent" | "user_stated" | "owner" | "owner-stated"
1765            );
1766            let mut wrote_any = false;
1767
1768            for (index, raw_name) in names.into_iter().enumerate() {
1769                let Some((canonical_name, aliases)) = legacy_person_name(&raw_name) else {
1770                    let now = Utc::now().to_rfc3339();
1771                    sqlx::query(
1772                        "INSERT OR IGNORE INTO memory_resolution_reviews
1773                         (review_kind, normalized_reference, candidate_entity_ids_json,
1774                          payload_json, source, source_fact_id, status, created_at, updated_at)
1775                         VALUES ('ambiguous_legacy_relationship', ?, '[]', ?, 'legacy', ?,
1776                                 'pending', ?, ?)",
1777                    )
1778                    .bind(words(&raw_name))
1779                    .bind(serde_json::json!({"key": &key, "value": &value}).to_string())
1780                    .bind(fact_id)
1781                    .bind(&now)
1782                    .bind(&now)
1783                    .execute(&self.pool)
1784                    .await?;
1785                    continue;
1786                };
1787
1788                let relative_id = format!("legacy_relative_{fact_id}_{index}");
1789                let relative_is_reference = !is_parent && !is_partner;
1790                let relationship_type = if is_parent {
1791                    "PARENT_OF"
1792                } else if key == "spouse_name" {
1793                    "SPOUSE_OF"
1794                } else if is_partner {
1795                    "PARTNER_OF"
1796                } else {
1797                    "PARENT_OF"
1798                };
1799                let mut write = PersonalMemoryWrite {
1800                    entities: vec![
1801                        PersonalEntityCandidate {
1802                            local_id: "owner".to_string(),
1803                            entity_type: "person".to_string(),
1804                            canonical_name: "Owner".to_string(),
1805                            is_reference: true,
1806                            canonical_name_confirmed: false,
1807                        },
1808                        PersonalEntityCandidate {
1809                            local_id: relative_id.clone(),
1810                            entity_type: "person".to_string(),
1811                            canonical_name,
1812                            is_reference: relative_is_reference,
1813                            canonical_name_confirmed: is_parent || is_partner,
1814                        },
1815                    ],
1816                    direct_user_statement: direct,
1817                    ..Default::default()
1818                };
1819                write
1820                    .aliases
1821                    .extend(aliases.into_iter().map(|value| PersonalAliasCandidate {
1822                        entity_local_id: relative_id.clone(),
1823                        value,
1824                        alias_type: "nickname".to_string(),
1825                    }));
1826                write.relationships.push(PersonalRelationshipCandidate {
1827                    source_local_id: if is_parent {
1828                        relative_id.clone()
1829                    } else {
1830                        "owner".to_string()
1831                    },
1832                    relationship_type: relationship_type.to_string(),
1833                    target_local_id: if is_parent {
1834                        "owner".to_string()
1835                    } else {
1836                        relative_id
1837                    },
1838                    valid_from: None,
1839                    valid_to: None,
1840                });
1841                let result = self
1842                    .reconcile_structured_personal_memory(
1843                        &write,
1844                        "legacy",
1845                        row.get::<Option<String>, _>("source_excerpt").as_deref(),
1846                        row.get::<Option<String>, _>("channel_id").as_deref(),
1847                        FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
1848                    )
1849                    .await?;
1850                wrote_any |= result.created_relationships > 0 || result.confirmed_relationships > 0;
1851            }
1852
1853            if wrote_any {
1854                sqlx::query(
1855                    "INSERT INTO memory_write_audit
1856                     (operation, record_type, record_id, source, source_fact_id, created_at)
1857                     VALUES ('legacy_relationship_backfill', 'legacy_fact', ?, 'legacy', ?, ?)",
1858                )
1859                .bind(fact_id)
1860                .bind(fact_id)
1861                .bind(Utc::now().to_rfc3339())
1862                .execute(&self.pool)
1863                .await?;
1864            }
1865        }
1866
1867        // Promote an explicit child full-name record onto the already-known
1868        // child entity when the record itself names exactly one nickname.
1869        // Example: `daughter_isabella_full_name =
1870        // "Isabella (nickname Bella)"` can safely rename the existing Bella
1871        // child and retain Bella as a nickname. Alias-only similarities are
1872        // intentionally insufficient.
1873        let child_identity_facts = sqlx::query(
1874            "SELECT f.id, f.key, f.value, f.source, f.channel_id, f.privacy,
1875                    f.source_excerpt
1876             FROM facts f
1877             WHERE f.superseded_at IS NULL
1878               AND f.archived_at IS NULL
1879               AND lower(f.category) IN ('user', 'personal', 'profile', 'family')
1880               AND (
1881                    lower(f.key) LIKE 'daughter_%_full_name'
1882                    OR lower(f.key) LIKE 'son_%_full_name'
1883               )
1884               AND NOT EXISTS (
1885                    SELECT 1 FROM memory_write_audit a
1886                    WHERE a.operation = 'legacy_child_identity_backfill'
1887                      AND a.source_fact_id = f.id
1888               )
1889             ORDER BY f.id",
1890        )
1891        .fetch_all(&self.pool)
1892        .await?;
1893        for row in child_identity_facts {
1894            let fact_id: i64 = row.get("id");
1895            let value: String = row.get("value");
1896            let Some((display_name, aliases)) = legacy_person_name(&value) else {
1897                continue;
1898            };
1899            if aliases.len() != 1 {
1900                continue;
1901            }
1902            let alias = aliases[0].clone();
1903            let alias_normalized = words(&alias);
1904            let candidates = sqlx::query_scalar::<_, i64>(
1905                "SELECT DISTINCT child.id
1906                 FROM memory_entities owner
1907                 JOIN memory_relationships rel
1908                   ON rel.source_entity_id = owner.id
1909                  AND rel.relationship_type = 'PARENT_OF'
1910                  AND rel.status = 'active' AND rel.valid_to IS NULL
1911                 JOIN memory_entities child
1912                   ON child.id = rel.target_entity_id
1913                  AND child.entity_type = 'person' AND child.status = 'active'
1914                 WHERE owner.is_owner = 1 AND owner.status = 'active'
1915                   AND (
1916                       child.canonical_name = ?
1917                       OR EXISTS (
1918                           SELECT 1 FROM memory_aliases a
1919                           WHERE a.entity_id = child.id AND a.status = 'active'
1920                             AND a.valid_to IS NULL AND a.normalized_value = ?
1921                       )
1922                   )",
1923            )
1924            .bind(&alias_normalized)
1925            .bind(&alias_normalized)
1926            .fetch_all(&self.pool)
1927            .await?;
1928            if candidates.len() != 1 {
1929                let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1930                review(
1931                    &mut tx,
1932                    "ambiguous_legacy_child_identity",
1933                    &alias_normalized,
1934                    &candidates,
1935                    serde_json::json!({"legacy_fact_id": fact_id, "value": value}),
1936                    "legacy",
1937                )
1938                .await?;
1939                tx.commit().await?;
1940                continue;
1941            }
1942
1943            let child_id = candidates[0];
1944            let canonical_name = words(&display_name);
1945            let collision = sqlx::query_scalar::<_, i64>(
1946                "SELECT id FROM memory_entities
1947                 WHERE entity_type = 'person' AND canonical_name = ? AND status = 'active'
1948                   AND id != ? LIMIT 1",
1949            )
1950            .bind(&canonical_name)
1951            .bind(child_id)
1952            .fetch_optional(&self.pool)
1953            .await?;
1954            if let Some(collision_id) = collision {
1955                let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1956                review(
1957                    &mut tx,
1958                    "legacy_child_name_collision",
1959                    &canonical_name,
1960                    &[child_id, collision_id],
1961                    serde_json::json!({"legacy_fact_id": fact_id, "value": value}),
1962                    "legacy",
1963                )
1964                .await?;
1965                tx.commit().await?;
1966                continue;
1967            }
1968
1969            let direct = matches!(
1970                row.get::<String, _>("source").as_str(),
1971                "agent" | "user_stated" | "owner" | "owner-stated"
1972            );
1973            let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")).to_string();
1974            let channel = row.get::<Option<String>, _>("channel_id");
1975            let provenance = row.get::<Option<String>, _>("source_excerpt");
1976            let mut result = PersonalMemoryWriteResult::default();
1977            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1978            let current: String =
1979                sqlx::query_scalar("SELECT canonical_name FROM memory_entities WHERE id = ?")
1980                    .bind(child_id)
1981                    .fetch_one(&mut *tx)
1982                    .await?;
1983            if current != canonical_name {
1984                sqlx::query(
1985                    "UPDATE memory_entities SET canonical_name = ?, display_name = ?,
1986                     updated_at = ? WHERE id = ?",
1987                )
1988                .bind(&canonical_name)
1989                .bind(display_name.trim())
1990                .bind(Utc::now().to_rfc3339())
1991                .bind(child_id)
1992                .execute(&mut *tx)
1993                .await?;
1994                audit(
1995                    &mut tx,
1996                    "update",
1997                    Some(child_id),
1998                    "entity",
1999                    Some(child_id),
2000                    serde_json::json!({
2001                        "canonical_name": canonical_name,
2002                        "evidence": "explicit child full name with nickname"
2003                    }),
2004                    "legacy",
2005                    provenance.as_deref(),
2006                )
2007                .await?;
2008            }
2009            write_alias(
2010                &mut tx,
2011                child_id,
2012                &PersonalAliasCandidate {
2013                    entity_local_id: "child".to_string(),
2014                    value: alias,
2015                    alias_type: "nickname".to_string(),
2016                },
2017                "legacy",
2018                provenance.as_deref(),
2019                confidence(&row.get::<String, _>("source"), direct),
2020                direct,
2021                &privacy,
2022                channel.as_deref(),
2023                &mut result,
2024            )
2025            .await?;
2026            sqlx::query(
2027                "INSERT INTO memory_write_audit
2028                 (operation, entity_id, record_type, record_id, source, source_fact_id,
2029                  provenance, created_at)
2030                 VALUES ('legacy_child_identity_backfill', ?, 'legacy_fact', ?,
2031                         'legacy', ?, ?, ?)",
2032            )
2033            .bind(child_id)
2034            .bind(fact_id)
2035            .bind(fact_id)
2036            .bind(provenance.as_deref())
2037            .bind(Utc::now().to_rfc3339())
2038            .execute(&mut *tx)
2039            .await?;
2040            tx.commit().await?;
2041        }
2042
2043        // A person-qualified legacy birthday key is safe to attach when its
2044        // name resolves to exactly one existing child canonical name or alias.
2045        // Generic keys such as `daughter_birthday` and ordinal keys remain
2046        // untouched because they do not identify a stable subject.
2047        let child_birth_facts = sqlx::query(
2048            "SELECT f.id, f.key, f.value, f.source, f.channel_id, f.privacy,
2049                    f.source_excerpt
2050             FROM facts f
2051             WHERE f.superseded_at IS NULL
2052               AND f.archived_at IS NULL
2053               AND lower(f.category) IN ('user', 'personal', 'profile', 'family')
2054               AND (
2055                    lower(f.key) LIKE 'daughter_%_birthday'
2056                    OR lower(f.key) LIKE 'daughter_%_birth_date'
2057                    OR lower(f.key) LIKE 'son_%_birthday'
2058                    OR lower(f.key) LIKE 'son_%_birth_date'
2059               )
2060               AND NOT EXISTS (
2061                    SELECT 1 FROM memory_write_audit a
2062                    WHERE a.operation = 'legacy_child_birth_backfill'
2063                      AND a.source_fact_id = f.id
2064               )
2065             ORDER BY f.id",
2066        )
2067        .fetch_all(&self.pool)
2068        .await?;
2069        for row in child_birth_facts {
2070            let fact_id: i64 = row.get("id");
2071            let key = token(&row.get::<String, _>("key"));
2072            let reference = ["daughter_", "son_"]
2073                .iter()
2074                .find_map(|prefix| key.strip_prefix(prefix))
2075                .and_then(|rest| {
2076                    rest.strip_suffix("_birthday")
2077                        .or_else(|| rest.strip_suffix("_birth_date"))
2078                })
2079                .map(str::to_string);
2080            let Some(reference) = reference else {
2081                continue;
2082            };
2083            if reference.is_empty()
2084                || matches!(
2085                    reference.as_str(),
2086                    "oldest" | "youngest" | "first" | "second"
2087                )
2088            {
2089                continue;
2090            }
2091            let value: String = row.get("value");
2092            if date_value(&value).is_none() {
2093                continue;
2094            }
2095            let candidates = sqlx::query_scalar::<_, i64>(
2096                "SELECT DISTINCT child.id
2097                 FROM memory_entities owner
2098                 JOIN memory_relationships rel
2099                   ON rel.source_entity_id = owner.id
2100                  AND rel.relationship_type = 'PARENT_OF'
2101                  AND rel.status = 'active' AND rel.valid_to IS NULL
2102                 JOIN memory_entities child
2103                   ON child.id = rel.target_entity_id
2104                  AND child.entity_type = 'person' AND child.status = 'active'
2105                 WHERE owner.is_owner = 1 AND owner.status = 'active'
2106                   AND (
2107                       child.canonical_name = ?
2108                       OR EXISTS (
2109                           SELECT 1 FROM memory_aliases a
2110                           WHERE a.entity_id = child.id AND a.status = 'active'
2111                             AND a.valid_to IS NULL AND a.normalized_value = ?
2112                       )
2113                   )",
2114            )
2115            .bind(&reference)
2116            .bind(&reference)
2117            .fetch_all(&self.pool)
2118            .await?;
2119            if candidates.len() != 1 {
2120                continue;
2121            }
2122            let child_id = candidates[0];
2123            let source: String = row.get("source");
2124            let direct = matches!(
2125                source.as_str(),
2126                "agent" | "user_stated" | "owner" | "owner-stated"
2127            );
2128            let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")).to_string();
2129            let channel = row.get::<Option<String>, _>("channel_id");
2130            let provenance = row.get::<Option<String>, _>("source_excerpt");
2131            let mut result = PersonalMemoryWriteResult::default();
2132            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2133            write_fact(
2134                &mut tx,
2135                child_id,
2136                &PersonalFactCandidate {
2137                    subject_local_id: "child".to_string(),
2138                    predicate: "birth_date".to_string(),
2139                    value,
2140                    display_value: None,
2141                    valid_from: None,
2142                    valid_to: None,
2143                    retract: false,
2144                },
2145                "legacy",
2146                provenance.as_deref(),
2147                confidence(&source, direct),
2148                direct,
2149                false,
2150                &privacy,
2151                channel.as_deref(),
2152                &mut result,
2153            )
2154            .await?;
2155            sqlx::query(
2156                "INSERT INTO memory_write_audit
2157                 (operation, entity_id, record_type, record_id, source, source_fact_id,
2158                  provenance, created_at)
2159                 VALUES ('legacy_child_birth_backfill', ?, 'legacy_fact', ?,
2160                         'legacy', ?, ?, ?)",
2161            )
2162            .bind(child_id)
2163            .bind(fact_id)
2164            .bind(fact_id)
2165            .bind(provenance.as_deref())
2166            .bind(Utc::now().to_rfc3339())
2167            .execute(&mut *tx)
2168            .await?;
2169            tx.commit().await?;
2170        }
2171
2172        // Preserve explicitly stated plural co-residence without inventing a
2173        // plural canonical fact. The already-established children each receive
2174        // a typed LIVES_WITH edge; the symmetric inverse is materialized by
2175        // write_edge. Residence is not inferred from this pass.
2176        let co_residence_facts = sqlx::query(
2177            "SELECT f.id, f.source, f.channel_id, f.privacy, f.source_excerpt
2178             FROM facts f
2179             WHERE f.superseded_at IS NULL
2180               AND f.archived_at IS NULL
2181               AND lower(f.category) IN ('user', 'personal', 'profile', 'family')
2182               AND lower(f.key) IN (
2183                   'daughters_live_with_user', 'sons_live_with_user',
2184                   'children_live_with_user'
2185               )
2186               AND lower(f.value) LIKE '%live%with%'
2187               AND NOT EXISTS (
2188                    SELECT 1 FROM memory_write_audit a
2189                    WHERE a.operation = 'legacy_children_lives_with_backfill'
2190                      AND a.source_fact_id = f.id
2191               )
2192             ORDER BY f.id",
2193        )
2194        .fetch_all(&self.pool)
2195        .await?;
2196        for row in co_residence_facts {
2197            let fact_id: i64 = row.get("id");
2198            let owner_id: i64 = sqlx::query_scalar(
2199                "SELECT id FROM memory_entities
2200                 WHERE is_owner = 1 AND status = 'active' LIMIT 1",
2201            )
2202            .fetch_one(&self.pool)
2203            .await?;
2204            let child_ids = sqlx::query_scalar::<_, i64>(
2205                "SELECT target_entity_id FROM memory_relationships
2206                 WHERE source_entity_id = ? AND relationship_type = 'PARENT_OF'
2207                   AND status = 'active' AND valid_to IS NULL
2208                 ORDER BY target_entity_id",
2209            )
2210            .bind(owner_id)
2211            .fetch_all(&self.pool)
2212            .await?;
2213            let source: String = row.get("source");
2214            let direct = matches!(
2215                source.as_str(),
2216                "agent" | "user_stated" | "owner" | "owner-stated"
2217            );
2218            let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")).to_string();
2219            let channel = row.get::<Option<String>, _>("channel_id");
2220            let provenance = row.get::<Option<String>, _>("source_excerpt");
2221            let mut result = PersonalMemoryWriteResult::default();
2222            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2223            for child_id in child_ids {
2224                write_edge(
2225                    &mut tx,
2226                    child_id,
2227                    owner_id,
2228                    &PersonalRelationshipCandidate {
2229                        source_local_id: "child".to_string(),
2230                        relationship_type: "LIVES_WITH".to_string(),
2231                        target_local_id: "owner".to_string(),
2232                        valid_from: None,
2233                        valid_to: None,
2234                    },
2235                    "legacy",
2236                    provenance.as_deref(),
2237                    confidence(&source, direct),
2238                    direct,
2239                    &privacy,
2240                    channel.as_deref(),
2241                    &mut result,
2242                )
2243                .await?;
2244            }
2245            sqlx::query(
2246                "INSERT INTO memory_write_audit
2247                 (operation, entity_id, record_type, record_id, source, source_fact_id,
2248                  provenance, created_at)
2249                 VALUES ('legacy_children_lives_with_backfill', ?, 'legacy_fact', ?,
2250                         'legacy', ?, ?, ?)",
2251            )
2252            .bind(owner_id)
2253            .bind(fact_id)
2254            .bind(fact_id)
2255            .bind(provenance.as_deref())
2256            .bind(Utc::now().to_rfc3339())
2257            .execute(&mut *tx)
2258            .await?;
2259            tx.commit().await?;
2260        }
2261
2262        // A legacy short-name row can predate a later, explicit full-name fact
2263        // that identifies the short name as a nickname (for example, a Person
2264        // named "Sol" followed by `Marisol "Sol" Vega`). Merge
2265        // only the narrow, auditable case where both entities have the same
2266        // complete active relationship set and the short-name entity carries
2267        // no independent aliases or facts. This is stronger than an alias-only
2268        // match and does not guess across ambiguous people.
2269        let merge_candidates = sqlx::query(
2270            "SELECT DISTINCT canonical.id AS canonical_id, duplicate.id AS duplicate_id,
2271                    alias.normalized_value
2272             FROM memory_aliases alias
2273             JOIN memory_entities canonical ON canonical.id = alias.entity_id
2274             JOIN memory_entities duplicate
2275               ON duplicate.entity_type = canonical.entity_type
2276              AND duplicate.canonical_name = alias.normalized_value
2277              AND duplicate.id != canonical.id
2278             WHERE alias.alias_type = 'nickname' AND alias.status = 'active'
2279               AND canonical.status = 'active' AND duplicate.status = 'active'
2280               AND NOT EXISTS (
2281                   SELECT 1 FROM memory_aliases duplicate_alias
2282                   WHERE duplicate_alias.entity_id = duplicate.id
2283               )
2284               AND NOT EXISTS (
2285                   SELECT 1 FROM memory_entity_facts duplicate_fact
2286                   WHERE duplicate_fact.subject_entity_id = duplicate.id
2287               )
2288               AND EXISTS (
2289                   SELECT 1 FROM memory_relationships duplicate_rel
2290                   WHERE duplicate_rel.status = 'active'
2291                     AND (duplicate_rel.source_entity_id = duplicate.id
2292                          OR duplicate_rel.target_entity_id = duplicate.id)
2293               )
2294               AND NOT EXISTS (
2295                   SELECT 1 FROM memory_relationships duplicate_rel
2296                   WHERE duplicate_rel.status = 'active'
2297                     AND (duplicate_rel.source_entity_id = duplicate.id
2298                          OR duplicate_rel.target_entity_id = duplicate.id)
2299                     AND NOT EXISTS (
2300                         SELECT 1 FROM memory_relationships canonical_rel
2301                         WHERE canonical_rel.status = 'active'
2302                           AND canonical_rel.relationship_type =
2303                               duplicate_rel.relationship_type
2304                           AND (
2305                               (duplicate_rel.source_entity_id = duplicate.id
2306                                AND canonical_rel.source_entity_id = canonical.id
2307                                AND canonical_rel.target_entity_id =
2308                                    duplicate_rel.target_entity_id)
2309                               OR
2310                               (duplicate_rel.target_entity_id = duplicate.id
2311                                AND canonical_rel.target_entity_id = canonical.id
2312                                AND canonical_rel.source_entity_id =
2313                                    duplicate_rel.source_entity_id)
2314                           )
2315                     )
2316               )",
2317        )
2318        .fetch_all(&self.pool)
2319        .await?;
2320        for candidate in merge_candidates {
2321            let canonical_id: i64 = candidate.get("canonical_id");
2322            let duplicate_id: i64 = candidate.get("duplicate_id");
2323            let normalized_value: String = candidate.get("normalized_value");
2324            let now = Utc::now().to_rfc3339();
2325            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2326            sqlx::query(
2327                "UPDATE memory_relationships
2328                 SET status = 'superseded', valid_to = ?, updated_at = ?
2329                 WHERE status = 'active'
2330                   AND (source_entity_id = ? OR target_entity_id = ?)",
2331            )
2332            .bind(&now)
2333            .bind(&now)
2334            .bind(duplicate_id)
2335            .bind(duplicate_id)
2336            .execute(&mut *tx)
2337            .await?;
2338            sqlx::query(
2339                "UPDATE memory_entities
2340                 SET status = 'merged', merged_into_entity_id = ?, updated_at = ?
2341                 WHERE id = ? AND status = 'active'",
2342            )
2343            .bind(canonical_id)
2344            .bind(&now)
2345            .bind(duplicate_id)
2346            .execute(&mut *tx)
2347            .await?;
2348            audit(
2349                &mut tx,
2350                "merge",
2351                Some(duplicate_id),
2352                "entity",
2353                Some(duplicate_id),
2354                serde_json::json!({
2355                    "merged_into_entity_id": canonical_id,
2356                    "evidence": "explicit nickname plus identical relationships",
2357                    "nickname": normalized_value,
2358                }),
2359                "legacy",
2360                Some("legacy relationship backfill reconciliation"),
2361            )
2362            .await?;
2363            tx.commit().await?;
2364        }
2365
2366        // Malformed combined parent identities are preserved but explicitly
2367        // quarantined for review; they are never parsed into one Person.
2368        let compound_parents = sqlx::query(
2369            "SELECT id, key, value FROM facts
2370             WHERE superseded_at IS NULL
2371               AND archived_at IS NULL
2372               AND lower(key) IN ('father_name', 'mother_name', 'parent_name', 'parents')
2373               AND (lower(value) LIKE '% and %' OR value LIKE '%&%')",
2374        )
2375        .fetch_all(&self.pool)
2376        .await?;
2377        for row in compound_parents {
2378            let id: i64 = row.get("id");
2379            let now = Utc::now().to_rfc3339();
2380            sqlx::query(
2381                "INSERT OR IGNORE INTO memory_resolution_reviews
2382                 (review_kind, normalized_reference, candidate_entity_ids_json, payload_json,
2383                  source, source_fact_id, status, created_at, updated_at)
2384                 VALUES ('compound_parent_identity', ?, '[]', ?, 'legacy', ?, 'pending', ?, ?)",
2385            )
2386            .bind(words(&row.get::<String, _>("value")))
2387            .bind(
2388                serde_json::json!({"legacy_fact_id": id, "key": row.get::<String, _>("key")})
2389                    .to_string(),
2390            )
2391            .bind(id)
2392            .bind(&now)
2393            .bind(&now)
2394            .execute(&self.pool)
2395            .await?;
2396        }
2397
2398        let rows = sqlx::query(
2399            "SELECT f.id, f.key, f.value, f.source, f.channel_id, f.privacy, f.source_excerpt
2400             FROM facts f
2401             WHERE f.superseded_at IS NULL
2402               AND f.archived_at IS NULL
2403               AND (
2404                 (lower(f.category) IN ('user', 'personal', 'profile')
2405                  AND lower(f.key) IN (
2406                    'name', 'full_name', 'preferred_name', 'nickname', 'username',
2407                    'online_nickname', 'online_handle', 'handle', 'birthday',
2408                    'birth_date', 'date_of_birth', 'residence', 'current_residence',
2409                    'birthplace', 'place_of_birth', 'address_as', 'call_me',
2410                    'preferred_address', 'addressing', 'avoid_names', 'rejected_alias'
2411                  ))
2412                 OR (lower(f.category) = 'preference'
2413                  AND lower(f.key) IN (
2414                    'name', 'full_name', 'preferred_name', 'nickname',
2415                    'address_as', 'call_me', 'preferred_address', 'addressing',
2416                    'avoid_names', 'rejected_alias'
2417                  ))
2418               )
2419               AND NOT EXISTS (
2420                 SELECT 1 FROM memory_write_audit a
2421                 WHERE a.operation = 'legacy_backfill' AND a.source_fact_id = f.id
2422               )
2423             ORDER BY f.id",
2424        )
2425        .fetch_all(&self.pool)
2426        .await?;
2427        let mut migrated = 0;
2428        for row in rows {
2429            let id: i64 = row.get("id");
2430            let key: String = row.get("key");
2431            let value: String = row.get("value");
2432            let normalized_key = predicate(&key);
2433            // Legacy free text has no typed entities: a compound name is
2434            // queued for review (see `legacy_person_name`).
2435            if matches!(normalized_key.as_str(), "name" | "full_name")
2436                && (value.to_lowercase().contains(" and ") || value.contains('&'))
2437            {
2438                let now = Utc::now().to_rfc3339();
2439                sqlx::query(
2440                    "INSERT OR IGNORE INTO memory_resolution_reviews
2441                     (review_kind, normalized_reference, candidate_entity_ids_json, payload_json,
2442                      source, source_fact_id, status, created_at, updated_at)
2443                     VALUES ('compound_legacy_name', ?, '[]', ?, 'legacy', ?, 'pending', ?, ?)",
2444                )
2445                .bind(words(&value))
2446                .bind(serde_json::json!({"legacy_fact_id": id}).to_string())
2447                .bind(id)
2448                .bind(&now)
2449                .bind(&now)
2450                .execute(&self.pool)
2451                .await?;
2452                continue;
2453            }
2454            let direct = matches!(
2455                row.get::<String, _>("source").as_str(),
2456                "agent" | "user_stated" | "owner" | "owner-stated"
2457            );
2458            let mut write = PersonalMemoryWrite {
2459                entities: vec![PersonalEntityCandidate {
2460                    local_id: "owner".to_string(),
2461                    entity_type: "person".to_string(),
2462                    canonical_name: if matches!(normalized_key.as_str(), "name" | "full_name") {
2463                        value.clone()
2464                    } else {
2465                        "Owner".to_string()
2466                    },
2467                    is_reference: false,
2468                    canonical_name_confirmed: matches!(
2469                        normalized_key.as_str(),
2470                        "name" | "full_name"
2471                    ),
2472                }],
2473                direct_user_statement: direct,
2474                ..Default::default()
2475            };
2476            match normalized_key.as_str() {
2477                "name" | "full_name" => write.aliases.push(PersonalAliasCandidate {
2478                    entity_local_id: "owner".to_string(),
2479                    value: value.clone(),
2480                    alias_type: "legal_name_variant".to_string(),
2481                }),
2482                "preferred_name" | "nickname" => write.aliases.push(PersonalAliasCandidate {
2483                    entity_local_id: "owner".to_string(),
2484                    value: value.clone(),
2485                    alias_type: normalized_key,
2486                }),
2487                "username" | "online_nickname" | "online_handle" | "handle" => {
2488                    write.aliases.push(PersonalAliasCandidate {
2489                        entity_local_id: "owner".to_string(),
2490                        value: value.clone(),
2491                        alias_type: "online_handle".to_string(),
2492                    })
2493                }
2494                _ => write.facts.push(PersonalFactCandidate {
2495                    subject_local_id: "owner".to_string(),
2496                    predicate: normalized_key,
2497                    value: value.clone(),
2498                    display_value: None,
2499                    valid_from: None,
2500                    valid_to: None,
2501                    retract: false,
2502                }),
2503            }
2504            let result = self
2505                .reconcile_structured_personal_memory(
2506                    &write,
2507                    "legacy",
2508                    row.get::<Option<String>, _>("source_excerpt").as_deref(),
2509                    row.get::<Option<String>, _>("channel_id").as_deref(),
2510                    FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
2511                )
2512                .await;
2513            if result.is_ok() {
2514                sqlx::query(
2515                    "INSERT INTO memory_write_audit
2516                     (operation, record_type, record_id, source, source_fact_id, created_at)
2517                     VALUES ('legacy_backfill', 'legacy_fact', ?, 'legacy', ?, ?)",
2518                )
2519                .bind(id)
2520                .bind(id)
2521                .bind(Utc::now().to_rfc3339())
2522                .execute(&self.pool)
2523                .await?;
2524                migrated += 1;
2525            }
2526        }
2527
2528        // Earlier versions may already have marked every profile fact as
2529        // migrated while leaving a preferred short name as the owner
2530        // canonical name. Re-evaluate only explicit `full_name` facts and
2531        // promote the strongest direct statement once. A startup does not
2532        // refresh confirmation timestamps when the canonical name is already
2533        // correct.
2534        if let Some(row) = sqlx::query(
2535            "SELECT f.value, f.source, f.channel_id, f.privacy, f.source_excerpt
2536             FROM facts f
2537             WHERE f.superseded_at IS NULL
2538               AND f.archived_at IS NULL
2539               AND lower(f.category) IN ('user', 'personal', 'profile')
2540               AND lower(f.key) = 'full_name'
2541               AND lower(f.value) NOT LIKE '% and %' AND f.value NOT LIKE '%&%'
2542             ORDER BY
2543               CASE WHEN f.source IN ('user_stated', 'owner', 'owner-stated', 'agent')
2544                    THEN 0 ELSE 1 END,
2545               length(f.value) DESC, f.id DESC
2546             LIMIT 1",
2547        )
2548        .fetch_optional(&self.pool)
2549        .await?
2550        {
2551            let value: String = row.get("value");
2552            let expected = words(&value);
2553            let current: Option<String> = sqlx::query_scalar(
2554                "SELECT canonical_name FROM memory_entities
2555                 WHERE is_owner = 1 AND status = 'active' LIMIT 1",
2556            )
2557            .fetch_optional(&self.pool)
2558            .await?;
2559            if current.as_deref() != Some(expected.as_str()) {
2560                let source: String = row.get("source");
2561                self.reconcile_structured_personal_memory(
2562                    &PersonalMemoryWrite {
2563                        entities: vec![PersonalEntityCandidate {
2564                            local_id: "owner".to_string(),
2565                            entity_type: "person".to_string(),
2566                            canonical_name: value.clone(),
2567                            is_reference: false,
2568                            canonical_name_confirmed: true,
2569                        }],
2570                        aliases: vec![PersonalAliasCandidate {
2571                            entity_local_id: "owner".to_string(),
2572                            value,
2573                            alias_type: "legal_name_variant".to_string(),
2574                        }],
2575                        direct_user_statement: matches!(
2576                            source.as_str(),
2577                            "user_stated" | "owner" | "owner-stated" | "agent"
2578                        ),
2579                        ..Default::default()
2580                    },
2581                    "legacy",
2582                    row.get::<Option<String>, _>("source_excerpt").as_deref(),
2583                    row.get::<Option<String>, _>("channel_id").as_deref(),
2584                    FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
2585                )
2586                .await?;
2587            }
2588        }
2589        Ok(migrated)
2590    }
2591}
2592
2593#[cfg(test)]
2594mod tests {
2595    use super::*;
2596
2597    #[test]
2598    fn dates_share_one_canonical_form() {
2599        assert_eq!(date_value("Feb 4 1988").as_deref(), Some("1988-02-04"));
2600        assert_eq!(
2601            date_value("February 4, 1988").as_deref(),
2602            Some("1988-02-04")
2603        );
2604        assert_eq!(date_value("1988-02-04").as_deref(), Some("1988-02-04"));
2605    }
2606
2607    #[test]
2608    fn handles_are_case_insensitive() {
2609        assert_eq!(alias_value("@RiveraDev", "online_handle"), "riveradev");
2610    }
2611
2612    #[test]
2613    fn inverse_family_edges_are_explicit() {
2614        assert_eq!(inverse("PARENT_OF"), Some("CHILD_OF"));
2615        assert_eq!(inverse("LIVES_WITH"), Some("LIVES_WITH"));
2616    }
2617}