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
18fn 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 other => other.to_string(),
58 }
59}
60
61fn alias_type(value: &str) -> String {
62 match token(value).as_str() {
63 "favorite_name" | "preferred" | "preferred_first_name" => "preferred_name".to_string(),
64 "online_nickname" | "online_username" => "online_handle".to_string(),
65 "legal_name" | "full_name" => "legal_name_variant".to_string(),
66 other => other.to_string(),
67 }
68}
69
70fn entity_type(value: &str) -> String {
71 match token(value).as_str() {
72 kind @ ("person" | "organization" | "project" | "place" | "account") => kind.to_string(),
73 _ => "person".to_string(),
74 }
75}
76
77fn relation(value: &str) -> String {
78 match token(value).as_str() {
79 "parent" | "parent_of" | "father_of" | "mother_of" => "PARENT_OF".to_string(),
80 "child" | "child_of" | "daughter_of" | "son_of" => "CHILD_OF".to_string(),
81 "lives_with" | "cohabits_with" => "LIVES_WITH".to_string(),
82 "lives_in" | "resident_of" => "LIVES_IN".to_string(),
83 "uses_alias" => "USES_ALIAS".to_string(),
84 "uses_handle" => "USES_HANDLE".to_string(),
85 "has_account" => "HAS_ACCOUNT".to_string(),
86 other => other.to_ascii_uppercase(),
87 }
88}
89
90fn inverse(value: &str) -> Option<&'static str> {
91 match value {
92 "PARENT_OF" => Some("CHILD_OF"),
93 "CHILD_OF" => Some("PARENT_OF"),
94 "LIVES_WITH" => Some("LIVES_WITH"),
95 "PARTNER_OF" => Some("PARTNER_OF"),
96 "SPOUSE_OF" => Some("SPOUSE_OF"),
97 _ => None,
98 }
99}
100
101fn legacy_person_name(value: &str) -> Option<(String, Vec<String>)> {
106 let mut display = value.trim().to_string();
107 if display.is_empty() || display.to_ascii_lowercase().contains(" and ") || display.contains('&')
108 {
109 return None;
110 }
111
112 let mut aliases = Vec::new();
113 if let Some(start) = display.find('"')
114 && let Some(relative_end) = display[start + 1..].find('"')
115 {
116 let end = start + 1 + relative_end;
117 let alias = display[start + 1..end].trim();
118 if !alias.is_empty() {
119 aliases.push(alias.to_string());
120 }
121 display.replace_range(start..=end, "");
122 }
123 if let (Some(start), Some(end)) = (display.find('('), display.rfind(')'))
124 && end > start
125 {
126 let note = display[start + 1..end].trim();
127 let lower = note.to_ascii_lowercase();
128 let alias = lower
129 .strip_prefix("nickname ")
130 .or_else(|| lower.strip_prefix("aka "))
131 .or_else(|| lower.strip_prefix("also known as "))
132 .map(|prefix_removed| {
133 let offset = note.len().saturating_sub(prefix_removed.len());
134 note[offset..].trim()
135 });
136 if let Some(alias) = alias.filter(|alias| !alias.is_empty()) {
137 aliases.push(alias.to_string());
138 display.replace_range(start..=end, "");
139 }
140 }
141 let canonical = display.split_whitespace().collect::<Vec<_>>().join(" ");
142 (!canonical.is_empty()).then_some((canonical, aliases))
143}
144
145fn split_legacy_people(value: &str) -> Vec<String> {
149 value
150 .replace(" & ", ",")
151 .split([',', ';'])
152 .flat_map(|part| part.split(" and "))
153 .map(str::trim)
154 .filter(|part| !part.is_empty())
155 .map(str::to_string)
156 .collect()
157}
158
159fn is_placeholder_value(value: &str) -> bool {
164 let value = value.trim();
165 value.is_empty()
166 || ["none", "null", "n/a", "unknown"]
167 .iter()
168 .any(|marker| value.eq_ignore_ascii_case(marker))
169}
170
171fn confidence(source: &str, direct: bool) -> f32 {
172 if direct {
173 1.0
174 } else if matches!(
175 source,
176 "legacy" | "consolidation" | "inferred" | "task_learning"
177 ) {
178 0.6
179 } else {
180 0.8
181 }
182}
183
184fn low_authority(source: &str) -> bool {
185 matches!(
186 source,
187 "legacy" | "consolidation" | "inferred" | "progressive" | "task_learning"
188 )
189}
190
191fn normalized_fact(predicate: &str, value: &str) -> anyhow::Result<(String, &'static str)> {
192 if predicate == "birth_date" {
193 Ok((
194 date_value(value).ok_or_else(|| anyhow::anyhow!("unsupported date: {value}"))?,
195 "date",
196 ))
197 } else {
198 Ok((words(value), "text"))
199 }
200}
201
202async fn retract(
205 tx: &mut Transaction<'_, Sqlite>,
206 table: &str,
207 record_type: &str,
208 ids: &[i64],
209 source: &str,
210) -> anyhow::Result<u64> {
211 let now = Utc::now().to_rfc3339();
212 let mut retracted = 0;
213 for &id in ids {
214 let entity_column = match table {
215 "memory_entity_facts" => "subject_entity_id",
216 "memory_aliases" => "entity_id",
217 _ => "source_entity_id",
218 };
219 let sql = format!(
220 "UPDATE {table} SET status = 'retracted', valid_to = ?, updated_at = ?
221 WHERE id = ? AND status IN ('active', 'disputed') AND valid_to IS NULL
222 RETURNING {entity_column}"
223 );
224 let Some(entity_id) = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(&*sql))
225 .bind(&now)
226 .bind(&now)
227 .bind(id)
228 .fetch_optional(&mut **tx)
229 .await?
230 else {
231 continue;
232 };
233 retracted += 1;
234 audit(
235 tx,
236 "retract",
237 Some(entity_id),
238 record_type,
239 Some(id),
240 serde_json::json!({"status": "retracted"}),
241 source,
242 None,
243 )
244 .await?;
245 }
246 Ok(retracted)
247}
248
249#[allow(clippy::too_many_arguments)]
250async fn audit(
251 tx: &mut Transaction<'_, Sqlite>,
252 operation: &str,
253 entity_id: Option<i64>,
254 record_type: &str,
255 record_id: Option<i64>,
256 state: serde_json::Value,
257 source: &str,
258 provenance: Option<&str>,
259) -> anyhow::Result<()> {
260 sqlx::query(
261 "INSERT INTO memory_write_audit
262 (operation, entity_id, record_type, record_id, new_state_json, source, provenance, created_at)
263 VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
264 )
265 .bind(operation)
266 .bind(entity_id)
267 .bind(record_type)
268 .bind(record_id)
269 .bind(state.to_string())
270 .bind(source)
271 .bind(provenance)
272 .bind(Utc::now().to_rfc3339())
273 .execute(&mut **tx)
274 .await?;
275 Ok(())
276}
277
278async fn review(
279 tx: &mut Transaction<'_, Sqlite>,
280 kind: &str,
281 reference: &str,
282 candidates: &[i64],
283 payload: serde_json::Value,
284 source: &str,
285) -> anyhow::Result<()> {
286 let now = Utc::now().to_rfc3339();
287 sqlx::query(
288 "INSERT OR IGNORE INTO memory_resolution_reviews
289 (review_kind, normalized_reference, candidate_entity_ids_json, payload_json,
290 source, status, created_at, updated_at)
291 VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)",
292 )
293 .bind(kind)
294 .bind(reference)
295 .bind(serde_json::to_string(candidates)?)
296 .bind(payload.to_string())
297 .bind(source)
298 .bind(&now)
299 .bind(&now)
300 .execute(&mut **tx)
301 .await?;
302 Ok(())
303}
304
305async fn owner_entity(
306 tx: &mut Transaction<'_, Sqlite>,
307 candidate: &PersonalEntityCandidate,
308 source: &str,
309 privacy: &str,
310 channel: Option<&str>,
311 result: &mut PersonalMemoryWriteResult,
312) -> anyhow::Result<i64> {
313 let existing = sqlx::query(
314 "SELECT id, canonical_name FROM memory_entities
315 WHERE is_owner = 1 AND status = 'active' LIMIT 1",
316 )
317 .fetch_optional(&mut **tx)
318 .await?;
319 let id = if let Some(row) = existing {
320 row.get("id")
321 } else if let Some(id) = sqlx::query_scalar::<_, i64>(
322 "SELECT id FROM memory_entities
323 WHERE entity_type = 'person' AND canonical_name = 'owner'
324 AND status = 'active' LIMIT 1",
325 )
326 .fetch_optional(&mut **tx)
327 .await?
328 {
329 sqlx::query(
330 "UPDATE memory_entities SET is_owner = 1, privacy = ?,
331 channel_id = COALESCE(channel_id, ?), updated_at = ? WHERE id = ?",
332 )
333 .bind(privacy)
334 .bind(channel)
335 .bind(Utc::now().to_rfc3339())
336 .bind(id)
337 .execute(&mut **tx)
338 .await?;
339 id
340 } else {
341 let now = Utc::now().to_rfc3339();
342 let id = sqlx::query(
343 "INSERT INTO memory_entities
344 (entity_type, canonical_name, display_name, aliases_json, channel_id, privacy,
345 status, is_owner, created_at, updated_at)
346 VALUES ('person', 'owner', 'Owner', '[]', ?, ?, 'active', 1, ?, ?)",
347 )
348 .bind(channel)
349 .bind(privacy)
350 .bind(&now)
351 .bind(&now)
352 .execute(&mut **tx)
353 .await?
354 .last_insert_rowid();
355 result.created_entities += 1;
356 audit(
357 tx,
358 "create",
359 Some(id),
360 "entity",
361 Some(id),
362 serde_json::json!({"entity_type": "person", "canonical_name": "owner"}),
363 source,
364 None,
365 )
366 .await?;
367 id
368 };
369
370 let display = candidate.canonical_name.trim();
371 let canonical = words(display);
372 if candidate.canonical_name_confirmed && !canonical.is_empty() && canonical != "owner" {
373 let current: String =
374 sqlx::query_scalar("SELECT canonical_name FROM memory_entities WHERE id = ?")
375 .bind(id)
376 .fetch_one(&mut **tx)
377 .await?;
378 if current != canonical {
379 let collision: Option<i64> = sqlx::query_scalar(
380 "SELECT id FROM memory_entities
381 WHERE entity_type = 'person' AND canonical_name = ? AND id != ?
382 AND status = 'active' LIMIT 1",
383 )
384 .bind(&canonical)
385 .bind(id)
386 .fetch_optional(&mut **tx)
387 .await?;
388 if let Some(collision_id) = collision {
389 review(
390 tx,
391 "owner_name_collision",
392 &canonical,
393 &[id, collision_id],
394 serde_json::json!({}),
395 source,
396 )
397 .await?;
398 result
399 .unresolved
400 .push("confirmed owner name matches another entity".to_string());
401 } else {
402 sqlx::query(
403 "UPDATE memory_entities SET canonical_name = ?, display_name = ?,
404 updated_at = ? WHERE id = ?",
405 )
406 .bind(&canonical)
407 .bind(display)
408 .bind(Utc::now().to_rfc3339())
409 .bind(id)
410 .execute(&mut **tx)
411 .await?;
412 result.updated_entities += 1;
413 audit(
414 tx,
415 "update",
416 Some(id),
417 "entity",
418 Some(id),
419 serde_json::json!({"canonical_name": canonical}),
420 source,
421 None,
422 )
423 .await?;
424 }
425 }
426 }
427 Ok(id)
428}
429
430async fn resolve_entity(
431 tx: &mut Transaction<'_, Sqlite>,
432 candidate: &PersonalEntityCandidate,
433 source: &str,
434 privacy: &str,
435 channel: Option<&str>,
436 result: &mut PersonalMemoryWriteResult,
437) -> anyhow::Result<Option<i64>> {
438 if candidate.local_id.eq_ignore_ascii_case("owner") {
439 return owner_entity(tx, candidate, source, privacy, channel, result)
440 .await
441 .map(Some);
442 }
443 let kind = entity_type(&candidate.entity_type);
444 let display = candidate.canonical_name.trim();
445 let canonical = words(display);
446 if canonical.is_empty() {
447 result
448 .unresolved
449 .push(format!("entity {} has no usable name", candidate.local_id));
450 return Ok(None);
451 }
452 let exact = sqlx::query(
453 "SELECT id, status, merged_into_entity_id FROM memory_entities
454 WHERE entity_type = ? AND canonical_name = ? LIMIT 1",
455 )
456 .bind(&kind)
457 .bind(&canonical)
458 .fetch_optional(&mut **tx)
459 .await?;
460 if let Some(row) = exact {
461 let id: i64 = row.get("id");
462 let status: String = row.get("status");
463 if status == "active" {
464 return Ok(Some(id));
465 }
466 if status == "merged"
467 && let Some(target_id) = row.get::<Option<i64>, _>("merged_into_entity_id")
468 {
469 let target_is_active: bool = sqlx::query_scalar(
470 "SELECT EXISTS(
471 SELECT 1 FROM memory_entities WHERE id = ? AND status = 'active'
472 )",
473 )
474 .bind(target_id)
475 .fetch_one(&mut **tx)
476 .await?;
477 if target_is_active {
478 return Ok(Some(target_id));
479 }
480 }
481 review(
482 tx,
483 "inactive_entity_reference",
484 &canonical,
485 &[id],
486 serde_json::json!({"local_id": candidate.local_id, "status": status}),
487 source,
488 )
489 .await?;
490 result
491 .unresolved
492 .push(format!("entity '{display}' exists but is not active"));
493 return Ok(None);
494 }
495 if candidate.is_reference {
496 let aliases: Vec<i64> = sqlx::query_scalar(
497 "SELECT DISTINCT a.entity_id FROM memory_aliases a
498 JOIN memory_entities e ON e.id = a.entity_id
499 WHERE a.normalized_value = ? AND a.status = 'active'
500 AND e.entity_type = ? AND e.status = 'active'",
501 )
502 .bind(&canonical)
503 .bind(&kind)
504 .fetch_all(&mut **tx)
505 .await?;
506 if aliases.len() == 1 {
507 return Ok(aliases.first().copied());
508 }
509 let kind_review = if aliases.is_empty() {
510 "unresolved_reference"
511 } else {
512 "ambiguous_alias"
513 };
514 review(
515 tx,
516 kind_review,
517 &canonical,
518 &aliases,
519 serde_json::json!({"local_id": candidate.local_id}),
520 source,
521 )
522 .await?;
523 result
524 .unresolved
525 .push(format!("unresolved entity reference '{display}'"));
526 return Ok(None);
527 }
528 let now = Utc::now().to_rfc3339();
529 let id = sqlx::query(
530 "INSERT INTO memory_entities
531 (entity_type, canonical_name, display_name, aliases_json, channel_id, privacy,
532 status, is_owner, created_at, updated_at)
533 VALUES (?, ?, ?, '[]', ?, ?, 'active', 0, ?, ?)",
534 )
535 .bind(&kind)
536 .bind(&canonical)
537 .bind(display)
538 .bind(channel)
539 .bind(privacy)
540 .bind(&now)
541 .bind(&now)
542 .execute(&mut **tx)
543 .await?
544 .last_insert_rowid();
545 result.created_entities += 1;
546 audit(
547 tx,
548 "create",
549 Some(id),
550 "entity",
551 Some(id),
552 serde_json::json!({"entity_type": kind, "canonical_name": canonical}),
553 source,
554 None,
555 )
556 .await?;
557 Ok(Some(id))
558}
559
560#[allow(clippy::too_many_arguments)]
561async fn write_alias(
562 tx: &mut Transaction<'_, Sqlite>,
563 entity_id: i64,
564 candidate: &PersonalAliasCandidate,
565 source: &str,
566 provenance: Option<&str>,
567 confidence: f32,
568 direct: bool,
569 privacy: &str,
570 channel: Option<&str>,
571 result: &mut PersonalMemoryWriteResult,
572) -> anyhow::Result<()> {
573 let kind = alias_type(&candidate.alias_type);
574 let normalized = alias_value(&candidate.value, &kind);
575 if normalized.is_empty() {
576 return Ok(());
577 }
578 let now = Utc::now().to_rfc3339();
579 if let Some(id) = sqlx::query_scalar::<_, i64>(
580 "SELECT id FROM memory_aliases
581 WHERE entity_id = ? AND alias_type = ? AND normalized_value = ?",
582 )
583 .bind(entity_id)
584 .bind(&kind)
585 .bind(&normalized)
586 .fetch_optional(&mut **tx)
587 .await?
588 {
589 sqlx::query(
590 "UPDATE memory_aliases SET status = 'active', value = ?,
591 confidence = MAX(confidence, ?), source = ?, provenance = COALESCE(?, provenance),
592 last_confirmed_at = CASE WHEN ? THEN ? ELSE last_confirmed_at END,
593 confirmed_at = CASE WHEN ? THEN COALESCE(confirmed_at, ?) ELSE confirmed_at END,
594 valid_to = NULL, updated_at = ? WHERE id = ?",
595 )
596 .bind(candidate.value.trim())
597 .bind(confidence)
598 .bind(source)
599 .bind(provenance)
600 .bind(direct)
601 .bind(&now)
602 .bind(direct)
603 .bind(&now)
604 .bind(&now)
605 .bind(id)
606 .execute(&mut **tx)
607 .await?;
608 result.confirmed_aliases += 1;
609 return Ok(());
610 }
611 let id = sqlx::query(
612 "INSERT INTO memory_aliases
613 (entity_id, alias_type, value, normalized_value, status, source, provenance,
614 confidence, channel_id, privacy, asserted_at, confirmed_at, last_confirmed_at,
615 created_at, updated_at)
616 VALUES (?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?,
617 CASE WHEN ? THEN ? END, CASE WHEN ? THEN ? END, ?, ?)",
618 )
619 .bind(entity_id)
620 .bind(&kind)
621 .bind(candidate.value.trim())
622 .bind(&normalized)
623 .bind(source)
624 .bind(provenance)
625 .bind(confidence)
626 .bind(channel)
627 .bind(privacy)
628 .bind(&now)
629 .bind(direct)
630 .bind(&now)
631 .bind(direct)
632 .bind(&now)
633 .bind(&now)
634 .bind(&now)
635 .execute(&mut **tx)
636 .await?
637 .last_insert_rowid();
638 result.created_aliases += 1;
639 audit(
640 tx,
641 "create",
642 Some(entity_id),
643 "alias",
644 Some(id),
645 serde_json::json!({"alias_type": kind, "normalized_value": normalized}),
646 source,
647 provenance,
648 )
649 .await
650}
651
652#[allow(clippy::too_many_arguments)]
653async fn write_fact(
654 tx: &mut Transaction<'_, Sqlite>,
655 entity_id: i64,
656 candidate: &PersonalFactCandidate,
657 source: &str,
658 provenance: Option<&str>,
659 confidence: f32,
660 direct: bool,
661 correction: bool,
662 privacy: &str,
663 channel: Option<&str>,
664 result: &mut PersonalMemoryWriteResult,
665) -> anyhow::Result<()> {
666 let pred = predicate(&candidate.predicate);
667 if candidate.retract {
668 if !direct || low_authority(source) {
671 return Ok(());
672 }
673 let ids: Vec<i64> = sqlx::query_scalar(
674 "SELECT id FROM memory_entity_facts
675 WHERE subject_entity_id = ? AND predicate = ?
676 AND status IN ('active', 'disputed') AND valid_to IS NULL",
677 )
678 .bind(entity_id)
679 .bind(&pred)
680 .fetch_all(&mut **tx)
681 .await?;
682 let retracted = retract(tx, "memory_entity_facts", "fact", &ids, source).await?;
683 result.superseded_facts += retracted as usize;
684 return Ok(());
685 }
686 if candidate.value.trim().is_empty()
689 || ((!direct || low_authority(source)) && is_placeholder_value(&candidate.value))
690 {
691 return Ok(());
692 }
693 let (normalized, value_type) = normalized_fact(&pred, &candidate.value)?;
694 let display = candidate
695 .display_value
696 .as_deref()
697 .unwrap_or(candidate.value.trim());
698 let now = Utc::now().to_rfc3339();
699 if let Some(id) = sqlx::query_scalar::<_, i64>(
700 "SELECT id FROM memory_entity_facts
701 WHERE subject_entity_id = ? AND predicate = ? AND normalized_value = ?
702 AND status = 'active' AND valid_to IS NULL LIMIT 1",
703 )
704 .bind(entity_id)
705 .bind(&pred)
706 .bind(&normalized)
707 .fetch_optional(&mut **tx)
708 .await?
709 {
710 sqlx::query(
711 "UPDATE memory_entity_facts SET display_value = ?, source = ?,
712 confidence = MAX(confidence, ?), provenance = COALESCE(?, provenance),
713 last_confirmed_at = CASE WHEN ? THEN ? ELSE last_confirmed_at END,
714 confirmed_at = CASE WHEN ? THEN COALESCE(confirmed_at, ?) ELSE confirmed_at END,
715 updated_at = ? WHERE id = ?",
716 )
717 .bind(display)
718 .bind(source)
719 .bind(confidence)
720 .bind(provenance)
721 .bind(direct)
722 .bind(&now)
723 .bind(direct)
724 .bind(&now)
725 .bind(&now)
726 .bind(id)
727 .execute(&mut **tx)
728 .await?;
729 result.confirmed_facts += 1;
730 return Ok(());
731 }
732 let active = sqlx::query(
733 "SELECT id, normalized_value, source, confidence FROM memory_entity_facts
734 WHERE subject_entity_id = ? AND predicate = ? AND status = 'active'
735 AND valid_to IS NULL ORDER BY confidence DESC, updated_at DESC LIMIT 1",
736 )
737 .bind(entity_id)
738 .bind(&pred)
739 .fetch_optional(&mut **tx)
740 .await?;
741 let mut supersedes = None;
742 if let Some(row) = active {
743 let old_id: i64 = row.get("id");
744 let old_source: String = row.get("source");
745 let old_confidence = row.get::<f64, _>("confidence") as f32;
746 let owner_restates = direct && !low_authority(source);
751 if direct
752 && (owner_restates || correction || old_confidence < 0.9 || low_authority(&old_source))
753 {
754 sqlx::query(
755 "UPDATE memory_entity_facts SET status = 'superseded', valid_to = ?,
756 updated_at = ? WHERE id = ?",
757 )
758 .bind(&now)
759 .bind(&now)
760 .bind(old_id)
761 .execute(&mut **tx)
762 .await?;
763 result.superseded_facts += 1;
764 supersedes = Some(old_id);
765 audit(
766 tx,
767 "supersede",
768 Some(entity_id),
769 "fact",
770 Some(old_id),
771 serde_json::json!({"replacement_value": normalized}),
772 source,
773 provenance,
774 )
775 .await?;
776 } else {
777 let disputed_id = sqlx::query(
778 "INSERT INTO memory_entity_facts
779 (subject_entity_id, predicate, value_type, value, normalized_value,
780 display_value, status, source, provenance, confidence, channel_id,
781 privacy, asserted_at, confirmed_at, last_confirmed_at, valid_from,
782 valid_to, created_at, updated_at)
783 VALUES (?, ?, ?, ?, ?, ?, 'disputed', ?, ?, ?, ?, ?, ?,
784 CASE WHEN ? THEN ? END, CASE WHEN ? THEN ? END, ?, ?, ?, ?)",
785 )
786 .bind(entity_id)
787 .bind(&pred)
788 .bind(value_type)
789 .bind(&normalized)
790 .bind(&normalized)
791 .bind(display)
792 .bind(source)
793 .bind(provenance)
794 .bind(confidence)
795 .bind(channel)
796 .bind(privacy)
797 .bind(&now)
798 .bind(direct)
799 .bind(&now)
800 .bind(direct)
801 .bind(&now)
802 .bind(period(&candidate.valid_from))
803 .bind(period(&candidate.valid_to))
804 .bind(&now)
805 .bind(&now)
806 .execute(&mut **tx)
807 .await?
808 .last_insert_rowid();
809 review(
810 tx,
811 "conflicting_fact",
812 &format!("{entity_id}:{pred}"),
813 &[entity_id],
814 serde_json::json!({"active_fact_id": old_id, "disputed_fact_id": disputed_id}),
815 source,
816 )
817 .await?;
818 result.disputed_facts += 1;
819 result
820 .unresolved
821 .push(format!("conflicting confirmed value for {pred}"));
822 return Ok(());
823 }
824 }
825 let id = sqlx::query(
826 "INSERT INTO memory_entity_facts
827 (subject_entity_id, predicate, value_type, value, normalized_value,
828 display_value, status, source, provenance, confidence, channel_id,
829 privacy, asserted_at, confirmed_at, last_confirmed_at, valid_from,
830 valid_to, supersedes_fact_id, created_at, updated_at)
831 VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?,
832 CASE WHEN ? THEN ? END, CASE WHEN ? THEN ? END, ?, ?, ?, ?, ?)",
833 )
834 .bind(entity_id)
835 .bind(&pred)
836 .bind(value_type)
837 .bind(&normalized)
838 .bind(&normalized)
839 .bind(display)
840 .bind(source)
841 .bind(provenance)
842 .bind(confidence)
843 .bind(channel)
844 .bind(privacy)
845 .bind(&now)
846 .bind(direct)
847 .bind(&now)
848 .bind(direct)
849 .bind(&now)
850 .bind(period(&candidate.valid_from))
851 .bind(period(&candidate.valid_to))
852 .bind(supersedes)
853 .bind(&now)
854 .bind(&now)
855 .execute(&mut **tx)
856 .await?
857 .last_insert_rowid();
858 result.created_facts += 1;
859 audit(
860 tx,
861 "create",
862 Some(entity_id),
863 "fact",
864 Some(id),
865 serde_json::json!({"predicate": pred, "normalized_value": normalized}),
866 source,
867 provenance,
868 )
869 .await
870}
871
872#[allow(clippy::too_many_arguments)]
873async fn one_edge(
874 tx: &mut Transaction<'_, Sqlite>,
875 from: i64,
876 rel: &str,
877 to: i64,
878 source: &str,
879 provenance: Option<&str>,
880 confidence: f32,
881 direct: bool,
882 privacy: &str,
883 channel: Option<&str>,
884 valid_from: Option<&str>,
885 valid_to: Option<&str>,
886 result: &mut PersonalMemoryWriteResult,
887) -> anyhow::Result<i64> {
888 let now = Utc::now().to_rfc3339();
889 if let Some(id) = sqlx::query_scalar::<_, i64>(
890 "SELECT id FROM memory_relationships
891 WHERE source_entity_id = ? AND relationship_type = ? AND target_entity_id = ?
892 AND status = 'active' AND valid_to IS NULL LIMIT 1",
893 )
894 .bind(from)
895 .bind(rel)
896 .bind(to)
897 .fetch_optional(&mut **tx)
898 .await?
899 {
900 sqlx::query(
901 "UPDATE memory_relationships SET source = ?, confidence = MAX(confidence, ?),
902 provenance = COALESCE(?, provenance),
903 last_confirmed_at = CASE WHEN ? THEN ? ELSE last_confirmed_at END,
904 confirmed_at = CASE WHEN ? THEN COALESCE(confirmed_at, ?) ELSE confirmed_at END,
905 updated_at = ? WHERE id = ?",
906 )
907 .bind(source)
908 .bind(confidence)
909 .bind(provenance)
910 .bind(direct)
911 .bind(&now)
912 .bind(direct)
913 .bind(&now)
914 .bind(&now)
915 .bind(id)
916 .execute(&mut **tx)
917 .await?;
918 result.confirmed_relationships += 1;
919 return Ok(id);
920 }
921 let id = sqlx::query(
922 "INSERT INTO memory_relationships
923 (source_entity_id, relationship_type, target_entity_id, status, source,
924 provenance, confidence, channel_id, privacy, asserted_at, confirmed_at,
925 last_confirmed_at, valid_from, valid_to, created_at, updated_at)
926 VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?,
927 CASE WHEN ? THEN ? END, CASE WHEN ? THEN ? END, ?, ?, ?, ?)",
928 )
929 .bind(from)
930 .bind(rel)
931 .bind(to)
932 .bind(source)
933 .bind(provenance)
934 .bind(confidence)
935 .bind(channel)
936 .bind(privacy)
937 .bind(&now)
938 .bind(direct)
939 .bind(&now)
940 .bind(direct)
941 .bind(&now)
942 .bind(valid_from)
943 .bind(valid_to)
944 .bind(&now)
945 .bind(&now)
946 .execute(&mut **tx)
947 .await?
948 .last_insert_rowid();
949 result.created_relationships += 1;
950 audit(
951 tx,
952 "create",
953 Some(from),
954 "relationship",
955 Some(id),
956 serde_json::json!({"relationship_type": rel, "target_entity_id": to}),
957 source,
958 provenance,
959 )
960 .await?;
961 Ok(id)
962}
963
964#[allow(clippy::too_many_arguments)]
965async fn write_edge(
966 tx: &mut Transaction<'_, Sqlite>,
967 from: i64,
968 to: i64,
969 candidate: &PersonalRelationshipCandidate,
970 source: &str,
971 provenance: Option<&str>,
972 confidence: f32,
973 direct: bool,
974 privacy: &str,
975 channel: Option<&str>,
976 result: &mut PersonalMemoryWriteResult,
977) -> anyhow::Result<()> {
978 if from == to {
979 return Ok(());
980 }
981 let rel = relation(&candidate.relationship_type);
982 let first = one_edge(
983 tx,
984 from,
985 &rel,
986 to,
987 source,
988 provenance,
989 confidence,
990 direct,
991 privacy,
992 channel,
993 period(&candidate.valid_from),
994 period(&candidate.valid_to),
995 result,
996 )
997 .await?;
998 if let Some(back_relation) = inverse(&rel) {
999 let second = one_edge(
1000 tx,
1001 to,
1002 back_relation,
1003 from,
1004 source,
1005 provenance,
1006 confidence,
1007 direct,
1008 privacy,
1009 channel,
1010 period(&candidate.valid_from),
1011 period(&candidate.valid_to),
1012 result,
1013 )
1014 .await?;
1015 sqlx::query(
1016 "UPDATE memory_relationships SET inverse_relationship_id =
1017 CASE WHEN id = ? THEN ? ELSE ? END WHERE id IN (?, ?)",
1018 )
1019 .bind(first)
1020 .bind(second)
1021 .bind(first)
1022 .bind(first)
1023 .bind(second)
1024 .execute(&mut **tx)
1025 .await?;
1026 }
1027 Ok(())
1028}
1029
1030impl SqliteMemory {
1031 pub async fn reconcile_structured_personal_memory(
1032 &self,
1033 write: &PersonalMemoryWrite,
1034 source: &str,
1035 provenance: Option<&str>,
1036 channel: Option<&str>,
1037 privacy: FactPrivacy,
1038 ) -> anyhow::Result<PersonalMemoryWriteResult> {
1039 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1040 let mut result = PersonalMemoryWriteResult::default();
1041 let confidence = confidence(source, write.direct_user_statement);
1042 let privacy = privacy.to_string();
1043 let mut entities = HashMap::new();
1044 for candidate in &write.entities {
1045 if let Some(id) =
1046 resolve_entity(&mut tx, candidate, source, &privacy, channel, &mut result).await?
1047 {
1048 entities.insert(candidate.local_id.clone(), id);
1049 }
1050 }
1051 for candidate in &write.aliases {
1052 if let Some(&id) = entities.get(&candidate.entity_local_id) {
1053 write_alias(
1054 &mut tx,
1055 id,
1056 candidate,
1057 source,
1058 provenance,
1059 confidence,
1060 write.direct_user_statement,
1061 &privacy,
1062 channel,
1063 &mut result,
1064 )
1065 .await?;
1066 } else {
1067 result.unresolved.push(format!(
1068 "alias '{}' has no resolved entity",
1069 candidate.value
1070 ));
1071 }
1072 }
1073 for candidate in &write.facts {
1074 if let Some(&id) = entities.get(&candidate.subject_local_id) {
1075 write_fact(
1076 &mut tx,
1077 id,
1078 candidate,
1079 source,
1080 provenance,
1081 confidence,
1082 write.direct_user_statement,
1083 write.correction,
1084 &privacy,
1085 channel,
1086 &mut result,
1087 )
1088 .await?;
1089 } else {
1090 result.unresolved.push(format!(
1091 "fact '{}' has no resolved entity",
1092 candidate.predicate
1093 ));
1094 }
1095 }
1096 for candidate in &write.relationships {
1097 if let (Some(&from), Some(&to)) = (
1098 entities.get(&candidate.source_local_id),
1099 entities.get(&candidate.target_local_id),
1100 ) {
1101 write_edge(
1102 &mut tx,
1103 from,
1104 to,
1105 candidate,
1106 source,
1107 provenance,
1108 confidence,
1109 write.direct_user_statement,
1110 &privacy,
1111 channel,
1112 &mut result,
1113 )
1114 .await?;
1115 } else {
1116 result.unresolved.push(format!(
1117 "relationship '{}' has an unresolved endpoint",
1118 candidate.relationship_type
1119 ));
1120 }
1121 }
1122 tx.commit().await?;
1123 Ok(result)
1124 }
1125
1126 pub async fn canonical_personal_facts(&self) -> anyhow::Result<Vec<Fact>> {
1127 let rows = sqlx::query(
1128 "SELECT f.id, f.predicate, f.display_value, f.value, f.source, f.asserted_at,
1129 f.updated_at, f.channel_id, f.privacy, e.display_name, e.is_owner
1130 FROM memory_entity_facts f
1131 JOIN memory_entities e ON e.id = f.subject_entity_id
1132 WHERE f.status = 'active' AND f.valid_to IS NULL AND e.status = 'active'
1133 ORDER BY f.updated_at DESC",
1134 )
1135 .fetch_all(&self.pool)
1136 .await?;
1137 let mut output = Vec::new();
1138 for row in rows {
1139 let asserted = crate::types::parse_ts(&row.get::<String, _>("asserted_at"))
1140 .ok_or_else(|| anyhow::anyhow!("unreadable asserted_at"))?;
1141 let updated = crate::types::parse_ts(&row.get::<String, _>("updated_at"))
1142 .ok_or_else(|| anyhow::anyhow!("unreadable updated_at"))?;
1143 let owner = row.get::<i64, _>("is_owner") != 0;
1144 let name: String = row.get("display_name");
1145 let pred: String = row.get("predicate");
1146 output.push(Fact {
1147 id: -1_000_000_000 - row.get::<i64, _>("id"),
1148 category: if owner { "user" } else { "people" }.to_string(),
1149 key: if owner {
1150 pred
1151 } else {
1152 format!("{name} · {pred}")
1153 },
1154 value: row
1155 .get::<Option<String>, _>("display_value")
1156 .unwrap_or_else(|| row.get("value")),
1157 source: format!("canonical:{}", row.get::<String, _>("source")),
1158 created_at: asserted,
1159 updated_at: updated,
1160 superseded_at: None,
1161 recall_count: 0,
1162 last_recalled_at: None,
1163 channel_id: row.get("channel_id"),
1164 privacy: FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
1165 first_seen_at: Some(asserted),
1166 source_excerpt: None,
1167 });
1168 }
1169 let aliases = sqlx::query(
1170 "SELECT a.id, a.alias_type, a.value, a.source, a.asserted_at, a.updated_at,
1171 a.channel_id, a.privacy, e.display_name, e.is_owner
1172 FROM memory_aliases a JOIN memory_entities e ON e.id = a.entity_id
1173 WHERE a.status = 'active' AND a.valid_to IS NULL AND e.status = 'active'",
1174 )
1175 .fetch_all(&self.pool)
1176 .await?;
1177 for row in aliases {
1178 let asserted = crate::types::parse_ts(&row.get::<String, _>("asserted_at"))
1179 .ok_or_else(|| anyhow::anyhow!("unreadable asserted_at"))?;
1180 let updated = crate::types::parse_ts(&row.get::<String, _>("updated_at"))
1181 .ok_or_else(|| anyhow::anyhow!("unreadable updated_at"))?;
1182 let owner = row.get::<i64, _>("is_owner") != 0;
1183 let name: String = row.get("display_name");
1184 let kind: String = row.get("alias_type");
1185 output.push(Fact {
1186 id: -2_000_000_000 - row.get::<i64, _>("id"),
1187 category: if owner { "user" } else { "people" }.to_string(),
1188 key: if owner {
1189 kind
1190 } else {
1191 format!("{name} · {kind}")
1192 },
1193 value: row.get("value"),
1194 source: format!("canonical:{}", row.get::<String, _>("source")),
1195 created_at: asserted,
1196 updated_at: updated,
1197 superseded_at: None,
1198 recall_count: 0,
1199 last_recalled_at: None,
1200 channel_id: row.get("channel_id"),
1201 privacy: FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
1202 first_seen_at: Some(asserted),
1203 source_excerpt: None,
1204 });
1205 }
1206 let edges = sqlx::query(
1207 "SELECT r.id, r.relationship_type, r.source, r.asserted_at, r.updated_at,
1208 r.channel_id, r.privacy, a.display_name source_name, b.display_name target_name
1209 FROM memory_relationships r
1210 JOIN memory_entities a ON a.id = r.source_entity_id
1211 JOIN memory_entities b ON b.id = r.target_entity_id
1212 WHERE r.status = 'active' AND r.valid_to IS NULL
1213 AND a.status = 'active' AND b.status = 'active'",
1214 )
1215 .fetch_all(&self.pool)
1216 .await?;
1217 for row in edges {
1218 let asserted = crate::types::parse_ts(&row.get::<String, _>("asserted_at"))
1219 .ok_or_else(|| anyhow::anyhow!("unreadable asserted_at"))?;
1220 let updated = crate::types::parse_ts(&row.get::<String, _>("updated_at"))
1221 .ok_or_else(|| anyhow::anyhow!("unreadable updated_at"))?;
1222 let rel: String = row.get("relationship_type");
1223 output.push(Fact {
1224 id: -3_000_000_000 - row.get::<i64, _>("id"),
1225 category: "relationships".to_string(),
1226 key: rel.clone(),
1227 value: format!(
1228 "{} {} {}",
1229 row.get::<String, _>("source_name"),
1230 rel,
1231 row.get::<String, _>("target_name")
1232 ),
1233 source: format!("canonical:{}", row.get::<String, _>("source")),
1234 created_at: asserted,
1235 updated_at: updated,
1236 superseded_at: None,
1237 recall_count: 0,
1238 last_recalled_at: None,
1239 channel_id: row.get("channel_id"),
1240 privacy: FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
1241 first_seen_at: Some(asserted),
1242 source_excerpt: None,
1243 });
1244 }
1245 Ok(output)
1246 }
1247
1248 pub async fn retract_canonical_projection(
1253 &self,
1254 projected_id: i64,
1255 source: &str,
1256 ) -> anyhow::Result<bool> {
1257 let (table, record_type, id) = match projected_id {
1258 id if id <= -3_000_000_000 => {
1259 ("memory_relationships", "relationship", -3_000_000_000 - id)
1260 }
1261 id if id <= -2_000_000_000 => ("memory_aliases", "alias", -2_000_000_000 - id),
1262 id if id <= -1_000_000_000 => ("memory_entity_facts", "fact", -1_000_000_000 - id),
1263 _ => return Ok(false),
1264 };
1265 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1266 let mut ids = vec![id];
1267 if record_type == "relationship" {
1268 let inverse: Option<i64> = sqlx::query_scalar(
1270 "SELECT inverse_relationship_id FROM memory_relationships WHERE id = ?",
1271 )
1272 .bind(id)
1273 .fetch_optional(&mut *tx)
1274 .await?
1275 .flatten();
1276 ids.extend(inverse);
1277 }
1278 let retracted = retract(&mut tx, table, record_type, &ids, source).await?;
1279 tx.commit().await?;
1280 Ok(retracted > 0)
1281 }
1282
1283 pub async fn retract_owner_profile_key(&self, key: &str, source: &str) -> anyhow::Result<bool> {
1288 let pred = predicate(key);
1289 let kind = match token(key).as_str() {
1290 "name" => "legal_name_variant".to_string(),
1291 "username" | "handle" | "online_handle" | "online_nickname" => {
1292 "online_handle".to_string()
1293 }
1294 other => alias_type(other),
1295 };
1296 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1297 let facts: Vec<i64> = sqlx::query_scalar(
1298 "SELECT f.id FROM memory_entity_facts f
1299 JOIN memory_entities e ON e.id = f.subject_entity_id
1300 WHERE e.is_owner = 1 AND f.predicate = ?
1301 AND f.status IN ('active', 'disputed') AND f.valid_to IS NULL",
1302 )
1303 .bind(&pred)
1304 .fetch_all(&mut *tx)
1305 .await?;
1306 let aliases: Vec<i64> = sqlx::query_scalar(
1307 "SELECT a.id FROM memory_aliases a
1308 JOIN memory_entities e ON e.id = a.entity_id
1309 WHERE e.is_owner = 1 AND a.alias_type = ?
1310 AND a.status = 'active' AND a.valid_to IS NULL",
1311 )
1312 .bind(&kind)
1313 .fetch_all(&mut *tx)
1314 .await?;
1315 let retracted = retract(&mut tx, "memory_entity_facts", "fact", &facts, source).await?
1316 + retract(&mut tx, "memory_aliases", "alias", &aliases, source).await?;
1317 tx.commit().await?;
1318 Ok(retracted > 0)
1319 }
1320
1321 pub async fn backfill_structured_personal_memory(&self) -> anyhow::Result<usize> {
1324 let people =
1328 sqlx::query("SELECT id, name, aliases_json, relationship FROM people ORDER BY id")
1329 .fetch_all(&self.pool)
1330 .await?;
1331 for person in people {
1332 let legacy_id: i64 = person.get("id");
1333 let name: String = person.get("name");
1334 let relationship: Option<String> = person.get("relationship");
1335 let relationship_key = relationship.as_deref().map(token);
1336 let local_id = format!("legacy_person_{legacy_id}");
1337 let is_owner = relationship_key.as_deref() == Some("owner");
1338 let mut write = PersonalMemoryWrite {
1339 entities: vec![
1340 PersonalEntityCandidate {
1341 local_id: "owner".to_string(),
1342 entity_type: "person".to_string(),
1343 canonical_name: if is_owner {
1344 name.clone()
1345 } else {
1346 "Owner".to_string()
1347 },
1348 is_reference: false,
1349 canonical_name_confirmed: false,
1353 },
1354 PersonalEntityCandidate {
1355 local_id: local_id.clone(),
1356 entity_type: "person".to_string(),
1357 canonical_name: name.clone(),
1358 is_reference: false,
1359 canonical_name_confirmed: true,
1360 },
1361 ],
1362 ..Default::default()
1363 };
1364 if is_owner {
1365 write.entities.pop();
1366 } else {
1367 let aliases: Vec<String> =
1368 serde_json::from_str(&person.get::<String, _>("aliases_json"))
1369 .unwrap_or_default();
1370 write
1371 .aliases
1372 .extend(aliases.into_iter().map(|value| PersonalAliasCandidate {
1373 entity_local_id: local_id.clone(),
1374 value,
1375 alias_type: "nickname".to_string(),
1376 }));
1377 match relationship_key.as_deref() {
1378 Some("father" | "mother" | "parent") => {
1379 write.relationships.push(PersonalRelationshipCandidate {
1380 source_local_id: local_id.clone(),
1381 relationship_type: "PARENT_OF".to_string(),
1382 target_local_id: "owner".to_string(),
1383 valid_from: None,
1384 valid_to: None,
1385 });
1386 }
1387 Some("daughter" | "son" | "child") => {
1388 write.relationships.push(PersonalRelationshipCandidate {
1389 source_local_id: "owner".to_string(),
1390 relationship_type: "PARENT_OF".to_string(),
1391 target_local_id: local_id,
1392 valid_from: None,
1393 valid_to: None,
1394 });
1395 }
1396 _ => {}
1397 }
1398 }
1399 self.reconcile_structured_personal_memory(
1400 &write,
1401 "legacy",
1402 Some("legacy people table"),
1403 None,
1404 FactPrivacy::Private,
1405 )
1406 .await?;
1407 }
1408
1409 let relationship_facts = sqlx::query(
1415 "SELECT f.id, f.key, f.value, f.source, f.channel_id, f.privacy, f.source_excerpt
1416 FROM facts f
1417 WHERE f.superseded_at IS NULL
1418 AND lower(f.category) IN ('user', 'personal', 'profile', 'family')
1419 AND lower(f.key) IN (
1420 'dad_name', 'father_name', 'mom_name', 'mother_name',
1421 'partner_name', 'spouse_name', 'daughter_name', 'daughter_name_2',
1422 'son_name', 'son_name_2', 'child_name', 'oldest_daughter_name',
1423 'youngest_daughter_name', 'oldest_son_name', 'youngest_son_name',
1424 'daughter_names', 'son_names', 'children_names',
1425 'has_daughter', 'has_son', 'has_children'
1426 )
1427 AND NOT EXISTS (
1428 SELECT 1 FROM memory_write_audit a
1429 WHERE a.operation = 'legacy_relationship_backfill'
1430 AND a.source_fact_id = f.id
1431 )
1432 ORDER BY f.id",
1433 )
1434 .fetch_all(&self.pool)
1435 .await?;
1436 for row in relationship_facts {
1437 let fact_id: i64 = row.get("id");
1438 let key = token(&row.get::<String, _>("key"));
1439 let value: String = row.get("value");
1440 let is_parent = matches!(
1441 key.as_str(),
1442 "dad_name" | "father_name" | "mom_name" | "mother_name"
1443 );
1444 let is_partner = matches!(key.as_str(), "partner_name" | "spouse_name");
1445 let is_plural_child = matches!(
1446 key.as_str(),
1447 "daughter_names"
1448 | "son_names"
1449 | "children_names"
1450 | "has_daughter"
1451 | "has_son"
1452 | "has_children"
1453 );
1454 let names = if is_plural_child {
1455 split_legacy_people(&value)
1456 } else {
1457 vec![value.clone()]
1458 };
1459 let direct = matches!(
1460 row.get::<String, _>("source").as_str(),
1461 "agent" | "user_stated" | "owner" | "owner-stated"
1462 );
1463 let mut wrote_any = false;
1464
1465 for (index, raw_name) in names.into_iter().enumerate() {
1466 let Some((canonical_name, aliases)) = legacy_person_name(&raw_name) else {
1467 let now = Utc::now().to_rfc3339();
1468 sqlx::query(
1469 "INSERT OR IGNORE INTO memory_resolution_reviews
1470 (review_kind, normalized_reference, candidate_entity_ids_json,
1471 payload_json, source, source_fact_id, status, created_at, updated_at)
1472 VALUES ('ambiguous_legacy_relationship', ?, '[]', ?, 'legacy', ?,
1473 'pending', ?, ?)",
1474 )
1475 .bind(words(&raw_name))
1476 .bind(serde_json::json!({"key": &key, "value": &value}).to_string())
1477 .bind(fact_id)
1478 .bind(&now)
1479 .bind(&now)
1480 .execute(&self.pool)
1481 .await?;
1482 continue;
1483 };
1484
1485 let relative_id = format!("legacy_relative_{fact_id}_{index}");
1486 let relative_is_reference = !is_parent && !is_partner;
1487 let relationship_type = if is_parent {
1488 "PARENT_OF"
1489 } else if key == "spouse_name" {
1490 "SPOUSE_OF"
1491 } else if is_partner {
1492 "PARTNER_OF"
1493 } else {
1494 "PARENT_OF"
1495 };
1496 let mut write = PersonalMemoryWrite {
1497 entities: vec![
1498 PersonalEntityCandidate {
1499 local_id: "owner".to_string(),
1500 entity_type: "person".to_string(),
1501 canonical_name: "Owner".to_string(),
1502 is_reference: true,
1503 canonical_name_confirmed: false,
1504 },
1505 PersonalEntityCandidate {
1506 local_id: relative_id.clone(),
1507 entity_type: "person".to_string(),
1508 canonical_name,
1509 is_reference: relative_is_reference,
1510 canonical_name_confirmed: is_parent || is_partner,
1511 },
1512 ],
1513 direct_user_statement: direct,
1514 ..Default::default()
1515 };
1516 write
1517 .aliases
1518 .extend(aliases.into_iter().map(|value| PersonalAliasCandidate {
1519 entity_local_id: relative_id.clone(),
1520 value,
1521 alias_type: "nickname".to_string(),
1522 }));
1523 write.relationships.push(PersonalRelationshipCandidate {
1524 source_local_id: if is_parent {
1525 relative_id.clone()
1526 } else {
1527 "owner".to_string()
1528 },
1529 relationship_type: relationship_type.to_string(),
1530 target_local_id: if is_parent {
1531 "owner".to_string()
1532 } else {
1533 relative_id
1534 },
1535 valid_from: None,
1536 valid_to: None,
1537 });
1538 let result = self
1539 .reconcile_structured_personal_memory(
1540 &write,
1541 "legacy",
1542 row.get::<Option<String>, _>("source_excerpt").as_deref(),
1543 row.get::<Option<String>, _>("channel_id").as_deref(),
1544 FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
1545 )
1546 .await?;
1547 wrote_any |= result.created_relationships > 0 || result.confirmed_relationships > 0;
1548 }
1549
1550 if wrote_any {
1551 sqlx::query(
1552 "INSERT INTO memory_write_audit
1553 (operation, record_type, record_id, source, source_fact_id, created_at)
1554 VALUES ('legacy_relationship_backfill', 'legacy_fact', ?, 'legacy', ?, ?)",
1555 )
1556 .bind(fact_id)
1557 .bind(fact_id)
1558 .bind(Utc::now().to_rfc3339())
1559 .execute(&self.pool)
1560 .await?;
1561 }
1562 }
1563
1564 let child_identity_facts = sqlx::query(
1571 "SELECT f.id, f.key, f.value, f.source, f.channel_id, f.privacy,
1572 f.source_excerpt
1573 FROM facts f
1574 WHERE f.superseded_at IS NULL
1575 AND lower(f.category) IN ('user', 'personal', 'profile', 'family')
1576 AND (
1577 lower(f.key) LIKE 'daughter_%_full_name'
1578 OR lower(f.key) LIKE 'son_%_full_name'
1579 )
1580 AND NOT EXISTS (
1581 SELECT 1 FROM memory_write_audit a
1582 WHERE a.operation = 'legacy_child_identity_backfill'
1583 AND a.source_fact_id = f.id
1584 )
1585 ORDER BY f.id",
1586 )
1587 .fetch_all(&self.pool)
1588 .await?;
1589 for row in child_identity_facts {
1590 let fact_id: i64 = row.get("id");
1591 let value: String = row.get("value");
1592 let Some((display_name, aliases)) = legacy_person_name(&value) else {
1593 continue;
1594 };
1595 if aliases.len() != 1 {
1596 continue;
1597 }
1598 let alias = aliases[0].clone();
1599 let alias_normalized = words(&alias);
1600 let candidates = sqlx::query_scalar::<_, i64>(
1601 "SELECT DISTINCT child.id
1602 FROM memory_entities owner
1603 JOIN memory_relationships rel
1604 ON rel.source_entity_id = owner.id
1605 AND rel.relationship_type = 'PARENT_OF'
1606 AND rel.status = 'active' AND rel.valid_to IS NULL
1607 JOIN memory_entities child
1608 ON child.id = rel.target_entity_id
1609 AND child.entity_type = 'person' AND child.status = 'active'
1610 WHERE owner.is_owner = 1 AND owner.status = 'active'
1611 AND (
1612 child.canonical_name = ?
1613 OR EXISTS (
1614 SELECT 1 FROM memory_aliases a
1615 WHERE a.entity_id = child.id AND a.status = 'active'
1616 AND a.valid_to IS NULL AND a.normalized_value = ?
1617 )
1618 )",
1619 )
1620 .bind(&alias_normalized)
1621 .bind(&alias_normalized)
1622 .fetch_all(&self.pool)
1623 .await?;
1624 if candidates.len() != 1 {
1625 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1626 review(
1627 &mut tx,
1628 "ambiguous_legacy_child_identity",
1629 &alias_normalized,
1630 &candidates,
1631 serde_json::json!({"legacy_fact_id": fact_id, "value": value}),
1632 "legacy",
1633 )
1634 .await?;
1635 tx.commit().await?;
1636 continue;
1637 }
1638
1639 let child_id = candidates[0];
1640 let canonical_name = words(&display_name);
1641 let collision = sqlx::query_scalar::<_, i64>(
1642 "SELECT id FROM memory_entities
1643 WHERE entity_type = 'person' AND canonical_name = ? AND status = 'active'
1644 AND id != ? LIMIT 1",
1645 )
1646 .bind(&canonical_name)
1647 .bind(child_id)
1648 .fetch_optional(&self.pool)
1649 .await?;
1650 if let Some(collision_id) = collision {
1651 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1652 review(
1653 &mut tx,
1654 "legacy_child_name_collision",
1655 &canonical_name,
1656 &[child_id, collision_id],
1657 serde_json::json!({"legacy_fact_id": fact_id, "value": value}),
1658 "legacy",
1659 )
1660 .await?;
1661 tx.commit().await?;
1662 continue;
1663 }
1664
1665 let direct = matches!(
1666 row.get::<String, _>("source").as_str(),
1667 "agent" | "user_stated" | "owner" | "owner-stated"
1668 );
1669 let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")).to_string();
1670 let channel = row.get::<Option<String>, _>("channel_id");
1671 let provenance = row.get::<Option<String>, _>("source_excerpt");
1672 let mut result = PersonalMemoryWriteResult::default();
1673 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1674 let current: String =
1675 sqlx::query_scalar("SELECT canonical_name FROM memory_entities WHERE id = ?")
1676 .bind(child_id)
1677 .fetch_one(&mut *tx)
1678 .await?;
1679 if current != canonical_name {
1680 sqlx::query(
1681 "UPDATE memory_entities SET canonical_name = ?, display_name = ?,
1682 updated_at = ? WHERE id = ?",
1683 )
1684 .bind(&canonical_name)
1685 .bind(display_name.trim())
1686 .bind(Utc::now().to_rfc3339())
1687 .bind(child_id)
1688 .execute(&mut *tx)
1689 .await?;
1690 audit(
1691 &mut tx,
1692 "update",
1693 Some(child_id),
1694 "entity",
1695 Some(child_id),
1696 serde_json::json!({
1697 "canonical_name": canonical_name,
1698 "evidence": "explicit child full name with nickname"
1699 }),
1700 "legacy",
1701 provenance.as_deref(),
1702 )
1703 .await?;
1704 }
1705 write_alias(
1706 &mut tx,
1707 child_id,
1708 &PersonalAliasCandidate {
1709 entity_local_id: "child".to_string(),
1710 value: alias,
1711 alias_type: "nickname".to_string(),
1712 },
1713 "legacy",
1714 provenance.as_deref(),
1715 confidence(&row.get::<String, _>("source"), direct),
1716 direct,
1717 &privacy,
1718 channel.as_deref(),
1719 &mut result,
1720 )
1721 .await?;
1722 sqlx::query(
1723 "INSERT INTO memory_write_audit
1724 (operation, entity_id, record_type, record_id, source, source_fact_id,
1725 provenance, created_at)
1726 VALUES ('legacy_child_identity_backfill', ?, 'legacy_fact', ?,
1727 'legacy', ?, ?, ?)",
1728 )
1729 .bind(child_id)
1730 .bind(fact_id)
1731 .bind(fact_id)
1732 .bind(provenance.as_deref())
1733 .bind(Utc::now().to_rfc3339())
1734 .execute(&mut *tx)
1735 .await?;
1736 tx.commit().await?;
1737 }
1738
1739 let child_birth_facts = sqlx::query(
1744 "SELECT f.id, f.key, f.value, f.source, f.channel_id, f.privacy,
1745 f.source_excerpt
1746 FROM facts f
1747 WHERE f.superseded_at IS NULL
1748 AND lower(f.category) IN ('user', 'personal', 'profile', 'family')
1749 AND (
1750 lower(f.key) LIKE 'daughter_%_birthday'
1751 OR lower(f.key) LIKE 'daughter_%_birth_date'
1752 OR lower(f.key) LIKE 'son_%_birthday'
1753 OR lower(f.key) LIKE 'son_%_birth_date'
1754 )
1755 AND NOT EXISTS (
1756 SELECT 1 FROM memory_write_audit a
1757 WHERE a.operation = 'legacy_child_birth_backfill'
1758 AND a.source_fact_id = f.id
1759 )
1760 ORDER BY f.id",
1761 )
1762 .fetch_all(&self.pool)
1763 .await?;
1764 for row in child_birth_facts {
1765 let fact_id: i64 = row.get("id");
1766 let key = token(&row.get::<String, _>("key"));
1767 let reference = ["daughter_", "son_"]
1768 .iter()
1769 .find_map(|prefix| key.strip_prefix(prefix))
1770 .and_then(|rest| {
1771 rest.strip_suffix("_birthday")
1772 .or_else(|| rest.strip_suffix("_birth_date"))
1773 })
1774 .map(str::to_string);
1775 let Some(reference) = reference else {
1776 continue;
1777 };
1778 if reference.is_empty()
1779 || matches!(
1780 reference.as_str(),
1781 "oldest" | "youngest" | "first" | "second"
1782 )
1783 {
1784 continue;
1785 }
1786 let value: String = row.get("value");
1787 if date_value(&value).is_none() {
1788 continue;
1789 }
1790 let candidates = sqlx::query_scalar::<_, i64>(
1791 "SELECT DISTINCT child.id
1792 FROM memory_entities owner
1793 JOIN memory_relationships rel
1794 ON rel.source_entity_id = owner.id
1795 AND rel.relationship_type = 'PARENT_OF'
1796 AND rel.status = 'active' AND rel.valid_to IS NULL
1797 JOIN memory_entities child
1798 ON child.id = rel.target_entity_id
1799 AND child.entity_type = 'person' AND child.status = 'active'
1800 WHERE owner.is_owner = 1 AND owner.status = 'active'
1801 AND (
1802 child.canonical_name = ?
1803 OR EXISTS (
1804 SELECT 1 FROM memory_aliases a
1805 WHERE a.entity_id = child.id AND a.status = 'active'
1806 AND a.valid_to IS NULL AND a.normalized_value = ?
1807 )
1808 )",
1809 )
1810 .bind(&reference)
1811 .bind(&reference)
1812 .fetch_all(&self.pool)
1813 .await?;
1814 if candidates.len() != 1 {
1815 continue;
1816 }
1817 let child_id = candidates[0];
1818 let source: String = row.get("source");
1819 let direct = matches!(
1820 source.as_str(),
1821 "agent" | "user_stated" | "owner" | "owner-stated"
1822 );
1823 let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")).to_string();
1824 let channel = row.get::<Option<String>, _>("channel_id");
1825 let provenance = row.get::<Option<String>, _>("source_excerpt");
1826 let mut result = PersonalMemoryWriteResult::default();
1827 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1828 write_fact(
1829 &mut tx,
1830 child_id,
1831 &PersonalFactCandidate {
1832 subject_local_id: "child".to_string(),
1833 predicate: "birth_date".to_string(),
1834 value,
1835 display_value: None,
1836 valid_from: None,
1837 valid_to: None,
1838 retract: false,
1839 },
1840 "legacy",
1841 provenance.as_deref(),
1842 confidence(&source, direct),
1843 direct,
1844 false,
1845 &privacy,
1846 channel.as_deref(),
1847 &mut result,
1848 )
1849 .await?;
1850 sqlx::query(
1851 "INSERT INTO memory_write_audit
1852 (operation, entity_id, record_type, record_id, source, source_fact_id,
1853 provenance, created_at)
1854 VALUES ('legacy_child_birth_backfill', ?, 'legacy_fact', ?,
1855 'legacy', ?, ?, ?)",
1856 )
1857 .bind(child_id)
1858 .bind(fact_id)
1859 .bind(fact_id)
1860 .bind(provenance.as_deref())
1861 .bind(Utc::now().to_rfc3339())
1862 .execute(&mut *tx)
1863 .await?;
1864 tx.commit().await?;
1865 }
1866
1867 let co_residence_facts = sqlx::query(
1872 "SELECT f.id, f.source, f.channel_id, f.privacy, f.source_excerpt
1873 FROM facts f
1874 WHERE f.superseded_at IS NULL
1875 AND lower(f.category) IN ('user', 'personal', 'profile', 'family')
1876 AND lower(f.key) IN (
1877 'daughters_live_with_user', 'sons_live_with_user',
1878 'children_live_with_user'
1879 )
1880 AND lower(f.value) LIKE '%live%with%'
1881 AND NOT EXISTS (
1882 SELECT 1 FROM memory_write_audit a
1883 WHERE a.operation = 'legacy_children_lives_with_backfill'
1884 AND a.source_fact_id = f.id
1885 )
1886 ORDER BY f.id",
1887 )
1888 .fetch_all(&self.pool)
1889 .await?;
1890 for row in co_residence_facts {
1891 let fact_id: i64 = row.get("id");
1892 let owner_id: i64 = sqlx::query_scalar(
1893 "SELECT id FROM memory_entities
1894 WHERE is_owner = 1 AND status = 'active' LIMIT 1",
1895 )
1896 .fetch_one(&self.pool)
1897 .await?;
1898 let child_ids = sqlx::query_scalar::<_, i64>(
1899 "SELECT target_entity_id FROM memory_relationships
1900 WHERE source_entity_id = ? AND relationship_type = 'PARENT_OF'
1901 AND status = 'active' AND valid_to IS NULL
1902 ORDER BY target_entity_id",
1903 )
1904 .bind(owner_id)
1905 .fetch_all(&self.pool)
1906 .await?;
1907 let source: String = row.get("source");
1908 let direct = matches!(
1909 source.as_str(),
1910 "agent" | "user_stated" | "owner" | "owner-stated"
1911 );
1912 let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")).to_string();
1913 let channel = row.get::<Option<String>, _>("channel_id");
1914 let provenance = row.get::<Option<String>, _>("source_excerpt");
1915 let mut result = PersonalMemoryWriteResult::default();
1916 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1917 for child_id in child_ids {
1918 write_edge(
1919 &mut tx,
1920 child_id,
1921 owner_id,
1922 &PersonalRelationshipCandidate {
1923 source_local_id: "child".to_string(),
1924 relationship_type: "LIVES_WITH".to_string(),
1925 target_local_id: "owner".to_string(),
1926 valid_from: None,
1927 valid_to: None,
1928 },
1929 "legacy",
1930 provenance.as_deref(),
1931 confidence(&source, direct),
1932 direct,
1933 &privacy,
1934 channel.as_deref(),
1935 &mut result,
1936 )
1937 .await?;
1938 }
1939 sqlx::query(
1940 "INSERT INTO memory_write_audit
1941 (operation, entity_id, record_type, record_id, source, source_fact_id,
1942 provenance, created_at)
1943 VALUES ('legacy_children_lives_with_backfill', ?, 'legacy_fact', ?,
1944 'legacy', ?, ?, ?)",
1945 )
1946 .bind(owner_id)
1947 .bind(fact_id)
1948 .bind(fact_id)
1949 .bind(provenance.as_deref())
1950 .bind(Utc::now().to_rfc3339())
1951 .execute(&mut *tx)
1952 .await?;
1953 tx.commit().await?;
1954 }
1955
1956 let merge_candidates = sqlx::query(
1964 "SELECT DISTINCT canonical.id AS canonical_id, duplicate.id AS duplicate_id,
1965 alias.normalized_value
1966 FROM memory_aliases alias
1967 JOIN memory_entities canonical ON canonical.id = alias.entity_id
1968 JOIN memory_entities duplicate
1969 ON duplicate.entity_type = canonical.entity_type
1970 AND duplicate.canonical_name = alias.normalized_value
1971 AND duplicate.id != canonical.id
1972 WHERE alias.alias_type = 'nickname' AND alias.status = 'active'
1973 AND canonical.status = 'active' AND duplicate.status = 'active'
1974 AND NOT EXISTS (
1975 SELECT 1 FROM memory_aliases duplicate_alias
1976 WHERE duplicate_alias.entity_id = duplicate.id
1977 )
1978 AND NOT EXISTS (
1979 SELECT 1 FROM memory_entity_facts duplicate_fact
1980 WHERE duplicate_fact.subject_entity_id = duplicate.id
1981 )
1982 AND EXISTS (
1983 SELECT 1 FROM memory_relationships duplicate_rel
1984 WHERE duplicate_rel.status = 'active'
1985 AND (duplicate_rel.source_entity_id = duplicate.id
1986 OR duplicate_rel.target_entity_id = duplicate.id)
1987 )
1988 AND NOT EXISTS (
1989 SELECT 1 FROM memory_relationships duplicate_rel
1990 WHERE duplicate_rel.status = 'active'
1991 AND (duplicate_rel.source_entity_id = duplicate.id
1992 OR duplicate_rel.target_entity_id = duplicate.id)
1993 AND NOT EXISTS (
1994 SELECT 1 FROM memory_relationships canonical_rel
1995 WHERE canonical_rel.status = 'active'
1996 AND canonical_rel.relationship_type =
1997 duplicate_rel.relationship_type
1998 AND (
1999 (duplicate_rel.source_entity_id = duplicate.id
2000 AND canonical_rel.source_entity_id = canonical.id
2001 AND canonical_rel.target_entity_id =
2002 duplicate_rel.target_entity_id)
2003 OR
2004 (duplicate_rel.target_entity_id = duplicate.id
2005 AND canonical_rel.target_entity_id = canonical.id
2006 AND canonical_rel.source_entity_id =
2007 duplicate_rel.source_entity_id)
2008 )
2009 )
2010 )",
2011 )
2012 .fetch_all(&self.pool)
2013 .await?;
2014 for candidate in merge_candidates {
2015 let canonical_id: i64 = candidate.get("canonical_id");
2016 let duplicate_id: i64 = candidate.get("duplicate_id");
2017 let normalized_value: String = candidate.get("normalized_value");
2018 let now = Utc::now().to_rfc3339();
2019 let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2020 sqlx::query(
2021 "UPDATE memory_relationships
2022 SET status = 'superseded', valid_to = ?, updated_at = ?
2023 WHERE status = 'active'
2024 AND (source_entity_id = ? OR target_entity_id = ?)",
2025 )
2026 .bind(&now)
2027 .bind(&now)
2028 .bind(duplicate_id)
2029 .bind(duplicate_id)
2030 .execute(&mut *tx)
2031 .await?;
2032 sqlx::query(
2033 "UPDATE memory_entities
2034 SET status = 'merged', merged_into_entity_id = ?, updated_at = ?
2035 WHERE id = ? AND status = 'active'",
2036 )
2037 .bind(canonical_id)
2038 .bind(&now)
2039 .bind(duplicate_id)
2040 .execute(&mut *tx)
2041 .await?;
2042 audit(
2043 &mut tx,
2044 "merge",
2045 Some(duplicate_id),
2046 "entity",
2047 Some(duplicate_id),
2048 serde_json::json!({
2049 "merged_into_entity_id": canonical_id,
2050 "evidence": "explicit nickname plus identical relationships",
2051 "nickname": normalized_value,
2052 }),
2053 "legacy",
2054 Some("legacy relationship backfill reconciliation"),
2055 )
2056 .await?;
2057 tx.commit().await?;
2058 }
2059
2060 let compound_parents = sqlx::query(
2063 "SELECT id, key, value FROM facts
2064 WHERE superseded_at IS NULL
2065 AND lower(key) IN ('father_name', 'mother_name', 'parent_name', 'parents')
2066 AND (lower(value) LIKE '% and %' OR value LIKE '%&%')",
2067 )
2068 .fetch_all(&self.pool)
2069 .await?;
2070 for row in compound_parents {
2071 let id: i64 = row.get("id");
2072 let now = Utc::now().to_rfc3339();
2073 sqlx::query(
2074 "INSERT OR IGNORE INTO memory_resolution_reviews
2075 (review_kind, normalized_reference, candidate_entity_ids_json, payload_json,
2076 source, source_fact_id, status, created_at, updated_at)
2077 VALUES ('compound_parent_identity', ?, '[]', ?, 'legacy', ?, 'pending', ?, ?)",
2078 )
2079 .bind(words(&row.get::<String, _>("value")))
2080 .bind(
2081 serde_json::json!({"legacy_fact_id": id, "key": row.get::<String, _>("key")})
2082 .to_string(),
2083 )
2084 .bind(id)
2085 .bind(&now)
2086 .bind(&now)
2087 .execute(&self.pool)
2088 .await?;
2089 }
2090
2091 let rows = sqlx::query(
2092 "SELECT f.id, f.key, f.value, f.source, f.channel_id, f.privacy, f.source_excerpt
2093 FROM facts f
2094 WHERE f.superseded_at IS NULL
2095 AND lower(f.category) IN ('user', 'personal', 'profile')
2096 AND lower(f.key) IN (
2097 'name', 'full_name', 'preferred_name', 'nickname', 'username',
2098 'online_nickname', 'online_handle', 'handle', 'birthday',
2099 'birth_date', 'date_of_birth', 'residence', 'current_residence',
2100 'birthplace', 'place_of_birth'
2101 )
2102 AND NOT EXISTS (
2103 SELECT 1 FROM memory_write_audit a
2104 WHERE a.operation = 'legacy_backfill' AND a.source_fact_id = f.id
2105 )
2106 ORDER BY f.id",
2107 )
2108 .fetch_all(&self.pool)
2109 .await?;
2110 let mut migrated = 0;
2111 for row in rows {
2112 let id: i64 = row.get("id");
2113 let key: String = row.get("key");
2114 let value: String = row.get("value");
2115 let normalized_key = predicate(&key);
2116 if matches!(normalized_key.as_str(), "name" | "full_name")
2119 && (value.to_lowercase().contains(" and ") || value.contains('&'))
2120 {
2121 let now = Utc::now().to_rfc3339();
2122 sqlx::query(
2123 "INSERT OR IGNORE INTO memory_resolution_reviews
2124 (review_kind, normalized_reference, candidate_entity_ids_json, payload_json,
2125 source, source_fact_id, status, created_at, updated_at)
2126 VALUES ('compound_legacy_name', ?, '[]', ?, 'legacy', ?, 'pending', ?, ?)",
2127 )
2128 .bind(words(&value))
2129 .bind(serde_json::json!({"legacy_fact_id": id}).to_string())
2130 .bind(id)
2131 .bind(&now)
2132 .bind(&now)
2133 .execute(&self.pool)
2134 .await?;
2135 continue;
2136 }
2137 let direct = matches!(
2138 row.get::<String, _>("source").as_str(),
2139 "agent" | "user_stated" | "owner" | "owner-stated"
2140 );
2141 let mut write = PersonalMemoryWrite {
2142 entities: vec![PersonalEntityCandidate {
2143 local_id: "owner".to_string(),
2144 entity_type: "person".to_string(),
2145 canonical_name: if matches!(normalized_key.as_str(), "name" | "full_name") {
2146 value.clone()
2147 } else {
2148 "Owner".to_string()
2149 },
2150 is_reference: false,
2151 canonical_name_confirmed: matches!(
2152 normalized_key.as_str(),
2153 "name" | "full_name"
2154 ),
2155 }],
2156 direct_user_statement: direct,
2157 ..Default::default()
2158 };
2159 match normalized_key.as_str() {
2160 "name" | "full_name" => write.aliases.push(PersonalAliasCandidate {
2161 entity_local_id: "owner".to_string(),
2162 value: value.clone(),
2163 alias_type: "legal_name_variant".to_string(),
2164 }),
2165 "preferred_name" | "nickname" => write.aliases.push(PersonalAliasCandidate {
2166 entity_local_id: "owner".to_string(),
2167 value: value.clone(),
2168 alias_type: normalized_key,
2169 }),
2170 "username" | "online_nickname" | "online_handle" | "handle" => {
2171 write.aliases.push(PersonalAliasCandidate {
2172 entity_local_id: "owner".to_string(),
2173 value: value.clone(),
2174 alias_type: "online_handle".to_string(),
2175 })
2176 }
2177 _ => write.facts.push(PersonalFactCandidate {
2178 subject_local_id: "owner".to_string(),
2179 predicate: normalized_key,
2180 value: value.clone(),
2181 display_value: None,
2182 valid_from: None,
2183 valid_to: None,
2184 retract: false,
2185 }),
2186 }
2187 let result = self
2188 .reconcile_structured_personal_memory(
2189 &write,
2190 "legacy",
2191 row.get::<Option<String>, _>("source_excerpt").as_deref(),
2192 row.get::<Option<String>, _>("channel_id").as_deref(),
2193 FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
2194 )
2195 .await;
2196 if result.is_ok() {
2197 sqlx::query(
2198 "INSERT INTO memory_write_audit
2199 (operation, record_type, record_id, source, source_fact_id, created_at)
2200 VALUES ('legacy_backfill', 'legacy_fact', ?, 'legacy', ?, ?)",
2201 )
2202 .bind(id)
2203 .bind(id)
2204 .bind(Utc::now().to_rfc3339())
2205 .execute(&self.pool)
2206 .await?;
2207 migrated += 1;
2208 }
2209 }
2210
2211 if let Some(row) = sqlx::query(
2218 "SELECT f.value, f.source, f.channel_id, f.privacy, f.source_excerpt
2219 FROM facts f
2220 WHERE f.superseded_at IS NULL
2221 AND lower(f.category) IN ('user', 'personal', 'profile')
2222 AND lower(f.key) = 'full_name'
2223 AND lower(f.value) NOT LIKE '% and %' AND f.value NOT LIKE '%&%'
2224 ORDER BY
2225 CASE WHEN f.source IN ('user_stated', 'owner', 'owner-stated', 'agent')
2226 THEN 0 ELSE 1 END,
2227 length(f.value) DESC, f.id DESC
2228 LIMIT 1",
2229 )
2230 .fetch_optional(&self.pool)
2231 .await?
2232 {
2233 let value: String = row.get("value");
2234 let expected = words(&value);
2235 let current: Option<String> = sqlx::query_scalar(
2236 "SELECT canonical_name FROM memory_entities
2237 WHERE is_owner = 1 AND status = 'active' LIMIT 1",
2238 )
2239 .fetch_optional(&self.pool)
2240 .await?;
2241 if current.as_deref() != Some(expected.as_str()) {
2242 let source: String = row.get("source");
2243 self.reconcile_structured_personal_memory(
2244 &PersonalMemoryWrite {
2245 entities: vec![PersonalEntityCandidate {
2246 local_id: "owner".to_string(),
2247 entity_type: "person".to_string(),
2248 canonical_name: value.clone(),
2249 is_reference: false,
2250 canonical_name_confirmed: true,
2251 }],
2252 aliases: vec![PersonalAliasCandidate {
2253 entity_local_id: "owner".to_string(),
2254 value,
2255 alias_type: "legal_name_variant".to_string(),
2256 }],
2257 direct_user_statement: matches!(
2258 source.as_str(),
2259 "user_stated" | "owner" | "owner-stated" | "agent"
2260 ),
2261 ..Default::default()
2262 },
2263 "legacy",
2264 row.get::<Option<String>, _>("source_excerpt").as_deref(),
2265 row.get::<Option<String>, _>("channel_id").as_deref(),
2266 FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy")),
2267 )
2268 .await?;
2269 }
2270 }
2271 Ok(migrated)
2272 }
2273}
2274
2275#[cfg(test)]
2276mod tests {
2277 use super::*;
2278
2279 #[test]
2280 fn dates_share_one_canonical_form() {
2281 assert_eq!(date_value("Feb 4 1988").as_deref(), Some("1988-02-04"));
2282 assert_eq!(
2283 date_value("February 4, 1988").as_deref(),
2284 Some("1988-02-04")
2285 );
2286 assert_eq!(date_value("1988-02-04").as_deref(), Some("1988-02-04"));
2287 }
2288
2289 #[test]
2290 fn handles_are_case_insensitive() {
2291 assert_eq!(alias_value("@RiveraDev", "online_handle"), "riveradev");
2292 }
2293
2294 #[test]
2295 fn inverse_family_edges_are_explicit() {
2296 assert_eq!(inverse("PARENT_OF"), Some("CHILD_OF"));
2297 assert_eq!(inverse("LIVES_WITH"), Some("LIVES_WITH"));
2298 }
2299}