Skip to main content

memvault_proxy/
extraction.rs

1use std::sync::Arc;
2
3use tracing::{debug, info, warn};
4
5use memvault_core::dedup::Deduplicator;
6use memvault_core::extractor::{ExtractedMemory, Extractor};
7use memvault_core::llm_extractor::{LazyLlmExtractor, LlmExtractor};
8use memvault_core::models::*;
9use memvault_core::storage::MemoryStore;
10
11/// What to do with agent-produced text on the assistant extraction path.
12///
13/// Agent output fed back into memory unchecked causes self-reinforcing
14/// drift (the store converges on the model's own phrasing and errors), so
15/// even the permissive default keeps such memories in a review-pending
16/// state instead of trusting them.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum AssistantExtractionPolicy {
19    /// Save, but downgraded: tagged `review:required` with lowered
20    /// confidence. Default for backwards compatibility — extraction stays
21    /// on, but nothing agent-produced is trusted before human review.
22    #[default]
23    Downgraded,
24    /// Do not save agent-produced extractions at all
25    /// (`MEMVAULT_EXTRACT_ASSISTANT=off`).
26    Disabled,
27}
28
29pub struct ExtractionConfig {
30    /// Only extract memories with confidence >= this threshold
31    pub min_confidence: f64,
32    /// Maximum memories to extract per response
33    pub max_per_response: usize,
34    /// Types allowed for extraction (whitelist)
35    pub allowed_types: Vec<MemoryType>,
36    /// Treatment of agent-produced text (see type docs).
37    pub assistant_policy: AssistantExtractionPolicy,
38}
39
40impl Default for ExtractionConfig {
41    fn default() -> Self {
42        Self {
43            min_confidence: 0.6,
44            max_per_response: 5,
45            allowed_types: vec![MemoryType::Preference, MemoryType::Fact, MemoryType::Skill],
46            assistant_policy: AssistantExtractionPolicy::default(),
47        }
48    }
49}
50
51impl ExtractionConfig {
52    /// Default config with environment overrides:
53    /// `MEMVAULT_EXTRACT_ASSISTANT=off|disabled|false|0` disables extracting
54    /// from agent responses entirely.
55    pub fn from_env() -> Self {
56        let mut cfg = Self::default();
57        if let Ok(v) = std::env::var("MEMVAULT_EXTRACT_ASSISTANT")
58            && memvault_core::env_file::parse_bool(&v) == Some(false)
59        {
60            cfg.assistant_policy = AssistantExtractionPolicy::Disabled;
61        }
62        cfg
63    }
64}
65
66pub struct ExtractionResult {
67    pub extracted: usize,
68    pub saved: usize,
69    pub skipped: usize,
70}
71
72pub struct ResponseExtractor {
73    store: Arc<dyn MemoryStore>,
74    config: ExtractionConfig,
75    /// Contextual (LLM-based) extractor holder. When it resolves to `None`,
76    /// extraction stays 100% rule-based — this mirrors the embedding
77    /// provider's optional-provider shape, but with no bundled local
78    /// fallback: an LLM call has real cost/latency/hallucination risk, so it
79    /// must be an explicit opt-in via `MEMVAULT_LLM_EXTRACTION_PROVIDER`.
80    /// The lazy holder re-probes the environment after a failed probe, so a
81    /// boot-time Ollama hiccup doesn't disable it for the process lifetime.
82    llm_extractor: LazyLlmExtractor,
83    /// Write-time duplicate guard. Before an extraction is saved it is
84    /// compared (keyword Jaccard; vector when a provider is configured)
85    /// against existing memories, so identical auto-extractions cannot
86    /// pile up between manual `run_dedup` cycles.
87    deduplicator: Deduplicator,
88}
89
90impl ResponseExtractor {
91    pub fn new(store: Arc<dyn MemoryStore>, config: ExtractionConfig) -> Self {
92        Self {
93            store: store.clone(),
94            config,
95            llm_extractor: LazyLlmExtractor::fixed(None),
96            deduplicator: Deduplicator::new(store, None),
97        }
98    }
99
100    pub fn with_llm_extractor(mut self, extractor: Arc<dyn LlmExtractor>) -> Self {
101        self.llm_extractor = LazyLlmExtractor::fixed(Some(extractor));
102        self
103    }
104
105    /// Production wiring: hand over a lazily-probed holder instead of a
106    /// one-shot startup result (see [`LazyLlmExtractor`]).
107    pub fn with_lazy_llm_extractor(mut self, extractor: LazyLlmExtractor) -> Self {
108        self.llm_extractor = extractor;
109        self
110    }
111
112    /// The same lazily-probed LLM extractor this extractor uses internally —
113    /// exposed so sibling tools (e.g. `infer_outcome`'s LLM-judge path) reuse
114    /// one probe/cache instead of each building their own.
115    pub async fn llm_extractor(&self) -> Option<Arc<dyn LlmExtractor>> {
116        self.llm_extractor.get().await
117    }
118
119    /// Extract memories from an agent's own response text and save to store as unreviewed (Inbox).
120    pub async fn extract_and_save(&self, response_text: &str, agent_id: &str) -> ExtractionResult {
121        self.extract_and_save_labeled(response_text, agent_id, "assistant")
122            .await
123    }
124
125    /// Extract memories directly from the user's own turn text. First-person
126    /// signal words ("我偏好"/"我喜欢") match a user's own statements about
127    /// themselves far more reliably than an assistant's restatement of them,
128    /// so this path typically has higher recall than `extract_and_save`.
129    pub async fn extract_and_save_from_user(
130        &self,
131        user_text: &str,
132        agent_id: &str,
133    ) -> ExtractionResult {
134        self.extract_and_save_labeled(user_text, agent_id, "user")
135            .await
136    }
137
138    async fn extract_and_save_labeled(
139        &self,
140        text: &str,
141        agent_id: &str,
142        source: &str,
143    ) -> ExtractionResult {
144        let role = self.role_for_source(source);
145
146        let guarded = Extractor::extract_guarded(text, role);
147        if let Some(reason) = guarded.rejection {
148            info!(
149                agent_id,
150                source,
151                reason = ?reason,
152                "extraction refused by source-role guard"
153            );
154            return ExtractionResult {
155                extracted: 0,
156                saved: 0,
157                skipped: 0,
158            };
159        }
160        let extracted = guarded.outcome.memories;
161        if extracted.is_empty() {
162            return ExtractionResult {
163                extracted: 0,
164                saved: 0,
165                skipped: 0,
166            };
167        }
168
169        let (saved, skipped) = self
170            .save_extracted(&extracted, agent_id, source, "rule")
171            .await;
172
173        info!(
174            extracted = extracted.len(),
175            saved, skipped, agent_id, source, "extraction complete"
176        );
177
178        ExtractionResult {
179            extracted: extracted.len(),
180            saved,
181            skipped,
182        }
183    }
184
185    /// Source-role guard: user turns extract normally; agent-produced text
186    /// is either refused outright (Disabled) or routed through the
187    /// untrusted-provenance path (Downgraded → review:required + lowered
188    /// confidence), never through the trusted one.
189    fn role_for_source(&self, source: &str) -> memvault_core::extractor::SourceRole {
190        if source == "user" {
191            memvault_core::extractor::SourceRole::User
192        } else {
193            match self.config.assistant_policy {
194                AssistantExtractionPolicy::Disabled => memvault_core::extractor::SourceRole::Agent,
195                AssistantExtractionPolicy::Downgraded => {
196                    memvault_core::extractor::SourceRole::Mixed
197                }
198            }
199        }
200    }
201
202    /// Convert extracted memories into `Memory` rows and save them,
203    /// applying the confidence/type filters. Any provenance downgrade
204    /// (review:required + confidence discount) must already be baked into
205    /// `extracted` by the caller — see [`Extractor::extract_guarded`] for
206    /// the rule-based path and [`Self::downgrade_mixed_provenance`] for the
207    /// LLM path — so this stays a pure convert-and-save step shared by
208    /// both, instead of each path re-deriving its own persistence logic.
209    async fn save_extracted(
210        &self,
211        extracted: &[ExtractedMemory],
212        agent_id: &str,
213        source: &str,
214        method: &str,
215    ) -> (usize, usize) {
216        let mut saved = 0;
217        let mut skipped = 0;
218
219        for e in extracted.iter().take(self.config.max_per_response) {
220            if e.confidence < self.config.min_confidence {
221                skipped += 1;
222                continue;
223            }
224            if !self.config.allowed_types.contains(&e.memory_type) {
225                skipped += 1;
226                continue;
227            }
228
229            // Skip extractions that duplicate an already-stored memory
230            // (exact or near-duplicate). Dedup was previously only a manual
231            // `run_dedup` step, which let identical auto-extractions
232            // accumulate (observed: the same user question saved twice
233            // four minutes apart as mem_cca7 + mem_a330).
234            if let Ok(Some(pair)) = self.deduplicator.check_duplicate(&e.content, None).await {
235                debug!(
236                    existing_id = %pair.existing_id,
237                    similarity = %pair.similarity,
238                    "extraction skipped as duplicate"
239                );
240                skipped += 1;
241                continue;
242            }
243
244            let mut mem = Memory::new(
245                e.memory_type.clone(),
246                e.content.clone(),
247                e.priority.clone(),
248                SourceAgent {
249                    id: agent_id.to_string(),
250                    agent_type: "extraction-pipeline".to_string(),
251                    session_id: None,
252                },
253            );
254            mem.instruction = e.instruction.clone();
255            mem.tags = e.tags.clone();
256            mem.tags.push(format!("source:{source}"));
257            mem.tags.push(format!("method:{method}"));
258            mem.confidence = e.confidence;
259            mem.ai_generated = true;
260            mem.human_reviewed = false;
261            mem.layer = match e.priority {
262                Priority::Must => MemoryLayer::L1,
263                _ => MemoryLayer::L1,
264            };
265
266            match self.store.save(mem).await {
267                Ok(m) => {
268                    debug!(id = %m.id, "extraction saved to inbox");
269                    saved += 1;
270                }
271                Err(err) => {
272                    warn!(error = %err, "extraction save failed");
273                    skipped += 1;
274                }
275            }
276        }
277
278        (saved, skipped)
279    }
280
281    /// Apply the same review-required downgrade that
282    /// [`Extractor::extract_guarded`]'s `Mixed`/`Unknown` branch applies to
283    /// rule-based extractions — but to LLM output, since the LLM path calls
284    /// the extractor trait directly and never goes through that guard.
285    /// "Provenance not confirmed as the user" must never be treated as
286    /// "confirmed user", regardless of which extraction method produced it.
287    fn downgrade_mixed_provenance(extracted: &mut [ExtractedMemory]) {
288        for m in extracted {
289            if !m.tags.iter().any(|t| t == "review:required") {
290                m.tags.push("review:required".to_string());
291            }
292            m.confidence *= 0.9;
293        }
294    }
295
296    /// Extract from a paired user+assistant turn as one piece of
297    /// *context*, rather than scanning each text independently for
298    /// keyword signals. When an LLM extractor is configured, it sees both
299    /// sides of the exchange together — recovering implicit preferences
300    /// and cross-sentence references the line-by-line rule engine misses.
301    /// Falls back to the rule-based per-text extraction (unchanged
302    /// behavior) when no LLM extractor is configured, or if the LLM call
303    /// fails — an LLM outage must never break the extraction pipeline.
304    pub async fn extract_and_save_contextual(
305        &self,
306        user_text: Option<&str>,
307        response_text: &str,
308        agent_id: &str,
309    ) -> ExtractionResult {
310        // Same per-source policy as the rule-based path: the assistant side
311        // is dropped from consideration entirely when the policy is
312        // Disabled, while the user side is never affected by that policy.
313        let assistant_included = !response_text.trim().is_empty()
314            && !matches!(
315                self.role_for_source("assistant"),
316                memvault_core::extractor::SourceRole::Agent
317            );
318        let user_included = user_text.is_some_and(|t| !t.trim().is_empty());
319
320        if !assistant_included && !user_included {
321            return ExtractionResult {
322                extracted: 0,
323                saved: 0,
324                skipped: 0,
325            };
326        }
327
328        if let Some(llm) = self.llm_extractor.get().await {
329            let mut context = String::new();
330            if user_included {
331                context.push_str("User: ");
332                context.push_str(user_text.unwrap());
333                context.push('\n');
334            }
335            if assistant_included {
336                context.push_str("Assistant: ");
337                context.push_str(response_text);
338            }
339
340            match llm.extract(&context).await {
341                Ok(mut extracted) if !extracted.is_empty() => {
342                    let contextual_source = if assistant_included { "mixed" } else { "user" };
343                    if contextual_source == "mixed" {
344                        Self::downgrade_mixed_provenance(&mut extracted);
345                    }
346                    let (saved, skipped) = self
347                        .save_extracted(&extracted, agent_id, contextual_source, "llm")
348                        .await;
349                    info!(
350                        extracted = extracted.len(),
351                        saved, skipped, agent_id, "contextual llm extraction complete"
352                    );
353                    return ExtractionResult {
354                        extracted: extracted.len(),
355                        saved,
356                        skipped,
357                    };
358                }
359                Ok(_) => {
360                    return ExtractionResult {
361                        extracted: 0,
362                        saved: 0,
363                        skipped: 0,
364                    };
365                }
366                Err(err) => {
367                    warn!(error = %err, "llm extraction failed, falling back to rule-based");
368                }
369            }
370        }
371
372        // No LLM extractor configured, or it failed above: fall back to
373        // the original rule-based, per-text extraction (each side keeps
374        // its own independent source-role guard, exactly as before).
375        let mut result = self
376            .extract_and_save_labeled(response_text, agent_id, "assistant")
377            .await;
378        if let Some(user_text) = user_text.filter(|t| !t.trim().is_empty()) {
379            let user_result = self
380                .extract_and_save_labeled(user_text, agent_id, "user")
381                .await;
382            result.extracted += user_result.extracted;
383            result.saved += user_result.saved;
384            result.skipped += user_result.skipped;
385        }
386        result
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393    use memvault_core::error::Result as CoreResult;
394    use memvault_core::storage::sqlite::SqliteStore;
395
396    /// Stub `LlmExtractor` returning a fixed set of memories (or an error),
397    /// so the contextual-extraction wiring can be tested without a real
398    /// network call.
399    struct StubLlmExtractor {
400        result: std::sync::Mutex<Option<CoreResult<Vec<ExtractedMemory>>>>,
401        seen_context: std::sync::Mutex<Option<String>>,
402    }
403
404    impl StubLlmExtractor {
405        fn returning(memories: Vec<ExtractedMemory>) -> Self {
406            Self {
407                result: std::sync::Mutex::new(Some(Ok(memories))),
408                seen_context: std::sync::Mutex::new(None),
409            }
410        }
411
412        fn failing(msg: &str) -> Self {
413            Self {
414                result: std::sync::Mutex::new(Some(Err(
415                    memvault_core::error::MemVaultError::LlmExtraction(msg.to_string()),
416                ))),
417                seen_context: std::sync::Mutex::new(None),
418            }
419        }
420    }
421
422    #[async_trait::async_trait]
423    impl memvault_core::llm_extractor::LlmExtractor for StubLlmExtractor {
424        async fn extract(&self, context: &str) -> CoreResult<Vec<ExtractedMemory>> {
425            *self.seen_context.lock().unwrap() = Some(context.to_string());
426            self.result
427                .lock()
428                .unwrap()
429                .take()
430                .unwrap_or_else(|| Ok(Vec::new()))
431        }
432    }
433
434    fn stub_memory(content: &str) -> ExtractedMemory {
435        ExtractedMemory {
436            content: content.to_string(),
437            instruction: None,
438            memory_type: MemoryType::Preference,
439            priority: Priority::Reference,
440            tags: vec!["stub".to_string()],
441            confidence: 0.9,
442        }
443    }
444
445    #[tokio::test]
446    async fn test_extract_from_preference_response() {
447        let store = Arc::new(SqliteStore::in_memory().unwrap());
448        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default());
449
450        // User-facing text that the extractor can pick up:
451        let user_text = "I prefer Python over Java. Our project uses FastAPI.";
452
453        let result = extractor.extract_and_save(user_text, "test-agent").await;
454        assert!(result.extracted >= 1);
455        assert!(result.saved >= 1);
456
457        let all = store.list(None, 100, 0).await.unwrap();
458        assert!(!all.is_empty());
459        assert!(!all[0].human_reviewed);
460    }
461
462    #[tokio::test]
463    async fn test_extract_nothing_from_irrelevant() {
464        let store = Arc::new(SqliteStore::in_memory().unwrap());
465        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default());
466
467        let text = "The weather is nice today. Let me help you with that code.";
468        let result = extractor.extract_and_save(text, "test-agent").await;
469        assert_eq!(result.extracted, 0);
470        assert_eq!(result.saved, 0);
471    }
472
473    #[tokio::test]
474    async fn test_confidence_threshold() {
475        let store = Arc::new(SqliteStore::in_memory().unwrap());
476        let config = ExtractionConfig {
477            min_confidence: 0.99, // very high threshold
478            ..ExtractionConfig::default()
479        };
480        let extractor = ResponseExtractor::new(store.clone(), config);
481
482        let text = "I prefer dark mode for all editors";
483        let result = extractor.extract_and_save(text, "test-agent").await;
484        // Extracted but not saved due to high threshold
485        assert!(result.extracted >= 1);
486        assert_eq!(result.saved, 0);
487    }
488
489    #[tokio::test]
490    async fn test_max_per_response_limit() {
491        let store = Arc::new(SqliteStore::in_memory().unwrap());
492        let config = ExtractionConfig {
493            max_per_response: 1,
494            ..ExtractionConfig::default()
495        };
496        let extractor = ResponseExtractor::new(store.clone(), config);
497
498        let text = "I prefer Python\nI always use dark mode\nI never add comments";
499        let result = extractor.extract_and_save(text, "test-agent").await;
500        assert!(result.extracted >= 2);
501        assert_eq!(result.saved, 1);
502    }
503
504    #[tokio::test]
505    async fn test_extract_and_save_tags_source_assistant() {
506        let store = Arc::new(SqliteStore::in_memory().unwrap());
507        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default());
508
509        let result = extractor
510            .extract_and_save("I prefer dark mode", "test-agent")
511            .await;
512        assert!(result.saved >= 1);
513
514        let all = store.list(None, 100, 0).await.unwrap();
515        assert!(
516            all.iter()
517                .any(|m| m.tags.contains(&"source:assistant".to_string()))
518        );
519    }
520
521    #[tokio::test]
522    async fn test_extract_and_save_from_user_tags_source_user() {
523        let store = Arc::new(SqliteStore::in_memory().unwrap());
524        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default());
525
526        let result = extractor
527            .extract_and_save_from_user("我偏好使用 tabs 缩进", "test-agent")
528            .await;
529        assert!(result.saved >= 1);
530
531        let all = store.list(None, 100, 0).await.unwrap();
532        assert!(
533            all.iter()
534                .any(|m| m.tags.contains(&"source:user".to_string()))
535        );
536        // User text is trusted provenance: no review-required downgrade.
537        assert!(
538            all.iter()
539                .all(|m| !m.tags.contains(&"review:required".to_string()))
540        );
541    }
542
543    /// Default assistant policy keeps extraction on but nothing it saves is
544    /// trusted: every memory carries review:required.
545    #[tokio::test]
546    async fn test_assistant_extraction_default_is_downgraded() {
547        let store = Arc::new(SqliteStore::in_memory().unwrap());
548        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default());
549
550        let result = extractor
551            .extract_and_save("I prefer dark mode", "test-agent")
552            .await;
553        assert!(result.saved >= 1);
554
555        let all = store.list(None, 100, 0).await.unwrap();
556        assert!(
557            all.iter()
558                .all(|m| m.tags.contains(&"review:required".to_string())),
559            "agent-produced memories must wait for human review"
560        );
561    }
562
563    /// With the Disabled policy, agent output never reaches the store — the
564    /// guard refuses it before any save.
565    #[tokio::test]
566    async fn test_assistant_extraction_disabled_saves_nothing() {
567        let store = Arc::new(SqliteStore::in_memory().unwrap());
568        let config = ExtractionConfig {
569            assistant_policy: AssistantExtractionPolicy::Disabled,
570            ..ExtractionConfig::default()
571        };
572        let extractor = ResponseExtractor::new(store.clone(), config);
573
574        let result = extractor
575            .extract_and_save("I prefer dark mode", "test-agent")
576            .await;
577        assert_eq!(result.saved, 0);
578
579        let all = store.list(None, 100, 0).await.unwrap();
580        assert!(all.is_empty());
581
582        // The user path is unaffected by the assistant policy.
583        let user_result = extractor
584            .extract_and_save_from_user("I prefer dark mode", "test-agent")
585            .await;
586        assert!(user_result.saved >= 1);
587    }
588
589    /// When an LLM extractor is configured, `extract_and_save_contextual`
590    /// must use it (not the rule-based path), pass it both sides of the
591    /// exchange, and mark the saved memory `method:llm`.
592    #[tokio::test]
593    async fn test_contextual_uses_llm_extractor_when_configured() {
594        let store = Arc::new(SqliteStore::in_memory().unwrap());
595        let llm = Arc::new(StubLlmExtractor::returning(vec![stub_memory("likes tabs")]));
596        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default())
597            .with_llm_extractor(llm);
598
599        let result = extractor
600            .extract_and_save_contextual(
601                Some("I like tabs, not spaces"),
602                "Noted, I'll use tabs.",
603                "test-agent",
604            )
605            .await;
606        assert_eq!(result.saved, 1);
607
608        let all = store.list(None, 100, 0).await.unwrap();
609        assert_eq!(all.len(), 1);
610        assert!(all[0].tags.contains(&"method:llm".to_string()));
611        // Both user and assistant text present -> mixed provenance, so the
612        // same review-required downgrade as the rule path's Mixed role
613        // must apply.
614        assert!(all[0].tags.contains(&"review:required".to_string()));
615        assert!(all[0].tags.contains(&"source:mixed".to_string()));
616    }
617
618    /// User-only context (no assistant text) is trusted provenance, same as
619    /// the rule-based user path: no review-required downgrade.
620    #[tokio::test]
621    async fn test_contextual_llm_user_only_is_trusted() {
622        let store = Arc::new(SqliteStore::in_memory().unwrap());
623        let llm = Arc::new(StubLlmExtractor::returning(vec![stub_memory("likes tabs")]));
624        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default())
625            .with_llm_extractor(llm);
626
627        let result = extractor
628            .extract_and_save_contextual(Some("I like tabs, not spaces"), "", "test-agent")
629            .await;
630        assert_eq!(result.saved, 1);
631
632        let all = store.list(None, 100, 0).await.unwrap();
633        assert!(all[0].tags.contains(&"source:user".to_string()));
634        assert!(!all[0].tags.contains(&"review:required".to_string()));
635    }
636
637    /// An LLM failure must not break extraction: it falls back to the
638    /// original rule-based, per-text path and still saves what the rule
639    /// engine can find.
640    #[tokio::test]
641    async fn test_contextual_falls_back_to_rule_based_on_llm_error() {
642        let store = Arc::new(SqliteStore::in_memory().unwrap());
643        let llm = Arc::new(StubLlmExtractor::failing("network down"));
644        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default())
645            .with_llm_extractor(llm);
646
647        let result = extractor
648            .extract_and_save_contextual(None, "I always prefer dark mode", "test-agent")
649            .await;
650        assert!(result.saved >= 1);
651
652        let all = store.list(None, 100, 0).await.unwrap();
653        assert!(
654            all.iter()
655                .any(|m| m.tags.contains(&"method:rule".to_string()))
656        );
657    }
658
659    /// With no LLM extractor configured at all, contextual extraction must
660    /// behave exactly like the pre-existing rule-based two-call path.
661    #[tokio::test]
662    async fn test_contextual_without_llm_extractor_uses_rule_based() {
663        let store = Arc::new(SqliteStore::in_memory().unwrap());
664        let extractor = ResponseExtractor::new(store.clone(), ExtractionConfig::default());
665
666        let result = extractor
667            .extract_and_save_contextual(Some("我偏好用 tabs 缩进"), "好的", "test-agent")
668            .await;
669        assert!(result.saved >= 1);
670
671        let all = store.list(None, 100, 0).await.unwrap();
672        assert!(
673            all.iter()
674                .any(|m| m.tags.contains(&"source:user".to_string())
675                    && m.tags.contains(&"method:rule".to_string()))
676        );
677    }
678
679    /// Disabled assistant policy: the assistant side must be excluded from
680    /// the LLM context entirely, while user text still gets extracted.
681    #[tokio::test]
682    async fn test_contextual_disabled_policy_excludes_assistant_from_llm_context() {
683        let store = Arc::new(SqliteStore::in_memory().unwrap());
684        let llm = Arc::new(StubLlmExtractor::returning(vec![stub_memory("likes tabs")]));
685        let config = ExtractionConfig {
686            assistant_policy: AssistantExtractionPolicy::Disabled,
687            ..ExtractionConfig::default()
688        };
689        let extractor =
690            ResponseExtractor::new(store.clone(), config).with_llm_extractor(llm.clone());
691
692        let result = extractor
693            .extract_and_save_contextual(
694                Some("I like tabs, not spaces"),
695                "I always prefer dark mode too",
696                "test-agent",
697            )
698            .await;
699        assert_eq!(result.saved, 1);
700
701        let seen = llm.seen_context.lock().unwrap().clone().unwrap();
702        assert!(seen.contains("I like tabs"));
703        assert!(
704            !seen.contains("Assistant:"),
705            "disabled assistant policy must exclude assistant text from the LLM context, got: {seen}"
706        );
707
708        let all = store.list(None, 100, 0).await.unwrap();
709        assert!(all[0].tags.contains(&"source:user".to_string()));
710        assert!(!all[0].tags.contains(&"review:required".to_string()));
711    }
712}