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