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