Skip to main content

vtcode_core/persistent_memory/
mod.rs

1use anyhow::{Context, Result, anyhow, bail};
2use serde::de::DeserializeOwned;
3use serde::{Deserialize, Serialize};
4use serde_json::json;
5use std::collections::BTreeSet;
6use std::fmt::Write;
7use std::path::{Path, PathBuf};
8use std::time::{SystemTime, UNIX_EPOCH};
9use tokio::time::{Duration, sleep};
10
11use crate::config::loader::VTCodeConfig;
12use crate::config::types::AgentConfig as RuntimeAgentConfig;
13use crate::config::{ConfigManager, PersistentMemoryConfig};
14use crate::llm::factory::infer_provider_from_model;
15use crate::llm::provider::{LLMProvider, LLMRequest, Message, MessageRole};
16use crate::llm::{
17    LightweightFeature, collect_single_response, create_provider_for_model_route, resolve_lightweight_route,
18};
19use vtcode_commons::VtCodePaths;
20
21mod batch;
22mod fact_extraction;
23mod legacy_migration;
24mod llm_ops;
25mod lock;
26mod reader;
27mod rendering;
28
29pub use batch::{BatchMemoryReport, batch_parameters_from_config, run_batch_memory_extraction};
30pub use fact_extraction::{
31    dedup_latest_facts, maybe_extract_tool_fact, maybe_extract_user_fact, normalize_whitespace, truncate_for_fact,
32};
33use legacy_migration::{
34    migrate_legacy_persistent_memory_dir_if_needed, persistent_memory_base_dir, persistent_memory_project_name,
35    sanitize_project_name,
36};
37use llm_ops::{classify_facts_strict, plan_memory_operation, summarize_memory};
38use lock::MemoryLock;
39use reader::{
40    MemoryNoteSummary, classify_fact, collect_all_memory_matches, collect_cleanup_candidates, collect_memory_matches,
41    count_pending_rollout_summaries, count_pending_rollout_summaries_async, decode_topic_source, encode_topic_source,
42    list_pending_rollout_files_async, list_rollout_markdown_files, list_rollout_markdown_files_async,
43    normalize_memory_query, parse_fact_line, parse_topic_file, read_note_summaries, read_rollout_records,
44    read_topic_records,
45};
46use rendering::{
47    render_memory_index, render_memory_summary, render_memory_summary_bullets, render_rollout_summary,
48    render_topic_file, unique_rollout_id,
49};
50
51// Re-exported at crate-visible-but-restricted scope solely so that
52// `persistent_memory_tests` (a descendant module of `persistent_memory`, see
53// `#[cfg(test)] mod persistent_memory_tests;` below) can reach these
54// otherwise-internal submodule items through its `use super::*;`. They are
55// not referenced by any non-test code in this module, so the imports are
56// gated behind `#[cfg(test)]` to avoid unused-import warnings in normal
57// builds.
58#[cfg(test)]
59use legacy_migration::migrate_legacy_memory_dir;
60#[cfg(test)]
61use llm_ops::{
62    MemoryModelRoute, MemoryPhase, classify_facts_with_provider, plan_memory_operation_with_provider,
63    resolve_memory_model_routes, summarize_memory_with_provider,
64};
65#[cfg(test)]
66use lock::{LOCK_STALE_AFTER_SECS, lock_age};
67
68mod facts;
69use facts::{
70    CLEANUP_NOTE_PREFIXES, FactsInput, SELF_FACT_PREFIXES, STRIP_PREFIXES, consolidate_memory_files,
71    detect_memory_cleanup_status, detect_memory_cleanup_status_async, ensure_memory_layout, is_regular_file,
72    looks_like_legacy_prompt, memory_plan_facts, persist_memory_internal, remove_rollout_markdown_files,
73    rewrite_topic_without_selected, scrub_rollout_file_by_selection, selected_memory_candidates,
74    truncate_memory_excerpt,
75};
76
77pub const MEMORY_FILENAME: &str = "MEMORY.md";
78pub const MEMORY_SUMMARY_FILENAME: &str = "memory_summary.md";
79pub const ROLLOUT_SUMMARIES_DIRNAME: &str = "rollout_summaries";
80pub const NOTES_DIRNAME: &str = "notes";
81
82const MEMORY_LOCK_FILENAME: &str = ".memory.lock";
83const PREFERENCES_FILENAME: &str = "preferences.md";
84const REPOSITORY_FACTS_FILENAME: &str = "repository-facts.md";
85const DEFAULT_FACT_LIMIT: usize = 24;
86const MEMORY_HIGHLIGHT_LIMIT: usize = 10;
87const TOPIC_FACT_LIMIT: usize = 32;
88
89#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
90pub struct GroundedFactRecord {
91    pub fact: String,
92    pub source: String,
93}
94
95#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
96pub struct PersistentMemoryStatus {
97    pub enabled: bool,
98    pub auto_write: bool,
99    pub directory: PathBuf,
100    pub summary_file: PathBuf,
101    pub memory_file: PathBuf,
102    pub preferences_file: PathBuf,
103    pub repository_facts_file: PathBuf,
104    pub notes_dir: PathBuf,
105    pub rollout_summaries_dir: PathBuf,
106    pub summary_exists: bool,
107    pub registry_exists: bool,
108    pub pending_rollout_summaries: usize,
109    pub cleanup_status: MemoryCleanupStatus,
110}
111
112#[derive(Debug, Clone, Serialize)]
113pub struct PersistentMemoryExcerpt {
114    pub status: PersistentMemoryStatus,
115    pub contents: String,
116    pub truncated: bool,
117    pub bytes_read: usize,
118    pub lines_read: usize,
119    /// Rough token estimate of the returned excerpt (0 when no token budget
120    /// is configured; whitespace-based approximation, not exact tokenization).
121    pub tokens_estimated: usize,
122}
123
124#[derive(Debug, Clone, Serialize)]
125pub struct PersistentMemoryWriteReport {
126    pub directory: PathBuf,
127    pub summary_file: PathBuf,
128    pub memory_file: PathBuf,
129    pub rollout_summary_file: Option<PathBuf>,
130    pub created_files: Vec<PathBuf>,
131    pub added_facts: usize,
132    pub pending_rollout_summaries: usize,
133}
134
135#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
136pub struct PersistentMemoryMatch {
137    pub source: String,
138    pub fact: String,
139}
140
141#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
142pub struct PersistentMemoryForgetReport {
143    pub directory: PathBuf,
144    pub summary_file: PathBuf,
145    pub memory_file: PathBuf,
146    pub removed_facts: usize,
147    pub pending_rollout_summaries: usize,
148}
149
150#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
151pub struct MemoryCleanupStatus {
152    pub needed: bool,
153    pub suspicious_facts: usize,
154    pub suspicious_summary_lines: usize,
155}
156
157#[derive(Debug, Clone, Serialize)]
158pub struct PersistentMemoryCleanupReport {
159    pub directory: PathBuf,
160    pub summary_file: PathBuf,
161    pub memory_file: PathBuf,
162    pub rewritten_facts: usize,
163    pub removed_rollout_files: usize,
164}
165
166pub fn extract_memory_highlights(contents: &str, limit: usize) -> Vec<String> {
167    if limit == 0 {
168        return Vec::new();
169    }
170    let mut highlights = Vec::with_capacity(limit);
171    for line in contents.lines() {
172        let trimmed = line.trim();
173        if trimmed.is_empty() || trimmed.starts_with('#') {
174            continue;
175        }
176        let normalized = trimmed
177            .strip_prefix("- ")
178            .or_else(|| trimmed.strip_prefix("* "))
179            .or_else(|| trimmed.strip_prefix("+ "))
180            .unwrap_or(trimmed);
181        if normalized.is_empty() || highlights.iter().any(|e| e == normalized) {
182            continue;
183        }
184        highlights.push(normalized.to_string());
185        if highlights.len() >= limit {
186            break;
187        }
188    }
189    highlights
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
193#[serde(rename_all = "snake_case")]
194pub enum MemoryOpKind {
195    Remember,
196    Forget,
197    AskMissing,
198    Noop,
199}
200
201#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
202pub struct MemoryOpCandidate {
203    pub id: usize,
204    pub source: String,
205    pub fact: String,
206}
207
208#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
209#[serde(rename_all = "snake_case")]
210pub enum MemoryPlannedTopic {
211    Preferences,
212    RepositoryFacts,
213}
214
215#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
216pub struct MemoryPlannedFact {
217    pub topic: MemoryPlannedTopic,
218    pub fact: String,
219    #[serde(default)]
220    pub source: String,
221}
222
223#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
224pub struct MemoryMissingField {
225    pub field: String,
226    pub prompt: String,
227}
228
229#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
230pub struct MemoryOpPlan {
231    pub kind: MemoryOpKind,
232    #[serde(default)]
233    pub facts: Vec<MemoryPlannedFact>,
234    #[serde(default)]
235    pub selected_ids: Vec<usize>,
236    #[serde(default)]
237    pub missing: Option<MemoryMissingField>,
238    #[serde(default)]
239    pub message: Option<String>,
240}
241
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243#[repr(usize)]
244enum MemoryTopic {
245    Preferences = 0,
246    RepositoryFacts = 1,
247}
248
249impl MemoryTopic {
250    fn title(self) -> &'static str {
251        ["Preferences", "Repository Facts"][self as usize]
252    }
253
254    fn description(self) -> &'static str {
255        [
256            "Durable user preferences and workflow notes.",
257            "Grounded repository facts and recurring tooling notes.",
258        ][self as usize]
259    }
260
261    fn slug(self) -> &'static str {
262        ["preferences", "repository_facts"][self as usize]
263    }
264
265    fn from_slug(value: &str) -> Option<Self> {
266        match value {
267            "preferences" => Some(Self::Preferences),
268            "repository_facts" => Some(Self::RepositoryFacts),
269            _ => None,
270        }
271    }
272}
273
274#[derive(Debug, Clone)]
275pub(super) struct PersistentMemoryFiles {
276    pub(super) directory: PathBuf,
277    pub(super) private_global: bool,
278    pub(super) summary_file: PathBuf,
279    pub(super) memory_file: PathBuf,
280    pub(super) preferences_file: PathBuf,
281    pub(super) repository_facts_file: PathBuf,
282    pub(super) notes_dir: PathBuf,
283    pub(super) rollout_summaries_dir: PathBuf,
284    pub(super) lock_file: PathBuf,
285}
286
287impl PersistentMemoryFiles {
288    fn new(directory: PathBuf, private_global: bool) -> Self {
289        Self {
290            summary_file: directory.join(MEMORY_SUMMARY_FILENAME),
291            memory_file: directory.join(MEMORY_FILENAME),
292            preferences_file: directory.join(PREFERENCES_FILENAME),
293            repository_facts_file: directory.join(REPOSITORY_FACTS_FILENAME),
294            notes_dir: directory.join(NOTES_DIRNAME),
295            rollout_summaries_dir: directory.join(ROLLOUT_SUMMARIES_DIRNAME),
296            lock_file: directory.join(MEMORY_LOCK_FILENAME),
297            directory,
298            private_global,
299        }
300    }
301}
302
303#[derive(Debug, Clone)]
304pub(super) struct ClassifiedFacts {
305    pub(super) preferences: Vec<GroundedFactRecord>,
306    pub(super) repository_facts: Vec<GroundedFactRecord>,
307}
308
309impl ClassifiedFacts {
310    pub(super) fn total(&self) -> usize {
311        self.preferences.len() + self.repository_facts.len()
312    }
313}
314
315/// Resolves the persistent memory directory for a project.
316///
317/// **Blocking**: This function may perform filesystem I/O (directory migration).
318/// Callers in async contexts must wrap this in `tokio::task::spawn_blocking`.
319pub fn resolve_persistent_memory_dir(
320    config: &PersistentMemoryConfig,
321    workspace_root: &Path,
322) -> Result<Option<PathBuf>> {
323    let project_name = persistent_memory_project_name(workspace_root);
324    let directory = persistent_memory_base_dir(config)?
325        .join("projects")
326        .join(sanitize_project_name(&project_name))
327        .join("memory");
328    migrate_legacy_persistent_memory_dir_if_needed(config, &project_name, &directory)?;
329    Ok(Some(directory))
330}
331
332/// Returns the current persistent memory status.
333///
334/// **Blocking**: This function performs filesystem I/O (directory migration,
335/// file existence checks, reading topic files). Callers in async contexts
336/// must wrap this in `tokio::task::spawn_blocking`.
337pub fn persistent_memory_status(
338    config: &PersistentMemoryConfig,
339    workspace_root: &Path,
340) -> Result<PersistentMemoryStatus> {
341    let directory = resolve_persistent_memory_dir(config, workspace_root)?
342        .ok_or_else(|| anyhow!("persistent memory path policy returned no storage directory"))?;
343    let files = PersistentMemoryFiles::new(directory, config.directory_override.is_none());
344    let pending_rollout_summaries = count_pending_rollout_summaries(&files.rollout_summaries_dir)?;
345    let cleanup_status = detect_memory_cleanup_status(&files)?;
346
347    Ok(PersistentMemoryStatus {
348        enabled: config.enabled,
349        auto_write: config.auto_write,
350        summary_exists: is_regular_file(&files.summary_file),
351        registry_exists: is_regular_file(&files.memory_file),
352        pending_rollout_summaries,
353        cleanup_status,
354        directory: files.directory,
355        summary_file: files.summary_file,
356        memory_file: files.memory_file,
357        preferences_file: files.preferences_file,
358        repository_facts_file: files.repository_facts_file,
359        notes_dir: files.notes_dir,
360        rollout_summaries_dir: files.rollout_summaries_dir,
361    })
362}
363
364pub async fn read_persistent_memory_excerpt(
365    config: &PersistentMemoryConfig,
366    workspace_root: &Path,
367) -> Result<Option<PersistentMemoryExcerpt>> {
368    if !config.enabled {
369        return Ok(None);
370    }
371
372    let config_clone = config.clone();
373    let workspace_root = workspace_root.to_path_buf();
374    let status = tokio::task::spawn_blocking(move || persistent_memory_status(&config_clone, &workspace_root))
375        .await
376        .context("Persistent memory status task panicked")??;
377    if !tokio::fs::try_exists(&status.summary_file).await.unwrap_or(false) {
378        return Ok(None);
379    }
380
381    let raw = String::from_utf8(vtcode_commons::fs::read_private_file_no_follow(&status.summary_file).await?)
382        .with_context(|| format!("Failed to decode persistent memory summary {}", status.summary_file.display()))?;
383
384    let (contents, truncated, bytes_read, lines_read) =
385        truncate_memory_excerpt(&raw, config.startup_line_limit, config.startup_byte_limit);
386    // Apply the token budget last (it sees the already line/byte-truncated
387    // text) so the injected excerpt always fits the configured prompt budget.
388    let (contents, truncated, tokens_estimated) = if config.startup_token_budget > 0 {
389        let trimmed = crate::llm::utils::truncate_to_token_limit(&contents, config.startup_token_budget);
390        let truncated = truncated || trimmed != contents;
391        // Estimate AFTER truncation so the count describes the excerpt that is
392        // actually injected, not the pre-truncation text.
393        let tokens = trimmed.split_whitespace().count();
394        (trimmed, truncated, tokens)
395    } else {
396        (contents, truncated, 0)
397    };
398
399    Ok(Some(PersistentMemoryExcerpt {
400        status,
401        contents,
402        truncated,
403        bytes_read,
404        lines_read,
405        tokens_estimated,
406    }))
407}
408
409pub async fn read_persistent_memory_excerpt_for_config(
410    vt_cfg: Option<&VTCodeConfig>,
411    workspace_root: &Path,
412) -> Result<Option<PersistentMemoryExcerpt>> {
413    let config = effective_persistent_memory_config(vt_cfg);
414    read_persistent_memory_excerpt(&config, workspace_root).await
415}
416
417pub async fn finalize_persistent_memory(
418    runtime_config: &RuntimeAgentConfig,
419    vt_cfg: Option<&VTCodeConfig>,
420    history: &[Message],
421    session_id: &str,
422) -> Result<Option<PersistentMemoryWriteReport>> {
423    let config = effective_generated_memory_config(vt_cfg);
424    if !config.enabled || !config.auto_write {
425        return Ok(None);
426    }
427
428    // Live producer for the per-session derived memory view: without this,
429    // cross-session queries (`vtcode_memory::query_facts` / `search_memory`)
430    // only ever observe legacy-migrated sessions. Cheap file I/O — run before
431    // the LLM-backed global persist so it completes even when finalization is
432    // cut short.
433    write_session_derived_view(runtime_config.workspace.as_path(), session_id, history);
434
435    let cfg_status = config.clone();
436    let ws_status = runtime_config.workspace.clone();
437    if tokio::task::spawn_blocking(move || persistent_memory_status(&cfg_status, ws_status.as_path()))
438        .await
439        .context("Persistent memory status task panicked")??
440        .cleanup_status
441        .needed
442    {
443        return Ok(None);
444    }
445
446    let facts = dedup_latest_facts(history, DEFAULT_FACT_LIMIT);
447    persist_memory_internal(
448        &config,
449        runtime_config.workspace.as_path(),
450        Some(runtime_config),
451        vt_cfg,
452        FactsInput::Candidates(&facts),
453        true,
454        false,
455    )
456    .await
457}
458
459/// Build the per-session memory view: prefer the compaction envelope's
460/// grounded facts when one was persisted, else re-run the lightweight
461/// extraction over the session history.
462fn session_memory_view(
463    workspace_root: &Path,
464    session_id: &str,
465    history: &[Message],
466) -> vtcode_memory::SessionMemoryView {
467    if let Some(envelope) = crate::compaction::memory_envelope::load_latest_memory_envelope(workspace_root, session_id)
468        && !envelope.grounded_facts.is_empty()
469    {
470        return vtcode_memory::SessionMemoryView {
471            summary: envelope.summary,
472            facts: envelope.grounded_facts.into_iter().map(|record| record.fact).collect(),
473        };
474    }
475    vtcode_memory::SessionMemoryView {
476        summary: String::new(),
477        facts: dedup_latest_facts(history, DEFAULT_FACT_LIMIT)
478            .into_iter()
479            .map(|record| record.fact)
480            .collect(),
481    }
482}
483
484/// Best-effort write of the derived memory view into the session store.
485fn write_session_derived_view(workspace_root: &Path, session_id: &str, history: &[Message]) {
486    let view = session_memory_view(workspace_root, session_id, history);
487    if let Err(error) = vtcode_memory::write_session_memory_view(workspace_root, session_id, &view) {
488        tracing::warn!(target: "vtcode.memory", session_id, error = %error, "failed to persist derived session memory view");
489    }
490}
491
492pub async fn rebuild_persistent_memory_summary(
493    runtime_config: &RuntimeAgentConfig,
494    vt_cfg: Option<&VTCodeConfig>,
495) -> Result<Option<PersistentMemoryWriteReport>> {
496    let config = effective_persistent_memory_config(vt_cfg);
497    if !config.enabled {
498        return Ok(None);
499    }
500    let cfg_rb = config.clone();
501    let ws_rb = runtime_config.workspace.clone();
502    if tokio::task::spawn_blocking(move || persistent_memory_status(&cfg_rb, ws_rb.as_path()))
503        .await
504        .context("Persistent memory status task panicked")??
505        .cleanup_status
506        .needed
507    {
508        bail!("persistent memory cleanup is required before rebuilding the summary");
509    }
510
511    persist_memory_internal(
512        &config,
513        runtime_config.workspace.as_path(),
514        Some(runtime_config),
515        vt_cfg,
516        FactsInput::Candidates(&[]),
517        false,
518        true,
519    )
520    .await
521}
522
523pub async fn rebuild_generated_memory_files(config: &PersistentMemoryConfig, workspace_root: &Path) -> Result<()> {
524    let cfg = config.clone();
525    let ws = workspace_root.to_path_buf();
526    let directory = tokio::task::spawn_blocking(move || resolve_persistent_memory_dir(&cfg, &ws))
527        .await
528        .context("Persistent memory directory resolution task panicked")??
529        .context("persistent memory directory should resolve")?;
530    let files = PersistentMemoryFiles::new(directory, config.directory_override.is_none());
531    let mut created_files = Vec::new();
532    ensure_memory_layout(&files, &mut created_files).await?;
533    let _lock = MemoryLock::acquire(&files.lock_file).await?;
534    // Consolidation is best-effort; log errors but don't fail initialization
535    if let Err(e) = consolidate_memory_files(None, None, workspace_root, &files).await {
536        tracing::warn!("Failed to consolidate memory files during init: {}", e);
537    }
538    Ok(())
539}
540
541pub async fn scaffold_persistent_memory(
542    config: &PersistentMemoryConfig,
543    workspace_root: &Path,
544) -> Result<Option<PersistentMemoryStatus>> {
545    let cfg = config.clone();
546    let ws = workspace_root.to_path_buf();
547    let status = tokio::task::spawn_blocking(move || persistent_memory_status(&cfg, &ws))
548        .await
549        .context("Persistent memory status task panicked")??;
550    let files = PersistentMemoryFiles::new(status.directory.clone(), config.directory_override.is_none());
551    let mut created_files = Vec::new();
552    ensure_memory_layout(&files, &mut created_files).await?;
553    let cfg2 = config.clone();
554    let ws2 = workspace_root.to_path_buf();
555    let final_status = tokio::task::spawn_blocking(move || persistent_memory_status(&cfg2, &ws2))
556        .await
557        .context("Persistent memory status task panicked")??;
558    Ok(Some(final_status))
559}
560
561/// Write classified facts to all memory files (topic files, index, summary).
562async fn write_classified_memory(
563    files: &PersistentMemoryFiles,
564    classified: &ClassifiedFacts,
565    notes: &[MemoryNoteSummary],
566    runtime_config: Option<&RuntimeAgentConfig>,
567    vt_cfg: Option<&VTCodeConfig>,
568    workspace_root: &Path,
569) -> Result<Vec<PathBuf>> {
570    let mut created_files = Vec::new();
571    async fn write_memory_file(
572        path: &Path,
573        contents: String,
574        created_files: &mut Vec<PathBuf>,
575        private_global: bool,
576    ) -> Result<()> {
577        if !tokio::fs::try_exists(path).await.unwrap_or(false) {
578            created_files.push(path.to_path_buf());
579        }
580        if private_global {
581            vtcode_commons::fs::write_private_file_atomic(path, contents.as_bytes())
582                .await
583                .with_context(|| format!("Failed to write private memory file {}", path.display()))
584        } else {
585            tokio::fs::write(path, contents)
586                .await
587                .with_context(|| format!("Failed to write {}", path.display()))
588        }
589    }
590    write_memory_file(
591        &files.preferences_file,
592        render_topic_file(MemoryTopic::Preferences, &classified.preferences),
593        &mut created_files,
594        files.private_global,
595    )
596    .await?;
597    write_memory_file(
598        &files.repository_facts_file,
599        render_topic_file(MemoryTopic::RepositoryFacts, &classified.repository_facts),
600        &mut created_files,
601        files.private_global,
602    )
603    .await?;
604    write_memory_file(
605        &files.memory_file,
606        render_memory_index(&classified.preferences, &classified.repository_facts, notes, 0),
607        &mut created_files,
608        files.private_global,
609    )
610    .await?;
611    let summary = summarize_memory(
612        runtime_config,
613        vt_cfg,
614        workspace_root,
615        &classified.preferences,
616        &classified.repository_facts,
617        notes,
618    )
619    .await
620    .unwrap_or_else(|| render_memory_summary(&classified.preferences, &classified.repository_facts, notes));
621    write_memory_file(&files.summary_file, summary, &mut created_files, files.private_global).await?;
622    Ok(created_files)
623}
624
625pub async fn cleanup_persistent_memory(
626    runtime_config: &RuntimeAgentConfig,
627    vt_cfg: Option<&VTCodeConfig>,
628    include_summary_only_signals: bool,
629) -> Result<Option<PersistentMemoryCleanupReport>> {
630    let config = effective_persistent_memory_config(vt_cfg);
631    if !config.enabled {
632        return Ok(None);
633    }
634
635    let cfg_dir = config.clone();
636    let ws_dir = runtime_config.workspace.clone();
637    let directory = tokio::task::spawn_blocking(move || resolve_persistent_memory_dir(&cfg_dir, ws_dir.as_path()))
638        .await
639        .context("Persistent memory directory resolution task panicked")??
640        .context("persistent memory directory should resolve when enabled")?;
641    let files = PersistentMemoryFiles::new(directory, config.directory_override.is_none());
642    let mut created_files = Vec::new();
643    ensure_memory_layout(&files, &mut created_files).await?;
644
645    let status = detect_memory_cleanup_status_async(&files).await?;
646    if !status.needed && !include_summary_only_signals {
647        return Ok(Some(PersistentMemoryCleanupReport {
648            directory: files.directory,
649            summary_file: files.summary_file,
650            memory_file: files.memory_file,
651            rewritten_facts: 0,
652            removed_rollout_files: 0,
653        }));
654    }
655
656    let _lock = MemoryLock::acquire(&files.lock_file).await?;
657    let (candidates, notes) =
658        tokio::try_join!(collect_cleanup_candidates(&files), read_note_summaries(&files.notes_dir))?;
659    let classified = if candidates.is_empty() {
660        ClassifiedFacts {
661            preferences: Vec::new(),
662            repository_facts: Vec::new(),
663        }
664    } else {
665        classify_facts_strict(Some(runtime_config), vt_cfg, runtime_config.workspace.as_path(), &candidates).await?
666    };
667
668    let removed_rollout_files = remove_rollout_markdown_files(&files.rollout_summaries_dir).await?;
669    // Write is critical; propagate errors
670    write_classified_memory(
671        &files,
672        &classified,
673        &notes,
674        Some(runtime_config),
675        vt_cfg,
676        runtime_config.workspace.as_path(),
677    )
678    .await?;
679
680    Ok(Some(PersistentMemoryCleanupReport {
681        directory: files.directory,
682        summary_file: files.summary_file,
683        memory_file: files.memory_file,
684        rewritten_facts: classified.total(),
685        removed_rollout_files,
686    }))
687}
688
689pub async fn list_persistent_memory_candidates(
690    config: &PersistentMemoryConfig,
691    workspace_root: &Path,
692) -> Result<Option<Vec<PersistentMemoryMatch>>> {
693    if !config.enabled {
694        return Ok(None);
695    }
696
697    let cfg = config.clone();
698    let ws = workspace_root.to_path_buf();
699    let directory = tokio::task::spawn_blocking(move || resolve_persistent_memory_dir(&cfg, &ws))
700        .await
701        .context("Persistent memory directory resolution task panicked")??
702        .context("persistent memory directory should resolve when enabled")?;
703    if !tokio::fs::try_exists(&directory).await.unwrap_or(false) {
704        return Ok(Some(Vec::new()));
705    }
706
707    let files = PersistentMemoryFiles::new(directory, config.directory_override.is_none());
708    collect_all_memory_matches(&files).await.map(Some)
709}
710
711pub async fn find_persistent_memory_matches(
712    config: &PersistentMemoryConfig,
713    workspace_root: &Path,
714    query: &str,
715) -> Result<Option<Vec<PersistentMemoryMatch>>> {
716    if !config.enabled {
717        return Ok(None);
718    }
719    let Some(normalized_query) = normalize_memory_query(query) else {
720        return Ok(Some(Vec::new()));
721    };
722    let cfg = config.clone();
723    let ws = workspace_root.to_path_buf();
724    let directory = tokio::task::spawn_blocking(move || resolve_persistent_memory_dir(&cfg, &ws))
725        .await
726        .context("Persistent memory directory resolution task panicked")??
727        .context("persistent memory directory should resolve when enabled")?;
728    if !tokio::fs::try_exists(&directory).await.unwrap_or(false) {
729        return Ok(Some(Vec::new()));
730    }
731
732    let files = PersistentMemoryFiles::new(directory, config.directory_override.is_none());
733    collect_memory_matches(&files, &normalized_query).await.map(Some)
734}
735
736/// Plan a user-approved persistent-memory save.
737///
738/// `prior_assistant_reply` is reference material for deictic requests such as
739/// "remember it" and must contain only the immediately preceding assistant
740/// reply. The caller remains responsible for limiting it to those requests and
741/// for obtaining confirmation before calling [`persist_remembered_memory_plan`].
742pub async fn plan_remember_persistent_memory(
743    runtime_config: &RuntimeAgentConfig,
744    vt_cfg: Option<&VTCodeConfig>,
745    request: &str,
746    supplemental_answer: Option<&str>,
747    prior_assistant_reply: Option<&str>,
748) -> Result<Option<MemoryOpPlan>> {
749    let config = effective_persistent_memory_config(vt_cfg);
750    if !config.enabled {
751        return Ok(None);
752    }
753
754    let plan = plan_memory_operation(
755        runtime_config,
756        vt_cfg,
757        runtime_config.workspace.as_path(),
758        MemoryOpKind::Remember,
759        request,
760        supplemental_answer,
761        prior_assistant_reply,
762        &[],
763    )
764    .await?;
765    Ok(Some(plan))
766}
767
768pub async fn persist_remembered_memory_plan(
769    runtime_config: &RuntimeAgentConfig,
770    vt_cfg: Option<&VTCodeConfig>,
771    plan: &MemoryOpPlan,
772) -> Result<Option<PersistentMemoryWriteReport>> {
773    let config = effective_persistent_memory_config(vt_cfg);
774    if !config.enabled || plan.kind != MemoryOpKind::Remember {
775        return Ok(None);
776    }
777
778    let facts = memory_plan_facts(plan)?;
779    persist_memory_internal(
780        &config,
781        runtime_config.workspace.as_path(),
782        Some(runtime_config),
783        vt_cfg,
784        FactsInput::Preclassified(&facts),
785        true,
786        false,
787    )
788    .await
789}
790
791pub async fn plan_forget_persistent_memory(
792    runtime_config: &RuntimeAgentConfig,
793    vt_cfg: Option<&VTCodeConfig>,
794    request: &str,
795    candidates: &[MemoryOpCandidate],
796) -> Result<Option<MemoryOpPlan>> {
797    let config = effective_persistent_memory_config(vt_cfg);
798    if !config.enabled {
799        return Ok(None);
800    }
801
802    let plan = plan_memory_operation(
803        runtime_config,
804        vt_cfg,
805        runtime_config.workspace.as_path(),
806        MemoryOpKind::Forget,
807        request,
808        None,
809        None,
810        candidates,
811    )
812    .await?;
813    Ok(Some(plan))
814}
815
816pub async fn forget_planned_persistent_memory_matches(
817    runtime_config: &RuntimeAgentConfig,
818    vt_cfg: Option<&VTCodeConfig>,
819    candidates: &[MemoryOpCandidate],
820    plan: &MemoryOpPlan,
821) -> Result<Option<PersistentMemoryForgetReport>> {
822    let config = effective_persistent_memory_config(vt_cfg);
823    if !config.enabled || plan.kind != MemoryOpKind::Forget {
824        return Ok(None);
825    }
826
827    let selected = selected_memory_candidates(candidates, &plan.selected_ids)?;
828    let cfg_dir = config.clone();
829    let ws_dir = runtime_config.workspace.clone();
830    let directory = tokio::task::spawn_blocking(move || resolve_persistent_memory_dir(&cfg_dir, ws_dir.as_path()))
831        .await
832        .context("Persistent memory directory resolution task panicked")??
833        .context("persistent memory directory should resolve when enabled")?;
834    let files = PersistentMemoryFiles::new(directory, config.directory_override.is_none());
835    if !tokio::fs::try_exists(&files.directory).await.unwrap_or(false) {
836        return Ok(Some(PersistentMemoryForgetReport {
837            directory: files.directory,
838            summary_file: files.summary_file,
839            memory_file: files.memory_file,
840            removed_facts: 0,
841            pending_rollout_summaries: 0,
842        }));
843    }
844
845    let _lock = MemoryLock::acquire(&files.lock_file).await?;
846    let mut removed_facts = 0usize;
847    removed_facts += rewrite_topic_without_selected(
848        &files.preferences_file,
849        MemoryTopic::Preferences,
850        &selected,
851        files.private_global,
852    )
853    .await?;
854    removed_facts += rewrite_topic_without_selected(
855        &files.repository_facts_file,
856        MemoryTopic::RepositoryFacts,
857        &selected,
858        files.private_global,
859    )
860    .await?;
861
862    let rollout_files = list_rollout_markdown_files_async(&files.rollout_summaries_dir).await?;
863    for path in rollout_files {
864        removed_facts += scrub_rollout_file_by_selection(&path, &selected, files.private_global).await?;
865    }
866
867    if removed_facts > 0 {
868        // Consolidation is best-effort; log errors but don't fail the forget operation
869        if let Err(e) =
870            consolidate_memory_files(Some(runtime_config), vt_cfg, runtime_config.workspace.as_path(), &files).await
871        {
872            tracing::warn!("Failed to consolidate memory files after forget: {}", e);
873        }
874    }
875
876    Ok(Some(PersistentMemoryForgetReport {
877        directory: files.directory,
878        summary_file: files.summary_file,
879        memory_file: files.memory_file,
880        removed_facts,
881        pending_rollout_summaries: count_pending_rollout_summaries_async(&files.rollout_summaries_dir).await?,
882    }))
883}
884
885fn effective_persistent_memory_config(vt_cfg: Option<&VTCodeConfig>) -> PersistentMemoryConfig {
886    let mut config = vt_cfg.map(|cfg| cfg.agent.persistent_memory.clone()).unwrap_or_default();
887    if let Some(cfg) = vt_cfg {
888        config.enabled = cfg.persistent_memory_enabled();
889    }
890    config
891}
892
893fn effective_generated_memory_config(vt_cfg: Option<&VTCodeConfig>) -> PersistentMemoryConfig {
894    let mut config = effective_persistent_memory_config(vt_cfg);
895    if let Some(cfg) = vt_cfg {
896        config.enabled = cfg.should_generate_memories();
897    }
898    config
899}
900
901#[cfg(test)]
902mod persistent_memory_tests;