1use crate::service::*;
45use crate::text::ArtifactReference;
46use adk_core::{Content, Result};
47use async_trait::async_trait;
48use chrono::{DateTime, Utc};
49use serde::{Deserialize, Serialize};
50use sqlx::sqlite::SqlitePoolOptions;
51use sqlx::{Row, SqlitePool};
52use std::time::Duration;
53
54const PROFILE_QUERY: &str = "session context";
57
58#[derive(Debug, Clone, Serialize, PartialEq)]
62pub struct Entity {
63 pub name: String,
65 pub entity_type: String,
67 pub observations: Vec<Observation>,
69}
70
71#[derive(Debug, Clone, Serialize, PartialEq)]
73pub struct Observation {
74 pub id: i64,
76 pub content: String,
78 pub valid_from: DateTime<Utc>,
80}
81
82#[derive(Debug, Clone, Serialize, PartialEq)]
84pub struct Relation {
85 pub id: i64,
87 pub source: String,
89 pub relation_type: String,
91 pub target: String,
93}
94
95#[derive(Debug, Clone, Serialize)]
97pub struct GraphSearchResult {
98 pub entity: Entity,
100 pub relations: Vec<Relation>,
102 pub score: f64,
104}
105
106#[derive(Debug, Clone, Deserialize)]
108pub struct CreateEntityInput {
109 pub name: String,
111 #[serde(default = "default_entity_type")]
113 pub entity_type: String,
114 #[serde(default)]
116 pub observations: Vec<String>,
117}
118
119fn default_entity_type() -> String {
120 "general".to_string()
121}
122
123#[derive(Debug, Clone, Deserialize)]
125pub struct CreateRelationInput {
126 pub source: String,
128 pub relation_type: String,
130 pub target: String,
132}
133
134pub struct GraphMemoryService {
138 pool: SqlitePool,
139 profile_entities: usize,
141 profile_observations: usize,
143 default_ttl: Option<Duration>,
145}
146
147impl GraphMemoryService {
148 pub async fn new(database_url: &str) -> Result<Self> {
154 Ok(Self::from_pool(crate::sqlite::connect(database_url, SqlitePoolOptions::new()).await?))
155 }
156
157 pub fn from_pool(pool: SqlitePool) -> Self {
159 Self { pool, profile_entities: 12, profile_observations: 5, default_ttl: None }
160 }
161
162 pub fn with_profile_budget(mut self, entities: usize, observations_per_entity: usize) -> Self {
164 self.profile_entities = entities;
165 self.profile_observations = observations_per_entity;
166 self
167 }
168
169 pub fn with_default_ttl(mut self, ttl: Duration) -> Self {
187 self.default_ttl = Some(ttl);
188 self
189 }
190
191 const REGISTRY_TABLE: &'static str = "_adk_kg_migrations";
192
193 const MIGRATIONS: &'static [(i64, &'static str, &'static str)] = &[
194 (
195 1,
196 "create bi-temporal knowledge-graph + episodic tables",
197 "\
198CREATE TABLE IF NOT EXISTS kg_entities (\
199 app_name TEXT NOT NULL, user_id TEXT NOT NULL, \
200 name TEXT NOT NULL, entity_type TEXT NOT NULL, updated_at TEXT NOT NULL, \
201 PRIMARY KEY (app_name, user_id, name)\
202);\
203CREATE TABLE IF NOT EXISTS kg_observations (\
204 id INTEGER PRIMARY KEY AUTOINCREMENT, \
205 app_name TEXT NOT NULL, user_id TEXT NOT NULL, entity_name TEXT NOT NULL, \
206 content TEXT NOT NULL, valid_from TEXT NOT NULL, valid_to TEXT\
207);\
208CREATE INDEX IF NOT EXISTS idx_kg_obs ON kg_observations(app_name, user_id, entity_name);\
209CREATE TABLE IF NOT EXISTS kg_relations (\
210 id INTEGER PRIMARY KEY AUTOINCREMENT, \
211 app_name TEXT NOT NULL, user_id TEXT NOT NULL, \
212 source TEXT NOT NULL, relation_type TEXT NOT NULL, target TEXT NOT NULL, \
213 valid_from TEXT NOT NULL, valid_to TEXT\
214);\
215CREATE INDEX IF NOT EXISTS idx_kg_rel ON kg_relations(app_name, user_id);\
216CREATE TABLE IF NOT EXISTS kg_episodic (\
217 id INTEGER PRIMARY KEY AUTOINCREMENT, \
218 app_name TEXT NOT NULL, user_id TEXT NOT NULL, session_id TEXT NOT NULL, \
219 author TEXT NOT NULL, text TEXT NOT NULL, timestamp TEXT NOT NULL\
220);\
221CREATE INDEX IF NOT EXISTS idx_kg_epi ON kg_episodic(app_name, user_id);",
222 ),
223 (
224 2,
225 "add memory_id and expires_at to the episodic log",
226 "\
227ALTER TABLE kg_episodic ADD COLUMN memory_id TEXT;\
228ALTER TABLE kg_episodic ADD COLUMN expires_at INTEGER;\
229UPDATE kg_episodic SET memory_id = lower(hex(randomblob(16))) WHERE memory_id IS NULL;\
230CREATE INDEX IF NOT EXISTS idx_kg_epi_memory_id ON kg_episodic(app_name, user_id, memory_id);\
231CREATE INDEX IF NOT EXISTS idx_kg_epi_expires_at ON kg_episodic(expires_at);",
232 ),
233 (
234 3,
235 "keep the artifacts an episodic turn refers to",
236 "ALTER TABLE kg_episodic ADD COLUMN artifacts TEXT;",
237 ),
238 ];
239
240 pub async fn migrate(&self) -> Result<()> {
242 let pool = self.pool.clone();
243 crate::migration::sqlite_runner::run_sql_migrations(
244 &pool,
245 Self::REGISTRY_TABLE,
246 Self::MIGRATIONS,
247 || async {
248 let row = sqlx::query(
249 "SELECT COUNT(*) AS cnt FROM sqlite_master \
250 WHERE type='table' AND name='kg_entities'",
251 )
252 .fetch_one(&pool)
253 .await
254 .map_err(|e| {
255 adk_core::AdkError::memory(format!("baseline detection failed: {e}"))
256 })?;
257 let count: i64 = row.try_get("cnt").unwrap_or(0);
258 Ok(count > 0)
259 },
260 )
261 .await
262 }
263
264 pub async fn create_entities(
269 &self,
270 app_name: &str,
271 user_id: &str,
272 inputs: Vec<CreateEntityInput>,
273 ) -> Result<Vec<String>> {
274 let now = Utc::now().to_rfc3339();
275 let mut touched = Vec::new();
276 let mut tx = self.begin().await?;
277
278 for input in inputs {
279 sqlx::query(
280 "INSERT INTO kg_entities (app_name, user_id, name, entity_type, updated_at) \
281 VALUES (?1, ?2, ?3, ?4, ?5) \
282 ON CONFLICT(app_name, user_id, name) \
283 DO UPDATE SET entity_type = excluded.entity_type, updated_at = excluded.updated_at",
284 )
285 .bind(app_name)
286 .bind(user_id)
287 .bind(&input.name)
288 .bind(&input.entity_type)
289 .bind(&now)
290 .execute(&mut *tx)
291 .await
292 .map_err(map_sql)?;
293
294 for content in &input.observations {
295 sqlx::query(
296 "INSERT INTO kg_observations \
297 (app_name, user_id, entity_name, content, valid_from, valid_to) \
298 VALUES (?1, ?2, ?3, ?4, ?5, NULL)",
299 )
300 .bind(app_name)
301 .bind(user_id)
302 .bind(&input.name)
303 .bind(content)
304 .bind(&now)
305 .execute(&mut *tx)
306 .await
307 .map_err(map_sql)?;
308 }
309 touched.push(input.name);
310 }
311
312 tx.commit().await.map_err(map_sql)?;
313 Ok(touched)
314 }
315
316 pub async fn create_relations(
318 &self,
319 app_name: &str,
320 user_id: &str,
321 inputs: Vec<CreateRelationInput>,
322 ) -> Result<Vec<i64>> {
323 let now = Utc::now().to_rfc3339();
324 let mut ids = Vec::new();
325 let mut tx = self.begin().await?;
326
327 for input in inputs {
328 let res = sqlx::query(
329 "INSERT INTO kg_relations \
330 (app_name, user_id, source, relation_type, target, valid_from, valid_to) \
331 VALUES (?1, ?2, ?3, ?4, ?5, ?6, NULL)",
332 )
333 .bind(app_name)
334 .bind(user_id)
335 .bind(&input.source)
336 .bind(&input.relation_type)
337 .bind(&input.target)
338 .bind(&now)
339 .execute(&mut *tx)
340 .await
341 .map_err(map_sql)?;
342 ids.push(res.last_insert_rowid());
343 }
344
345 tx.commit().await.map_err(map_sql)?;
346 Ok(ids)
347 }
348
349 pub async fn add_observations(
352 &self,
353 app_name: &str,
354 user_id: &str,
355 entity_name: &str,
356 contents: Vec<String>,
357 ) -> Result<Vec<i64>> {
358 if !self.entity_exists(app_name, user_id, entity_name).await? {
359 return Err(adk_core::AdkError::memory(format!("unknown entity: {entity_name}")));
360 }
361 let now = Utc::now().to_rfc3339();
362 let mut ids = Vec::new();
363 let mut tx = self.begin().await?;
364 for content in contents {
365 let res = sqlx::query(
366 "INSERT INTO kg_observations \
367 (app_name, user_id, entity_name, content, valid_from, valid_to) \
368 VALUES (?1, ?2, ?3, ?4, ?5, NULL)",
369 )
370 .bind(app_name)
371 .bind(user_id)
372 .bind(entity_name)
373 .bind(&content)
374 .bind(&now)
375 .execute(&mut *tx)
376 .await
377 .map_err(map_sql)?;
378 ids.push(res.last_insert_rowid());
379 }
380 tx.commit().await.map_err(map_sql)?;
381 Ok(ids)
382 }
383
384 pub async fn invalidate_observation(&self, id: i64) -> Result<()> {
388 let now = Utc::now().to_rfc3339();
389 sqlx::query("UPDATE kg_observations SET valid_to = ?1 WHERE id = ?2 AND valid_to IS NULL")
390 .bind(&now)
391 .bind(id)
392 .execute(&self.pool)
393 .await
394 .map_err(map_sql)?;
395 Ok(())
396 }
397
398 pub async fn invalidate_relation(&self, id: i64) -> Result<()> {
400 let now = Utc::now().to_rfc3339();
401 sqlx::query("UPDATE kg_relations SET valid_to = ?1 WHERE id = ?2 AND valid_to IS NULL")
402 .bind(&now)
403 .bind(id)
404 .execute(&self.pool)
405 .await
406 .map_err(map_sql)?;
407 Ok(())
408 }
409
410 pub async fn delete_entities(
415 &self,
416 app_name: &str,
417 user_id: &str,
418 names: Vec<String>,
419 ) -> Result<Vec<String>> {
420 let mut deleted = Vec::new();
421 let mut tx = self.begin().await?;
422 for name in names {
423 let res =
424 sqlx::query("DELETE FROM kg_entities WHERE app_name=?1 AND user_id=?2 AND name=?3")
425 .bind(app_name)
426 .bind(user_id)
427 .bind(&name)
428 .execute(&mut *tx)
429 .await
430 .map_err(map_sql)?;
431 if res.rows_affected() == 0 {
432 continue;
433 }
434 sqlx::query(
435 "DELETE FROM kg_observations WHERE app_name=?1 AND user_id=?2 AND entity_name=?3",
436 )
437 .bind(app_name)
438 .bind(user_id)
439 .bind(&name)
440 .execute(&mut *tx)
441 .await
442 .map_err(map_sql)?;
443 sqlx::query(
444 "DELETE FROM kg_relations WHERE app_name=?1 AND user_id=?2 AND (source=?3 OR target=?3)",
445 )
446 .bind(app_name)
447 .bind(user_id)
448 .bind(&name)
449 .execute(&mut *tx)
450 .await
451 .map_err(map_sql)?;
452 deleted.push(name);
453 }
454 tx.commit().await.map_err(map_sql)?;
455 Ok(deleted)
456 }
457
458 pub async fn entity_count(&self, app_name: &str, user_id: &str) -> Result<usize> {
462 let row =
463 sqlx::query("SELECT COUNT(*) AS cnt FROM kg_entities WHERE app_name=?1 AND user_id=?2")
464 .bind(app_name)
465 .bind(user_id)
466 .fetch_one(&self.pool)
467 .await
468 .map_err(map_sql)?;
469 Ok(row.try_get::<i64, _>("cnt").unwrap_or(0) as usize)
470 }
471
472 pub async fn search_nodes(
482 &self,
483 app_name: &str,
484 user_id: &str,
485 query: &str,
486 limit: usize,
487 ) -> Result<Vec<GraphSearchResult>> {
488 let tokens = tokenize(query);
489 let mut results = Vec::new();
490
491 for entity in self.load_entities(app_name, user_id, None).await? {
492 let name = entity.name.to_lowercase();
493 let ty = entity.entity_type.to_lowercase();
494 let mut score = 0.0;
495 for t in &tokens {
496 if name.contains(t) {
497 score += 3.0;
498 }
499 if ty.contains(t) {
500 score += 2.0;
501 }
502 for obs in &entity.observations {
503 if obs.content.to_lowercase().contains(t) {
504 score += 1.0;
505 }
506 }
507 }
508 if score > 0.0 {
509 let relations = self.load_relations(app_name, user_id, &entity.name).await?;
510 results.push(GraphSearchResult { entity, relations, score });
511 }
512 }
513 results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
514 results.truncate(limit);
515 Ok(results)
516 }
517
518 pub async fn open_nodes(
520 &self,
521 app_name: &str,
522 user_id: &str,
523 names: Vec<String>,
524 ) -> Result<Vec<GraphSearchResult>> {
525 let mut out = Vec::new();
526 for entity in self.load_entities(app_name, user_id, Some(&names)).await? {
527 let relations = self.load_relations(app_name, user_id, &entity.name).await?;
528 out.push(GraphSearchResult { entity, relations, score: 1.0 });
529 }
530 Ok(out)
531 }
532
533 pub async fn read_graph(
535 &self,
536 app_name: &str,
537 user_id: &str,
538 ) -> Result<(Vec<Entity>, Vec<Relation>)> {
539 let entities = self.load_entities(app_name, user_id, None).await?;
540 let relations = self.load_all_relations(app_name, user_id).await?;
541 Ok((entities, relations))
542 }
543
544 pub async fn profile_card(&self, app_name: &str, user_id: &str) -> Result<String> {
547 let names: Vec<String> = sqlx::query(
548 "SELECT name FROM kg_entities WHERE app_name=?1 AND user_id=?2 \
549 ORDER BY updated_at DESC LIMIT ?3",
550 )
551 .bind(app_name)
552 .bind(user_id)
553 .bind(self.profile_entities as i64)
554 .fetch_all(&self.pool)
555 .await
556 .map_err(map_sql)?
557 .into_iter()
558 .map(|r| r.get::<String, _>("name"))
559 .collect();
560
561 if names.is_empty() {
562 return Ok(String::new());
563 }
564
565 let entities = self.load_entities(app_name, user_id, Some(&names)).await?;
566 let mut out = String::from("[Known about the user]\n");
567 for e in &entities {
568 out.push_str(&format!("• {} ({})", e.name, e.entity_type));
569 if !e.observations.is_empty() {
570 let recent: Vec<&str> = e
571 .observations
572 .iter()
573 .rev()
574 .take(self.profile_observations)
575 .map(|o| o.content.as_str())
576 .collect();
577 out.push_str(": ");
578 out.push_str(&recent.into_iter().rev().collect::<Vec<_>>().join("; "));
579 }
580 out.push('\n');
581 }
582 Ok(out)
583 }
584
585 async fn begin(&self) -> Result<sqlx::Transaction<'_, sqlx::Sqlite>> {
588 self.pool.begin().await.map_err(map_sql)
589 }
590
591 async fn entity_exists(&self, app_name: &str, user_id: &str, name: &str) -> Result<bool> {
592 let row = sqlx::query(
593 "SELECT 1 AS x FROM kg_entities WHERE app_name=?1 AND user_id=?2 AND name=?3 LIMIT 1",
594 )
595 .bind(app_name)
596 .bind(user_id)
597 .bind(name)
598 .fetch_optional(&self.pool)
599 .await
600 .map_err(map_sql)?;
601 Ok(row.is_some())
602 }
603
604 async fn load_entities(
606 &self,
607 app_name: &str,
608 user_id: &str,
609 names: Option<&[String]>,
610 ) -> Result<Vec<Entity>> {
611 let ent_rows = sqlx::query(
612 "SELECT name, entity_type FROM kg_entities WHERE app_name=?1 AND user_id=?2 ORDER BY name",
613 )
614 .bind(app_name)
615 .bind(user_id)
616 .fetch_all(&self.pool)
617 .await
618 .map_err(map_sql)?;
619
620 let mut entities = Vec::new();
621 for row in ent_rows {
622 let name: String = row.get("name");
623 if let Some(filter) = names
624 && !filter.iter().any(|n| n == &name)
625 {
626 continue;
627 }
628 let entity_type: String = row.get("entity_type");
629 let obs = sqlx::query(
630 "SELECT id, content, valid_from FROM kg_observations \
631 WHERE app_name=?1 AND user_id=?2 AND entity_name=?3 AND valid_to IS NULL \
632 ORDER BY id",
633 )
634 .bind(app_name)
635 .bind(user_id)
636 .bind(&name)
637 .fetch_all(&self.pool)
638 .await
639 .map_err(map_sql)?
640 .into_iter()
641 .map(|r| Observation {
642 id: r.get::<i64, _>("id"),
643 content: r.get::<String, _>("content"),
644 valid_from: parse_ts(&r.get::<String, _>("valid_from")),
645 })
646 .collect();
647
648 entities.push(Entity { name, entity_type, observations: obs });
649 }
650 Ok(entities)
651 }
652
653 async fn load_relations(
654 &self,
655 app_name: &str,
656 user_id: &str,
657 entity: &str,
658 ) -> Result<Vec<Relation>> {
659 let rows = sqlx::query(
660 "SELECT id, source, relation_type, target FROM kg_relations \
661 WHERE app_name=?1 AND user_id=?2 AND (source=?3 OR target=?3) AND valid_to IS NULL \
662 ORDER BY id",
663 )
664 .bind(app_name)
665 .bind(user_id)
666 .bind(entity)
667 .fetch_all(&self.pool)
668 .await
669 .map_err(map_sql)?;
670 Ok(rows.into_iter().map(row_to_relation).collect())
671 }
672
673 async fn load_all_relations(&self, app_name: &str, user_id: &str) -> Result<Vec<Relation>> {
674 let rows = sqlx::query(
675 "SELECT id, source, relation_type, target FROM kg_relations \
676 WHERE app_name=?1 AND user_id=?2 AND valid_to IS NULL ORDER BY id",
677 )
678 .bind(app_name)
679 .bind(user_id)
680 .fetch_all(&self.pool)
681 .await
682 .map_err(map_sql)?;
683 Ok(rows.into_iter().map(row_to_relation).collect())
684 }
685
686 async fn recall_episodic(
692 &self,
693 app_name: &str,
694 user_id: &str,
695 query: &str,
696 limit: usize,
697 ) -> Result<Vec<MemoryEntry>> {
698 let tokens = tokenize(query);
699 const WINDOW: i64 = 200;
702 let rows = sqlx::query(
703 "SELECT memory_id, author, text, artifacts, timestamp, expires_at FROM kg_episodic \
704 WHERE app_name=?1 AND user_id=?2 AND (expires_at IS NULL OR expires_at > ?4) \
705 ORDER BY id DESC LIMIT ?3",
706 )
707 .bind(app_name)
708 .bind(user_id)
709 .bind(WINDOW)
710 .bind(Utc::now().timestamp_millis())
712 .fetch_all(&self.pool)
713 .await
714 .map_err(map_sql)?;
715
716 let mut scored: Vec<(usize, MemoryEntry)> = rows
719 .into_iter()
720 .filter_map(|r| {
721 let text: String = r.get("text");
722 let lc = text.to_lowercase();
723 let overlap = tokens.iter().filter(|t| lc.contains(t.as_str())).count();
724 if overlap == 0 {
725 return None;
726 }
727 Some((overlap, episodic_entry(&r, text)))
728 })
729 .collect();
730 scored.sort_by_key(|(score, _)| std::cmp::Reverse(*score));
731 Ok(scored.into_iter().take(limit).map(|(_, m)| m).collect())
732 }
733}
734
735fn tokenize(query: &str) -> Vec<String> {
741 const STOPWORDS: &[&str] = &[
742 "the", "and", "you", "your", "yours", "for", "with", "what", "that", "this", "are", "was",
743 "has", "have", "had", "about", "when", "where", "which", "will", "can", "did", "does",
744 "into", "from", "they", "them", "our", "but", "not", "any", "all", "know", "tell", "there",
745 "their", "would", "should", "could", "been", "were", "who",
746 ];
747 let mut tokens: Vec<String> = query
748 .to_lowercase()
749 .split(|c: char| !c.is_alphanumeric())
750 .filter(|t| t.len() >= 3 && !STOPWORDS.contains(t))
751 .map(str::to_string)
752 .collect();
753 tokens.sort();
754 tokens.dedup();
755 if tokens.is_empty() {
756 let q = query.trim().to_lowercase();
757 if !q.is_empty() {
758 tokens.push(q);
759 }
760 }
761 tokens
762}
763
764fn result_to_sentence(r: &GraphSearchResult) -> String {
766 let mut s = format!("{} ({})", r.entity.name, r.entity.entity_type);
767 if !r.entity.observations.is_empty() {
768 let obs: Vec<&str> = r.entity.observations.iter().map(|o| o.content.as_str()).collect();
769 s.push_str(": ");
770 s.push_str(&obs.join("; "));
771 }
772 for rel in &r.relations {
773 s.push_str(&format!(" | {} -[{}]-> {}", rel.source, rel.relation_type, rel.target));
774 }
775 s
776}
777
778fn row_to_relation(r: sqlx::sqlite::SqliteRow) -> Relation {
779 Relation {
780 id: r.get::<i64, _>("id"),
781 source: r.get::<String, _>("source"),
782 relation_type: r.get::<String, _>("relation_type"),
783 target: r.get::<String, _>("target"),
784 }
785}
786
787fn episodic_entry(row: &sqlx::sqlite::SqliteRow, text: String) -> MemoryEntry {
790 let author: String = row.get("author");
791 let mut content = Content::new(author.clone());
792 if !text.is_empty() {
793 content = content.with_text(text);
794 }
795 let artifacts: Vec<ArtifactReference> = row
796 .get::<Option<String>, _>("artifacts")
797 .and_then(|json| serde_json::from_str(&json).ok())
798 .unwrap_or_default();
799 content.parts.extend(artifacts.iter().map(ArtifactReference::to_part));
800 let mut entry = MemoryEntry::new(content, author)
801 .with_timestamp(parse_ts(&row.get::<String, _>("timestamp")));
802 entry.id = row.get("memory_id");
803 entry.expires_at =
804 row.get::<Option<i64>, _>("expires_at").and_then(DateTime::from_timestamp_millis);
805 entry
806}
807
808fn parse_ts(s: &str) -> DateTime<Utc> {
809 DateTime::parse_from_rfc3339(s).map(|d| d.with_timezone(&Utc)).unwrap_or_else(|_| Utc::now())
810}
811
812fn content_text(c: &Content) -> String {
814 c.parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join(" ")
815}
816
817fn map_sql(e: sqlx::Error) -> adk_core::AdkError {
818 adk_core::AdkError::memory(format!("knowledge-graph sqlite error: {e}"))
819}
820
821#[async_trait]
824impl MemoryService for GraphMemoryService {
825 async fn add_session(
833 &self,
834 app_name: &str,
835 user_id: &str,
836 session_id: &str,
837 entries: Vec<MemoryEntry>,
838 ) -> Result<()> {
839 let now = Utc::now();
840 let mut tx = self.begin().await?;
841 for e in entries {
842 let text = content_text(&e.content);
843 let artifacts = crate::text::artifact_references(&e.content);
844 if text.is_empty() && artifacts.is_empty() {
845 continue;
846 }
847 let artifacts = if artifacts.is_empty() {
848 None
849 } else {
850 Some(serde_json::to_string(&artifacts).map_err(|err| {
851 adk_core::AdkError::memory(format!("artifact references: {err}"))
852 })?)
853 };
854 let e = crate::expiry::stamp(e, self.default_ttl, now);
855 sqlx::query(
856 "INSERT INTO kg_episodic \
857 (app_name, user_id, session_id, author, text, timestamp, memory_id, expires_at, \
858 artifacts) \
859 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
860 )
861 .bind(app_name)
862 .bind(user_id)
863 .bind(session_id)
864 .bind(&e.author)
865 .bind(&text)
866 .bind(e.timestamp.to_rfc3339())
867 .bind(&e.id)
868 .bind(e.expires_at.map(|at| at.timestamp_millis()))
869 .bind(artifacts)
870 .execute(&mut *tx)
871 .await
872 .map_err(map_sql)?;
873 }
874 tx.commit().await.map_err(map_sql)?;
875 Ok(())
876 }
877
878 async fn search(&self, req: SearchRequest) -> Result<SearchResponse> {
884 let limit = req.limit.unwrap_or(10);
885
886 if req.query.trim().is_empty() || req.query == PROFILE_QUERY {
888 let card = self.profile_card(&req.app_name, &req.user_id).await?;
889 if card.is_empty() {
890 return Ok(SearchResponse { memories: Vec::new() });
891 }
892 return Ok(SearchResponse {
893 memories: vec![MemoryEntry::new(Content::new("memory").with_text(card), "memory")],
894 });
895 }
896
897 let mut memories = Vec::new();
899 for r in self.search_nodes(&req.app_name, &req.user_id, &req.query, limit).await? {
900 memories.push(MemoryEntry::new(
901 Content::new("memory").with_text(result_to_sentence(&r)),
902 "memory",
903 ));
904 }
905 if memories.len() < limit {
906 let remaining = limit - memories.len();
907 memories.extend(
908 self.recall_episodic(&req.app_name, &req.user_id, &req.query, remaining).await?,
909 );
910 }
911 memories.truncate(limit);
912 Ok(SearchResponse { memories })
913 }
914
915 async fn export_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserMemory>> {
919 let graph_entry = |text: String, timestamp: &str| UserMemory {
920 entry: MemoryEntry::new(Content::new("model").with_text(text), "graph")
921 .with_timestamp(parse_ts(timestamp)),
922 session_id: None,
923 project_id: None,
924 };
925 let until = |valid_to: Option<String>| {
926 valid_to.map(|to| format!(" (until {to})")).unwrap_or_default()
927 };
928 let query = |sql: &'static str| sqlx::query(sql).bind(app_name).bind(user_id);
929 let mut memories = Vec::new();
930 for row in query(
931 "SELECT name, entity_type, updated_at FROM kg_entities \
932 WHERE app_name=?1 AND user_id=?2",
933 )
934 .fetch_all(&self.pool)
935 .await
936 .map_err(map_sql)?
937 {
938 let (name, kind): (String, String) = (row.get("name"), row.get("entity_type"));
939 memories
940 .push(graph_entry(format!("{name} ({kind})"), &row.get::<String, _>("updated_at")));
941 }
942 for row in query(
943 "SELECT entity_name, content, valid_from, valid_to FROM kg_observations \
944 WHERE app_name=?1 AND user_id=?2",
945 )
946 .fetch_all(&self.pool)
947 .await
948 .map_err(map_sql)?
949 {
950 let (entity, content): (String, String) = (row.get("entity_name"), row.get("content"));
951 let text = format!("{entity}: {content}{}", until(row.get("valid_to")));
952 memories.push(graph_entry(text, &row.get::<String, _>("valid_from")));
953 }
954 for row in query(
955 "SELECT source, relation_type, target, valid_from, valid_to FROM kg_relations \
956 WHERE app_name=?1 AND user_id=?2",
957 )
958 .fetch_all(&self.pool)
959 .await
960 .map_err(map_sql)?
961 {
962 let (source, relation, target): (String, String, String) =
963 (row.get("source"), row.get("relation_type"), row.get("target"));
964 let text = format!("{source} {relation} {target}{}", until(row.get("valid_to")));
965 memories.push(graph_entry(text, &row.get::<String, _>("valid_from")));
966 }
967 for row in query(
968 "SELECT session_id, memory_id, author, text, artifacts, timestamp, expires_at \
969 FROM kg_episodic \
970 WHERE app_name=?1 AND user_id=?2",
971 )
972 .fetch_all(&self.pool)
973 .await
974 .map_err(map_sql)?
975 {
976 memories.push(UserMemory {
977 entry: episodic_entry(&row, row.get("text")),
978 session_id: Some(row.get("session_id")),
979 project_id: None,
980 });
981 }
982 memories.sort_by_key(|memory| memory.entry.timestamp);
983 Ok(memories)
984 }
985
986 async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<()> {
988 let mut tx = self.begin().await?;
989 for delete in [
990 "DELETE FROM kg_entities WHERE app_name=?1 AND user_id=?2",
991 "DELETE FROM kg_observations WHERE app_name=?1 AND user_id=?2",
992 "DELETE FROM kg_relations WHERE app_name=?1 AND user_id=?2",
993 "DELETE FROM kg_episodic WHERE app_name=?1 AND user_id=?2",
994 ] {
995 sqlx::query(delete)
996 .bind(app_name)
997 .bind(user_id)
998 .execute(&mut *tx)
999 .await
1000 .map_err(map_sql)?;
1001 }
1002 tx.commit().await.map_err(map_sql)?;
1003 Ok(())
1004 }
1005
1006 async fn delete_session(&self, app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
1007 sqlx::query("DELETE FROM kg_episodic WHERE app_name=?1 AND user_id=?2 AND session_id=?3")
1008 .bind(app_name)
1009 .bind(user_id)
1010 .bind(session_id)
1011 .execute(&self.pool)
1012 .await
1013 .map_err(map_sql)?;
1014 Ok(())
1015 }
1016
1017 async fn delete_memory(&self, app_name: &str, user_id: &str, memory_id: &str) -> Result<u64> {
1021 let result = sqlx::query(
1022 "DELETE FROM kg_episodic WHERE app_name=?1 AND user_id=?2 AND memory_id=?3",
1023 )
1024 .bind(app_name)
1025 .bind(user_id)
1026 .bind(memory_id)
1027 .execute(&self.pool)
1028 .await
1029 .map_err(map_sql)?;
1030 Ok(result.rows_affected())
1031 }
1032
1033 async fn purge_expired(&self) -> Result<u64> {
1034 let result = sqlx::query("DELETE FROM kg_episodic WHERE expires_at <= ?1")
1035 .bind(Utc::now().timestamp_millis())
1036 .execute(&self.pool)
1037 .await
1038 .map_err(map_sql)?;
1039 Ok(result.rows_affected())
1040 }
1041
1042 async fn health_check(&self) -> Result<()> {
1043 sqlx::query("SELECT 1").execute(&self.pool).await.map_err(map_sql)?;
1044 Ok(())
1045 }
1046}
1047
1048#[cfg(test)]
1051mod tests {
1052 use super::*;
1053
1054 async fn svc() -> GraphMemoryService {
1055 let s = GraphMemoryService::new("sqlite::memory:").await.unwrap();
1056 s.migrate().await.unwrap();
1057 s
1058 }
1059
1060 fn entry(author: &str, text: &str) -> MemoryEntry {
1061 MemoryEntry::new(Content::new(author).with_text(text), author.to_string())
1062 }
1063
1064 #[tokio::test]
1065 async fn episodic_turns_keep_their_artifact_references() {
1066 let kg = svc().await;
1067 let frame = "artifact://inspector/u1/s1/vision-ab12.png#0";
1068 let captioned = entry("model", "torn seal on carton 117, conveyor 1")
1069 .with_id("caption-1")
1070 .with_artifact(frame, "image/png");
1071 let mut inline = entry("model", "a page").with_id("page-1");
1073 inline.content.parts.push(adk_core::Part::InlineData {
1074 mime_type: "image/png".into(),
1075 data: vec![1, 2, 3],
1076 uri: Some("artifact://inspector/u1/s1/page.png#2".into()),
1077 annotations: None,
1078 });
1079 let mut bare = MemoryEntry::new(Content::new("model"), "model").with_id("frame-only");
1080 bare.content.parts.push(ArtifactReference::new(frame, "image/png").to_part());
1081 let empty = MemoryEntry::new(Content::new("model"), "model");
1082 kg.add_session("app", "u1", "s1", vec![captioned, inline, bare, empty]).await.unwrap();
1083
1084 let found = kg
1085 .search(SearchRequest {
1086 query: "torn seal".into(),
1087 user_id: "u1".into(),
1088 app_name: "app".into(),
1089 limit: Some(5),
1090 min_score: None,
1091 project_id: None,
1092 })
1093 .await
1094 .unwrap();
1095 let caption = found.memories.iter().find(|m| m.id.as_deref() == Some("caption-1")).unwrap();
1096 assert_eq!(
1097 crate::text::extract_text(&caption.content),
1098 "torn seal on carton 117, conveyor 1"
1099 );
1100 assert_eq!(caption.artifact_references(), vec![ArtifactReference::new(frame, "image/png")]);
1101
1102 let exported = kg.export_user("app", "u1").await.unwrap();
1103 let by_id = |id: &str| {
1104 exported.iter().find(|m| m.entry.id.as_deref() == Some(id)).map(|m| &m.entry).unwrap()
1105 };
1106 assert_eq!(
1107 by_id("page-1").artifact_references(),
1108 vec![ArtifactReference::new("artifact://inspector/u1/s1/page.png#2", "image/png")]
1109 );
1110 assert!(
1111 by_id("page-1")
1112 .content
1113 .parts
1114 .iter()
1115 .all(|p| !matches!(p, adk_core::Part::InlineData { .. }))
1116 );
1117 assert_eq!(
1118 by_id("frame-only").content.parts,
1119 vec![ArtifactReference::new(frame, "image/png").to_part()]
1120 );
1121 assert_eq!(exported.len(), 3, "a turn with no text and no artifact is skipped");
1122
1123 assert_eq!(kg.delete_memory("app", "u1", "caption-1").await.unwrap(), 1);
1124 }
1125
1126 #[tokio::test]
1127 async fn an_in_memory_graph_keeps_its_tables_past_the_pool_idle_timeout() {
1128 let reaping = SqlitePoolOptions::new().idle_timeout(Duration::from_millis(50));
1129 let kg = GraphMemoryService::from_pool(
1130 crate::sqlite::connect("sqlite::memory:", reaping).await.unwrap(),
1131 );
1132 kg.migrate().await.unwrap();
1133 let mia = CreateEntityInput {
1134 name: "Mia".into(),
1135 entity_type: "person".into(),
1136 observations: vec!["Prefers the night shift".into()],
1137 };
1138 kg.create_entities("app", "u", vec![mia]).await.unwrap();
1139 tokio::time::sleep(Duration::from_millis(500)).await;
1141 assert_eq!(kg.entity_count("app", "u").await.unwrap(), 1);
1142 }
1143
1144 #[tokio::test]
1145 async fn only_an_in_memory_graph_changes_the_pool_settings() {
1146 let settings = |options: &SqlitePoolOptions| {
1147 (options.get_max_connections(), options.get_idle_timeout(), options.get_max_lifetime())
1148 };
1149 let path = std::env::temp_dir().join(format!("adk-kg-pool-{}.db", uuid::Uuid::new_v4()));
1150 let on_disk =
1151 GraphMemoryService::new(&format!("sqlite://{}", path.display())).await.unwrap();
1152 assert_eq!(settings(on_disk.pool.options()), settings(&SqlitePoolOptions::new()));
1153 on_disk.pool.close().await;
1154 let _ = std::fs::remove_file(&path);
1155
1156 let named = format!("sqlite:kg-{}?mode=memory", uuid::Uuid::new_v4());
1157 for url in ["sqlite::memory:", named.as_str()] {
1158 let in_memory = GraphMemoryService::new(url).await.unwrap();
1159 assert_eq!(settings(in_memory.pool.options()), (1, None, None), "{url}");
1160 }
1161 }
1162
1163 #[tokio::test]
1164 async fn create_search_and_relations() {
1165 let kg = svc().await;
1166 kg.create_entities(
1167 "app",
1168 "shai",
1169 vec![CreateEntityInput {
1170 name: "Shai".into(),
1171 entity_type: "person".into(),
1172 observations: vec!["Relocated to the Bay Area".into()],
1173 }],
1174 )
1175 .await
1176 .unwrap();
1177 kg.create_relations(
1178 "app",
1179 "shai",
1180 vec![CreateRelationInput {
1181 source: "Shai".into(),
1182 relation_type: "house_hunting_in".into(),
1183 target: "Bay Area".into(),
1184 }],
1185 )
1186 .await
1187 .unwrap();
1188
1189 assert_eq!(kg.entity_count("app", "shai").await.unwrap(), 1);
1190 let hits = kg.search_nodes("app", "shai", "bay area", 10).await.unwrap();
1191 assert_eq!(hits.len(), 1);
1192 assert_eq!(hits[0].entity.name, "Shai");
1193 assert_eq!(hits[0].relations.len(), 1);
1194 }
1195
1196 #[tokio::test]
1197 async fn search_matches_individual_query_tokens() {
1198 let kg = svc().await;
1199 kg.create_entities(
1200 "app",
1201 "alex",
1202 vec![CreateEntityInput {
1203 name: "Alex".into(),
1204 entity_type: "person".into(),
1205 observations: vec!["vegetarian".into(), "severely allergic to peanuts".into()],
1206 }],
1207 )
1208 .await
1209 .unwrap();
1210
1211 let hits =
1214 kg.search_nodes("app", "alex", "peanuts and vegetarian dishes", 5).await.unwrap();
1215 assert_eq!(hits.len(), 1);
1216 assert_eq!(hits[0].entity.name, "Alex");
1217
1218 let none = kg.search_nodes("app", "alex", "quarterly revenue forecast", 5).await.unwrap();
1220 assert!(none.is_empty());
1221 }
1222
1223 #[tokio::test]
1224 async fn episodic_recall_ranks_by_token_overlap() {
1225 let kg = svc().await;
1226 kg.add_session(
1227 "app",
1228 "alex",
1229 "s1",
1230 vec![
1231 entry("user", "I am training for a marathon in April"),
1232 entry("user", "I work at Acme Corp as a data engineer"),
1233 ],
1234 )
1235 .await
1236 .unwrap();
1237
1238 let resp = kg
1241 .search(SearchRequest {
1242 query: "where does the user work".into(),
1243 user_id: "alex".into(),
1244 app_name: "app".into(),
1245 limit: Some(5),
1246 min_score: None,
1247 project_id: None,
1248 })
1249 .await
1250 .unwrap();
1251 let joined: String =
1252 resp.memories.iter().map(|m| content_text(&m.content)).collect::<Vec<_>>().join(" ");
1253 assert!(joined.contains("Acme"), "expected the Acme turn; got: {joined}");
1254 assert!(!joined.contains("marathon"), "marathon turn shares no token; got: {joined}");
1255 }
1256
1257 #[test]
1258 fn tokenize_drops_stopwords_and_short_tokens() {
1259 let t = tokenize("What do you know about my allergies?");
1260 assert!(t.contains(&"allergies".to_string()));
1261 assert!(!t.iter().any(|w| w == "you" || w == "what" || w == "do"));
1262 assert_eq!(tokenize("is it?"), vec!["is it?".to_string()]);
1264 }
1265
1266 #[tokio::test]
1267 async fn merge_observations_on_duplicate_entity() {
1268 let kg = svc().await;
1269 let mk = |obs: &str| CreateEntityInput {
1270 name: "Shai".into(),
1271 entity_type: "person".into(),
1272 observations: vec![obs.into()],
1273 };
1274 kg.create_entities("app", "u", vec![mk("Likes breath work")]).await.unwrap();
1275 kg.create_entities("app", "u", vec![mk("Dislikes somatic grounding")]).await.unwrap();
1276
1277 assert_eq!(kg.entity_count("app", "u").await.unwrap(), 1, "entity must not duplicate");
1278 let (entities, _) = kg.read_graph("app", "u").await.unwrap();
1279 assert_eq!(entities[0].observations.len(), 2, "observations must merge");
1280 }
1281
1282 #[tokio::test]
1283 async fn bitemporal_supersede_hides_stale_facts() {
1284 let kg = svc().await;
1285 kg.create_entities(
1286 "app",
1287 "u",
1288 vec![CreateEntityInput {
1289 name: "Shai".into(),
1290 entity_type: "person".into(),
1291 observations: vec!["Lives in the Bay Area".into()],
1292 }],
1293 )
1294 .await
1295 .unwrap();
1296 let (e, _) = kg.read_graph("app", "u").await.unwrap();
1297 let stale_id = e[0].observations[0].id;
1298
1299 kg.invalidate_observation(stale_id).await.unwrap();
1301 kg.add_observations("app", "u", "Shai", vec!["Moved to Austin".into()]).await.unwrap();
1302
1303 let (e, _) = kg.read_graph("app", "u").await.unwrap();
1304 let current: Vec<&str> = e[0].observations.iter().map(|o| o.content.as_str()).collect();
1305 assert_eq!(current, vec!["Moved to Austin"], "stale fact must not surface");
1306 }
1307
1308 #[tokio::test]
1309 async fn memoryservice_add_session_then_recall() {
1310 let kg = svc().await;
1311 kg.add_session(
1312 "app",
1313 "u",
1314 "s1",
1315 vec![
1316 entry("user", "I want to talk about my sleep schedule"),
1317 entry("model", "Tell me more"),
1318 ],
1319 )
1320 .await
1321 .unwrap();
1322
1323 let resp = kg
1324 .search(SearchRequest {
1325 query: "sleep".into(),
1326 user_id: "u".into(),
1327 app_name: "app".into(),
1328 limit: Some(5),
1329 min_score: None,
1330 project_id: None,
1331 })
1332 .await
1333 .unwrap();
1334 assert!(
1335 resp.memories.iter().any(|m| content_text(&m.content).contains("sleep schedule")),
1336 "episodic recall should find the turn"
1337 );
1338 }
1339
1340 #[tokio::test]
1341 async fn profile_card_is_returned_for_session_context() {
1342 let kg = svc().await;
1343 kg.create_entities(
1344 "app",
1345 "u",
1346 vec![CreateEntityInput {
1347 name: "Shai".into(),
1348 entity_type: "person".into(),
1349 observations: vec!["Prefers to be addressed by name".into()],
1350 }],
1351 )
1352 .await
1353 .unwrap();
1354
1355 let resp = kg
1356 .search(SearchRequest {
1357 query: PROFILE_QUERY.into(),
1358 user_id: "u".into(),
1359 app_name: "app".into(),
1360 limit: Some(10),
1361 min_score: None,
1362 project_id: None,
1363 })
1364 .await
1365 .unwrap();
1366 assert_eq!(resp.memories.len(), 1);
1367 let card = content_text(&resp.memories[0].content);
1368 assert!(card.contains("Shai"));
1369 assert!(card.contains("addressed by name"));
1370 }
1371
1372 #[tokio::test]
1373 async fn delete_user_clears_everything() {
1374 let kg = svc().await;
1375 kg.create_entities(
1376 "app",
1377 "u",
1378 vec![CreateEntityInput {
1379 name: "X".into(),
1380 entity_type: "t".into(),
1381 observations: vec!["o".into()],
1382 }],
1383 )
1384 .await
1385 .unwrap();
1386 kg.add_session("app", "u", "s", vec![entry("user", "hello")]).await.unwrap();
1387
1388 kg.delete_user("app", "u").await.unwrap();
1389 assert_eq!(kg.entity_count("app", "u").await.unwrap(), 0);
1390 let (e, r) = kg.read_graph("app", "u").await.unwrap();
1391 assert!(e.is_empty() && r.is_empty());
1392 }
1393
1394 #[tokio::test]
1395 async fn per_user_isolation() {
1396 let kg = svc().await;
1397 kg.create_entities(
1398 "app",
1399 "alice",
1400 vec![CreateEntityInput {
1401 name: "Secret".into(),
1402 entity_type: "t".into(),
1403 observations: vec![],
1404 }],
1405 )
1406 .await
1407 .unwrap();
1408 assert_eq!(kg.entity_count("app", "alice").await.unwrap(), 1);
1409 assert_eq!(kg.entity_count("app", "bob").await.unwrap(), 0, "users must be isolated");
1410 }
1411
1412 #[tokio::test]
1413 async fn cascade_delete_removes_relations() {
1414 let kg = svc().await;
1415 kg.create_entities(
1416 "app",
1417 "u",
1418 vec![
1419 CreateEntityInput {
1420 name: "A".into(),
1421 entity_type: "t".into(),
1422 observations: vec![],
1423 },
1424 CreateEntityInput {
1425 name: "B".into(),
1426 entity_type: "t".into(),
1427 observations: vec![],
1428 },
1429 ],
1430 )
1431 .await
1432 .unwrap();
1433 kg.create_relations(
1434 "app",
1435 "u",
1436 vec![CreateRelationInput {
1437 source: "A".into(),
1438 relation_type: "knows".into(),
1439 target: "B".into(),
1440 }],
1441 )
1442 .await
1443 .unwrap();
1444
1445 kg.delete_entities("app", "u", vec!["A".into()]).await.unwrap();
1446 let (_, relations) = kg.read_graph("app", "u").await.unwrap();
1447 assert!(relations.is_empty(), "relations touching a deleted entity must be removed");
1448 }
1449}