Skip to main content

lean_ctx/core/
episodic_memory.rs

1//! Episodic Memory — persistent cross-session experiences with outcomes.
2//!
3//! Automatically records what the agent did in each session, with what result.
4//! Enables learning from past experiences: "What happened last time I refactored auth?"
5
6use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use std::{
9    collections::HashMap,
10    path::{Component, Path, PathBuf},
11    sync::{Arc, Mutex, OnceLock},
12};
13
14use crate::core::context_admission::stores::StoreAdmission;
15use crate::core::memory_policy::EpisodicPolicy;
16use crate::core::policy::runtime::PublicationAuthority;
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct EpisodicStore {
20    pub project_hash: String,
21    pub episodes: Vec<Episode>,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct Episode {
26    pub id: String,
27    pub session_id: String,
28    pub timestamp: DateTime<Utc>,
29    pub task_description: String,
30    pub actions: Vec<Action>,
31    pub outcome: Outcome,
32    pub affected_files: Vec<String>,
33    pub summary: String,
34    pub duration_secs: u64,
35    pub tokens_used: u64,
36    #[serde(default)]
37    pub agent_id: Option<String>,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct Action {
42    pub tool: String,
43    pub description: String,
44    pub timestamp: DateTime<Utc>,
45    pub duration_ms: u64,
46    pub success: bool,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
50pub enum Outcome {
51    Success { tests_passed: bool },
52    Failure { error: String },
53    Partial { details: String },
54    Unknown,
55}
56
57impl Outcome {
58    pub fn label(&self) -> &'static str {
59        match self {
60            Outcome::Success { .. } => "success",
61            Outcome::Failure { .. } => "failure",
62            Outcome::Partial { .. } => "partial",
63            Outcome::Unknown => "unknown",
64        }
65    }
66}
67
68fn episodic_lock(project_hash: &str) -> Arc<Mutex<()>> {
69    static LOCKS: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
70    let mut locks = LOCKS
71        .get_or_init(|| Mutex::new(HashMap::new()))
72        .lock()
73        .unwrap_or_else(std::sync::PoisonError::into_inner);
74    locks.entry(project_hash.to_string()).or_default().clone()
75}
76
77/// How long an episodic write waits for another holder of the store's file
78/// lock (a parallel CLI, daemon or MCP write). A single attempt dropped the
79/// episode whenever two writers met (#18, a flaky gate on 24.10.).
80const EPISODIC_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
81
82fn acquire_file_lock(path: &Path) -> Option<std::fs::File> {
83    let parent = path.parent()?;
84    let name = path.file_name()?.to_string_lossy();
85    let lock_path = parent.join(format!(".{name}.lock"));
86    let file = std::fs::OpenOptions::new()
87        .create(true)
88        .truncate(false)
89        .write(true)
90        .open(&lock_path)
91        .ok()?;
92    #[cfg(unix)]
93    {
94        use std::os::unix::fs::PermissionsExt;
95        let _ = std::fs::set_permissions(&lock_path, std::fs::Permissions::from_mode(0o600));
96    }
97    crate::core::file_lock::acquire_exclusive_timeout(&file, EPISODIC_LOCK_WAIT).ok()?;
98    Some(file)
99}
100
101/// Require every nonempty affected-path list to stay inside its owning project.
102/// This is retrieval scoping only: no file contents are opened and no stored
103/// episode is rewritten by the view.
104fn episode_paths_belong_to_project(
105    project_root: &Path,
106    canonical_root: &Path,
107    affected_files: &[String],
108) -> bool {
109    if affected_files.is_empty() {
110        return true;
111    }
112
113    affected_files.iter().all(|raw| {
114        if raw.is_empty() || raw.as_bytes().contains(&0) {
115            return false;
116        }
117        let path = Path::new(raw);
118        if has_ambiguous_foreign_path_syntax(raw, path)
119            || path
120                .components()
121                .any(|component| matches!(component, Component::ParentDir))
122        {
123            return false;
124        }
125
126        if path.is_absolute()
127            && !path.starts_with(project_root)
128            && !path.starts_with(canonical_root)
129        {
130            // Avoid probing an arbitrary absolute path from an untrusted store.
131            return false;
132        }
133        let candidate = if path.is_absolute() {
134            path.to_path_buf()
135        } else {
136            canonical_root.join(path)
137        };
138        canonicalized_existing_ancestor(&candidate)
139            .is_some_and(|resolved| resolved.starts_with(canonical_root))
140    })
141}
142
143/// On Unix, Windows absolute/drive paths otherwise look relative and could be
144/// reinterpreted beneath the active project. On Windows, reject rooted paths
145/// without a drive/share prefix and drive-relative paths.
146#[cfg(unix)]
147fn has_ambiguous_foreign_path_syntax(raw: &str, _path: &Path) -> bool {
148    let bytes = raw.as_bytes();
149    bytes.contains(&0x5c)
150        || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
151}
152
153#[cfg(windows)]
154fn has_ambiguous_foreign_path_syntax(_raw: &str, path: &Path) -> bool {
155    !path.is_absolute()
156        && (path.has_root() || matches!(path.components().next(), Some(Component::Prefix(_))))
157}
158
159#[cfg(not(any(unix, windows)))]
160fn has_ambiguous_foreign_path_syntax(_raw: &str, _path: &Path) -> bool {
161    false
162}
163
164/// Resolve the longest existing ancestor before appending a missing historical
165/// suffix. symlink_metadata detects dangling symlinks; canonicalization then
166/// rejects existing and missing descendants that escape through a link.
167fn canonicalized_existing_ancestor(path: &Path) -> Option<PathBuf> {
168    let mut current = path.to_path_buf();
169    let mut missing: Vec<std::ffi::OsString> = Vec::new();
170    loop {
171        match std::fs::symlink_metadata(&current) {
172            Ok(_) => {
173                let mut resolved = std::fs::canonicalize(&current).ok()?;
174                for name in missing.iter().rev() {
175                    resolved.push(name);
176                }
177                return Some(resolved);
178            }
179            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
180                missing.push(current.file_name()?.to_os_string());
181                if !current.pop() {
182                    return None;
183                }
184            }
185            Err(_) => return None,
186        }
187    }
188}
189
190impl EpisodicStore {
191    pub fn new(project_hash: &str) -> Self {
192        Self {
193            project_hash: project_hash.to_string(),
194            episodes: Vec::new(),
195        }
196    }
197
198    pub fn record_episode(&mut self, mut episode: Episode, policy: &EpisodicPolicy) {
199        episode.actions.truncate(policy.max_actions_per_episode);
200
201        if episode.summary.is_empty() {
202            episode.summary = auto_summarize(&episode, policy.summary_max_chars);
203        }
204
205        self.episodes.push(episode);
206
207        if self.episodes.len() > policy.max_episodes {
208            self.episodes
209                .drain(0..self.episodes.len() - policy.max_episodes);
210        }
211    }
212
213    pub fn search(&self, query: &str) -> Vec<&Episode> {
214        let q = query.to_lowercase();
215        let terms: Vec<&str> = q.split_whitespace().collect();
216
217        let mut scored: Vec<(&Episode, f32)> = self
218            .episodes
219            .iter()
220            .filter_map(|ep| {
221                let searchable = format!(
222                    "{} {} {}",
223                    ep.task_description.to_lowercase(),
224                    ep.summary.to_lowercase(),
225                    ep.affected_files.join(" ").to_lowercase()
226                );
227                let hits = terms.iter().filter(|t| searchable.contains(**t)).count();
228                if hits > 0 {
229                    let relevance = hits as f32 / terms.len() as f32;
230                    Some((ep, relevance))
231                } else {
232                    None
233                }
234            })
235            .collect();
236
237        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
238        scored.into_iter().map(|(ep, _)| ep).collect()
239    }
240
241    pub fn recent(&self, n: usize) -> Vec<&Episode> {
242        self.episodes.iter().rev().take(n).collect()
243    }
244
245    pub fn by_outcome(&self, outcome_label: &str) -> Vec<&Episode> {
246        self.episodes
247            .iter()
248            .filter(|ep| ep.outcome.label() == outcome_label)
249            .collect()
250    }
251
252    pub fn by_file(&self, file_path: &str) -> Vec<&Episode> {
253        self.episodes
254            .iter()
255            .filter(|ep| ep.affected_files.iter().any(|f| f.contains(file_path)))
256            .collect()
257    }
258
259    pub fn stats(&self) -> EpisodicStats {
260        let total = self.episodes.len();
261        let successes = self
262            .episodes
263            .iter()
264            .filter(|ep| matches!(ep.outcome, Outcome::Success { .. }))
265            .count();
266        let failures = self
267            .episodes
268            .iter()
269            .filter(|ep| matches!(ep.outcome, Outcome::Failure { .. }))
270            .count();
271        let total_tokens: u64 = self.episodes.iter().map(|ep| ep.tokens_used).sum();
272
273        EpisodicStats {
274            total_episodes: total,
275            successes,
276            failures,
277            success_rate: if total > 0 {
278                successes as f32 / total as f32
279            } else {
280                0.0
281            },
282            total_tokens,
283        }
284    }
285
286    fn store_path(project_hash: &str) -> Option<PathBuf> {
287        let dir = crate::core::data_dir::lean_ctx_data_dir()
288            .ok()?
289            .join("memory")
290            .join("episodes");
291        Some(dir.join(format!("{project_hash}.json")))
292    }
293
294    pub fn load(project_hash: &str) -> Option<Self> {
295        let mut store = Self::load_raw(project_hash).ok()??;
296        store.migrate_legacy_episodes();
297        Some(store)
298    }
299
300    fn load_raw(project_hash: &str) -> Result<Option<Self>, String> {
301        let Some(path) = Self::store_path(project_hash) else {
302            return Err("Cannot determine data directory".into());
303        };
304        let data = match std::fs::read_to_string(path) {
305            Ok(data) => data,
306            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
307            Err(error) => return Err(error.to_string()),
308        };
309        let store: Self = serde_json::from_str(&data).map_err(|error| error.to_string())?;
310        if store.project_hash != project_hash {
311            return Err("episodic store project scope mismatch".into());
312        }
313        Ok(Some(store))
314    }
315
316    /// Load content after admitting every textual field. Migration and project
317    /// scoping are in-memory only; reads never rewrite persisted history.
318    pub(crate) fn load_admitted(
319        project_hash: &str,
320        admission: &StoreAdmission,
321    ) -> Result<Self, String> {
322        Self::load_admitted_inner(project_hash, None, admission)
323    }
324
325    /// Retrieval-only view that withholds any episode whose affected paths do
326    /// not all resolve inside this project. Empty path lists keep the existing
327    /// per-project-store behavior because there is no path evidence to inspect.
328    pub(crate) fn load_admitted_for_project(
329        project_hash: &str,
330        project_root: &Path,
331        admission: &StoreAdmission,
332    ) -> Result<Self, String> {
333        let canonical_root = std::fs::canonicalize(project_root)
334            .map_err(|error| format!("cannot verify episodic project root: {error}"))?;
335        Self::load_admitted_inner(
336            project_hash,
337            Some((project_root, canonical_root.as_path())),
338            admission,
339        )
340    }
341
342    fn load_admitted_inner(
343        project_hash: &str,
344        project_scope: Option<(&Path, &Path)>,
345        admission: &StoreAdmission,
346    ) -> Result<Self, String> {
347        let mut store = Self::load_raw(project_hash)?.unwrap_or_else(|| Self::new(project_hash));
348        if let Some((root, canonical_root)) = project_scope {
349            store.retain_episodes_for_project(root, canonical_root);
350        }
351        let mut admit =
352            |text: &str| crate::core::session::admission::admit_store_text(admission, text);
353        store
354            .episodes
355            .retain_mut(|episode| sanitize_episode(episode, &mut admit));
356        store.migrate_legacy_episodes();
357        if !admission.is_current() {
358            return Err("session admission policy changed; retry".into());
359        }
360        Ok(store)
361    }
362
363    fn retain_episodes_for_project(&mut self, project_root: &Path, canonical_root: &Path) {
364        self.episodes.retain(|episode| {
365            episode_paths_belong_to_project(project_root, canonical_root, &episode.affected_files)
366        });
367    }
368
369    /// Mutate an admitted store under its project file lock. Old records are
370    /// scrubbed before migration or derivation, and the policy epoch is checked
371    /// under the lock immediately before persistence.
372    pub(crate) fn mutate_locked_admitted<T>(
373        project_hash: &str,
374        admission: &StoreAdmission,
375        mut admit: impl FnMut(&str) -> Option<String>,
376        mutate: impl FnOnce(&mut Self) -> Result<T, String>,
377    ) -> Result<(Self, T), String> {
378        let authority = PublicationAuthority::capture()
379            .map_err(|_| "source authority unavailable".to_string())?;
380        let lock = episodic_lock(project_hash);
381        let _guard = lock
382            .try_lock()
383            .map_err(|_| "episodic store is busy; retry".to_string())?;
384        let path = Self::store_path(project_hash)
385            .ok_or_else(|| "Cannot determine data directory".to_string())?;
386        if let Some(dir) = path.parent() {
387            std::fs::create_dir_all(dir).map_err(|error| error.to_string())?;
388        }
389        let _file_lock = acquire_file_lock(&path)
390            .ok_or_else(|| "episodic store lock unavailable".to_string())?;
391        let mut store = Self::load_raw(project_hash)?.unwrap_or_else(|| Self::new(project_hash));
392        store
393            .episodes
394            .retain_mut(|episode| sanitize_episode(episode, &mut admit));
395        store.migrate_legacy_episodes();
396        let result = mutate(&mut store)?;
397        store
398            .episodes
399            .retain_mut(|episode| sanitize_episode(episode, &mut admit));
400        let json = serde_json::to_string_pretty(&store).map_err(|error| error.to_string())?;
401        admission.authorize_publication(&authority)?;
402        crate::core::atomic_fs::write_bytes_with_fallback(&path, json.as_bytes(), None)?;
403        Ok((store, result))
404    }
405
406    /// One-time repair for episodes recorded before per-task metrics existed:
407    /// those episodes share one id per session (derived from the session
408    /// *start* date) and carry cumulative session token counters instead of
409    /// per-task deltas. Detected via duplicate ids within one session;
410    /// idempotent because rewritten ids are unique afterwards.
411    fn migrate_legacy_episodes(&mut self) -> bool {
412        use std::collections::HashSet;
413
414        let mut seen: HashSet<(String, String)> = HashSet::new();
415        let mut needs_migration = false;
416        for ep in &self.episodes {
417            if !seen.insert((ep.session_id.clone(), ep.id.clone())) {
418                needs_migration = true;
419                break;
420            }
421        }
422        if !needs_migration {
423            return false;
424        }
425
426        let mut sessions: HashSet<String> = HashSet::new();
427        for ep in &self.episodes {
428            sessions.insert(ep.session_id.clone());
429        }
430
431        for session_id in sessions {
432            let mut idx: Vec<usize> = (0..self.episodes.len())
433                .filter(|&i| self.episodes[i].session_id == session_id)
434                .collect();
435            idx.sort_by_key(|&i| self.episodes[i].timestamp);
436
437            // Cumulative counters are monotonically non-decreasing; only
438            // then is converting to deltas safe.
439            let monotonic = idx
440                .windows(2)
441                .all(|w| self.episodes[w[0]].tokens_used <= self.episodes[w[1]].tokens_used);
442
443            let mut prev_tokens: u64 = 0;
444            let mut prev_ts: Option<DateTime<Utc>> = None;
445            let mut used_ids: HashSet<String> = HashSet::new();
446            for &i in &idx {
447                let ts = self.episodes[i].timestamp;
448                let ep = &mut self.episodes[i];
449                let mut id = format!("ep-{}", ts.format("%Y%m%d-%H%M%S"));
450                let mut n = 1;
451                while !used_ids.insert(id.clone()) {
452                    n += 1;
453                    id = format!("ep-{}-{n}", ts.format("%Y%m%d-%H%M%S"));
454                }
455                ep.id = id;
456                if monotonic {
457                    let cumulative = ep.tokens_used;
458                    ep.tokens_used = cumulative.saturating_sub(prev_tokens);
459                    prev_tokens = cumulative;
460                }
461                if ep.duration_secs == 0
462                    && let Some(p) = prev_ts
463                {
464                    ep.duration_secs = (ts - p).num_seconds().max(0) as u64;
465                }
466                prev_ts = Some(ts);
467            }
468        }
469        true
470    }
471
472    pub fn load_or_create(project_hash: &str) -> Self {
473        Self::load(project_hash).unwrap_or_else(|| Self::new(project_hash))
474    }
475
476    pub fn mutate_locked<T>(
477        project_hash: &str,
478        mutate: impl FnOnce(&mut Self) -> T,
479    ) -> Result<(Self, T), String> {
480        let lock = episodic_lock(project_hash);
481        let _guard = lock
482            .lock()
483            .unwrap_or_else(std::sync::PoisonError::into_inner);
484
485        let path = Self::store_path(project_hash)
486            .ok_or_else(|| "Cannot determine data directory".to_string())?;
487        if let Some(dir) = path.parent() {
488            std::fs::create_dir_all(dir).map_err(|e| format!("{e}"))?;
489        }
490        let _file_lock = acquire_file_lock(&path)
491            .ok_or_else(|| "episodic store lock unavailable".to_string())?;
492
493        let mut store = Self::load_or_create(project_hash);
494        let result = mutate(&mut store);
495        store.save()?;
496        Ok((store, result))
497    }
498
499    pub fn save(&self) -> Result<(), String> {
500        let path = Self::store_path(&self.project_hash)
501            .ok_or_else(|| "Cannot determine data directory".to_string())?;
502        if let Some(dir) = path.parent() {
503            std::fs::create_dir_all(dir).map_err(|e| format!("{e}"))?;
504        }
505        let json = serde_json::to_string_pretty(self).map_err(|e| format!("{e}"))?;
506        crate::core::atomic_fs::write_bytes_with_fallback(&path, json.as_bytes(), None)
507    }
508}
509
510#[derive(Debug)]
511pub struct EpisodicStats {
512    pub total_episodes: usize,
513    pub successes: usize,
514    pub failures: usize,
515    pub success_rate: f32,
516    pub total_tokens: u64,
517}
518
519pub fn create_episode_from_session(
520    session: &super::session::SessionState,
521    tool_calls: &[(String, u64)],
522) -> Episode {
523    let actions: Vec<Action> = tool_calls
524        .iter()
525        .map(|(tool, duration_ms)| Action {
526            tool: tool.clone(),
527            description: String::new(),
528            timestamp: Utc::now(),
529            duration_ms: *duration_ms,
530            success: true,
531        })
532        .collect();
533
534    let affected_files: Vec<String> = session
535        .files_touched
536        .iter()
537        .map(|f| f.path.clone())
538        .collect();
539
540    let task_description = session
541        .task
542        .as_ref()
543        .map(|t| t.description.clone())
544        .unwrap_or_default();
545
546    let outcome = if session.findings.iter().any(|f| {
547        f.summary.to_lowercase().contains("error") || f.summary.to_lowercase().contains("failed")
548    }) {
549        Outcome::Failure {
550            error: session
551                .findings
552                .iter()
553                .find(|f| {
554                    f.summary.to_lowercase().contains("error")
555                        || f.summary.to_lowercase().contains("failed")
556                })
557                .map(|f| f.summary.clone())
558                .unwrap_or_default(),
559        }
560    } else if !session.findings.is_empty() || !session.decisions.is_empty() {
561        Outcome::Success { tests_passed: true }
562    } else {
563        Outcome::Unknown
564    };
565
566    Episode {
567        // Record-time based id: session ids start with the session *start*
568        // date, so deriving the episode id from them produced colliding ids
569        // for every task completed in one long-running session.
570        id: format!("ep-{}", Utc::now().format("%Y%m%d-%H%M%S")),
571        session_id: session.id.clone(),
572        timestamp: Utc::now(),
573        task_description,
574        actions,
575        outcome,
576        affected_files,
577        summary: String::new(),
578        duration_secs: 0,
579        // Cumulative session counter at record time; the caller converts
580        // this into a per-task delta (see `finalize_episode_metrics`).
581        tokens_used: session.stats.total_tokens_saved,
582        agent_id: None,
583    }
584}
585
586pub fn record_session_episode(
587    project_hash: &str,
588    session: &super::session::SessionState,
589    tool_calls: &[(String, u64)],
590    agent_id: Option<&str>,
591    policy: &EpisodicPolicy,
592    deduplicate: bool,
593) -> Result<Option<String>, String> {
594    let root = session
595        .strict_project_root()
596        .ok_or_else(|| "session project scope unavailable".to_string())?;
597    if crate::core::project_hash::hash_project_root(&root) != project_hash {
598        return Err("episodic store project scope mismatch".into());
599    }
600
601    crate::core::session::admission::with_store_admission(session, |admission| {
602        let admitted_session = crate::core::session::admission::for_storage(session)?;
603        let normalized_agent_id = agent_id
604            .map(str::trim)
605            .filter(|id| !id.is_empty())
606            .map(str::to_string);
607        let mut episode = create_episode_from_session(&admitted_session, tool_calls);
608        episode.agent_id.clone_from(&normalized_agent_id);
609        let mut admit =
610            |text: &str| crate::core::session::admission::admit_store_text(admission, text);
611        if !sanitize_episode(&mut episode, &mut admit) {
612            return Err("episode content withheld by current policy".into());
613        }
614
615        let (_, episode_id) = EpisodicStore::mutate_locked_admitted(
616            project_hash,
617            admission,
618            |text| crate::core::session::admission::admit_store_text(admission, text),
619            |store| {
620                if deduplicate
621                    && store.episodes.iter().any(|existing| {
622                        existing.session_id == episode.session_id
623                            && existing.agent_id == episode.agent_id
624                            && existing.task_description == episode.task_description
625                    })
626                {
627                    return Ok(None);
628                }
629                let mut episode = episode;
630                finalize_episode_metrics(&mut episode, store, admitted_session.started_at);
631                let id = episode.id.clone();
632                store.record_episode(episode, policy);
633                Ok(Some(id))
634            },
635        )?;
636        Ok(episode_id)
637    })
638}
639
640fn sanitize_episode(episode: &mut Episode, admit: &mut impl FnMut(&str) -> Option<String>) -> bool {
641    fn field(value: &mut String, admit: &mut impl FnMut(&str) -> Option<String>) -> bool {
642        if value.is_empty() {
643            return true;
644        }
645        let Some(projected) = admit(value) else {
646            return false;
647        };
648        *value = projected;
649        true
650    }
651
652    if !field(&mut episode.task_description, admit)
653        || !field(&mut episode.summary, admit)
654        || !episode
655            .affected_files
656            .iter_mut()
657            .all(|path| field(path, admit))
658        || !episode
659            .actions
660            .iter_mut()
661            .all(|action| field(&mut action.tool, admit) && field(&mut action.description, admit))
662    {
663        return false;
664    }
665    let outcome_is_admitted = match &mut episode.outcome {
666        Outcome::Failure { error } => field(error, admit),
667        Outcome::Partial { details } => field(details, admit),
668        Outcome::Success { .. } | Outcome::Unknown => true,
669    };
670    outcome_is_admitted
671        && episode
672            .agent_id
673            .as_mut()
674            .is_none_or(|agent| field(agent, admit))
675}
676
677/// Converts the cumulative session counters captured by
678/// [`create_episode_from_session`] into per-task values.
679///
680/// `tokens_used` becomes the delta since the previous episode of the same
681/// session (so the per-session sum of episode tokens matches the session
682/// total), and `duration_secs` becomes the wall-clock span this task was the
683/// active one (since the previous episode, or since session start for the
684/// first).
685pub fn finalize_episode_metrics(
686    episode: &mut Episode,
687    store: &EpisodicStore,
688    session_started_at: DateTime<Utc>,
689) {
690    let prior_tokens: u64 = store
691        .episodes
692        .iter()
693        .filter(|e| e.session_id == episode.session_id)
694        .map(|e| e.tokens_used)
695        .sum();
696    episode.tokens_used = episode.tokens_used.saturating_sub(prior_tokens);
697
698    let since = store
699        .episodes
700        .iter()
701        .filter(|e| e.session_id == episode.session_id)
702        .map(|e| e.timestamp)
703        .max()
704        .unwrap_or(session_started_at);
705    episode.duration_secs = (episode.timestamp - since).num_seconds().max(0) as u64;
706}
707
708fn auto_summarize(episode: &Episode, max_chars: usize) -> String {
709    let tool_counts = count_tools(&episode.actions);
710    let top_tools: Vec<String> = tool_counts
711        .into_iter()
712        .take(3)
713        .map(|(tool, count)| format!("{tool}x{count}"))
714        .collect();
715
716    let files_hint = if episode.affected_files.len() <= 3 {
717        episode.affected_files.join(", ")
718    } else {
719        format!(
720            "{}, ... +{} more",
721            episode.affected_files[..3].join(", "),
722            episode.affected_files.len() - 3
723        )
724    };
725
726    let task = if episode.task_description.chars().count() > max_chars {
727        episode.task_description.chars().take(max_chars).collect()
728    } else {
729        episode.task_description.clone()
730    };
731    let mut summary = format!(
732        "{task} [{}] tools:[{}]",
733        episode.outcome.label(),
734        top_tools.join(",")
735    );
736
737    if !files_hint.is_empty() {
738        summary.push_str(&format!(" files:[{files_hint}]"));
739    }
740
741    summary
742}
743
744fn count_tools(actions: &[Action]) -> Vec<(String, usize)> {
745    let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
746    for action in actions {
747        *counts.entry(&action.tool).or_insert(0) += 1;
748    }
749    let mut sorted: Vec<(String, usize)> = counts
750        .into_iter()
751        .map(|(k, v)| (k.to_string(), v))
752        .collect();
753    sorted.sort_by_key(|item| std::cmp::Reverse(item.1));
754    sorted
755}
756
757pub fn format_episode_compact(episode: &Episode) -> String {
758    format!(
759        "[{}] {} — {} ({} actions, {} files)",
760        episode.outcome.label(),
761        episode.task_description,
762        episode.summary,
763        episode.actions.len(),
764        episode.affected_files.len()
765    )
766}
767
768#[cfg(test)]
769pub mod tests {
770    use super::*;
771
772    fn make_episode(task: &str, outcome: Outcome) -> Episode {
773        Episode {
774            id: "ep-test".to_string(),
775            session_id: "sess-1".to_string(),
776            timestamp: Utc::now(),
777            task_description: task.to_string(),
778            actions: vec![
779                Action {
780                    tool: "ctx_read".to_string(),
781                    description: String::new(),
782                    timestamp: Utc::now(),
783                    duration_ms: 50,
784                    success: true,
785                },
786                Action {
787                    tool: "ctx_shell".to_string(),
788                    description: String::new(),
789                    timestamp: Utc::now(),
790                    duration_ms: 200,
791                    success: true,
792                },
793            ],
794            outcome,
795            affected_files: vec!["src/main.rs".to_string(), "src/lib.rs".to_string()],
796            summary: String::new(),
797            duration_secs: 60,
798            tokens_used: 5000,
799            agent_id: None,
800        }
801    }
802
803    #[test]
804    fn admission_scrubs_all_episode_text_and_drops_on_any_denial() {
805        let mut episode = make_episode(
806            "TASK PRIVATE",
807            Outcome::Failure {
808                error: "ERROR PRIVATE".into(),
809            },
810        );
811        episode.summary = "SUMMARY PRIVATE".into();
812        episode.affected_files = vec!["PATH PRIVATE".into()];
813        episode.actions[0].description = "ACTION PRIVATE".into();
814        episode.agent_id = Some("AGENT PRIVATE".into());
815        let mut admit = |text: &str| Some(text.replace("PRIVATE", "redacted"));
816
817        assert!(sanitize_episode(&mut episode, &mut admit));
818        assert_eq!(episode.task_description, "TASK redacted");
819        assert_eq!(episode.summary, "SUMMARY redacted");
820        assert_eq!(episode.affected_files[0], "PATH redacted");
821        assert_eq!(episode.actions[0].description, "ACTION redacted");
822        assert_eq!(episode.agent_id.as_deref(), Some("AGENT redacted"));
823        assert!(
824            matches!(&episode.outcome, Outcome::Failure { error } if error == "ERROR redacted")
825        );
826
827        let mut denied = make_episode("safe task", Outcome::Unknown);
828        denied.agent_id = Some("BLOCK".into());
829        assert!(!sanitize_episode(&mut denied, &mut |text| {
830            (text != "BLOCK").then(|| text.to_string())
831        }));
832    }
833
834    #[test]
835    fn mutate_locked_preserves_successive_agent_episodes() {
836        let policy = EpisodicPolicy::default();
837        let mut store = EpisodicStore::new("locked-writes-unit");
838
839        let mut ep_a = make_episode("Task from agent A", Outcome::Unknown);
840        ep_a.agent_id = Some("agent-a".to_string());
841        store.record_episode(ep_a, &policy);
842
843        let mut ep_b = make_episode("Task from agent B", Outcome::Unknown);
844        ep_b.agent_id = Some("agent-b".to_string());
845        store.record_episode(ep_b, &policy);
846
847        assert_eq!(store.episodes.len(), 2);
848        assert!(
849            store
850                .episodes
851                .iter()
852                .any(|episode| episode.agent_id.as_deref() == Some("agent-a"))
853        );
854        assert!(
855            store
856                .episodes
857                .iter()
858                .any(|episode| episode.agent_id.as_deref() == Some("agent-b"))
859        );
860    }
861
862    /// #18: a write that meets another holder of the store's file lock waits
863    /// for it instead of failing with "episodic store lock unavailable".
864    #[test]
865    fn a_write_waits_for_another_holder_of_the_file_lock() {
866        use fs2::FileExt;
867        let _isolated = crate::core::data_dir::isolated_data_dir();
868        let path = EpisodicStore::store_path("waits").unwrap();
869        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
870        let other = acquire_file_lock(&path).expect("first holder");
871        let holder = std::thread::spawn(move || {
872            std::thread::sleep(std::time::Duration::from_millis(300));
873            FileExt::unlock(&other).unwrap();
874        });
875        let written = EpisodicStore::mutate_locked("waits", |_| ());
876        holder.join().unwrap();
877        assert!(written.is_ok(), "{written:?}");
878    }
879
880    #[test]
881    fn record_session_episode_deduplicates_per_agent() {
882        let _isolated = crate::core::data_dir::isolated_data_dir();
883        let policy = EpisodicPolicy::default();
884        let project = tempfile::tempdir().expect("project root");
885        let project_root = project.path().to_string_lossy().into_owned();
886        let project_hash = crate::core::project_hash::hash_project_root(&project_root);
887        let mut session = super::super::session::SessionState::new();
888        session.project_root = Some(project_root.clone());
889        session.shell_cwd = Some(project_root);
890        session.set_task("same task", None);
891        let tool_calls = vec![("ctx_read".to_string(), 10)];
892
893        assert!(
894            record_session_episode(
895                &project_hash,
896                &session,
897                &tool_calls,
898                Some("agent-a"),
899                &policy,
900                true,
901            )
902            .unwrap()
903            .is_some()
904        );
905        assert!(
906            record_session_episode(
907                &project_hash,
908                &session,
909                &tool_calls,
910                Some("agent-a"),
911                &policy,
912                true,
913            )
914            .unwrap()
915            .is_none()
916        );
917        assert!(
918            record_session_episode(
919                &project_hash,
920                &session,
921                &tool_calls,
922                Some("agent-b"),
923                &policy,
924                true,
925            )
926            .unwrap()
927            .is_some()
928        );
929
930        let store = EpisodicStore::load_or_create(&project_hash);
931        assert_eq!(store.episodes.len(), 2);
932    }
933
934    #[test]
935    fn record_and_search() {
936        let policy = EpisodicPolicy::default();
937        let mut store = EpisodicStore::new("test");
938        store.record_episode(
939            make_episode(
940                "Refactor auth module",
941                Outcome::Success { tests_passed: true },
942            ),
943            &policy,
944        );
945        store.record_episode(
946            make_episode(
947                "Fix database connection",
948                Outcome::Failure {
949                    error: "timeout".to_string(),
950                },
951            ),
952            &policy,
953        );
954
955        let results = store.search("auth refactor");
956        assert_eq!(results.len(), 1);
957        assert!(results[0].task_description.contains("auth"));
958    }
959
960    #[test]
961    fn filter_by_outcome() {
962        let policy = EpisodicPolicy::default();
963        let mut store = EpisodicStore::new("test");
964        store.record_episode(
965            make_episode("Task 1", Outcome::Success { tests_passed: true }),
966            &policy,
967        );
968        store.record_episode(
969            make_episode(
970                "Task 2",
971                Outcome::Failure {
972                    error: "err".to_string(),
973                },
974            ),
975            &policy,
976        );
977        store.record_episode(
978            make_episode(
979                "Task 3",
980                Outcome::Success {
981                    tests_passed: false,
982                },
983            ),
984            &policy,
985        );
986
987        assert_eq!(store.by_outcome("success").len(), 2);
988        assert_eq!(store.by_outcome("failure").len(), 1);
989    }
990
991    #[test]
992    fn filter_by_file() {
993        let policy = EpisodicPolicy::default();
994        let mut store = EpisodicStore::new("test");
995        store.record_episode(make_episode("Task", Outcome::Unknown), &policy);
996
997        let results = store.by_file("main.rs");
998        assert_eq!(results.len(), 1);
999
1000        let results = store.by_file("nonexistent.rs");
1001        assert!(results.is_empty());
1002    }
1003
1004    #[test]
1005    fn recent_episodes() {
1006        let policy = EpisodicPolicy::default();
1007        let mut store = EpisodicStore::new("test");
1008        for i in 0..5 {
1009            store.record_episode(
1010                make_episode(&format!("Task {i}"), Outcome::Unknown),
1011                &policy,
1012            );
1013        }
1014
1015        let recent = store.recent(3);
1016        assert_eq!(recent.len(), 3);
1017        assert!(recent[0].task_description.contains('4'));
1018    }
1019
1020    #[test]
1021    fn stats_calculation() {
1022        let policy = EpisodicPolicy::default();
1023        let mut store = EpisodicStore::new("test");
1024        store.record_episode(
1025            make_episode("T1", Outcome::Success { tests_passed: true }),
1026            &policy,
1027        );
1028        store.record_episode(
1029            make_episode(
1030                "T2",
1031                Outcome::Failure {
1032                    error: "e".to_string(),
1033                },
1034            ),
1035            &policy,
1036        );
1037        store.record_episode(
1038            make_episode(
1039                "T3",
1040                Outcome::Success {
1041                    tests_passed: false,
1042                },
1043            ),
1044            &policy,
1045        );
1046
1047        let stats = store.stats();
1048        assert_eq!(stats.total_episodes, 3);
1049        assert_eq!(stats.successes, 2);
1050        assert_eq!(stats.failures, 1);
1051        assert!((stats.success_rate - 0.6667).abs() < 0.01);
1052    }
1053
1054    #[test]
1055    fn auto_summary_generation() {
1056        let mut ep = make_episode("Fix the login bug", Outcome::Success { tests_passed: true });
1057        ep.summary = String::new();
1058        let summary = auto_summarize(&ep, EpisodicPolicy::default().summary_max_chars);
1059        assert!(summary.contains("Fix the login bug"));
1060        assert!(summary.contains("[success]"));
1061        assert!(summary.contains("ctx_read"));
1062    }
1063
1064    #[test]
1065    fn max_episodes_enforced() {
1066        let policy = EpisodicPolicy::default();
1067        let mut store = EpisodicStore::new("test");
1068        for i in 0..510 {
1069            store.record_episode(
1070                make_episode(&format!("Task {i}"), Outcome::Unknown),
1071                &policy,
1072            );
1073        }
1074        assert!(store.episodes.len() <= policy.max_episodes);
1075    }
1076
1077    #[test]
1078    fn format_compact() {
1079        let ep = make_episode("Deploy v2", Outcome::Success { tests_passed: true });
1080        let output = format_episode_compact(&ep);
1081        assert!(output.contains("[success]"));
1082        assert!(output.contains("Deploy v2"));
1083    }
1084
1085    #[test]
1086    fn finalize_metrics_converts_cumulative_to_delta() {
1087        let mut store = EpisodicStore::new("test");
1088        let started = Utc::now() - chrono::Duration::seconds(600);
1089
1090        let mut first = make_episode("T1", Outcome::Unknown);
1091        first.session_id = "sess-x".to_string();
1092        first.tokens_used = 1000; // cumulative at record time
1093        first.timestamp = started + chrono::Duration::seconds(100);
1094        finalize_episode_metrics(&mut first, &store, started);
1095        assert_eq!(first.tokens_used, 1000);
1096        assert_eq!(first.duration_secs, 100);
1097        store.episodes.push(first);
1098
1099        let mut second = make_episode("T2", Outcome::Unknown);
1100        second.session_id = "sess-x".to_string();
1101        second.tokens_used = 1800; // cumulative at record time
1102        second.timestamp = started + chrono::Duration::seconds(400);
1103        finalize_episode_metrics(&mut second, &store, started);
1104        assert_eq!(second.tokens_used, 800); // delta since first
1105        assert_eq!(second.duration_secs, 300);
1106    }
1107
1108    #[test]
1109    fn migrate_legacy_dedupes_ids_and_converts_tokens() {
1110        let mut store = EpisodicStore::new("test");
1111        let base = Utc::now() - chrono::Duration::seconds(1000);
1112        for (i, cumulative) in [1000u64, 3000, 6000].iter().enumerate() {
1113            let mut ep = make_episode(&format!("T{i}"), Outcome::Unknown);
1114            ep.id = "ep-20260516".to_string(); // legacy colliding id
1115            ep.session_id = "sess-legacy".to_string();
1116            ep.tokens_used = *cumulative;
1117            ep.duration_secs = 0;
1118            ep.timestamp = base + chrono::Duration::seconds(i as i64 * 120);
1119            store.episodes.push(ep);
1120        }
1121
1122        assert!(store.migrate_legacy_episodes());
1123        let ids: std::collections::HashSet<String> =
1124            store.episodes.iter().map(|e| e.id.clone()).collect();
1125        assert_eq!(ids.len(), 3, "ids must be unique after migration");
1126        let tokens: Vec<u64> = store.episodes.iter().map(|e| e.tokens_used).collect();
1127        assert_eq!(tokens, vec![1000, 2000, 3000]);
1128        // Idempotent: unique ids → no second migration.
1129        assert!(!store.migrate_legacy_episodes());
1130    }
1131
1132    #[test]
1133    fn project_scope_withholds_whole_mixed_episode_and_keeps_empty_history() {
1134        let root = tempfile::tempdir().unwrap();
1135        let foreign = tempfile::tempdir().unwrap();
1136        std::fs::create_dir_all(root.path().join("src")).unwrap();
1137        std::fs::write(root.path().join("src/local.rs"), "local").unwrap();
1138        std::fs::write(foreign.path().join("secret.rs"), "foreign").unwrap();
1139        let canonical_root = std::fs::canonicalize(root.path()).unwrap();
1140        let local = root
1141            .path()
1142            .join("src/local.rs")
1143            .to_string_lossy()
1144            .into_owned();
1145        let historical_missing = root
1146            .path()
1147            .join("src/removed.rs")
1148            .to_string_lossy()
1149            .into_owned();
1150        let outside = foreign
1151            .path()
1152            .join("secret.rs")
1153            .to_string_lossy()
1154            .into_owned();
1155
1156        assert!(episode_paths_belong_to_project(
1157            root.path(),
1158            &canonical_root,
1159            std::slice::from_ref(&local),
1160        ));
1161        assert!(episode_paths_belong_to_project(
1162            root.path(),
1163            &canonical_root,
1164            &[historical_missing],
1165        ));
1166        assert!(episode_paths_belong_to_project(
1167            root.path(),
1168            &canonical_root,
1169            &[],
1170        ));
1171        assert!(!episode_paths_belong_to_project(
1172            root.path(),
1173            &canonical_root,
1174            std::slice::from_ref(&outside),
1175        ));
1176        assert!(!episode_paths_belong_to_project(
1177            root.path(),
1178            &canonical_root,
1179            &[local.clone(), outside.clone()],
1180        ));
1181        assert!(!episode_paths_belong_to_project(
1182            root.path(),
1183            &canonical_root,
1184            &["../foreign/secret.rs".to_string()],
1185        ));
1186        assert!(!episode_paths_belong_to_project(
1187            root.path(),
1188            &canonical_root,
1189            &["C:/foreign/secret.rs".to_string()],
1190        ));
1191
1192        let root_name = root.path().file_name().unwrap().to_string_lossy();
1193        let prefix_neighbor = root
1194            .path()
1195            .with_file_name(format!("{root_name}-neighbor/file.rs"));
1196        assert!(!episode_paths_belong_to_project(
1197            root.path(),
1198            &canonical_root,
1199            &[prefix_neighbor.to_string_lossy().into_owned()],
1200        ));
1201
1202        let mut safe = make_episode("safe", Outcome::Unknown);
1203        safe.id = "safe".into();
1204        safe.affected_files = vec![local.clone()];
1205        let mut mixed = make_episode("mixed", Outcome::Unknown);
1206        mixed.id = "mixed".into();
1207        mixed.affected_files = vec![local, outside];
1208        let mut no_paths = make_episode("legacy without paths", Outcome::Unknown);
1209        no_paths.id = "legacy-empty".into();
1210        no_paths.affected_files.clear();
1211        let mut view = EpisodicStore::new("scope-test");
1212        view.episodes = vec![safe, mixed, no_paths];
1213        view.retain_episodes_for_project(root.path(), &canonical_root);
1214        let visible_ids: Vec<_> = view
1215            .episodes
1216            .iter()
1217            .map(|episode| episode.id.as_str())
1218            .collect();
1219        assert_eq!(visible_ids, vec!["safe", "legacy-empty"]);
1220    }
1221
1222    #[cfg(unix)]
1223    #[test]
1224    fn project_scope_rejects_existing_and_missing_symlink_escapes() {
1225        use std::os::unix::fs::symlink;
1226
1227        let root = tempfile::tempdir().unwrap();
1228        let foreign = tempfile::tempdir().unwrap();
1229        std::fs::write(foreign.path().join("existing.rs"), "foreign").unwrap();
1230        symlink(foreign.path(), root.path().join("escape")).unwrap();
1231        let canonical_root = std::fs::canonicalize(root.path()).unwrap();
1232        let existing = root
1233            .path()
1234            .join("escape/existing.rs")
1235            .to_string_lossy()
1236            .into_owned();
1237        let missing = root
1238            .path()
1239            .join("escape/not-yet-created.rs")
1240            .to_string_lossy()
1241            .into_owned();
1242
1243        assert!(!episode_paths_belong_to_project(
1244            root.path(),
1245            &canonical_root,
1246            &[existing],
1247        ));
1248        assert!(!episode_paths_belong_to_project(
1249            root.path(),
1250            &canonical_root,
1251            &[missing],
1252        ));
1253    }
1254}