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