Skip to main content

adk_harness/facts/
store.rs

1//! `FactStore`: the system of record of long-term facts (spec 3.1 §7.15.2).
2
3use std::collections::HashMap;
4use std::path::PathBuf;
5
6use adk_core::principal::SubjectRef;
7use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
8use async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use tokio::sync::{Mutex, RwLock};
12
13use super::consolidate::ConsolidationRecord;
14use super::types::{FactFilter, FactScope, FactSource, FactStatus, MemoryFact};
15
16/// A fact's vector and the id of the embedder that produced it (spec 3.1 §7.32, I73).
17///
18/// Recall compares vectors of one embedder only: a vector whose `embedder` differs from
19/// the index's is embedded again, even when the two models share a length. Vectors
20/// stored before the id existed read back with an empty `embedder`.
21///
22/// # Example
23///
24/// ```rust
25/// use adk_harness::FactEmbedding;
26///
27/// let embedding = FactEmbedding::new("onnx/BAAI/bge-small-en-v1.5", vec![0.6, 0.8]);
28/// assert!(embedding.is_from("onnx/BAAI/bge-small-en-v1.5"));
29/// assert!(!embedding.is_from("gemini/gemini-embedding-2"));
30/// ```
31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32pub struct FactEmbedding {
33    /// The embedder's id: its [`adk_memory::EmbeddingProvider::model_id`], or
34    /// `unnamed/<dimensions>` for an embedder without one.
35    pub embedder: String,
36    /// The vector.
37    pub vector: Vec<f32>,
38}
39
40impl FactEmbedding {
41    /// `vector`, produced by the embedder `embedder`.
42    pub fn new(embedder: impl Into<String>, vector: Vec<f32>) -> Self {
43        Self { embedder: embedder.into(), vector }
44    }
45
46    /// Whether the embedder `embedder` produced this vector, and it is usable.
47    pub fn is_from(&self, embedder: &str) -> bool {
48        !self.vector.is_empty() && self.embedder == embedder
49    }
50}
51
52/// A stored vector: tagged, or a bare vector written before embedder ids existed.
53#[derive(Clone, Debug, Serialize, Deserialize)]
54#[serde(untagged)]
55enum StoredEmbedding {
56    Tagged(FactEmbedding),
57    Untagged(Vec<f32>),
58}
59
60impl From<StoredEmbedding> for FactEmbedding {
61    fn from(stored: StoredEmbedding) -> Self {
62        match stored {
63            StoredEmbedding::Tagged(embedding) => embedding,
64            StoredEmbedding::Untagged(vector) => Self::new("", vector),
65        }
66    }
67}
68
69/// The system of record of long-term facts (spec 3.1 §7.15.2).
70///
71/// The store keeps every fact with its provenance and history; a [`FactIndex`] only finds
72/// candidates, so status, scope and forgetting are enforced by reading the store
73/// (spec 3.1 §9.2 I44). Implementations: [`InMemoryFactStore`], [`FileFactStore`], with
74/// feature `sqlite` `SqliteFactStore`, and with feature `postgres` `PostgresFactStore`, the
75/// shared store of `adk-rust up --store postgres://…` (spec 3.3 §12 phase 3).
76///
77/// | Method | Contract |
78/// |---|---|
79/// | `put` | stores a fact; a live fact with the same (scope, digest) is kept instead, its `uses` bumped, and returned |
80/// | `set_status` | changes a live fact's status; `Superseded` and `Forgotten` set `valid_to`; promoting `Assumed` to `Known` records the source `UserConfirmed`; a fact that is no longer live keeps its status |
81/// | `put_embedding`, `embeddings` | one vector per fact, tagged with the id of the embedder that produced it; `embeddings` returns those of the live facts of exactly `scope` (spec 3.1 §7.32, I73) |
82/// | `record_recall` | sets `last_recalled` and bumps `uses` of recalled facts |
83/// | `distilled_sessions`, `mark_distilled` | the cursor of the sessions distillation read, which only moves forward (spec 3.2 §10 HK2) |
84/// | `put_consolidation`, `consolidations` | the records of consolidation ticks, newest first (spec 3.2 §7.5) |
85/// | `restore_assumed` | sets a superseded or forgotten fact back to `Assumed`, clearing `valid_to`: how `undo` reverts a tick |
86///
87/// [`FactIndex`]: crate::FactIndex
88///
89/// # Example
90///
91/// ```rust
92/// use adk_harness::{FactKind, FactScope, FactSource, FactStatus, FactStore, InMemoryFactStore, MemoryFact, Provenance};
93///
94/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
95/// let store = InMemoryFactStore::new();
96/// let scope = FactScope::new("app", "alice", None);
97/// let fact = MemoryFact::new(scope, FactKind::Preference, "Use pnpm, not npm", FactStatus::Known,
98///     Provenance::new(FactSource::UserStated, "s1", "inv-1"));
99/// let stored = store.put(fact.clone()).await.unwrap();
100/// let again = store.put(MemoryFact { id: "other".into(), ..fact }).await.unwrap();
101/// assert_eq!((again.id, again.uses), (stored.id, 1));
102/// # });
103/// ```
104#[async_trait]
105pub trait FactStore: Send + Sync {
106    /// Stores `fact`, or bumps and returns the live fact with the same (scope, digest).
107    async fn put(&self, fact: MemoryFact) -> Result<MemoryFact>;
108    /// The fact with `id`.
109    async fn get(&self, id: &str) -> Result<Option<MemoryFact>>;
110    /// The facts `filter` matches, newest first.
111    async fn list(&self, filter: FactFilter) -> Result<Vec<MemoryFact>>;
112    /// Changes the status of the live fact `id`; `by` is the person or service doing it.
113    async fn set_status(&self, id: &str, status: FactStatus, by: &SubjectRef) -> Result<()>;
114    /// Stores the embedding of fact `id`, replacing an earlier one.
115    async fn put_embedding(&self, id: &str, embedding: FactEmbedding) -> Result<()>;
116    /// The embeddings of the live facts of exactly `scope`, each with its embedder's id.
117    async fn embeddings(&self, scope: &FactScope) -> Result<Vec<(String, FactEmbedding)>>;
118    /// Records that `ids` were recalled at `at`: `last_recalled` is set and `uses` bumped.
119    /// The default does nothing.
120    async fn record_recall(&self, ids: &[String], at: DateTime<Utc>) -> Result<()> {
121        let _ = (ids, at);
122        Ok(())
123    }
124
125    /// The sessions of `user` of `app` that distillation has read, each with the time of
126    /// the last event it read (spec 3.2 §10 HK2): the cursor that keeps a consolidation tick
127    /// from distilling a session the per-session distiller already handled. The default
128    /// keeps no cursor.
129    async fn distilled_sessions(
130        &self,
131        app: &str,
132        user: &str,
133    ) -> Result<Vec<(String, DateTime<Utc>)>> {
134        let _ = (app, user);
135        Ok(Vec::new())
136    }
137
138    /// Records that distillation read session `session` of `user` of `app` up to `upto`;
139    /// an earlier `upto` than the recorded one changes nothing (spec 3.2 §10 HK2). The
140    /// default does nothing.
141    async fn mark_distilled(
142        &self,
143        app: &str,
144        user: &str,
145        session: &str,
146        upto: DateTime<Utc>,
147    ) -> Result<()> {
148        let _ = (app, user, session, upto);
149        Ok(())
150    }
151
152    /// Stores, or replaces, the record of consolidation tick `record.tick_id`
153    /// (spec 3.2 §7.5).
154    ///
155    /// # Errors
156    ///
157    /// The default returns `harness.memory.consolidation_unsupported`: a tick runs only
158    /// on a store that keeps its record, so `undo` can revert it.
159    async fn put_consolidation(&self, record: &ConsolidationRecord) -> Result<()> {
160        let _ = record;
161        Err(consolidation_unsupported())
162    }
163
164    /// The consolidation records of `user` of `app`, newest first (spec 3.2 §7.5). The
165    /// default has none.
166    async fn consolidations(&self, app: &str, user: &str) -> Result<Vec<ConsolidationRecord>> {
167        let _ = (app, user);
168        Ok(Vec::new())
169    }
170
171    /// Sets fact `id`, superseded or forgotten, back to `Assumed` and clears `valid_to`
172    /// (spec 3.2 §7.5): how `undo` reverts a consolidation tick, which changes only
173    /// `Assumed` facts. `by` is the person or service doing it.
174    ///
175    /// # Errors
176    ///
177    /// Returns `harness.memory.fact_not_found`, `harness.memory.fact_live` for a fact that
178    /// is live, or, by default, `harness.memory.consolidation_unsupported`.
179    async fn restore_assumed(&self, id: &str, by: &SubjectRef) -> Result<()> {
180        let _ = (id, by);
181        Err(consolidation_unsupported())
182    }
183}
184
185fn consolidation_unsupported() -> AdkError {
186    AdkError::new(
187        ErrorComponent::Agent,
188        ErrorCategory::Unsupported,
189        "harness.memory.consolidation_unsupported",
190        "this fact store keeps no consolidation records, so a tick could not be undone; use \
191         InMemoryFactStore, FileFactStore, SqliteFactStore or PostgresFactStore, or implement \
192         put_consolidation, consolidations and restore_assumed",
193    )
194}
195
196fn still_live(fact: &MemoryFact) -> AdkError {
197    AdkError::new(
198        ErrorComponent::Agent,
199        ErrorCategory::Conflict,
200        "harness.memory.fact_live",
201        format!(
202            "fact '{}' is {}; only a superseded or forgotten fact is restored",
203            fact.id,
204            fact.status.label()
205        ),
206    )
207}
208
209/// Sets a superseded or forgotten `fact` back to `Assumed`.
210pub(crate) fn apply_restore(fact: &mut MemoryFact) -> Result<()> {
211    if fact.status.is_live() {
212        return Err(still_live(fact));
213    }
214    fact.status = FactStatus::Assumed;
215    fact.valid_to = None;
216    Ok(())
217}
218
219/// The key of a session's distillation cursor in the in-memory and file stores.
220fn cursor_key(app: &str, user: &str, session: &str) -> String {
221    format!("{app}\u{1f}{user}\u{1f}{session}")
222}
223
224pub(crate) fn not_found(id: &str) -> AdkError {
225    AdkError::new(
226        ErrorComponent::Agent,
227        ErrorCategory::NotFound,
228        "harness.memory.fact_not_found",
229        format!("there is no fact '{id}'; /memory lists the facts"),
230    )
231}
232
233fn not_live(fact: &MemoryFact) -> AdkError {
234    AdkError::new(
235        ErrorComponent::Agent,
236        ErrorCategory::Conflict,
237        "harness.memory.fact_not_live",
238        format!(
239            "fact '{}' is {} and keeps that status; record the fact again instead",
240            fact.id,
241            fact.status.label()
242        ),
243    )
244}
245
246/// Applies a status change to `fact` under the store contract.
247pub(crate) fn apply_status(fact: &mut MemoryFact, status: FactStatus) -> Result<()> {
248    if !fact.status.is_live() {
249        return Err(not_live(fact));
250    }
251    if status == FactStatus::Known
252        && fact.status == FactStatus::Assumed
253        && fact.provenance.source != FactSource::UserStated
254    {
255        fact.provenance.source = FactSource::UserConfirmed;
256    }
257    if !status.is_live() {
258        fact.valid_to = Some(Utc::now());
259    }
260    fact.status = status;
261    Ok(())
262}
263
264fn same_live(a: &MemoryFact, b: &MemoryFact) -> bool {
265    a.status.is_live() && a.scope == b.scope && a.digest == b.digest
266}
267
268fn sort_newest_first(facts: &mut [MemoryFact]) {
269    facts.sort_by(|a, b| b.valid_from.cmp(&a.valid_from).then_with(|| b.id.cmp(&a.id)));
270}
271
272#[derive(Default, Serialize, Deserialize)]
273struct Facts {
274    #[serde(default)]
275    facts: HashMap<String, MemoryFact>,
276    #[serde(default)]
277    embeddings: HashMap<String, StoredEmbedding>,
278    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
279    cursors: HashMap<String, DateTime<Utc>>,
280    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
281    ticks: HashMap<String, ConsolidationRecord>,
282}
283
284impl Facts {
285    fn put(&mut self, fact: MemoryFact) -> MemoryFact {
286        if let Some(existing) = self.facts.values_mut().find(|existing| same_live(existing, &fact))
287        {
288            existing.uses = existing.uses.saturating_add(1);
289            return existing.clone();
290        }
291        self.facts.insert(fact.id.clone(), fact.clone());
292        fact
293    }
294
295    fn list(&self, filter: &FactFilter) -> Vec<MemoryFact> {
296        let mut facts: Vec<MemoryFact> =
297            self.facts.values().filter(|fact| filter.matches(fact)).cloned().collect();
298        sort_newest_first(&mut facts);
299        facts
300    }
301
302    fn set_status(&mut self, id: &str, status: FactStatus) -> Result<()> {
303        let fact = self.facts.get_mut(id).ok_or_else(|| not_found(id))?;
304        apply_status(fact, status)
305    }
306
307    fn put_embedding(&mut self, id: &str, embedding: FactEmbedding) -> Result<()> {
308        if !self.facts.contains_key(id) {
309            return Err(not_found(id));
310        }
311        self.embeddings.insert(id.to_string(), StoredEmbedding::Tagged(embedding));
312        Ok(())
313    }
314
315    fn embeddings(&self, scope: &FactScope) -> Vec<(String, FactEmbedding)> {
316        let mut out: Vec<(String, FactEmbedding)> = self
317            .embeddings
318            .iter()
319            .filter(|(id, _)| {
320                self.facts
321                    .get(*id)
322                    .is_some_and(|fact| fact.status.is_live() && fact.scope == *scope)
323            })
324            .map(|(id, stored)| (id.clone(), stored.clone().into()))
325            .collect();
326        out.sort_by(|a, b| a.0.cmp(&b.0));
327        out
328    }
329
330    fn record_recall(&mut self, ids: &[String], at: DateTime<Utc>) {
331        for id in ids {
332            if let Some(fact) = self.facts.get_mut(id) {
333                fact.last_recalled = Some(at);
334                fact.uses = fact.uses.saturating_add(1);
335            }
336        }
337    }
338
339    fn distilled_sessions(&self, app: &str, user: &str) -> Vec<(String, DateTime<Utc>)> {
340        let prefix = cursor_key(app, user, "");
341        let mut out: Vec<(String, DateTime<Utc>)> = self
342            .cursors
343            .iter()
344            .filter_map(|(key, upto)| Some((key.strip_prefix(&prefix)?.to_string(), *upto)))
345            .collect();
346        out.sort();
347        out
348    }
349
350    fn mark_distilled(&mut self, app: &str, user: &str, session: &str, upto: DateTime<Utc>) {
351        let cursor = self.cursors.entry(cursor_key(app, user, session)).or_insert(upto);
352        *cursor = (*cursor).max(upto);
353    }
354
355    fn consolidations(&self, app: &str, user: &str) -> Vec<ConsolidationRecord> {
356        let mut out: Vec<ConsolidationRecord> = self
357            .ticks
358            .values()
359            .filter(|record| record.app == app && record.user == user)
360            .cloned()
361            .collect();
362        out.sort_by(|a, b| b.at.cmp(&a.at).then_with(|| b.tick_id.cmp(&a.tick_id)));
363        out
364    }
365
366    fn restore_assumed(&mut self, id: &str) -> Result<()> {
367        apply_restore(self.facts.get_mut(id).ok_or_else(|| not_found(id))?)
368    }
369}
370
371/// A [`FactStore`] in process memory, the builder default (spec 3.1 §7.2).
372///
373/// # Example
374///
375/// ```rust
376/// let store = adk_harness::InMemoryFactStore::new();
377/// # let _ = store;
378/// ```
379#[derive(Default)]
380pub struct InMemoryFactStore {
381    facts: RwLock<Facts>,
382}
383
384impl std::fmt::Debug for InMemoryFactStore {
385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386        f.debug_struct("InMemoryFactStore").finish_non_exhaustive()
387    }
388}
389
390impl InMemoryFactStore {
391    /// An empty store.
392    pub fn new() -> Self {
393        Self::default()
394    }
395}
396
397#[async_trait]
398impl FactStore for InMemoryFactStore {
399    async fn put(&self, fact: MemoryFact) -> Result<MemoryFact> {
400        Ok(self.facts.write().await.put(fact))
401    }
402
403    async fn get(&self, id: &str) -> Result<Option<MemoryFact>> {
404        Ok(self.facts.read().await.facts.get(id).cloned())
405    }
406
407    async fn list(&self, filter: FactFilter) -> Result<Vec<MemoryFact>> {
408        Ok(self.facts.read().await.list(&filter))
409    }
410
411    async fn set_status(&self, id: &str, status: FactStatus, _by: &SubjectRef) -> Result<()> {
412        self.facts.write().await.set_status(id, status)
413    }
414
415    async fn put_embedding(&self, id: &str, embedding: FactEmbedding) -> Result<()> {
416        self.facts.write().await.put_embedding(id, embedding)
417    }
418
419    async fn embeddings(&self, scope: &FactScope) -> Result<Vec<(String, FactEmbedding)>> {
420        Ok(self.facts.read().await.embeddings(scope))
421    }
422
423    async fn record_recall(&self, ids: &[String], at: DateTime<Utc>) -> Result<()> {
424        self.facts.write().await.record_recall(ids, at);
425        Ok(())
426    }
427
428    async fn distilled_sessions(
429        &self,
430        app: &str,
431        user: &str,
432    ) -> Result<Vec<(String, DateTime<Utc>)>> {
433        Ok(self.facts.read().await.distilled_sessions(app, user))
434    }
435
436    async fn mark_distilled(
437        &self,
438        app: &str,
439        user: &str,
440        session: &str,
441        upto: DateTime<Utc>,
442    ) -> Result<()> {
443        self.facts.write().await.mark_distilled(app, user, session, upto);
444        Ok(())
445    }
446
447    async fn put_consolidation(&self, record: &ConsolidationRecord) -> Result<()> {
448        self.facts.write().await.ticks.insert(record.tick_id.clone(), record.clone());
449        Ok(())
450    }
451
452    async fn consolidations(&self, app: &str, user: &str) -> Result<Vec<ConsolidationRecord>> {
453        Ok(self.facts.read().await.consolidations(app, user))
454    }
455
456    async fn restore_assumed(&self, id: &str, _by: &SubjectRef) -> Result<()> {
457        self.facts.write().await.restore_assumed(id)
458    }
459}
460
461/// A [`FactStore`] of one private JSON file per user (spec 3.1 §7.15.2).
462///
463/// Files are `<root>/<sha256(app, user)>.json`, written to a temporary sibling and renamed
464/// into place with mode `0600` on Unix, so no identifier reaches a path. Writers in one
465/// process take turns; the default root is `~/.adk/harness/facts`.
466///
467/// # Example
468///
469/// ```rust
470/// use adk_harness::{FactKind, FactScope, FactSource, FactStatus, FactStore, FileFactStore, MemoryFact, Provenance};
471///
472/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
473/// let dir = tempfile::tempdir().unwrap();
474/// let fact = MemoryFact::new(FactScope::new("app", "alice", None), FactKind::Preference,
475///     "Use pnpm", FactStatus::Assumed, Provenance::new(FactSource::AgentInferred, "s", "i"));
476/// FileFactStore::new(dir.path()).put(fact.clone()).await.unwrap();
477/// assert!(FileFactStore::new(dir.path()).get(&fact.id).await.unwrap().is_some());
478/// # });
479/// ```
480#[derive(Debug)]
481pub struct FileFactStore {
482    root: PathBuf,
483    lock: Mutex<()>,
484}
485
486impl FileFactStore {
487    /// A store under `root`, created on first write.
488    pub fn new(root: impl Into<PathBuf>) -> Self {
489        Self { root: root.into(), lock: Mutex::new(()) }
490    }
491
492    /// A store under `~/.adk/harness/facts`.
493    ///
494    /// # Errors
495    ///
496    /// Returns a configuration error when the home directory cannot be determined.
497    pub fn in_home() -> Result<Self> {
498        Ok(Self::new(crate::fsutil::adk_home()?.join("harness").join("facts")))
499    }
500
501    fn path(&self, app: &str, user: &str) -> PathBuf {
502        self.root.join(format!("{}.json", crate::fsutil::sha256_hex(&format!("{app}\u{1f}{user}"))))
503    }
504
505    async fn load(path: &std::path::Path) -> Result<Facts> {
506        match crate::fsutil::read_optional(path).await? {
507            Some(bytes) => serde_json::from_slice(&bytes).map_err(|error| {
508                AdkError::new(
509                    ErrorComponent::Agent,
510                    ErrorCategory::Internal,
511                    "harness.memory.store_corrupt",
512                    format!("{} is not a fact file: {error}", path.display()),
513                )
514            }),
515            None => Ok(Facts::default()),
516        }
517    }
518
519    async fn save(path: &std::path::Path, facts: &Facts) -> Result<()> {
520        let bytes = serde_json::to_vec(facts)
521            .map_err(|error| crate::fsutil::serialize_error("facts", &error))?;
522        crate::fsutil::write_atomic_private(path, &bytes).await
523    }
524
525    /// The files of every user.
526    async fn all_files(&self) -> Result<Vec<PathBuf>> {
527        let mut entries = match tokio::fs::read_dir(&self.root).await {
528            Ok(entries) => entries,
529            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
530            Err(error) => {
531                return Err(AdkError::new(
532                    ErrorComponent::Agent,
533                    ErrorCategory::Unavailable,
534                    "harness.store.io",
535                    format!("read {}: {error}", self.root.display()),
536                ));
537            }
538        };
539        let mut files = Vec::new();
540        while let Ok(Some(entry)) = entries.next_entry().await {
541            let path = entry.path();
542            if path.extension().is_some_and(|ext| ext == "json") {
543                files.push(path);
544            }
545        }
546        Ok(files)
547    }
548
549    /// The file holding fact `id`, with its contents.
550    async fn find(&self, id: &str) -> Result<Option<(PathBuf, Facts)>> {
551        for path in self.all_files().await? {
552            let facts = Self::load(&path).await?;
553            if facts.facts.contains_key(id) {
554                return Ok(Some((path, facts)));
555            }
556        }
557        Ok(None)
558    }
559}
560
561#[async_trait]
562impl FactStore for FileFactStore {
563    async fn put(&self, fact: MemoryFact) -> Result<MemoryFact> {
564        let _guard = self.lock.lock().await;
565        let path = self.path(&fact.scope.app, &fact.scope.user);
566        let mut facts = Self::load(&path).await?;
567        let stored = facts.put(fact);
568        Self::save(&path, &facts).await?;
569        Ok(stored)
570    }
571
572    async fn get(&self, id: &str) -> Result<Option<MemoryFact>> {
573        Ok(self.find(id).await?.and_then(|(_, facts)| facts.facts.get(id).cloned()))
574    }
575
576    async fn list(&self, filter: FactFilter) -> Result<Vec<MemoryFact>> {
577        Ok(Self::load(&self.path(&filter.app, &filter.user)).await?.list(&filter))
578    }
579
580    async fn set_status(&self, id: &str, status: FactStatus, _by: &SubjectRef) -> Result<()> {
581        let _guard = self.lock.lock().await;
582        let (path, mut facts) = self.find(id).await?.ok_or_else(|| not_found(id))?;
583        facts.set_status(id, status)?;
584        Self::save(&path, &facts).await
585    }
586
587    async fn put_embedding(&self, id: &str, embedding: FactEmbedding) -> Result<()> {
588        let _guard = self.lock.lock().await;
589        let (path, mut facts) = self.find(id).await?.ok_or_else(|| not_found(id))?;
590        facts.put_embedding(id, embedding)?;
591        Self::save(&path, &facts).await
592    }
593
594    async fn embeddings(&self, scope: &FactScope) -> Result<Vec<(String, FactEmbedding)>> {
595        Ok(Self::load(&self.path(&scope.app, &scope.user)).await?.embeddings(scope))
596    }
597
598    async fn record_recall(&self, ids: &[String], at: DateTime<Utc>) -> Result<()> {
599        let _guard = self.lock.lock().await;
600        for path in self.all_files().await? {
601            let mut facts = Self::load(&path).await?;
602            if ids.iter().any(|id| facts.facts.contains_key(id)) {
603                facts.record_recall(ids, at);
604                Self::save(&path, &facts).await?;
605            }
606        }
607        Ok(())
608    }
609
610    async fn distilled_sessions(
611        &self,
612        app: &str,
613        user: &str,
614    ) -> Result<Vec<(String, DateTime<Utc>)>> {
615        Ok(Self::load(&self.path(app, user)).await?.distilled_sessions(app, user))
616    }
617
618    async fn mark_distilled(
619        &self,
620        app: &str,
621        user: &str,
622        session: &str,
623        upto: DateTime<Utc>,
624    ) -> Result<()> {
625        let _guard = self.lock.lock().await;
626        let path = self.path(app, user);
627        let mut facts = Self::load(&path).await?;
628        facts.mark_distilled(app, user, session, upto);
629        Self::save(&path, &facts).await
630    }
631
632    async fn put_consolidation(&self, record: &ConsolidationRecord) -> Result<()> {
633        let _guard = self.lock.lock().await;
634        let path = self.path(&record.app, &record.user);
635        let mut facts = Self::load(&path).await?;
636        facts.ticks.insert(record.tick_id.clone(), record.clone());
637        Self::save(&path, &facts).await
638    }
639
640    async fn consolidations(&self, app: &str, user: &str) -> Result<Vec<ConsolidationRecord>> {
641        Ok(Self::load(&self.path(app, user)).await?.consolidations(app, user))
642    }
643
644    async fn restore_assumed(&self, id: &str, _by: &SubjectRef) -> Result<()> {
645        let _guard = self.lock.lock().await;
646        let (path, mut facts) = self.find(id).await?.ok_or_else(|| not_found(id))?;
647        facts.restore_assumed(id)?;
648        Self::save(&path, &facts).await
649    }
650}
651
652/// A [`FactStore`] in SQLite (spec 3.1 §7.15.2, feature `sqlite`): the CLI keeps it in
653/// `harness.db`.
654///
655/// Call [`migrate`](Self::migrate) once before use. The tables are `adk_harness_facts` and
656/// `adk_harness_fact_embeddings`, distinct from every other store's tables. A change that
657/// reads a fact and writes it back opens with `BEGIN IMMEDIATE`, so it waits for another
658/// writer on the file under the pool's busy timeout instead of failing with `database is
659/// locked`.
660///
661/// # Example
662///
663/// ```rust,ignore
664/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await?;
665/// let store = adk_harness::SqliteFactStore::new(pool);
666/// store.migrate().await?;
667/// ```
668#[cfg(feature = "sqlite")]
669#[derive(Debug, Clone)]
670pub struct SqliteFactStore {
671    pool: sqlx::SqlitePool,
672    #[cfg(feature = "encrypted")]
673    envelope: Option<crate::encrypted::StoreEnvelope>,
674}
675
676/// Opens every transaction that reads a fact and writes it back. A deferred transaction that
677/// has read cannot wait for the write lock: SQLite fails its first write at once, whatever
678/// the busy timeout.
679#[cfg(feature = "sqlite")]
680const BEGIN_WRITE: &str = "BEGIN IMMEDIATE";
681
682#[cfg(feature = "sqlite")]
683impl SqliteFactStore {
684    /// A store over `pool`.
685    pub fn new(pool: sqlx::SqlitePool) -> Self {
686        Self {
687            pool,
688            #[cfg(feature = "encrypted")]
689            envelope: None,
690        }
691    }
692
693    /// Seals every record under `keyring` (spec 3.1 §7.12).
694    #[cfg(feature = "encrypted")]
695    #[must_use]
696    pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
697        self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "facts"));
698        self
699    }
700
701    /// Re-seals every record a previous key sealed with the current key, seals records
702    /// written before a key was configured, and returns how many rows changed (spec 3.1
703    /// §7.12). Without a keyring, nothing changes.
704    ///
705    /// # Errors
706    ///
707    /// Returns `harness.store.decrypt_failed` when a row opens under no key the keyring
708    /// holds, or the database error.
709    #[cfg(feature = "encrypted")]
710    pub async fn rewrap(&self) -> Result<u64> {
711        let Some(envelope) = &self.envelope else {
712            return Ok(0);
713        };
714        let rows: Vec<(String, String)> =
715            sqlx::query_as("SELECT id, record FROM adk_harness_facts")
716                .fetch_all(&self.pool)
717                .await
718                .map_err(crate::fsutil::db_error)?;
719        let mut changed = 0;
720        for (id, text) in rows {
721            if let Some(resealed) = envelope.reseal_or_seal(&[&id], &text)? {
722                sqlx::query("UPDATE adk_harness_facts SET record = ? WHERE id = ?")
723                    .bind(resealed)
724                    .bind(&id)
725                    .execute(&self.pool)
726                    .await
727                    .map_err(crate::fsutil::db_error)?;
728                changed += 1;
729            }
730        }
731        Ok(changed)
732    }
733
734    #[cfg(feature = "encrypted")]
735    fn encode(&self, address: &[&str], text: String) -> Result<String> {
736        crate::encrypted::encode_row(self.envelope.as_ref(), address, text)
737    }
738
739    #[cfg(not(feature = "encrypted"))]
740    fn encode(&self, _address: &[&str], text: String) -> Result<String> {
741        Ok(text)
742    }
743
744    #[cfg(feature = "encrypted")]
745    fn decode(&self, address: &[&str], text: String) -> Result<String> {
746        crate::encrypted::decode_row(self.envelope.as_ref(), "facts", address, text)
747    }
748
749    #[cfg(not(feature = "encrypted"))]
750    fn decode(&self, _address: &[&str], text: String) -> Result<String> {
751        Ok(text)
752    }
753
754    /// Creates the store's tables if they do not exist.
755    ///
756    /// # Errors
757    ///
758    /// Returns the database error when a statement fails.
759    pub async fn migrate(&self) -> Result<()> {
760        for statement in [
761            "CREATE TABLE IF NOT EXISTS adk_harness_facts (\
762                id TEXT PRIMARY KEY, app_name TEXT NOT NULL, user_id TEXT NOT NULL, \
763                project TEXT, digest TEXT NOT NULL, live INTEGER NOT NULL, \
764                valid_from TEXT NOT NULL, record TEXT NOT NULL)",
765            "CREATE INDEX IF NOT EXISTS adk_harness_facts_scope \
766                ON adk_harness_facts (app_name, user_id, project, digest)",
767            "CREATE TABLE IF NOT EXISTS adk_harness_fact_embeddings (\
768                id TEXT PRIMARY KEY, vector TEXT NOT NULL, embedder TEXT NOT NULL DEFAULT '')",
769            "CREATE TABLE IF NOT EXISTS adk_harness_fact_cursors (\
770                app_name TEXT NOT NULL, user_id TEXT NOT NULL, session_id TEXT NOT NULL, \
771                upto TEXT NOT NULL, PRIMARY KEY (app_name, user_id, session_id))",
772            "CREATE TABLE IF NOT EXISTS adk_harness_fact_ticks (\
773                tick_id TEXT PRIMARY KEY, app_name TEXT NOT NULL, user_id TEXT NOT NULL, \
774                at TEXT NOT NULL, record TEXT NOT NULL)",
775        ] {
776            sqlx::query(statement).execute(&self.pool).await.map_err(crate::fsutil::db_error)?;
777        }
778        // Tables created before embedder ids (spec 3.1 §7.32) gain the column; their
779        // vectors read back untagged and are embedded again when recall needs them.
780        let (tagged,): (i64,) = sqlx::query_as(
781            "SELECT COUNT(*) FROM pragma_table_info('adk_harness_fact_embeddings') \
782             WHERE name = 'embedder'",
783        )
784        .fetch_one(&self.pool)
785        .await
786        .map_err(crate::fsutil::db_error)?;
787        if tagged == 0 {
788            sqlx::query(
789                "ALTER TABLE adk_harness_fact_embeddings \
790                 ADD COLUMN embedder TEXT NOT NULL DEFAULT ''",
791            )
792            .execute(&self.pool)
793            .await
794            .map_err(crate::fsutil::db_error)?;
795        }
796        Ok(())
797    }
798
799    fn decode_fact(&self, id: &str, text: String) -> Result<MemoryFact> {
800        let text = self.decode(&[id], text)?;
801        serde_json::from_str(&text).map_err(|error| {
802            AdkError::new(
803                ErrorComponent::Agent,
804                ErrorCategory::Internal,
805                "harness.memory.store_corrupt",
806                format!("a stored fact does not parse: {error}"),
807            )
808        })
809    }
810
811    async fn write(
812        &self,
813        executor: impl sqlx::Executor<'_, Database = sqlx::Sqlite>,
814        fact: &MemoryFact,
815    ) -> Result<()> {
816        let record = serde_json::to_string(fact)
817            .map_err(|error| crate::fsutil::serialize_error("fact", &error))?;
818        let record = self.encode(&[&fact.id], record)?;
819        sqlx::query(
820            "INSERT INTO adk_harness_facts (id, app_name, user_id, project, digest, live, valid_from, record) \
821             VALUES (?, ?, ?, ?, ?, ?, ?, ?) \
822             ON CONFLICT (id) DO UPDATE SET live = excluded.live, record = excluded.record",
823        )
824        .bind(&fact.id)
825        .bind(&fact.scope.app)
826        .bind(&fact.scope.user)
827        .bind(&fact.scope.project)
828        .bind(&fact.digest)
829        .bind(fact.status.is_live())
830        .bind(fact.valid_from.to_rfc3339())
831        .bind(record)
832        .execute(executor)
833        .await
834        .map_err(crate::fsutil::db_error)?;
835        Ok(())
836    }
837}
838
839#[cfg(feature = "sqlite")]
840#[async_trait]
841impl FactStore for SqliteFactStore {
842    async fn put(&self, fact: MemoryFact) -> Result<MemoryFact> {
843        let mut tx = self.pool.begin_with(BEGIN_WRITE).await.map_err(crate::fsutil::db_error)?;
844        let existing: Option<(String, String)> = sqlx::query_as(
845            "SELECT id, record FROM adk_harness_facts WHERE app_name = ? AND user_id = ? \
846             AND project IS ? AND digest = ? AND live = 1 LIMIT 1",
847        )
848        .bind(&fact.scope.app)
849        .bind(&fact.scope.user)
850        .bind(&fact.scope.project)
851        .bind(&fact.digest)
852        .fetch_optional(&mut *tx)
853        .await
854        .map_err(crate::fsutil::db_error)?;
855        let stored = match existing {
856            Some((id, record)) => {
857                let mut existing = self.decode_fact(&id, record)?;
858                existing.uses = existing.uses.saturating_add(1);
859                existing
860            }
861            None => fact,
862        };
863        self.write(&mut *tx, &stored).await?;
864        tx.commit().await.map_err(crate::fsutil::db_error)?;
865        Ok(stored)
866    }
867
868    async fn get(&self, id: &str) -> Result<Option<MemoryFact>> {
869        let row: Option<(String,)> =
870            sqlx::query_as("SELECT record FROM adk_harness_facts WHERE id = ?")
871                .bind(id)
872                .fetch_optional(&self.pool)
873                .await
874                .map_err(crate::fsutil::db_error)?;
875        row.map(|(record,)| self.decode_fact(id, record)).transpose()
876    }
877
878    async fn list(&self, filter: FactFilter) -> Result<Vec<MemoryFact>> {
879        let rows: Vec<(String, String)> = sqlx::query_as(
880            "SELECT id, record FROM adk_harness_facts WHERE app_name = ? AND user_id = ? \
881             AND (? = 0 OR live = 1)",
882        )
883        .bind(&filter.app)
884        .bind(&filter.user)
885        .bind(filter.live_only)
886        .fetch_all(&self.pool)
887        .await
888        .map_err(crate::fsutil::db_error)?;
889        let mut facts = Vec::with_capacity(rows.len());
890        for (id, record) in rows {
891            let fact = self.decode_fact(&id, record)?;
892            if filter.matches(&fact) {
893                facts.push(fact);
894            }
895        }
896        sort_newest_first(&mut facts);
897        Ok(facts)
898    }
899
900    async fn set_status(&self, id: &str, status: FactStatus, _by: &SubjectRef) -> Result<()> {
901        let mut tx = self.pool.begin_with(BEGIN_WRITE).await.map_err(crate::fsutil::db_error)?;
902        let row: Option<(String,)> =
903            sqlx::query_as("SELECT record FROM adk_harness_facts WHERE id = ?")
904                .bind(id)
905                .fetch_optional(&mut *tx)
906                .await
907                .map_err(crate::fsutil::db_error)?;
908        let mut fact = self.decode_fact(id, row.ok_or_else(|| not_found(id))?.0)?;
909        apply_status(&mut fact, status)?;
910        self.write(&mut *tx, &fact).await?;
911        tx.commit().await.map_err(crate::fsutil::db_error)
912    }
913
914    async fn put_embedding(&self, id: &str, embedding: FactEmbedding) -> Result<()> {
915        if self.get(id).await?.is_none() {
916            return Err(not_found(id));
917        }
918        let vector = serde_json::to_string(&embedding.vector)
919            .map_err(|error| crate::fsutil::serialize_error("embedding", &error))?;
920        sqlx::query(
921            "INSERT INTO adk_harness_fact_embeddings (id, vector, embedder) VALUES (?, ?, ?) \
922             ON CONFLICT (id) DO UPDATE SET vector = excluded.vector, \
923             embedder = excluded.embedder",
924        )
925        .bind(id)
926        .bind(vector)
927        .bind(&embedding.embedder)
928        .execute(&self.pool)
929        .await
930        .map_err(crate::fsutil::db_error)?;
931        Ok(())
932    }
933
934    async fn embeddings(&self, scope: &FactScope) -> Result<Vec<(String, FactEmbedding)>> {
935        let rows: Vec<(String, String, String)> = sqlx::query_as(
936            "SELECT e.id, e.vector, e.embedder FROM adk_harness_fact_embeddings e \
937             JOIN adk_harness_facts f ON f.id = e.id \
938             WHERE f.app_name = ? AND f.user_id = ? AND f.project IS ? AND f.live = 1 \
939             ORDER BY e.id",
940        )
941        .bind(&scope.app)
942        .bind(&scope.user)
943        .bind(&scope.project)
944        .fetch_all(&self.pool)
945        .await
946        .map_err(crate::fsutil::db_error)?;
947        Ok(rows
948            .into_iter()
949            .filter_map(|(id, vector, embedder)| {
950                serde_json::from_str::<Vec<f32>>(&vector)
951                    .ok()
952                    .map(|vector| (id, FactEmbedding::new(embedder, vector)))
953            })
954            .collect())
955    }
956
957    async fn record_recall(&self, ids: &[String], at: DateTime<Utc>) -> Result<()> {
958        for id in ids {
959            let mut tx =
960                self.pool.begin_with(BEGIN_WRITE).await.map_err(crate::fsutil::db_error)?;
961            let row: Option<(String,)> =
962                sqlx::query_as("SELECT record FROM adk_harness_facts WHERE id = ?")
963                    .bind(id)
964                    .fetch_optional(&mut *tx)
965                    .await
966                    .map_err(crate::fsutil::db_error)?;
967            if let Some((record,)) = row {
968                let mut fact = self.decode_fact(id, record)?;
969                fact.last_recalled = Some(at);
970                fact.uses = fact.uses.saturating_add(1);
971                self.write(&mut *tx, &fact).await?;
972            }
973            tx.commit().await.map_err(crate::fsutil::db_error)?;
974        }
975        Ok(())
976    }
977
978    async fn distilled_sessions(
979        &self,
980        app: &str,
981        user: &str,
982    ) -> Result<Vec<(String, DateTime<Utc>)>> {
983        let rows: Vec<(String, String)> = sqlx::query_as(
984            "SELECT session_id, upto FROM adk_harness_fact_cursors \
985             WHERE app_name = ? AND user_id = ? ORDER BY session_id",
986        )
987        .bind(app)
988        .bind(user)
989        .fetch_all(&self.pool)
990        .await
991        .map_err(crate::fsutil::db_error)?;
992        Ok(rows
993            .into_iter()
994            .filter_map(|(session, upto)| {
995                let upto = DateTime::parse_from_rfc3339(&upto).ok()?.with_timezone(&Utc);
996                Some((session, upto))
997            })
998            .collect())
999    }
1000
1001    async fn mark_distilled(
1002        &self,
1003        app: &str,
1004        user: &str,
1005        session: &str,
1006        upto: DateTime<Utc>,
1007    ) -> Result<()> {
1008        // A fixed-width UTC timestamp, so text order is time order.
1009        let upto = upto.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true);
1010        sqlx::query(
1011            "INSERT INTO adk_harness_fact_cursors (app_name, user_id, session_id, upto) \
1012             VALUES (?, ?, ?, ?) ON CONFLICT (app_name, user_id, session_id) \
1013             DO UPDATE SET upto = excluded.upto WHERE excluded.upto > adk_harness_fact_cursors.upto",
1014        )
1015        .bind(app)
1016        .bind(user)
1017        .bind(session)
1018        .bind(upto)
1019        .execute(&self.pool)
1020        .await
1021        .map_err(crate::fsutil::db_error)?;
1022        Ok(())
1023    }
1024
1025    async fn put_consolidation(&self, record: &ConsolidationRecord) -> Result<()> {
1026        let text = serde_json::to_string(record)
1027            .map_err(|error| crate::fsutil::serialize_error("consolidation record", &error))?;
1028        let text = self.encode(&["consolidation", &record.tick_id], text)?;
1029        sqlx::query(
1030            "INSERT INTO adk_harness_fact_ticks (tick_id, app_name, user_id, at, record) \
1031             VALUES (?, ?, ?, ?, ?) ON CONFLICT (tick_id) DO UPDATE SET record = excluded.record",
1032        )
1033        .bind(&record.tick_id)
1034        .bind(&record.app)
1035        .bind(&record.user)
1036        .bind(record.at.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true))
1037        .bind(text)
1038        .execute(&self.pool)
1039        .await
1040        .map_err(crate::fsutil::db_error)?;
1041        Ok(())
1042    }
1043
1044    async fn consolidations(&self, app: &str, user: &str) -> Result<Vec<ConsolidationRecord>> {
1045        let rows: Vec<(String, String)> = sqlx::query_as(
1046            "SELECT tick_id, record FROM adk_harness_fact_ticks \
1047             WHERE app_name = ? AND user_id = ? ORDER BY at DESC, tick_id DESC",
1048        )
1049        .bind(app)
1050        .bind(user)
1051        .fetch_all(&self.pool)
1052        .await
1053        .map_err(crate::fsutil::db_error)?;
1054        let mut out = Vec::with_capacity(rows.len());
1055        for (tick_id, text) in rows {
1056            let text = self.decode(&["consolidation", &tick_id], text)?;
1057            out.push(serde_json::from_str(&text).map_err(|error| {
1058                AdkError::new(
1059                    ErrorComponent::Agent,
1060                    ErrorCategory::Internal,
1061                    "harness.memory.store_corrupt",
1062                    format!("a stored consolidation record does not parse: {error}"),
1063                )
1064            })?);
1065        }
1066        Ok(out)
1067    }
1068
1069    async fn restore_assumed(&self, id: &str, _by: &SubjectRef) -> Result<()> {
1070        let mut tx = self.pool.begin_with(BEGIN_WRITE).await.map_err(crate::fsutil::db_error)?;
1071        let row: Option<(String,)> =
1072            sqlx::query_as("SELECT record FROM adk_harness_facts WHERE id = ?")
1073                .bind(id)
1074                .fetch_optional(&mut *tx)
1075                .await
1076                .map_err(crate::fsutil::db_error)?;
1077        let mut fact = self.decode_fact(id, row.ok_or_else(|| not_found(id))?.0)?;
1078        apply_restore(&mut fact)?;
1079        self.write(&mut *tx, &fact).await?;
1080        tx.commit().await.map_err(crate::fsutil::db_error)
1081    }
1082}
1083
1084/// Migrations of [`PostgresFactStore`], recorded in `_adk_harness_fact_migrations`.
1085#[cfg(feature = "postgres")]
1086const POSTGRES_FACT_MIGRATIONS: &[(i64, &str, &str)] = &[(
1087    1,
1088    "create long-term fact tables",
1089    "CREATE TABLE IF NOT EXISTS adk_harness_facts (\
1090        id TEXT PRIMARY KEY, app_name TEXT NOT NULL, user_id TEXT NOT NULL, \
1091        project TEXT, digest TEXT NOT NULL, live BOOLEAN NOT NULL, \
1092        valid_from TEXT NOT NULL, record TEXT NOT NULL); \
1093     CREATE INDEX IF NOT EXISTS adk_harness_facts_scope \
1094        ON adk_harness_facts (app_name, user_id, project, digest); \
1095     CREATE TABLE IF NOT EXISTS adk_harness_fact_embeddings (\
1096        id TEXT PRIMARY KEY, vector TEXT NOT NULL, embedder TEXT NOT NULL DEFAULT ''); \
1097     CREATE TABLE IF NOT EXISTS adk_harness_fact_cursors (\
1098        app_name TEXT NOT NULL, user_id TEXT NOT NULL, session_id TEXT NOT NULL, \
1099        upto TEXT NOT NULL, PRIMARY KEY (app_name, user_id, session_id)); \
1100     CREATE TABLE IF NOT EXISTS adk_harness_fact_ticks (\
1101        tick_id TEXT PRIMARY KEY, app_name TEXT NOT NULL, user_id TEXT NOT NULL, \
1102        at TEXT NOT NULL, record TEXT NOT NULL);",
1103)];
1104
1105/// A fixed-width UTC timestamp, so text order is time order.
1106#[cfg(feature = "postgres")]
1107fn sortable(at: DateTime<Utc>) -> String {
1108    at.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true)
1109}
1110
1111#[cfg(feature = "postgres")]
1112fn corrupt_record(what: &str, error: &serde_json::Error) -> AdkError {
1113    AdkError::new(
1114        ErrorComponent::Agent,
1115        ErrorCategory::Internal,
1116        "harness.memory.store_corrupt",
1117        format!("a stored {what} does not parse: {error}"),
1118    )
1119}
1120
1121/// A [`FactStore`] in PostgreSQL, shared by every replica of a served harness and by
1122/// `adk-rust up --store postgres://…` (spec 3.1 §7.15.2, §13 Q2; spec 3.3 §12 phase 3;
1123/// feature `postgres`).
1124///
1125/// The tables are the SQLite store's, by the same names: `adk_harness_facts`,
1126/// `adk_harness_fact_embeddings`, `adk_harness_fact_cursors` and `adk_harness_fact_ticks`.
1127/// [`put`](FactStore::put) takes a transaction-scoped advisory lock on the fact's (scope,
1128/// digest), so two replicas storing the same fact keep one; every other change reads its
1129/// row `FOR UPDATE`. [`migrate`](Self::migrate) records its steps in
1130/// `_adk_harness_fact_migrations` under an advisory lock, so replicas starting together
1131/// migrate one at a time. Records are not sealed: encrypt the shared database at rest, as
1132/// for the mode and standing-rule stores.
1133///
1134/// # Example
1135///
1136/// ```rust,no_run
1137/// use adk_harness::{FactKind, FactScope, FactSource, FactStatus, FactStore, MemoryFact};
1138/// use adk_harness::{PostgresFactStore, Provenance};
1139///
1140/// # async fn example() -> adk_core::Result<()> {
1141/// let store = PostgresFactStore::connect("postgres://localhost/app").await?;
1142/// store.migrate().await?;
1143/// let fact = MemoryFact::new(FactScope::new("app", "alice", None), FactKind::Preference,
1144///     "Use pnpm, not npm", FactStatus::Known, Provenance::new(FactSource::UserStated, "s1", "inv-1"));
1145/// let stored = store.put(fact).await?;
1146/// assert_eq!(store.get(&stored.id).await?.map(|fact| fact.uses), Some(stored.uses));
1147/// # Ok(())
1148/// # }
1149/// ```
1150#[cfg(feature = "postgres")]
1151#[derive(Debug, Clone)]
1152pub struct PostgresFactStore {
1153    pool: sqlx::PgPool,
1154}
1155
1156#[cfg(feature = "postgres")]
1157impl PostgresFactStore {
1158    /// A store over `pool`, such as the one the session service and the approval store use.
1159    pub fn new(pool: sqlx::PgPool) -> Self {
1160        Self { pool }
1161    }
1162
1163    /// Connects to `database_url` with a pool of its own.
1164    ///
1165    /// # Errors
1166    ///
1167    /// Returns `harness.store.database` when the server cannot be reached.
1168    pub async fn connect(database_url: &str) -> Result<Self> {
1169        let pool = sqlx::PgPool::connect(database_url).await.map_err(crate::fsutil::db_error)?;
1170        Ok(Self::new(pool))
1171    }
1172
1173    /// Creates or upgrades the store's tables.
1174    ///
1175    /// # Errors
1176    ///
1177    /// Returns the database error when a statement fails, or a version mismatch when the
1178    /// database was migrated by a newer release.
1179    pub async fn migrate(&self) -> Result<()> {
1180        crate::fsutil::migrate_postgres(
1181            &self.pool,
1182            "_adk_harness_fact_migrations",
1183            POSTGRES_FACT_MIGRATIONS,
1184        )
1185        .await
1186    }
1187
1188    fn decode_fact(text: &str) -> Result<MemoryFact> {
1189        serde_json::from_str(text).map_err(|error| corrupt_record("fact", &error))
1190    }
1191
1192    /// The fact `id`, its row locked until `tx` ends.
1193    async fn locked(
1194        tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
1195        id: &str,
1196    ) -> Result<Option<MemoryFact>> {
1197        let row: Option<(String,)> =
1198            sqlx::query_as("SELECT record FROM adk_harness_facts WHERE id = $1 FOR UPDATE")
1199                .bind(id)
1200                .fetch_optional(&mut **tx)
1201                .await
1202                .map_err(crate::fsutil::db_error)?;
1203        row.map(|(record,)| Self::decode_fact(&record)).transpose()
1204    }
1205
1206    async fn write(
1207        executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
1208        fact: &MemoryFact,
1209    ) -> Result<()> {
1210        let record = serde_json::to_string(fact)
1211            .map_err(|error| crate::fsutil::serialize_error("fact", &error))?;
1212        sqlx::query(
1213            "INSERT INTO adk_harness_facts \
1214             (id, app_name, user_id, project, digest, live, valid_from, record) \
1215             VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \
1216             ON CONFLICT (id) DO UPDATE SET live = excluded.live, record = excluded.record",
1217        )
1218        .bind(&fact.id)
1219        .bind(&fact.scope.app)
1220        .bind(&fact.scope.user)
1221        .bind(&fact.scope.project)
1222        .bind(&fact.digest)
1223        .bind(fact.status.is_live())
1224        .bind(sortable(fact.valid_from))
1225        .bind(record)
1226        .execute(executor)
1227        .await
1228        .map_err(crate::fsutil::db_error)?;
1229        Ok(())
1230    }
1231
1232    /// Applies `change` to the fact `id` under its row lock.
1233    async fn update(
1234        &self,
1235        id: &str,
1236        change: impl FnOnce(&mut MemoryFact) -> Result<()>,
1237    ) -> Result<()> {
1238        let mut tx = self.pool.begin().await.map_err(crate::fsutil::db_error)?;
1239        let mut fact = Self::locked(&mut tx, id).await?.ok_or_else(|| not_found(id))?;
1240        change(&mut fact)?;
1241        Self::write(&mut *tx, &fact).await?;
1242        tx.commit().await.map_err(crate::fsutil::db_error)
1243    }
1244}
1245
1246#[cfg(feature = "postgres")]
1247#[async_trait]
1248impl FactStore for PostgresFactStore {
1249    async fn put(&self, fact: MemoryFact) -> Result<MemoryFact> {
1250        let mut tx = self.pool.begin().await.map_err(crate::fsutil::db_error)?;
1251        // Two replicas storing the same fact at once keep one: the lock orders them, and the
1252        // second finds the first's row.
1253        let key = format!(
1254            "{}\u{1f}{}\u{1f}{}\u{1f}{}",
1255            fact.scope.app,
1256            fact.scope.user,
1257            fact.scope.project.as_deref().unwrap_or("\u{1f}"),
1258            fact.digest
1259        );
1260        sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
1261            .bind(key)
1262            .execute(&mut *tx)
1263            .await
1264            .map_err(crate::fsutil::db_error)?;
1265        let existing: Option<(String,)> = sqlx::query_as(
1266            "SELECT record FROM adk_harness_facts WHERE app_name = $1 AND user_id = $2 \
1267             AND project IS NOT DISTINCT FROM $3 AND digest = $4 AND live LIMIT 1 FOR UPDATE",
1268        )
1269        .bind(&fact.scope.app)
1270        .bind(&fact.scope.user)
1271        .bind(&fact.scope.project)
1272        .bind(&fact.digest)
1273        .fetch_optional(&mut *tx)
1274        .await
1275        .map_err(crate::fsutil::db_error)?;
1276        let stored = match existing {
1277            Some((record,)) => {
1278                let mut existing = Self::decode_fact(&record)?;
1279                existing.uses = existing.uses.saturating_add(1);
1280                existing
1281            }
1282            None => fact,
1283        };
1284        Self::write(&mut *tx, &stored).await?;
1285        tx.commit().await.map_err(crate::fsutil::db_error)?;
1286        Ok(stored)
1287    }
1288
1289    async fn get(&self, id: &str) -> Result<Option<MemoryFact>> {
1290        let row: Option<(String,)> =
1291            sqlx::query_as("SELECT record FROM adk_harness_facts WHERE id = $1")
1292                .bind(id)
1293                .fetch_optional(&self.pool)
1294                .await
1295                .map_err(crate::fsutil::db_error)?;
1296        row.map(|(record,)| Self::decode_fact(&record)).transpose()
1297    }
1298
1299    async fn list(&self, filter: FactFilter) -> Result<Vec<MemoryFact>> {
1300        let rows: Vec<(String,)> = sqlx::query_as(
1301            "SELECT record FROM adk_harness_facts WHERE app_name = $1 AND user_id = $2 \
1302             AND (NOT $3 OR live)",
1303        )
1304        .bind(&filter.app)
1305        .bind(&filter.user)
1306        .bind(filter.live_only)
1307        .fetch_all(&self.pool)
1308        .await
1309        .map_err(crate::fsutil::db_error)?;
1310        let mut facts = Vec::with_capacity(rows.len());
1311        for (record,) in rows {
1312            let fact = Self::decode_fact(&record)?;
1313            if filter.matches(&fact) {
1314                facts.push(fact);
1315            }
1316        }
1317        sort_newest_first(&mut facts);
1318        Ok(facts)
1319    }
1320
1321    async fn set_status(&self, id: &str, status: FactStatus, _by: &SubjectRef) -> Result<()> {
1322        self.update(id, |fact| apply_status(fact, status)).await
1323    }
1324
1325    async fn put_embedding(&self, id: &str, embedding: FactEmbedding) -> Result<()> {
1326        let vector = serde_json::to_string(&embedding.vector)
1327            .map_err(|error| crate::fsutil::serialize_error("embedding", &error))?;
1328        let mut tx = self.pool.begin().await.map_err(crate::fsutil::db_error)?;
1329        // The fact's row lock keeps its vector from outliving a concurrent removal.
1330        if Self::locked(&mut tx, id).await?.is_none() {
1331            return Err(not_found(id));
1332        }
1333        sqlx::query(
1334            "INSERT INTO adk_harness_fact_embeddings (id, vector, embedder) VALUES ($1, $2, $3) \
1335             ON CONFLICT (id) DO UPDATE SET vector = excluded.vector, \
1336             embedder = excluded.embedder",
1337        )
1338        .bind(id)
1339        .bind(vector)
1340        .bind(&embedding.embedder)
1341        .execute(&mut *tx)
1342        .await
1343        .map_err(crate::fsutil::db_error)?;
1344        tx.commit().await.map_err(crate::fsutil::db_error)
1345    }
1346
1347    async fn embeddings(&self, scope: &FactScope) -> Result<Vec<(String, FactEmbedding)>> {
1348        let rows: Vec<(String, String, String)> = sqlx::query_as(
1349            "SELECT e.id, e.vector, e.embedder FROM adk_harness_fact_embeddings e \
1350             JOIN adk_harness_facts f ON f.id = e.id \
1351             WHERE f.app_name = $1 AND f.user_id = $2 AND f.project IS NOT DISTINCT FROM $3 \
1352             AND f.live ORDER BY e.id",
1353        )
1354        .bind(&scope.app)
1355        .bind(&scope.user)
1356        .bind(&scope.project)
1357        .fetch_all(&self.pool)
1358        .await
1359        .map_err(crate::fsutil::db_error)?;
1360        Ok(rows
1361            .into_iter()
1362            .filter_map(|(id, vector, embedder)| {
1363                serde_json::from_str::<Vec<f32>>(&vector)
1364                    .ok()
1365                    .map(|vector| (id, FactEmbedding::new(embedder, vector)))
1366            })
1367            .collect())
1368    }
1369
1370    async fn record_recall(&self, ids: &[String], at: DateTime<Utc>) -> Result<()> {
1371        for id in ids {
1372            let recalled = self
1373                .update(id, |fact| {
1374                    fact.last_recalled = Some(at);
1375                    fact.uses = fact.uses.saturating_add(1);
1376                    Ok(())
1377                })
1378                .await;
1379            match recalled {
1380                Err(error) if error.code == "harness.memory.fact_not_found" => {}
1381                other => other?,
1382            }
1383        }
1384        Ok(())
1385    }
1386
1387    async fn distilled_sessions(
1388        &self,
1389        app: &str,
1390        user: &str,
1391    ) -> Result<Vec<(String, DateTime<Utc>)>> {
1392        let rows: Vec<(String, String)> = sqlx::query_as(
1393            "SELECT session_id, upto FROM adk_harness_fact_cursors \
1394             WHERE app_name = $1 AND user_id = $2 ORDER BY session_id",
1395        )
1396        .bind(app)
1397        .bind(user)
1398        .fetch_all(&self.pool)
1399        .await
1400        .map_err(crate::fsutil::db_error)?;
1401        Ok(rows
1402            .into_iter()
1403            .filter_map(|(session, upto)| {
1404                let upto = DateTime::parse_from_rfc3339(&upto).ok()?.with_timezone(&Utc);
1405                Some((session, upto))
1406            })
1407            .collect())
1408    }
1409
1410    async fn mark_distilled(
1411        &self,
1412        app: &str,
1413        user: &str,
1414        session: &str,
1415        upto: DateTime<Utc>,
1416    ) -> Result<()> {
1417        sqlx::query(
1418            "INSERT INTO adk_harness_fact_cursors (app_name, user_id, session_id, upto) \
1419             VALUES ($1, $2, $3, $4) ON CONFLICT (app_name, user_id, session_id) \
1420             DO UPDATE SET upto = excluded.upto WHERE excluded.upto > adk_harness_fact_cursors.upto",
1421        )
1422        .bind(app)
1423        .bind(user)
1424        .bind(session)
1425        .bind(sortable(upto))
1426        .execute(&self.pool)
1427        .await
1428        .map_err(crate::fsutil::db_error)?;
1429        Ok(())
1430    }
1431
1432    async fn put_consolidation(&self, record: &ConsolidationRecord) -> Result<()> {
1433        let text = serde_json::to_string(record)
1434            .map_err(|error| crate::fsutil::serialize_error("consolidation record", &error))?;
1435        sqlx::query(
1436            "INSERT INTO adk_harness_fact_ticks (tick_id, app_name, user_id, at, record) \
1437             VALUES ($1, $2, $3, $4, $5) ON CONFLICT (tick_id) DO UPDATE SET record = excluded.record",
1438        )
1439        .bind(&record.tick_id)
1440        .bind(&record.app)
1441        .bind(&record.user)
1442        .bind(sortable(record.at))
1443        .bind(text)
1444        .execute(&self.pool)
1445        .await
1446        .map_err(crate::fsutil::db_error)?;
1447        Ok(())
1448    }
1449
1450    async fn consolidations(&self, app: &str, user: &str) -> Result<Vec<ConsolidationRecord>> {
1451        let rows: Vec<(String,)> = sqlx::query_as(
1452            "SELECT record FROM adk_harness_fact_ticks \
1453             WHERE app_name = $1 AND user_id = $2 ORDER BY at DESC, tick_id DESC",
1454        )
1455        .bind(app)
1456        .bind(user)
1457        .fetch_all(&self.pool)
1458        .await
1459        .map_err(crate::fsutil::db_error)?;
1460        rows.into_iter()
1461            .map(|(text,)| {
1462                serde_json::from_str(&text)
1463                    .map_err(|error| corrupt_record("consolidation record", &error))
1464            })
1465            .collect()
1466    }
1467
1468    async fn restore_assumed(&self, id: &str, _by: &SubjectRef) -> Result<()> {
1469        self.update(id, apply_restore).await
1470    }
1471}