Skip to main content

weavatrix_memory/context/
retrieved.rs

1use super::{
2    ContextBundle, ContextCompiler, ContextRequest, FusedRetrievalHit, RetrievalProvider,
3    RetrievalQuery, TokenEstimator, fuse_retrieval,
4};
5use crate::{
6    error::{MemoryError, Result},
7    projection::MemoryProjection,
8};
9
10#[derive(Debug, Clone)]
11pub struct RetrievedContextBundle {
12    pub context: ContextBundle,
13    pub retrieval: Vec<FusedRetrievalHit>,
14}
15
16impl<T> ContextCompiler<T>
17where
18    T: TokenEstimator,
19{
20    /// Resolves free text into exact graph seeds and compiles their context.
21    ///
22    /// Providers can be lexical, BM25, vector, or hybrid implementations from
23    /// separate crates. Rank fusion is deterministic and provider scores never
24    /// need to share a scale.
25    ///
26    /// # Errors
27    ///
28    /// Returns provider, missing-entity, scope, graph, or budget failures.
29    pub fn compile_with_retrieval(
30        &self,
31        projection: &MemoryProjection,
32        request: &ContextRequest,
33        query: &RetrievalQuery,
34        providers: &[&dyn RetrievalProvider],
35    ) -> Result<RetrievedContextBundle> {
36        let retrieval = fuse_retrieval(providers, query).map_err(MemoryError::from)?;
37        let seeds = retrieval
38            .iter()
39            .filter(|hit| {
40                projection
41                    .visible_node(&hit.entity, request.known_at)
42                    .is_some()
43            })
44            .map(|hit| hit.entity.clone())
45            .collect::<Vec<_>>();
46        if seeds.is_empty() {
47            return Err(MemoryError::Retrieval {
48                provider: "fusion".to_owned(),
49                message: "no retrieved entity exists in this projection".to_owned(),
50            });
51        }
52        let mut exact = request.clone();
53        exact.seeds = seeds;
54        Ok(RetrievedContextBundle {
55            context: self.compile(projection, &exact)?,
56            retrieval,
57        })
58    }
59}