Skip to main content

memvault_proxy/
injection.rs

1use std::sync::Arc;
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::time::{Duration, Instant};
4
5use chrono::Utc;
6use tokio::sync::{Notify, RwLock};
7use tracing::debug;
8use uuid::Uuid;
9
10use memvault_core::models::InjectChannel;
11use memvault_core::router::MemoryRouter;
12
13use crate::context::SessionContext;
14
15/// How long a caller may block waiting for the semantic prefetch to land
16/// before proceeding with the deterministic baseline (Feature C). Kept short
17/// on purpose: the whole point is that the request is never held hostage by
18/// embedding latency.
19pub const PREFETCH_WAIT_WINDOW: Duration = Duration::from_millis(250);
20
21/// Conversation n-gram window (Feature D): how many recent observed turns
22/// build the recency-weighted retrieval key. Overridable via
23/// `MEMVAULT_CONTEXT_NGRAM_WINDOW`; invalid/zero values fall back to 5.
24pub fn ngram_window_from_env() -> usize {
25    std::env::var("MEMVAULT_CONTEXT_NGRAM_WINDOW")
26        .ok()
27        .and_then(|v| v.parse::<usize>().ok())
28        .filter(|w| *w > 0)
29        .unwrap_or(5)
30}
31
32/// Which phase produced the current injection state.
33///
34/// Feature C (docs/PAPER-INSPIRATIONS.md, paper §2.3): deterministic
35/// addressing (MUST rules + namespace rules, zero embedding calls) can be
36/// served immediately; the semantic pipeline prefetches in the background
37/// and replaces the state when it lands.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum InjectionPhase {
40    /// Fast path only: MUST-level memories resolved by pure rules.
41    Deterministic,
42    /// Full layered pipeline (semantic/hybrid search) completed.
43    Full,
44}
45
46pub struct InjectionState {
47    pub session_id: String,
48    pub formatted_text: String,
49    #[allow(dead_code)]
50    pub injected_memory_ids: Vec<String>,
51    #[allow(dead_code)]
52    pub updated_at: chrono::DateTime<Utc>,
53    /// Candidates dropped during this injection, with reasons — kept so the
54    /// proxy can answer "why didn't memory X reach the model?" after the fact.
55    #[allow(dead_code)]
56    pub skipped: Vec<memvault_core::models::SkippedMemory>,
57    /// Which phase produced this state.
58    pub phase: InjectionPhase,
59}
60
61pub struct InjectionEngine {
62    router: Arc<MemoryRouter>,
63    context: Arc<SessionContext>,
64    state: RwLock<Option<InjectionState>>,
65    agent_id: RwLock<String>,
66    /// Monotonic refresh generation. A slow prefetch that returns after a
67    /// newer refresh started must not overwrite the fresher state.
68    generation: AtomicU64,
69    /// Wakes `wait_full` waiters whenever the state is (re)placed.
70    prefetch_notify: Notify,
71}
72
73impl InjectionEngine {
74    pub fn new(router: Arc<MemoryRouter>, context: Arc<SessionContext>) -> Arc<Self> {
75        Arc::new(Self {
76            router,
77            context,
78            state: RwLock::new(None),
79            agent_id: RwLock::new("proxy-client".to_string()),
80            generation: AtomicU64::new(0),
81            prefetch_notify: Notify::new(),
82        })
83    }
84
85    #[allow(dead_code)]
86    pub async fn set_agent_id(&self, agent_id: &str) {
87        *self.agent_id.write().await = agent_id.to_string();
88    }
89
90    pub async fn refresh_if_needed(&self) -> bool {
91        if !self.context.take_if_changed().await {
92            return false;
93        }
94        self.refresh().await
95    }
96
97    /// Returns `true` when the injection state was successfully replaced, so
98    /// callers can tell a real refresh from a failed one instead of re-using
99    /// stale instructions for the current session.
100    pub async fn refresh(&self) -> bool {
101        let agent_id = self.agent_id.read().await.clone();
102        // Feature F: if this agent's canonical injection channel is not the
103        // transparent proxy, skip auto-injection so the same memory is not
104        // delivered twice (another channel owns it).
105        if !self.router.channel_allows(&agent_id, InjectChannel::Proxy) {
106            debug!(agent_id = %agent_id, "proxy auto-injection skipped: not the canonical channel");
107            return false;
108        }
109        // Feature D: condition retrieval on the recent turn window, weighted
110        // by recency, rather than a single flat hint.
111        let context_hint = self
112            .context
113            .conversation_ngram(ngram_window_from_env())
114            .await;
115        let project = self.context.get_project().await;
116
117        let output = match self
118            .router
119            .session_start_layered(&agent_id, context_hint.as_deref(), project.as_deref())
120            .await
121        {
122            Ok(r) => r,
123            Err(e) => {
124                tracing::warn!(error = %e, "injection refresh failed");
125                return false;
126            }
127        };
128
129        let formatted = self.router.format_layered_instructions(&output);
130        let session_id = format!("inj_{}", Uuid::new_v4().simple());
131        let memory_ids: Vec<String> = output
132            .injected
133            .iter()
134            .map(|r| r.memory.id.clone())
135            .collect();
136
137        let formatted_with_session =
138            format!("[MEMORY CONTEXT - session: {}]\n{}", session_id, formatted);
139
140        debug!(
141            session_id = %session_id,
142            memories = memory_ids.len(),
143            overflow = output.overflow_count,
144            "injection refreshed (layered)"
145        );
146
147        *self.state.write().await = Some(InjectionState {
148            session_id,
149            formatted_text: formatted_with_session,
150            injected_memory_ids: memory_ids,
151            updated_at: Utc::now(),
152            skipped: output.skipped.clone(),
153            phase: InjectionPhase::Full,
154        });
155        self.prefetch_notify.notify_waiters();
156        true
157    }
158
159    /// Two-phase refresh — Feature C (paper §2.3 deterministic addressing +
160    /// async prefetch).
161    ///
162    /// Phase 1 (deterministic, synchronous): MUST-level memories resolved by
163    /// pure rules, zero embedding calls. Stored immediately so a caller can
164    /// proceed without waiting on the semantic pipeline.
165    ///
166    /// Phase 2 (prefetch, async): the full layered pipeline runs in the
167    /// background and replaces the state when it lands. If it fails, the
168    /// deterministic baseline is kept rather than dropped. A generation
169    /// counter stops a slow prefetch from clobbering a fresher refresh.
170    ///
171    /// Returns `true` when a refresh was kicked off (i.e. the context had
172    /// changed), mirroring [`Self::refresh_if_needed`].
173    pub async fn refresh_if_needed_two_phase(self: &Arc<Self>) -> bool {
174        if !self.context.take_if_changed().await {
175            return false;
176        }
177        self.refresh_two_phase().await
178    }
179
180    /// Unconditional two-phase refresh. See [`Self::refresh_if_needed_two_phase`].
181    pub async fn refresh_two_phase(self: &Arc<Self>) -> bool {
182        let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
183        // One session id spans both phases of a single refresh, so compliance
184        // tracking stays coherent as the state upgrades Deterministic -> Full.
185        let session_id = format!("inj_{}", Uuid::new_v4().simple());
186
187        let agent_id = self.agent_id.read().await.clone();
188        // Feature F: skip auto-injection when another channel owns this agent.
189        if !self.router.channel_allows(&agent_id, InjectChannel::Proxy) {
190            debug!(agent_id = %agent_id, "proxy auto-injection skipped: not the canonical channel");
191            return false;
192        }
193        // Feature D: recency-weighted conversation n-gram as the retrieval key.
194        let context_hint = self
195            .context
196            .conversation_ngram(ngram_window_from_env())
197            .await;
198        let project = self.context.get_project().await;
199
200        // —— Phase 1: deterministic fast path. Never fails the refresh: an
201        // error here only means we fall through to phase 2 with no baseline.
202        match self
203            .router
204            .deterministic_injection(&agent_id, project.as_deref())
205            .await
206        {
207            Ok(results) if !results.is_empty() => {
208                let formatted = self.router.format_as_instructions(&results);
209                let formatted_with_session =
210                    format!("[MEMORY CONTEXT - session: {}]\n{}", session_id, formatted);
211                let memory_ids: Vec<String> = results.iter().map(|r| r.memory.id.clone()).collect();
212                debug!(
213                    session_id = %session_id,
214                    memories = memory_ids.len(),
215                    "deterministic fast-path injection ready"
216                );
217                *self.state.write().await = Some(InjectionState {
218                    session_id: session_id.clone(),
219                    formatted_text: formatted_with_session,
220                    injected_memory_ids: memory_ids,
221                    updated_at: Utc::now(),
222                    skipped: Vec::new(),
223                    phase: InjectionPhase::Deterministic,
224                });
225                self.prefetch_notify.notify_waiters();
226            }
227            Ok(_) => {
228                debug!("no MUST memories for deterministic fast path");
229            }
230            Err(e) => {
231                tracing::warn!(error = %e, "deterministic fast path failed; waiting for prefetch only");
232            }
233        }
234
235        // —— Phase 2: full pipeline in the background.
236        let engine = Arc::clone(self);
237        let hint = context_hint.clone();
238        let proj = project.clone();
239        tokio::spawn(async move {
240            let output = engine
241                .router
242                .session_start_layered(&agent_id, hint.as_deref(), proj.as_deref())
243                .await;
244
245            // A newer refresh superseded this one — drop the stale result.
246            if engine.generation.load(Ordering::SeqCst) != generation {
247                debug!(generation, "prefetch superseded by a newer refresh");
248                return;
249            }
250
251            let output = match output {
252                Ok(r) => r,
253                Err(e) => {
254                    tracing::warn!(error = %e, "injection prefetch failed; keeping deterministic baseline");
255                    return;
256                }
257            };
258
259            let formatted = engine.router.format_layered_instructions(&output);
260            let formatted_with_session =
261                format!("[MEMORY CONTEXT - session: {}]\n{}", session_id, formatted);
262            let memory_ids: Vec<String> = output
263                .injected
264                .iter()
265                .map(|r| r.memory.id.clone())
266                .collect();
267            debug!(
268                session_id = %session_id,
269                memories = memory_ids.len(),
270                overflow = output.overflow_count,
271                "injection prefetch complete (layered)"
272            );
273            *engine.state.write().await = Some(InjectionState {
274                session_id,
275                formatted_text: formatted_with_session,
276                injected_memory_ids: memory_ids,
277                updated_at: Utc::now(),
278                skipped: output.skipped.clone(),
279                phase: InjectionPhase::Full,
280            });
281            engine.prefetch_notify.notify_waiters();
282        });
283
284        true
285    }
286
287    /// Wait until the injection state was produced by the full pipeline, or
288    /// the timeout elapses. Returns `true` when the state is `Full`. A
289    /// deterministic baseline (or no state at all) returns `false` after the
290    /// timeout — callers must treat that as "proceed with what is available",
291    /// never as an error.
292    pub async fn wait_full(&self, timeout: Duration) -> bool {
293        let deadline = Instant::now() + timeout;
294        loop {
295            let notified = self.prefetch_notify.notified();
296            // Check AFTER arming the waiter so a completion between check and
297            // await cannot be missed.
298            {
299                let state = self.state.read().await;
300                if let Some(s) = state.as_ref()
301                    && s.phase == InjectionPhase::Full
302                {
303                    return true;
304                }
305            }
306            let remaining = deadline.saturating_duration_since(Instant::now());
307            if remaining.is_zero() {
308                return false;
309            }
310            if tokio::time::timeout(remaining, notified).await.is_err() {
311                return false;
312            }
313        }
314    }
315
316    /// Current injection phase, if any state exists.
317    pub async fn get_phase(&self) -> Option<InjectionPhase> {
318        self.state.read().await.as_ref().map(|s| s.phase)
319    }
320
321    pub async fn get_current_injection(&self) -> Option<String> {
322        let state = self.state.read().await;
323        state.as_ref().map(|s| s.formatted_text.clone())
324    }
325
326    #[allow(dead_code)]
327    pub async fn get_session_id(&self) -> Option<String> {
328        let state = self.state.read().await;
329        state.as_ref().map(|s| s.session_id.clone())
330    }
331
332    #[allow(dead_code)]
333    pub async fn get_injected_memory_ids(&self) -> Vec<String> {
334        let state = self.state.read().await;
335        state
336            .as_ref()
337            .map(|s| s.injected_memory_ids.clone())
338            .unwrap_or_default()
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345    use memvault_core::models::{Memory, MemoryType, Priority, SourceAgent};
346    use memvault_core::storage::MemoryStore;
347    use memvault_core::storage::sqlite::SqliteStore;
348
349    async fn make_engine() -> (Arc<InjectionEngine>, Arc<SessionContext>, Arc<SqliteStore>) {
350        let store = Arc::new(SqliteStore::in_memory().unwrap());
351        let router = Arc::new(MemoryRouter::new(store.clone()));
352        let context = SessionContext::new();
353        let engine = InjectionEngine::new(router, context.clone());
354        (engine, context, store)
355    }
356
357    #[tokio::test]
358    async fn test_new_engine_has_no_state() {
359        let (engine, _ctx, _store) = make_engine().await;
360        assert!(engine.get_current_injection().await.is_none());
361        assert!(engine.get_session_id().await.is_none());
362        assert!(engine.get_injected_memory_ids().await.is_empty());
363    }
364
365    #[tokio::test]
366    async fn test_refresh_without_changes_does_not_run() {
367        let (engine, _ctx, _store) = make_engine().await;
368        let ran = engine.refresh_if_needed().await;
369        assert!(!ran);
370        assert!(engine.get_current_injection().await.is_none());
371    }
372
373    #[tokio::test]
374    async fn test_refresh_if_needed_after_context_change() {
375        let (engine, ctx, _store) = make_engine().await;
376        ctx.observe_tool_call(
377            "read",
378            &serde_json::json!({ "path": "/repo/myapp/src/main.rs" }),
379        )
380        .await;
381        let ran = engine.refresh_if_needed().await;
382        assert!(ran, "context changed -> refresh runs");
383        let injection = engine.get_current_injection().await.expect("state present");
384        assert!(injection.contains("MEMORY CONTEXT"));
385        assert!(engine.get_session_id().await.unwrap().starts_with("inj_"));
386    }
387
388    #[tokio::test]
389    async fn test_refresh_after_change_only_once() {
390        let (engine, ctx, _store) = make_engine().await;
391        ctx.observe_tool_call(
392            "read",
393            &serde_json::json!({ "path": "/repo/myapp/src/main.rs" }),
394        )
395        .await;
396        assert!(engine.refresh_if_needed().await);
397        assert!(
398            !engine.refresh_if_needed().await,
399            "second refresh is a no-op until the next change"
400        );
401    }
402
403    #[tokio::test]
404    async fn test_refresh_saves_injection_with_memories() {
405        let (engine, ctx, store) = make_engine().await;
406        store
407            .save(Memory::new(
408                MemoryType::Preference,
409                "prefers vim".to_string(),
410                Priority::Must,
411                SourceAgent {
412                    id: "proxy-client".to_string(),
413                    agent_type: "general".to_string(),
414                    session_id: None,
415                },
416            ))
417            .await
418            .unwrap();
419
420        ctx.observe_tool_call(
421            "edit",
422            &serde_json::json!({ "path": "/repo/myapp/src/main.rs" }),
423        )
424        .await;
425        assert!(engine.refresh_if_needed().await);
426        let ids = engine.get_injected_memory_ids().await;
427        assert!(!ids.is_empty());
428        let text = engine.get_current_injection().await.unwrap();
429        assert!(text.contains("prefers vim"));
430    }
431
432    #[tokio::test]
433    async fn test_set_agent_id_changes_scope() {
434        let (engine, _ctx, _store) = make_engine().await;
435        engine.set_agent_id("other-agent").await;
436        let refreshed = engine.refresh().await;
437        assert!(refreshed, "refresh should report success");
438        // refresh stores state (possibly empty injection) and a fresh session
439        let _ = engine.get_current_injection().await;
440        assert!(engine.get_session_id().await.is_some());
441    }
442
443    // —— Feature C: two-phase refresh (deterministic fast path + prefetch) ——
444
445    /// Embedder whose `embed` blocks until the test flips a watch to `true`.
446    /// Lets us freeze the semantic pipeline in phase 2 deterministically.
447    struct GatedEmbedder {
448        rx: tokio::sync::watch::Receiver<bool>,
449    }
450    #[async_trait::async_trait]
451    impl memvault_core::embedding::EmbeddingProvider for GatedEmbedder {
452        async fn embed(&self, texts: &[String]) -> memvault_core::error::Result<Vec<Vec<f32>>> {
453            let mut rx = self.rx.clone();
454            while !*rx.borrow_and_update() {
455                if rx.changed().await.is_err() {
456                    break;
457                }
458            }
459            Ok(texts.iter().map(|_| vec![0.1_f32, 0.2]).collect())
460        }
461        fn dimension(&self) -> usize {
462            2
463        }
464    }
465
466    async fn make_gated_engine() -> (
467        Arc<InjectionEngine>,
468        Arc<SessionContext>,
469        Arc<SqliteStore>,
470        tokio::sync::watch::Sender<bool>,
471    ) {
472        let store = Arc::new(SqliteStore::in_memory().unwrap());
473        let (tx, rx) = tokio::sync::watch::channel(false);
474        let router = Arc::new(
475            MemoryRouter::new(store.clone()).with_embedder(Arc::new(GatedEmbedder { rx })),
476        );
477        let context = SessionContext::new();
478        let engine = InjectionEngine::new(router, context.clone());
479        (engine, context, store, tx)
480    }
481
482    fn agent() -> SourceAgent {
483        SourceAgent {
484            id: "proxy-client".to_string(),
485            agent_type: "general".to_string(),
486            session_id: None,
487        }
488    }
489
490    #[tokio::test]
491    async fn test_two_phase_serves_deterministic_then_full() {
492        let (engine, ctx, store, gate) = make_gated_engine().await;
493        // A MUST rule (deterministic fast path) plus a plain reference memory
494        // (only reachable through the full search pipeline).
495        store
496            .save(Memory::new(
497                MemoryType::Preference,
498                "always use Rust".to_string(),
499                Priority::Must,
500                agent(),
501            ))
502            .await
503            .unwrap();
504        store
505            .save(Memory::new(
506                MemoryType::Fact,
507                "the checkout service uses PostgreSQL".to_string(),
508                Priority::Reference,
509                agent(),
510            ))
511            .await
512            .unwrap();
513
514        ctx.observe_tool_call(
515            "edit",
516            &serde_json::json!({ "path": "/repo/myapp/src/main.rs" }),
517        )
518        .await;
519
520        assert!(engine.refresh_if_needed_two_phase().await);
521
522        // Phase 1 lands synchronously: MUST rule present, still not Full
523        // because the semantic pipeline is frozen inside embed().
524        let text = engine
525            .get_current_injection()
526            .await
527            .expect("deterministic baseline must be available immediately");
528        assert!(text.contains("always use Rust"), "baseline: {}", text);
529        assert_eq!(
530            engine.get_phase().await,
531            Some(InjectionPhase::Deterministic)
532        );
533        assert!(
534            !engine.wait_full(Duration::from_millis(50)).await,
535            "prefetch is still blocked; wait_full must time out, not hang"
536        );
537
538        // Release the embedder: the prefetch completes and upgrades the state.
539        gate.send(true).unwrap();
540        assert!(
541            engine.wait_full(Duration::from_secs(5)).await,
542            "prefetch should land once the embedder unblocks"
543        );
544        assert_eq!(engine.get_phase().await, Some(InjectionPhase::Full));
545        let full = engine.get_current_injection().await.unwrap();
546        assert!(full.contains("always use Rust"), "full: {}", full);
547    }
548
549    #[tokio::test]
550    async fn test_two_phase_without_must_memories_still_reaches_full() {
551        let (engine, ctx, store, gate) = make_gated_engine().await;
552        store
553            .save(Memory::new(
554                MemoryType::Fact,
555                "the checkout service uses PostgreSQL".to_string(),
556                Priority::Reference,
557                agent(),
558            ))
559            .await
560            .unwrap();
561
562        ctx.observe_tool_call(
563            "edit",
564            &serde_json::json!({ "path": "/repo/myapp/src/main.rs" }),
565        )
566        .await;
567
568        assert!(engine.refresh_if_needed_two_phase().await);
569        // No MUST memories -> no deterministic baseline state yet.
570        assert!(engine.get_phase().await.is_none());
571
572        gate.send(true).unwrap();
573        assert!(engine.wait_full(Duration::from_secs(5)).await);
574        assert_eq!(engine.get_phase().await, Some(InjectionPhase::Full));
575    }
576
577    #[tokio::test]
578    async fn test_two_phase_no_change_is_noop() {
579        let (engine, _ctx, _store, _gate) = make_gated_engine().await;
580        assert!(!engine.refresh_if_needed_two_phase().await);
581        assert!(engine.get_phase().await.is_none());
582    }
583
584    // —— Feature F: canonical injection channel ——
585
586    #[tokio::test]
587    async fn test_refresh_skipped_when_proxy_not_canonical() {
588        // The engine's agent ("proxy-client") is owned by the MCP channel, so
589        // the transparent proxy must not auto-inject for it.
590        let store = Arc::new(SqliteStore::in_memory().unwrap());
591        let registry = vec![memvault_core::models::AgentProfile {
592            id: "proxy-client".to_string(),
593            agent_type: "general".to_string(),
594            description: String::new(),
595            inject_rules: memvault_core::models::InjectRules::default(),
596            api_key: None,
597            inject_channel: Some(InjectChannel::Mcp),
598        }];
599        let router = Arc::new(MemoryRouter::with_registry(store.clone(), registry));
600        let context = SessionContext::new();
601        let engine = InjectionEngine::new(router, context.clone());
602
603        context
604            .observe_tool_call(
605                "edit",
606                &serde_json::json!({ "path": "/repo/myapp/src/main.rs" }),
607            )
608            .await;
609
610        assert!(
611            !engine.refresh_if_needed().await,
612            "proxy auto-injection must be skipped when another channel is canonical"
613        );
614        assert!(engine.get_current_injection().await.is_none());
615        assert!(engine.get_phase().await.is_none());
616        // Two-phase refresh is gated the same way.
617        context
618            .observe_tool_call(
619                "read",
620                &serde_json::json!({ "path": "/repo/myapp/src/x.rs" }),
621            )
622            .await;
623        assert!(!engine.refresh_if_needed_two_phase().await);
624        assert!(engine.get_phase().await.is_none());
625    }
626
627    #[tokio::test]
628    async fn test_refresh_allowed_when_proxy_canonical_or_unset() {
629        // No registry entry -> unrestricted -> proxy auto-injection proceeds.
630        let (engine, ctx, _store) = make_engine().await;
631        ctx.observe_tool_call(
632            "edit",
633            &serde_json::json!({ "path": "/repo/myapp/src/main.rs" }),
634        )
635        .await;
636        assert!(engine.refresh_if_needed().await);
637        assert!(engine.get_current_injection().await.is_some());
638    }
639}