Skip to main content

lean_ctx/core/
procedural_memory.rs

1//! Procedural Memory — recurring workflow detection and template storage.
2//!
3//! Detects repeated tool-call sequences in Episodic Memory and stores them
4//! as reusable Procedures with activation/termination conditions.
5
6use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use std::{
9    collections::HashMap,
10    path::{Path, PathBuf},
11    sync::{Arc, Mutex, OnceLock},
12};
13
14use super::episodic_memory::{Episode, Outcome};
15
16use crate::core::context_admission::stores::StoreAdmission;
17use crate::core::memory_policy::ProceduralPolicy;
18use crate::core::policy::runtime::PublicationAuthority;
19
20fn procedural_lock(project_hash: &str) -> Arc<Mutex<()>> {
21    static LOCKS: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
22    let mut locks = LOCKS
23        .get_or_init(|| Mutex::new(HashMap::new()))
24        .lock()
25        .unwrap_or_else(std::sync::PoisonError::into_inner);
26    locks.entry(project_hash.to_string()).or_default().clone()
27}
28
29fn acquire_procedural_file_lock(path: &Path) -> Result<std::fs::File, String> {
30    use fs2::FileExt;
31
32    let parent = path
33        .parent()
34        .ok_or_else(|| "procedural store path has no parent".to_string())?;
35    let name = path
36        .file_name()
37        .ok_or_else(|| "procedural store path has no filename".to_string())?
38        .to_string_lossy();
39    let lock_path = parent.join(format!(".{name}.lock"));
40    let file = std::fs::OpenOptions::new()
41        .create(true)
42        .truncate(false)
43        .write(true)
44        .open(&lock_path)
45        .map_err(|error| format!("procedural store lock unavailable: {error}"))?;
46    #[cfg(unix)]
47    {
48        use std::os::unix::fs::PermissionsExt;
49        let _ = std::fs::set_permissions(&lock_path, std::fs::Permissions::from_mode(0o600));
50    }
51    file.try_lock_exclusive()
52        .map_err(|error| format!("procedural store lock unavailable: {error}"))?;
53    Ok(file)
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct ProceduralStore {
58    pub project_hash: String,
59    pub procedures: Vec<Procedure>,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize)]
63pub struct Procedure {
64    pub id: String,
65    pub name: String,
66    pub description: String,
67    pub steps: Vec<ProcedureStep>,
68    pub activation_keywords: Vec<String>,
69    pub confidence: f32,
70    pub times_used: u32,
71    pub times_succeeded: u32,
72    pub last_used: DateTime<Utc>,
73    pub project_specific: bool,
74    pub created_at: DateTime<Utc>,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
78pub struct ProcedureStep {
79    pub tool: String,
80    pub description: String,
81    pub optional: bool,
82}
83
84/// Retention value of a procedure (higher = keep): confidence-weighted, with a
85/// success-rate and usage component. The single ranking used by both the
86/// per-write reclaim ([`ProceduralStore::add_procedure`]) and the consolidation
87/// capacity pass, so procedure eviction is consistent everywhere (#995).
88pub fn retention_score(p: &Procedure) -> f32 {
89    let use_score = (p.times_used.min(20) as f32) / 20.0;
90    p.confidence * 0.5 + p.success_rate() * 0.3 + use_score * 0.2
91}
92
93/// Order procedures best-kept first (descending retention), deterministically.
94/// Pass to `memory_capacity::reclaim_store`, which archives the
95/// lowest-ranked tail.
96pub fn retention_cmp(a: &Procedure, b: &Procedure) -> std::cmp::Ordering {
97    retention_score(b)
98        .total_cmp(&retention_score(a))
99        .then_with(|| b.last_used.cmp(&a.last_used))
100        .then_with(|| b.created_at.cmp(&a.created_at))
101        .then_with(|| a.name.cmp(&b.name))
102        .then_with(|| a.id.cmp(&b.id))
103}
104
105impl Procedure {
106    pub fn success_rate(&self) -> f32 {
107        if self.times_used == 0 {
108            return 0.0;
109        }
110        self.times_succeeded as f32 / self.times_used as f32
111    }
112
113    pub fn matches_context(&self, task: &str) -> bool {
114        let task_lower = task.to_lowercase();
115        self.activation_keywords
116            .iter()
117            .any(|kw| task_lower.contains(&kw.to_lowercase()))
118    }
119}
120
121impl ProceduralStore {
122    pub fn new(project_hash: &str) -> Self {
123        Self {
124            project_hash: project_hash.to_string(),
125            procedures: Vec::new(),
126        }
127    }
128
129    pub fn suggest(&self, task: &str) -> Vec<&Procedure> {
130        let mut matches: Vec<(&Procedure, f32)> = self
131            .procedures
132            .iter()
133            .filter(|p| p.matches_context(task) && p.confidence >= 0.3)
134            .map(|p| {
135                let score = p.confidence * 0.5 + p.success_rate() * 0.3 + usage_recency(p) * 0.2;
136                (p, score)
137            })
138            .collect();
139
140        matches.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
141        matches.into_iter().map(|(p, _)| p).collect()
142    }
143
144    pub fn record_usage(&mut self, procedure_id: &str, success: bool) {
145        if let Some(proc) = self.procedures.iter_mut().find(|p| p.id == procedure_id) {
146            proc.times_used += 1;
147            if success {
148                proc.times_succeeded += 1;
149            }
150            proc.last_used = Utc::now();
151            proc.confidence =
152                (proc.confidence * 0.8 + if success { 0.2 } else { -0.1 }).clamp(0.0, 1.0);
153        }
154    }
155
156    pub fn add_procedure(&mut self, procedure: Procedure, policy: &ProceduralPolicy) {
157        if let Some(existing) = self
158            .procedures
159            .iter_mut()
160            .find(|p| p.name == procedure.name)
161        {
162            existing.confidence = existing.confidence.midpoint(procedure.confidence);
163            existing.steps = procedure.steps;
164            existing.activation_keywords = procedure.activation_keywords;
165        } else {
166            self.procedures.push(procedure);
167        }
168
169        // Lossless capacity reclaim (#995): keep the highest-value procedures and
170        // archive the rest instead of truncating them away. `add_procedure` only
171        // sees `ProceduralPolicy`, so it uses the standard headroom default and is
172        // always lossless (procedure eviction was already unconditional — it just
173        // used to lose the dropped procedures). Same `retention_cmp` as the
174        // consolidation capacity pass, so ranking is identical everywhere.
175        if let Err(error) = crate::core::memory_capacity::reclaim_store(
176            crate::core::memory_archive::MemoryStore::Procedures,
177            Some(&self.project_hash),
178            &mut self.procedures,
179            policy.max_procedures,
180            crate::core::memory_lifecycle::DEFAULT_RECLAIM_HEADROOM_PCT,
181            true,
182            retention_cmp,
183        ) {
184            tracing::warn!(%error, "procedure capacity reclaim failed");
185        }
186    }
187
188    pub(crate) fn add_procedure_admitted(
189        &mut self,
190        mut procedure: Procedure,
191        policy: &ProceduralPolicy,
192        admission: &StoreAdmission,
193        authority: &PublicationAuthority,
194    ) -> Result<(), String> {
195        let mut admit =
196            |text: &str| crate::core::session::admission::admit_store_text(admission, text);
197        if !sanitize_procedure(&mut procedure, &mut admit) {
198            return Err("procedure content withheld by current policy".into());
199        }
200        if let Some(existing) = self
201            .procedures
202            .iter_mut()
203            .find(|existing| existing.name == procedure.name)
204        {
205            existing.confidence = existing.confidence.midpoint(procedure.confidence);
206            existing.steps = procedure.steps;
207            existing.activation_keywords = procedure.activation_keywords;
208        } else {
209            self.procedures.push(procedure);
210        }
211
212        crate::core::memory_capacity::reclaim_store_with_authority(
213            crate::core::memory_archive::MemoryStore::Procedures,
214            Some(&self.project_hash),
215            &mut self.procedures,
216            policy.max_procedures,
217            crate::core::memory_lifecycle::DEFAULT_RECLAIM_HEADROOM_PCT,
218            true,
219            (admission, authority),
220            retention_cmp,
221        )?;
222        Ok(())
223    }
224
225    pub fn detect_patterns(&mut self, episodes: &[Episode], policy: &ProceduralPolicy) {
226        let sequences = extract_tool_sequences(episodes);
227        let patterns = find_repeated_sequences(&sequences, policy);
228
229        for (steps, count, keywords) in patterns {
230            if count < policy.min_repetitions || steps.len() < policy.min_sequence_len {
231                continue;
232            }
233
234            let name = generate_procedure_name(&steps);
235            let already_exists = self.procedures.iter().any(|p| p.name == name);
236            if already_exists {
237                continue;
238            }
239
240            let success_count = episodes
241                .iter()
242                .filter(|ep| matches!(ep.outcome, Outcome::Success { .. }))
243                .count();
244            let confidence = success_count as f32 / episodes.len().max(1) as f32;
245
246            self.add_procedure(
247                Procedure {
248                    id: format!("proc-{}", md5_short(&name)),
249                    name,
250                    description: format!("Detected workflow ({count} repetitions)"),
251                    steps,
252                    activation_keywords: keywords,
253                    confidence,
254                    times_used: count as u32,
255                    times_succeeded: success_count as u32,
256                    last_used: Utc::now(),
257                    project_specific: true,
258                    created_at: Utc::now(),
259                },
260                policy,
261            );
262        }
263    }
264
265    /// Derive procedures from admitted episodes, sanitize each candidate, then
266    /// route capacity eviction through the authority-checked archive sink.
267    pub(crate) fn detect_patterns_admitted(
268        &mut self,
269        episodes: &[Episode],
270        policy: &ProceduralPolicy,
271        admission: &StoreAdmission,
272        authority: &PublicationAuthority,
273    ) -> Result<(), String> {
274        let sequences = extract_tool_sequences(episodes);
275        let patterns = find_repeated_sequences(&sequences, policy);
276        let success_count = episodes
277            .iter()
278            .filter(|ep| matches!(ep.outcome, Outcome::Success { .. }))
279            .count();
280        let confidence = success_count as f32 / episodes.len().max(1) as f32;
281        let mut candidate_names = std::collections::HashSet::new();
282        let mut candidates = Vec::new();
283
284        for (steps, count, keywords) in patterns {
285            if count < policy.min_repetitions || steps.len() < policy.min_sequence_len {
286                continue;
287            }
288
289            let name = generate_procedure_name(&steps);
290            if self
291                .procedures
292                .iter()
293                .any(|procedure| procedure.name == name)
294                || !candidate_names.insert(name.clone())
295            {
296                continue;
297            }
298            let mut procedure = Procedure {
299                id: format!("proc-{}", md5_short(&name)),
300                name,
301                description: format!("Detected workflow ({count} repetitions)"),
302                steps,
303                activation_keywords: keywords,
304                confidence,
305                times_used: count as u32,
306                times_succeeded: success_count as u32,
307                last_used: Utc::now(),
308                project_specific: true,
309                created_at: Utc::now(),
310            };
311            let mut admit =
312                |text: &str| crate::core::session::admission::admit_store_text(admission, text);
313            if sanitize_procedure(&mut procedure, &mut admit) {
314                candidates.push(procedure);
315            }
316        }
317
318        for procedure in candidates {
319            self.add_procedure_admitted(procedure, policy, admission, authority)?;
320        }
321        Ok(())
322    }
323
324    fn store_path(project_hash: &str) -> Option<PathBuf> {
325        let dir = crate::core::data_dir::lean_ctx_data_dir()
326            .ok()?
327            .join("memory")
328            .join("procedures");
329        Some(dir.join(format!("{project_hash}.json")))
330    }
331
332    pub fn load(project_hash: &str) -> Option<Self> {
333        let path = Self::store_path(project_hash)?;
334        let data = std::fs::read_to_string(path).ok()?;
335        serde_json::from_str(&data).ok()
336    }
337
338    /// Load procedures only after every content-bearing field is admitted for
339    /// the trusted project's storage policy.
340    pub(crate) fn load_admitted(
341        project_hash: &str,
342        admission: &StoreAdmission,
343    ) -> Result<Self, String> {
344        let mut store = match Self::store_path(project_hash) {
345            Some(path) => match std::fs::read_to_string(path) {
346                Ok(data) => {
347                    serde_json::from_str::<Self>(&data).map_err(|error| error.to_string())?
348                }
349                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
350                    Self::new(project_hash)
351                }
352                Err(error) => return Err(error.to_string()),
353            },
354            None => return Err("Cannot determine data directory".into()),
355        };
356        if store.project_hash != project_hash {
357            return Err("procedural store project scope mismatch".into());
358        }
359        let mut admit =
360            |text: &str| crate::core::session::admission::admit_store_text(admission, text);
361        store
362            .procedures
363            .retain_mut(|procedure| sanitize_procedure(procedure, &mut admit));
364        if !admission.is_current() {
365            return Err("session admission policy changed; retry".into());
366        }
367        Ok(store)
368    }
369
370    pub fn load_or_create(project_hash: &str) -> Self {
371        Self::load(project_hash).unwrap_or_else(|| Self::new(project_hash))
372    }
373
374    /// Reload, sanitize, derive and atomically persist under one per-project
375    /// lock so concurrent session completions cannot overwrite each other.
376    pub(crate) fn mutate_locked_admitted<T>(
377        project_hash: &str,
378        admission: &StoreAdmission,
379        mutate: impl FnOnce(&mut Self) -> Result<T, String>,
380    ) -> Result<(Self, T), String> {
381        Self::mutate_locked_admitted_with_authority(project_hash, admission, |store, _| {
382            mutate(store)
383        })
384    }
385
386    /// Admitted mutation variant for derived writes that may archive evictions.
387    /// The scoped authority is supplied to the closure so each archive sink can
388    /// revalidate immediately before publishing its recovery artifact.
389    pub(crate) fn mutate_locked_admitted_with_authority<T>(
390        project_hash: &str,
391        admission: &StoreAdmission,
392        mutate: impl FnOnce(&mut Self, &PublicationAuthority) -> Result<T, String>,
393    ) -> Result<(Self, T), String> {
394        let authority = PublicationAuthority::capture()
395            .map_err(|_| "source authority unavailable".to_string())?;
396        let lock = procedural_lock(project_hash);
397        let _guard = lock
398            .try_lock()
399            .map_err(|_| "procedural store is busy; retry".to_string())?;
400        let path = Self::store_path(project_hash)
401            .ok_or_else(|| "Cannot determine data directory".to_string())?;
402        if let Some(dir) = path.parent() {
403            std::fs::create_dir_all(dir).map_err(|error| error.to_string())?;
404        }
405        let _file_lock = acquire_procedural_file_lock(&path)?;
406        let mut store = match std::fs::read_to_string(&path) {
407            Ok(data) => serde_json::from_str::<Self>(&data).map_err(|error| error.to_string())?,
408            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Self::new(project_hash),
409            Err(error) => return Err(error.to_string()),
410        };
411        if store.project_hash != project_hash {
412            return Err("procedural store project scope mismatch".into());
413        }
414        let mut admit =
415            |text: &str| crate::core::session::admission::admit_store_text(admission, text);
416        store
417            .procedures
418            .retain_mut(|procedure| sanitize_procedure(procedure, &mut admit));
419        let result = mutate(&mut store, &authority)?;
420        store
421            .procedures
422            .retain_mut(|procedure| sanitize_procedure(procedure, &mut admit));
423        let json = serde_json::to_string_pretty(&store).map_err(|error| error.to_string())?;
424        admission.authorize_publication(&authority)?;
425        crate::config_io::write_atomic(&path, &json)?;
426        Ok((store, result))
427    }
428
429    pub fn save(&self) -> Result<(), String> {
430        let path = Self::store_path(&self.project_hash)
431            .ok_or_else(|| "Cannot determine data directory".to_string())?;
432        if let Some(dir) = path.parent() {
433            std::fs::create_dir_all(dir).map_err(|e| format!("{e}"))?;
434        }
435        let json = serde_json::to_string_pretty(self).map_err(|e| format!("{e}"))?;
436        std::fs::write(path, json).map_err(|e| format!("{e}"))
437    }
438}
439
440/// Compatibility entry point for callers already running inside a trusted
441/// project source view. Calls without that authority fail closed. New callers
442/// should pass the project root explicitly to avoid relying on ambient state.
443pub fn auto_detect_from_episodes(project_hash: &str, policy: &ProceduralPolicy) -> Option<usize> {
444    let _authority = PublicationAuthority::capture().ok()?;
445    let project_root = crate::core::policy::runtime::detached_project_root(Path::new("")).ok()?;
446    auto_detect_from_episodes_for_project(&project_root, project_hash, policy)
447}
448
449/// Explicit-project variant for trusted callers outside the session tool.
450pub fn auto_detect_from_episodes_for_project(
451    project_root: &Path,
452    project_hash: &str,
453    policy: &ProceduralPolicy,
454) -> Option<usize> {
455    let project_root_text = project_root.to_str()?;
456    if crate::core::project_hash::hash_project_root(project_root_text) != project_hash {
457        return None;
458    }
459
460    crate::core::policy::runtime::with_explicit_project_source_view(
461        project_root,
462        |authority| -> Result<Option<usize>, String> {
463            let admission = StoreAdmission::current();
464            let episodes =
465                super::episodic_memory::EpisodicStore::load_admitted(project_hash, &admission)?;
466            if episodes.episodes.is_empty() {
467                return Ok(None);
468            }
469            let (procedures, ()) = ProceduralStore::mutate_locked_admitted_with_authority(
470                project_hash,
471                &admission,
472                |store, store_authority| {
473                    store.detect_patterns_admitted(
474                        &episodes.episodes,
475                        policy,
476                        &admission,
477                        store_authority,
478                    )
479                },
480            )?;
481            admission.authorize_publication(authority)?;
482            Ok(Some(procedures.procedures.len()))
483        },
484    )
485    .ok()?
486    .ok()?
487}
488
489fn sanitize_procedure(
490    procedure: &mut Procedure,
491    admit: &mut impl FnMut(&str) -> Option<String>,
492) -> bool {
493    fn field(value: &mut String, admit: &mut impl FnMut(&str) -> Option<String>) -> bool {
494        if value.is_empty() {
495            return true;
496        }
497        let Some(projected) = admit(value) else {
498            return false;
499        };
500        *value = projected;
501        true
502    }
503
504    field(&mut procedure.name, admit)
505        && field(&mut procedure.description, admit)
506        && procedure
507            .activation_keywords
508            .iter_mut()
509            .all(|keyword| field(keyword, admit))
510        && procedure
511            .steps
512            .iter_mut()
513            .all(|step| field(&mut step.tool, admit) && field(&mut step.description, admit))
514}
515
516fn extract_tool_sequences(episodes: &[Episode]) -> Vec<Vec<String>> {
517    episodes
518        .iter()
519        .map(|ep| ep.actions.iter().map(|a| a.tool.clone()).collect())
520        .collect()
521}
522
523fn find_repeated_sequences(
524    sequences: &[Vec<String>],
525    policy: &ProceduralPolicy,
526) -> Vec<(Vec<ProcedureStep>, usize, Vec<String>)> {
527    let mut ngram_counts: HashMap<Vec<String>, usize> = HashMap::new();
528
529    for seq in sequences {
530        if seq.len() < policy.min_sequence_len {
531            continue;
532        }
533        let max_win = seq.len().min(policy.max_window_size);
534        for window_size in policy.min_sequence_len..=max_win {
535            for window in seq.windows(window_size) {
536                let key: Vec<String> = window.to_vec();
537                *ngram_counts.entry(key).or_insert(0) += 1;
538            }
539        }
540    }
541
542    let mut results: Vec<(Vec<ProcedureStep>, usize, Vec<String>)> = Vec::new();
543
544    let mut sorted: Vec<_> = ngram_counts.into_iter().collect();
545    sorted.sort_by(|a, b| {
546        let score_a = a.1 * a.0.len();
547        let score_b = b.1 * b.0.len();
548        score_b.cmp(&score_a)
549    });
550
551    let mut seen_prefixes: std::collections::HashSet<String> = std::collections::HashSet::new();
552
553    for (tools, count) in sorted {
554        if count < policy.min_repetitions {
555            continue;
556        }
557
558        let prefix = tools.join("->");
559        let is_substring = seen_prefixes.iter().any(|s| s.contains(&prefix));
560        if is_substring {
561            continue;
562        }
563
564        seen_prefixes.insert(prefix);
565
566        let steps: Vec<ProcedureStep> = tools
567            .iter()
568            .map(|t| ProcedureStep {
569                tool: t.clone(),
570                description: String::new(),
571                optional: false,
572            })
573            .collect();
574
575        let keywords: Vec<String> = tools
576            .iter()
577            .filter(|t| !t.starts_with("ctx_"))
578            .cloned()
579            .collect();
580
581        results.push((steps, count, keywords));
582    }
583
584    results
585}
586
587fn generate_procedure_name(steps: &[ProcedureStep]) -> String {
588    let tools: Vec<&str> = steps.iter().map(|s| s.tool.as_str()).collect();
589    let short: Vec<&str> = tools
590        .iter()
591        .map(|t| t.strip_prefix("ctx_").unwrap_or(t))
592        .collect();
593    format!("workflow-{}", short.join("-"))
594}
595
596fn md5_short(input: &str) -> String {
597    use md5::{Digest, Md5};
598    let result = Md5::digest(input.as_bytes());
599    crate::core::agent_identity::hex_encode(&result)[..8].to_string()
600}
601
602fn usage_recency(proc: &Procedure) -> f32 {
603    let days_old = Utc::now().signed_duration_since(proc.last_used).num_days() as f32;
604    (1.0 - days_old / 30.0).max(0.0)
605}
606
607pub fn format_suggestion(proc: &Procedure) -> String {
608    let mut output = format!(
609        "Suggested workflow: {} (confidence: {:.0}%, used {}x, success rate: {:.0}%)\n",
610        proc.name,
611        proc.confidence * 100.0,
612        proc.times_used,
613        proc.success_rate() * 100.0
614    );
615    for (i, step) in proc.steps.iter().enumerate() {
616        let opt = if step.optional { " (optional)" } else { "" };
617        output.push_str(&format!("  {}. {}{opt}\n", i + 1, step.tool));
618    }
619    output
620}
621
622#[cfg(test)]
623pub mod tests {
624    use super::*;
625    use crate::core::episodic_memory::{Action, Episode, Outcome};
626
627    fn make_episode_with_tools(tools: &[&str]) -> Episode {
628        Episode {
629            id: "ep-1".to_string(),
630            session_id: "s-1".to_string(),
631            timestamp: Utc::now(),
632            task_description: "test task".to_string(),
633            actions: tools
634                .iter()
635                .map(|t| Action {
636                    tool: t.to_string(),
637                    description: String::new(),
638                    timestamp: Utc::now(),
639                    duration_ms: 100,
640                    success: true,
641                })
642                .collect(),
643            outcome: Outcome::Success { tests_passed: true },
644            affected_files: vec![],
645            summary: String::new(),
646            duration_secs: 60,
647            tokens_used: 1000,
648            agent_id: None,
649        }
650    }
651
652    #[test]
653    fn admitted_procedure_rejects_restricted_candidate_before_archive() {
654        let _data_dir = crate::core::data_dir::isolated_data_dir();
655
656        let project = tempfile::tempdir().expect("project root");
657        let project_path = project.path().to_str().expect("UTF-8 project path");
658        crate::core::policy::runtime::with_project_source_view(project_path, || {
659            let authority = PublicationAuthority::capture().expect("project authority");
660            let admission = StoreAdmission::current();
661            let policy = ProceduralPolicy {
662                max_procedures: 1,
663                ..Default::default()
664            };
665            let mut store = ProceduralStore::new("procedure-admission-test");
666            let candidate = Procedure {
667                id: "restricted".into(),
668                name: "TOP SECRET\ncandidate".into(),
669                description: "safe description".into(),
670                steps: vec![],
671                activation_keywords: vec![],
672                confidence: 0.5,
673                times_used: 1,
674                times_succeeded: 1,
675                last_used: Utc::now(),
676                project_specific: true,
677                created_at: Utc::now(),
678            };
679
680            assert!(
681                store
682                    .add_procedure_admitted(candidate, &policy, &admission, &authority)
683                    .is_err()
684            );
685            assert!(store.procedures.is_empty());
686            assert!(
687                crate::core::memory_archive::list_archives(
688                    crate::core::memory_archive::MemoryStore::Procedures,
689                    Some("procedure-admission-test"),
690                )
691                .is_empty()
692            );
693        })
694        .expect("source view");
695    }
696
697    #[test]
698    fn admission_scrubs_every_procedure_field_or_drops_the_record() {
699        let mut procedure = Procedure {
700            id: "proc-test".into(),
701            name: "NAME PRIVATE".into(),
702            description: "DESCRIPTION PRIVATE".into(),
703            steps: vec![ProcedureStep {
704                tool: "TOOL PRIVATE".into(),
705                description: "STEP PRIVATE".into(),
706                optional: false,
707            }],
708            activation_keywords: vec!["KEYWORD PRIVATE".into()],
709            confidence: 0.8,
710            times_used: 2,
711            times_succeeded: 1,
712            last_used: Utc::now(),
713            project_specific: true,
714            created_at: Utc::now(),
715        };
716        assert!(sanitize_procedure(&mut procedure, &mut |text| {
717            Some(text.replace("PRIVATE", "redacted"))
718        }));
719        assert_eq!(procedure.name, "NAME redacted");
720        assert_eq!(procedure.description, "DESCRIPTION redacted");
721        assert_eq!(procedure.steps[0].tool, "TOOL redacted");
722        assert_eq!(procedure.steps[0].description, "STEP redacted");
723        assert_eq!(procedure.activation_keywords[0], "KEYWORD redacted");
724
725        assert!(!sanitize_procedure(&mut procedure, &mut |text| {
726            (text != "NAME redacted").then(|| text.to_string())
727        }));
728    }
729
730    #[test]
731    fn detect_patterns_from_episodes() {
732        let policy = ProceduralPolicy::default();
733        let episodes: Vec<Episode> = (0..5)
734            .map(|_| make_episode_with_tools(&["ctx_read", "ctx_shell", "ctx_read"]))
735            .collect();
736
737        let mut store = ProceduralStore::new("test");
738        store.detect_patterns(&episodes, &policy);
739
740        assert!(
741            !store.procedures.is_empty(),
742            "Should detect at least one pattern"
743        );
744    }
745
746    #[test]
747    fn suggest_matching_procedure() {
748        let policy = ProceduralPolicy::default();
749        let mut store = ProceduralStore::new("test");
750        store.add_procedure(
751            Procedure {
752                id: "proc-1".to_string(),
753                name: "deploy-workflow".to_string(),
754                description: "Deploy".to_string(),
755                steps: vec![ProcedureStep {
756                    tool: "ctx_shell".to_string(),
757                    description: "cargo build".to_string(),
758                    optional: false,
759                }],
760                activation_keywords: vec!["deploy".to_string(), "release".to_string()],
761                confidence: 0.8,
762                times_used: 5,
763                times_succeeded: 4,
764                last_used: Utc::now(),
765                project_specific: true,
766                created_at: Utc::now(),
767            },
768            &policy,
769        );
770
771        let suggestions = store.suggest("deploy the new version");
772        assert_eq!(suggestions.len(), 1);
773        assert_eq!(suggestions[0].name, "deploy-workflow");
774
775        let none = store.suggest("refactor the database layer");
776        assert!(none.is_empty());
777    }
778
779    #[test]
780    fn record_usage_updates_confidence() {
781        let policy = ProceduralPolicy::default();
782        let mut store = ProceduralStore::new("test");
783        store.add_procedure(
784            Procedure {
785                id: "proc-1".to_string(),
786                name: "test-workflow".to_string(),
787                description: "Test".to_string(),
788                steps: vec![],
789                activation_keywords: vec![],
790                confidence: 0.5,
791                times_used: 0,
792                times_succeeded: 0,
793                last_used: Utc::now(),
794                project_specific: false,
795                created_at: Utc::now(),
796            },
797            &policy,
798        );
799
800        store.record_usage("proc-1", true);
801        let proc = &store.procedures[0];
802        assert_eq!(proc.times_used, 1);
803        assert_eq!(proc.times_succeeded, 1);
804        assert!(proc.confidence > 0.5);
805    }
806
807    #[test]
808    fn success_rate_calculation() {
809        let proc = Procedure {
810            id: "p".to_string(),
811            name: "n".to_string(),
812            description: String::new(),
813            steps: vec![],
814            activation_keywords: vec![],
815            confidence: 0.5,
816            times_used: 10,
817            times_succeeded: 7,
818            last_used: Utc::now(),
819            project_specific: false,
820            created_at: Utc::now(),
821        };
822        assert!((proc.success_rate() - 0.7).abs() < 0.01);
823    }
824
825    #[test]
826    fn max_procedures_enforced() {
827        // Eviction archives the dropped procedures and keeps them all when the
828        // archive write fails (lossless, #995); in the shared test sandbox that
829        // write competed with every parallel memory test and lost.
830        let _data = crate::core::data_dir::isolated_data_dir();
831        let policy = ProceduralPolicy::default();
832        let mut store = ProceduralStore::new("test");
833        for i in 0..110 {
834            store.add_procedure(
835                Procedure {
836                    id: format!("p-{i}"),
837                    name: format!("workflow-{i}"),
838                    description: String::new(),
839                    steps: vec![],
840                    activation_keywords: vec![],
841                    confidence: i as f32 / 110.0,
842                    times_used: 0,
843                    times_succeeded: 0,
844                    last_used: Utc::now(),
845                    project_specific: false,
846                    created_at: Utc::now(),
847                },
848                &policy,
849            );
850        }
851        assert!(store.procedures.len() <= policy.max_procedures);
852    }
853
854    #[test]
855    fn auto_detect_learns_from_recorded_episodes() {
856        let _isolated = crate::core::data_dir::isolated_data_dir();
857        let project = tempfile::tempdir().expect("project root");
858        let root = project.path().to_str().expect("UTF-8 project root");
859        let hash = crate::core::project_hash::hash_project_root(root);
860        let policy = crate::core::memory_policy::MemoryPolicy::default();
861        let mut episodes = crate::core::episodic_memory::EpisodicStore::new(&hash);
862        for _ in 0..5 {
863            episodes.record_episode(
864                make_episode_with_tools(&["ctx_read", "ctx_shell", "ctx_read"]),
865                &policy.episodic,
866            );
867        }
868        episodes.save().expect("episodic save");
869
870        assert!(
871            auto_detect_from_episodes(&hash, &policy.procedural).is_none(),
872            "ambient compatibility entry point must fail closed"
873        );
874        let learned =
875            auto_detect_from_episodes_for_project(project.path(), &hash, &policy.procedural);
876        assert!(
877            learned.is_some_and(|count| count > 0),
878            "admitted auto-detect should learn a workflow, got {learned:?}"
879        );
880        let reloaded = ProceduralStore::load(&hash).expect("procedural store persisted");
881        assert!(!reloaded.procedures.is_empty());
882    }
883
884    #[test]
885    fn format_suggestion_output() {
886        let proc = Procedure {
887            id: "p".to_string(),
888            name: "deploy-workflow".to_string(),
889            description: String::new(),
890            steps: vec![
891                ProcedureStep {
892                    tool: "ctx_shell".to_string(),
893                    description: "test".to_string(),
894                    optional: false,
895                },
896                ProcedureStep {
897                    tool: "ctx_shell".to_string(),
898                    description: "build".to_string(),
899                    optional: true,
900                },
901            ],
902            activation_keywords: vec![],
903            confidence: 0.85,
904            times_used: 10,
905            times_succeeded: 8,
906            last_used: Utc::now(),
907            project_specific: false,
908            created_at: Utc::now(),
909        };
910        let output = format_suggestion(&proc);
911        assert!(output.contains("deploy-workflow"));
912        assert!(output.contains("85%"));
913        assert!(output.contains("(optional)"));
914    }
915}