Skip to main content

aidaemon_memory/sqlite/
people.rs

1use super::*;
2
3#[async_trait]
4impl PeopleStore for SqliteMemory {
5    async fn upsert_person(&self, person: &crate::records::Person) -> anyhow::Result<i64> {
6        let aliases_json = serde_json::to_string(&person.aliases)?;
7        let platform_ids_json = serde_json::to_string(&person.platform_ids)?;
8        let now = chrono::Utc::now().to_rfc3339();
9
10        if person.id > 0 {
11            sqlx::query(
12                "UPDATE people SET name = ?, aliases_json = ?, relationship = ?, platform_ids_json = ?, \
13                 notes = ?, communication_style = ?, language_preference = ?, updated_at = ? WHERE id = ?"
14            )
15            .bind(&person.name)
16            .bind(&aliases_json)
17            .bind(&person.relationship)
18            .bind(&platform_ids_json)
19            .bind(&person.notes)
20            .bind(&person.communication_style)
21            .bind(&person.language_preference)
22            .bind(&now)
23            .bind(person.id)
24            .execute(&self.pool)
25            .await?;
26            Ok(person.id)
27        } else {
28            // Use INSERT OR IGNORE to handle the unique index on LOWER(name).
29            // If a duplicate exists, the INSERT silently does nothing and we
30            // return the existing row's id.
31            sqlx::query(
32                "INSERT OR IGNORE INTO people (name, aliases_json, relationship, platform_ids_json, notes, \
33                 communication_style, language_preference, created_at, updated_at) \
34                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
35            )
36            .bind(&person.name)
37            .bind(&aliases_json)
38            .bind(&person.relationship)
39            .bind(&platform_ids_json)
40            .bind(&person.notes)
41            .bind(&person.communication_style)
42            .bind(&person.language_preference)
43            .bind(&now)
44            .bind(&now)
45            .execute(&self.pool)
46            .await?;
47
48            // Fetch the id — works whether we just inserted or the row already existed
49            let row = sqlx::query("SELECT id FROM people WHERE LOWER(name) = ?")
50                .bind(person.name.to_lowercase())
51                .fetch_one(&self.pool)
52                .await?;
53            Ok(row.get::<i64, _>("id"))
54        }
55    }
56
57    async fn get_person(&self, id: i64) -> anyhow::Result<Option<crate::records::Person>> {
58        let row = sqlx::query(
59            "SELECT id, name, aliases_json, relationship, platform_ids_json, notes, \
60             communication_style, language_preference, last_interaction_at, interaction_count, \
61             created_at, updated_at FROM people WHERE id = ?",
62        )
63        .bind(id)
64        .fetch_optional(&self.pool)
65        .await?;
66
67        Ok(row.map(|r| Self::row_to_person(&r)))
68    }
69
70    async fn get_person_by_platform_id(
71        &self,
72        platform_id: &str,
73    ) -> anyhow::Result<Option<crate::records::Person>> {
74        // Search platform_ids_json for a key matching the platform_id
75        // SQLite json_each lets us iterate JSON object keys
76        let row = sqlx::query(
77            "SELECT p.id, p.name, p.aliases_json, p.relationship, p.platform_ids_json, p.notes, \
78             p.communication_style, p.language_preference, p.last_interaction_at, p.interaction_count, \
79             p.created_at, p.updated_at \
80             FROM people p, json_each(p.platform_ids_json) j \
81             WHERE j.key = ?"
82        )
83        .bind(platform_id)
84        .fetch_optional(&self.pool)
85        .await?;
86
87        Ok(row.map(|r| Self::row_to_person(&r)))
88    }
89
90    async fn find_person_by_name(
91        &self,
92        name: &str,
93    ) -> anyhow::Result<Option<crate::records::Person>> {
94        let name_lower = name.to_lowercase();
95        // Check name first (case-insensitive)
96        let row = sqlx::query(
97            "SELECT id, name, aliases_json, relationship, platform_ids_json, notes, \
98             communication_style, language_preference, last_interaction_at, interaction_count, \
99             created_at, updated_at FROM people WHERE LOWER(name) = ?",
100        )
101        .bind(&name_lower)
102        .fetch_optional(&self.pool)
103        .await?;
104
105        if let Some(r) = row {
106            return Ok(Some(Self::row_to_person(&r)));
107        }
108
109        // Check aliases (JSON array search)
110        let rows = sqlx::query(
111            "SELECT id, name, aliases_json, relationship, platform_ids_json, notes, \
112             communication_style, language_preference, last_interaction_at, interaction_count, \
113             created_at, updated_at FROM people",
114        )
115        .fetch_all(&self.pool)
116        .await?;
117
118        for r in &rows {
119            let aliases_str: String = r.get("aliases_json");
120            if let Ok(aliases) = serde_json::from_str::<Vec<String>>(&aliases_str)
121                && aliases.iter().any(|a| a.to_lowercase() == name_lower)
122            {
123                return Ok(Some(Self::row_to_person(r)));
124            }
125        }
126
127        Ok(None)
128    }
129
130    async fn get_all_people(&self) -> anyhow::Result<Vec<crate::records::Person>> {
131        let rows = sqlx::query(
132            "SELECT id, name, aliases_json, relationship, platform_ids_json, notes, \
133             communication_style, language_preference, last_interaction_at, interaction_count, \
134             created_at, updated_at FROM people ORDER BY name ASC",
135        )
136        .fetch_all(&self.pool)
137        .await?;
138
139        Ok(rows.iter().map(Self::row_to_person).collect())
140    }
141
142    async fn delete_person(&self, id: i64) -> anyhow::Result<()> {
143        // person_facts has ON DELETE CASCADE, but be explicit
144        sqlx::query("DELETE FROM person_facts WHERE person_id = ?")
145            .bind(id)
146            .execute(&self.pool)
147            .await?;
148        sqlx::query("DELETE FROM people WHERE id = ?")
149            .bind(id)
150            .execute(&self.pool)
151            .await?;
152        Ok(())
153    }
154
155    async fn link_platform_id(
156        &self,
157        person_id: i64,
158        platform_id: &str,
159        display_name: &str,
160    ) -> anyhow::Result<()> {
161        // Read current platform_ids, add new one, write back
162        let row = sqlx::query("SELECT platform_ids_json FROM people WHERE id = ?")
163            .bind(person_id)
164            .fetch_optional(&self.pool)
165            .await?;
166
167        let mut ids: std::collections::HashMap<String, String> = match row {
168            Some(r) => {
169                let json_str: String = r.get("platform_ids_json");
170                serde_json::from_str(&json_str).unwrap_or_default()
171            }
172            None => return Err(anyhow::anyhow!("Person {} not found", person_id)),
173        };
174
175        ids.insert(platform_id.to_string(), display_name.to_string());
176        let updated_json = serde_json::to_string(&ids)?;
177        let now = chrono::Utc::now().to_rfc3339();
178
179        sqlx::query("UPDATE people SET platform_ids_json = ?, updated_at = ? WHERE id = ?")
180            .bind(&updated_json)
181            .bind(&now)
182            .bind(person_id)
183            .execute(&self.pool)
184            .await?;
185        Ok(())
186    }
187
188    async fn touch_person_interaction(&self, person_id: i64) -> anyhow::Result<()> {
189        let now = chrono::Utc::now().to_rfc3339();
190        sqlx::query(
191            "UPDATE people SET last_interaction_at = ?, interaction_count = interaction_count + 1, updated_at = ? WHERE id = ?"
192        )
193        .bind(&now)
194        .bind(&now)
195        .bind(person_id)
196        .execute(&self.pool)
197        .await?;
198        Ok(())
199    }
200
201    async fn upsert_person_fact(
202        &self,
203        person_id: i64,
204        category: &str,
205        key: &str,
206        value: &str,
207        source: &str,
208        confidence: f32,
209    ) -> anyhow::Result<()> {
210        let now = chrono::Utc::now().to_rfc3339();
211        sqlx::query(
212            "INSERT INTO person_facts (person_id, category, key, value, source, confidence, created_at, updated_at) \
213             VALUES (?, ?, ?, ?, ?, ?, ?, ?) \
214             ON CONFLICT(person_id, category, key) DO UPDATE SET \
215             value = excluded.value, source = excluded.source, confidence = excluded.confidence, updated_at = excluded.updated_at"
216        )
217        .bind(person_id)
218        .bind(category)
219        .bind(key)
220        .bind(value)
221        .bind(source)
222        .bind(confidence)
223        .bind(&now)
224        .bind(&now)
225        .execute(&self.pool)
226        .await?;
227        Ok(())
228    }
229
230    async fn get_person_facts(
231        &self,
232        person_id: i64,
233        category: Option<&str>,
234    ) -> anyhow::Result<Vec<crate::records::PersonFact>> {
235        let rows = if let Some(cat) = category {
236            sqlx::query(
237                "SELECT id, person_id, category, key, value, source, confidence, created_at, updated_at \
238                 FROM person_facts WHERE person_id = ? AND category = ? ORDER BY category, key"
239            )
240            .bind(person_id)
241            .bind(cat)
242            .fetch_all(&self.pool)
243            .await?
244        } else {
245            sqlx::query(
246                "SELECT id, person_id, category, key, value, source, confidence, created_at, updated_at \
247                 FROM person_facts WHERE person_id = ? ORDER BY category, key"
248            )
249            .bind(person_id)
250            .fetch_all(&self.pool)
251            .await?
252        };
253
254        Ok(rows.iter().map(Self::row_to_person_fact).collect())
255    }
256
257    async fn delete_person_fact(&self, fact_id: i64) -> anyhow::Result<()> {
258        sqlx::query("DELETE FROM person_facts WHERE id = ?")
259            .bind(fact_id)
260            .execute(&self.pool)
261            .await?;
262        Ok(())
263    }
264
265    async fn confirm_person_fact(&self, fact_id: i64) -> anyhow::Result<()> {
266        let now = chrono::Utc::now().to_rfc3339();
267        sqlx::query("UPDATE person_facts SET confidence = 1.0, source = 'owner', updated_at = ? WHERE id = ?")
268            .bind(&now)
269            .bind(fact_id)
270            .execute(&self.pool)
271            .await?;
272        Ok(())
273    }
274
275    async fn get_people_with_upcoming_dates(
276        &self,
277        within_days: i32,
278    ) -> anyhow::Result<Vec<(crate::records::Person, crate::records::PersonFact)>> {
279        // Get all birthday/important_date facts, then filter by upcoming date in Rust
280        let rows = sqlx::query(
281            "SELECT pf.id as fact_id, pf.person_id, pf.category, pf.key, pf.value, pf.source, pf.confidence, \
282             pf.created_at as fact_created, pf.updated_at as fact_updated, \
283             p.id, p.name, p.aliases_json, p.relationship, p.platform_ids_json, p.notes, \
284             p.communication_style, p.language_preference, p.last_interaction_at, p.interaction_count, \
285             p.created_at, p.updated_at \
286             FROM person_facts pf JOIN people p ON pf.person_id = p.id \
287             WHERE pf.category IN ('birthday', 'important_date')"
288        )
289        .fetch_all(&self.pool)
290        .await?;
291
292        let today = chrono::Utc::now().date_naive();
293        let mut results = Vec::new();
294
295        for r in &rows {
296            let value: String = r.get("value");
297            // ISO dates only (`crate::dates`): a value in any other form
298            // is never guessed at.
299            if let Some(upcoming_in) = crate::dates::days_until_anniversary(&value, today)
300                && upcoming_in <= within_days as i64
301                && upcoming_in >= 0
302            {
303                let person = Self::row_to_person(r);
304                let fact = crate::records::PersonFact {
305                    id: r.get("fact_id"),
306                    person_id: r.get("person_id"),
307                    category: r.get("category"),
308                    key: r.get("key"),
309                    value: r.get("value"),
310                    source: r.get("source"),
311                    confidence: r.get("confidence"),
312                    created_at: parse_dt(r.get::<String, _>("fact_created")),
313                    updated_at: parse_dt(r.get::<String, _>("fact_updated")),
314                };
315                results.push((person, fact));
316            }
317        }
318
319        Ok(results)
320    }
321
322    async fn prune_stale_person_facts(&self, retention_days: u32) -> anyhow::Result<u64> {
323        let cutoff =
324            (chrono::Utc::now() - chrono::Duration::days(retention_days as i64)).to_rfc3339();
325        let result = sqlx::query(
326            "DELETE FROM person_facts WHERE source = 'consolidation' AND confidence < 1.0 AND updated_at < ?"
327        )
328        .bind(&cutoff)
329        .execute(&self.pool)
330        .await?;
331        Ok(result.rows_affected())
332    }
333
334    async fn get_people_needing_reconnect(
335        &self,
336        inactive_days: u32,
337    ) -> anyhow::Result<Vec<crate::records::Person>> {
338        let cutoff =
339            (chrono::Utc::now() - chrono::Duration::days(inactive_days as i64)).to_rfc3339();
340        let rows = sqlx::query(
341            "SELECT id, name, aliases_json, relationship, platform_ids_json, notes, \
342             communication_style, language_preference, last_interaction_at, interaction_count, \
343             created_at, updated_at FROM people \
344             WHERE last_interaction_at IS NOT NULL AND last_interaction_at < ? \
345             AND relationship IN ('friend', 'family', 'coworker') \
346             ORDER BY last_interaction_at ASC",
347        )
348        .bind(&cutoff)
349        .fetch_all(&self.pool)
350        .await?;
351
352        Ok(rows.iter().map(Self::row_to_person).collect())
353    }
354}