Skip to main content

memvault_proxy/
context.rs

1use std::sync::Arc;
2
3use chrono::Utc;
4use tokio::sync::RwLock;
5use tracing::debug;
6
7use memvault_core::intent::{self, Intent, IntentResult};
8
9#[allow(dead_code)]
10#[derive(Debug, Clone)]
11struct ObservedToolCall {
12    tool_name: String,
13    arguments_hint: Option<String>,
14    timestamp: chrono::DateTime<Utc>,
15}
16
17pub struct SessionContext {
18    tool_calls: RwLock<Vec<ObservedToolCall>>,
19    inferred_project: RwLock<Option<String>>,
20    #[allow(dead_code)]
21    inferred_intent: RwLock<IntentResult>,
22    context_changed: RwLock<bool>,
23}
24
25impl SessionContext {
26    pub fn new() -> Arc<Self> {
27        Arc::new(Self {
28            tool_calls: RwLock::new(Vec::new()),
29            inferred_project: RwLock::new(None),
30            inferred_intent: RwLock::new(IntentResult {
31                primary: Intent::General,
32                domains: vec!["general".to_string()],
33                confidence: 0.5,
34            }),
35            context_changed: RwLock::new(false),
36        })
37    }
38
39    #[allow(dead_code)]
40    pub async fn observe_tool_call(&self, tool_name: &str, arguments: &serde_json::Value) {
41        let hint = Self::extract_context_hint(tool_name, arguments);
42
43        self.tool_calls.write().await.push(ObservedToolCall {
44            tool_name: tool_name.to_string(),
45            arguments_hint: hint.clone(),
46            timestamp: Utc::now(),
47        });
48
49        if let Some(project) = Self::infer_project_from_args(arguments) {
50            let mut proj = self.inferred_project.write().await;
51            if proj.as_deref() != Some(&project) {
52                *proj = Some(project.clone());
53                *self.context_changed.write().await = true;
54                debug!(project = %project, "inferred project from tool call");
55            }
56        }
57
58        if let Some(ref h) = hint {
59            let new_intent = intent::analyze_intent(h);
60            if new_intent.confidence > 0.3 {
61                let mut current = self.inferred_intent.write().await;
62                if current.primary != new_intent.primary {
63                    *current = new_intent;
64                    *self.context_changed.write().await = true;
65                }
66            }
67        }
68    }
69
70    pub async fn take_if_changed(&self) -> bool {
71        let mut changed = self.context_changed.write().await;
72        if *changed {
73            *changed = false;
74            true
75        } else {
76            false
77        }
78    }
79
80    pub async fn get_context_hint(&self) -> Option<String> {
81        let calls = self.tool_calls.read().await;
82        let recent: Vec<&ObservedToolCall> = calls.iter().rev().take(5).collect();
83        if recent.is_empty() {
84            return None;
85        }
86        let hints: Vec<String> = recent
87            .iter()
88            .filter_map(|c| c.arguments_hint.clone())
89            .collect();
90        if hints.is_empty() {
91            Some(
92                recent
93                    .iter()
94                    .map(|c| c.tool_name.clone())
95                    .collect::<Vec<_>>()
96                    .join(", "),
97            )
98        } else {
99            Some(hints.join("; "))
100        }
101    }
102
103    /// Conversation n-gram retrieval key — Feature D (docs/PAPER-INSPIRATIONS.md,
104    /// paper §2.3 "conditional memory").
105    ///
106    /// Instead of keying retrieval on a single query sentence (unigram-style),
107    /// condition it on the recent window of observed turns — and weight that
108    /// window by recency, so the turn the agent is acting on *right now*
109    /// dominates retrieval while slightly older turns still shape it. The
110    /// newest turn is repeated most, decaying linearly with age, which biases
111    /// both the keyword tier (term frequency) and the embedding toward the
112    /// current focus. Output is length-bounded so a long session cannot bloat
113    /// the query unboundedly.
114    ///
115    /// Returns `None` when nothing has been observed yet.
116    pub async fn conversation_ngram(&self, window: usize) -> Option<String> {
117        /// Hard cap on the assembled key; retrieval quality saturates long
118        /// before this and the embedding/FTS input must stay bounded.
119        const MAX_KEY_LEN: usize = 600;
120
121        let window = window.max(1);
122        let calls = self.tool_calls.read().await;
123        if calls.is_empty() {
124            return None;
125        }
126
127        // Newest first: index 0 is the most recent observation.
128        let recent: Vec<&ObservedToolCall> = calls.iter().rev().take(window).collect();
129        let n = recent.len();
130
131        let mut segments: Vec<String> = Vec::new();
132        let mut total_len = 0usize;
133        'outer: for (i, call) in recent.iter().enumerate() {
134            let text = call
135                .arguments_hint
136                .clone()
137                .unwrap_or_else(|| call.tool_name.clone());
138            // Recency weight: newest turn repeated `n` times, decaying to 1
139            // for the oldest turn in the window.
140            let weight = n - i;
141            for _ in 0..weight {
142                if total_len + text.len() > MAX_KEY_LEN {
143                    break 'outer;
144                }
145                segments.push(text.clone());
146                total_len += text.len();
147            }
148        }
149
150        if segments.is_empty() {
151            None
152        } else {
153            Some(segments.join(" "))
154        }
155    }
156
157    pub async fn get_project(&self) -> Option<String> {
158        self.inferred_project.read().await.clone()
159    }
160
161    #[allow(dead_code)]
162    pub async fn get_intent(&self) -> IntentResult {
163        self.inferred_intent.read().await.clone()
164    }
165
166    #[allow(dead_code)]
167    fn extract_context_hint(tool_name: &str, arguments: &serde_json::Value) -> Option<String> {
168        let mut parts = vec![tool_name.to_string()];
169        if let Some(path) = arguments.get("path").and_then(|v| v.as_str()) {
170            parts.push(path.to_string());
171        }
172        if let Some(query) = arguments.get("query").and_then(|v| v.as_str()) {
173            parts.push(query.to_string());
174        }
175        if let Some(content) = arguments.get("content").and_then(|v| v.as_str())
176            && content.len() < 200
177        {
178            parts.push(content.to_string());
179        }
180        if parts.len() > 1 {
181            Some(parts.join(" "))
182        } else {
183            None
184        }
185    }
186
187    #[allow(dead_code)]
188    fn infer_project_from_args(arguments: &serde_json::Value) -> Option<String> {
189        let path = arguments.get("path").and_then(|v| v.as_str())?;
190        let parts: Vec<&str> = path.split('/').collect();
191        // Look for common project directory patterns
192        for (i, part) in parts.iter().enumerate() {
193            if (*part == "src" || *part == "lib" || *part == "crates" || *part == "packages")
194                && i > 0
195            {
196                return Some(format!("project:{}", parts[i - 1]));
197            }
198        }
199        // Fallback: use the first non-home directory component
200        if parts.len() >= 4 {
201            return Some(format!("project:{}", parts[3]));
202        }
203        None
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[tokio::test]
212    async fn test_take_if_changed_starts_false() {
213        let ctx = SessionContext::new();
214        assert!(!ctx.take_if_changed().await);
215    }
216
217    #[tokio::test]
218    async fn test_observe_tool_call_sets_project_and_changed() {
219        let ctx = SessionContext::new();
220        ctx.observe_tool_call(
221            "read_file",
222            &serde_json::json!({ "path": "/Users/me/work/app/src/main.rs" }),
223        )
224        .await;
225        assert!(ctx.take_if_changed().await);
226        assert_eq!(ctx.get_project().await.as_deref(), Some("project:app"));
227    }
228
229    #[tokio::test]
230    async fn test_take_changed_resets_after_read() {
231        let ctx = SessionContext::new();
232        ctx.observe_tool_call(
233            "read_file",
234            &serde_json::json!({ "path": "/repo/myapp/src/main.rs" }),
235        )
236        .await;
237        assert!(
238            ctx.take_if_changed().await,
239            "project inference marks change"
240        );
241        assert!(!ctx.take_if_changed().await, "flag resets to false");
242    }
243
244    #[tokio::test]
245    async fn test_get_context_hint_builds_hint() {
246        let ctx = SessionContext::new();
247        ctx.observe_tool_call(
248            "edit_file",
249            &serde_json::json!({ "path": "/a/b/c.rs", "query": "fix bug" }),
250        )
251        .await;
252        let hint = ctx.get_context_hint().await.unwrap();
253        assert!(hint.contains("edit_file"));
254        assert!(hint.contains("fix bug"));
255    }
256
257    #[tokio::test]
258    async fn test_get_context_hint_empty() {
259        let ctx = SessionContext::new();
260        assert!(ctx.get_context_hint().await.is_none());
261    }
262
263    #[tokio::test]
264    async fn test_get_context_hint_falls_back_to_tool_names() {
265        let ctx = SessionContext::new();
266        ctx.observe_tool_call("bash", &serde_json::json!({})).await;
267        let hint = ctx.get_context_hint().await.unwrap();
268        assert_eq!(hint, "bash");
269    }
270
271    // —— Feature D: recency-weighted conversation n-gram ——
272
273    #[tokio::test]
274    async fn test_conversation_ngram_empty() {
275        let ctx = SessionContext::new();
276        assert!(ctx.conversation_ngram(5).await.is_none());
277    }
278
279    #[tokio::test]
280    async fn test_conversation_ngram_weights_recent_turns_more() {
281        let ctx = SessionContext::new();
282        // Oldest -> newest: A, B, C.
283        ctx.observe_tool_call("a", &serde_json::json!({ "query": "alpha" }))
284            .await;
285        ctx.observe_tool_call("b", &serde_json::json!({ "query": "beta" }))
286            .await;
287        ctx.observe_tool_call("c", &serde_json::json!({ "query": "gamma" }))
288            .await;
289
290        // window=3 -> weights newest 3, next 2, oldest 1.
291        let key = ctx.conversation_ngram(3).await.unwrap();
292        let count = |needle: &str| key.matches(needle).count();
293        assert_eq!(count("gamma"), 3, "newest turn repeats most: {}", key);
294        assert_eq!(count("beta"), 2, "middle turn: {}", key);
295        assert_eq!(count("alpha"), 1, "oldest turn: {}", key);
296        // Newest first.
297        assert!(
298            key.find("gamma").unwrap() < key.find("alpha").unwrap(),
299            "newest turn must lead the key: {}",
300            key
301        );
302    }
303
304    #[tokio::test]
305    async fn test_conversation_ngram_respects_window() {
306        let ctx = SessionContext::new();
307        for name in ["one", "two", "three", "four"] {
308            ctx.observe_tool_call(name, &serde_json::json!({ "query": name }))
309                .await;
310        }
311        // window=2 keeps only the two most recent turns.
312        let key = ctx.conversation_ngram(2).await.unwrap();
313        assert!(key.contains("four"));
314        assert!(key.contains("three"));
315        assert!(!key.contains("two"), "older turns drop out: {}", key);
316        assert!(!key.contains("one"), "older turns drop out: {}", key);
317    }
318
319    #[tokio::test]
320    async fn test_conversation_ngram_bounded_length() {
321        let ctx = SessionContext::new();
322        // Many long turns: the assembled key must stay bounded.
323        for i in 0..20 {
324            ctx.observe_tool_call(
325                "edit",
326                &serde_json::json!({ "content": format!("turn content number {} padding padding", i) }),
327            )
328            .await;
329        }
330        let key = ctx.conversation_ngram(10).await.unwrap();
331        assert!(
332            key.len() <= 600 + 60,
333            "key must stay bounded: len={}",
334            key.len()
335        );
336    }
337
338    #[tokio::test]
339    async fn test_conversation_ngram_falls_back_to_tool_name() {
340        let ctx = SessionContext::new();
341        ctx.observe_tool_call("bash", &serde_json::json!({})).await;
342        let key = ctx.conversation_ngram(5).await.unwrap();
343        assert!(key.contains("bash"), "tool name used when no hint: {}", key);
344    }
345
346    #[test]
347    fn test_extract_context_hint_parts() {
348        let args = serde_json::json!({ "path": "/x", "query": "q", "content": "c" });
349        let hint = SessionContext::extract_context_hint("tool", &args);
350        assert_eq!(hint.as_deref(), Some("tool /x q c"));
351
352        // content longer than 200 chars is omitted but path/query remain
353        let long = "x".repeat(250);
354        let args = serde_json::json!({ "path": "/x", "query": "q", "content": long });
355        let hint = SessionContext::extract_context_hint("tool", &args);
356        assert_eq!(hint.as_deref(), Some("tool /x q"));
357
358        // only tool name -> None
359        let hint = SessionContext::extract_context_hint("tool", &serde_json::json!({}));
360        assert!(hint.is_none());
361    }
362
363    #[test]
364    fn test_infer_project_from_src_path() {
365        let args = serde_json::json!({ "path": "/repo/app/src/main.rs" });
366        assert_eq!(
367            SessionContext::infer_project_from_args(&args),
368            Some("project:app".to_string())
369        );
370    }
371
372    #[test]
373    fn test_infer_project_from_crates_path() {
374        let args = serde_json::json!({ "path": "/workspace/backend/crates/api/lib.rs" });
375        // the directory BEFORE "crates" is taken as the project root
376        assert_eq!(
377            SessionContext::infer_project_from_args(&args),
378            Some("project:backend".to_string())
379        );
380    }
381
382    #[test]
383    fn test_infer_project_fallback_deep_path() {
384        let args = serde_json::json!({ "path": "/Users/x/Projects/webshop/frontend/" });
385        // no src/lib/crates/packages marker -> first non-home component
386        assert_eq!(
387            SessionContext::infer_project_from_args(&args),
388            Some("project:Projects".to_string())
389        );
390    }
391
392    #[test]
393    fn test_infer_project_missing_path() {
394        let args = serde_json::json!({});
395        assert_eq!(SessionContext::infer_project_from_args(&args), None);
396    }
397}