Skip to main content

lean_ctx/core/ocla/
compose_cache.rs

1//! Section-aware cache for `ctx_compose` results.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::sync::{Mutex, OnceLock};
6
7use crate::core::ocla::cache_types::{CacheKeyBuilder, ComposedContextKey};
8
9#[derive(Clone, Debug)]
10struct ComposeRecord {
11    corpus_revision: String,
12    source_paths: Vec<PathBuf>,
13    source_digests: Vec<String>,
14    text: String,
15}
16
17/// In-process composition cache. A record is valid only when every source file
18/// still has the digest used to build its `ComposedContextKey`.
19#[derive(Default)]
20pub struct ComposeSectionCache {
21    records: Mutex<BTreeMap<(String, String), ComposeRecord>>,
22}
23
24impl ComposeSectionCache {
25    pub fn check(&self, task: &str, path: &str) -> Option<String> {
26        // Legacy records do not bind their complete source set to a policy.
27        if crate::core::policy::runtime::is_active() {
28            return None;
29        }
30        let key = (task.trim().to_string(), path.to_string());
31        let record = self.records.lock().ok()?.get(&key)?.clone();
32        if source_revision(path)? != record.corpus_revision {
33            return None;
34        }
35        let source_digests = source_digests(path, &record.source_paths)?;
36        let builder = ComposedContextKey {
37            task: key.0,
38            path: key.1,
39            source_digests,
40        };
41        (builder.source_digests == record.source_digests).then_some(record.text)
42    }
43
44    pub fn record(&self, task: &str, path: &str, text: String, corpus_revision: &str) -> bool {
45        if source_revision(path).as_deref() != Some(corpus_revision) {
46            return false;
47        }
48        let source_paths = source_paths(path, &text);
49        let Some(source_digests) = source_digests(path, &source_paths) else {
50            return false;
51        };
52        if source_revision(path).as_deref() != Some(corpus_revision) {
53            return false;
54        }
55        let builder = ComposedContextKey {
56            task: task.trim().to_string(),
57            path: path.to_string(),
58            source_digests: source_digests.clone(),
59        };
60        let _cache_key = builder.cache_key();
61        let key = (builder.task, builder.path);
62        if let Ok(mut records) = self.records.lock() {
63            records.insert(
64                key,
65                ComposeRecord {
66                    corpus_revision: corpus_revision.to_string(),
67                    source_paths,
68                    source_digests,
69                    text,
70                },
71            );
72            return true;
73        }
74        false
75    }
76}
77
78/// A legacy Community cache is reusable only while the bounded source corpus
79/// and secret-path visibility are unchanged, including after policy removal.
80pub(crate) fn source_revision(path: &str) -> Option<String> {
81    if crate::core::policy::runtime::is_active() {
82        return None;
83    }
84    let role = crate::core::roles::active_role();
85    let allow_secret = role.io.allow_secret_paths;
86    let role_fingerprint = crate::core::policy::runtime::role_fingerprint(&role).ok()?;
87    crate::core::search_index::corpus_signature(path, true, allow_secret)
88        .map(|revision| format!("{revision}:role={role_fingerprint}"))
89}
90
91pub fn global() -> &'static ComposeSectionCache {
92    static CACHE: OnceLock<ComposeSectionCache> = OnceLock::new();
93    CACHE.get_or_init(ComposeSectionCache::default)
94}
95
96fn source_paths(project_root: &str, text: &str) -> Vec<PathBuf> {
97    let root = Path::new(project_root);
98    let mut paths = text
99        .lines()
100        .filter_map(|line| line.trim().strip_prefix("File: "))
101        .filter_map(|raw| raw.split_whitespace().next())
102        .map(|raw| {
103            let path = PathBuf::from(raw);
104            if path.is_absolute() {
105                path
106            } else {
107                root.join(path)
108            }
109        })
110        .filter(|path| path.is_file())
111        .collect::<Vec<_>>();
112    paths.sort();
113    paths.dedup();
114    paths
115}
116
117fn source_digests(root: &str, paths: &[PathBuf]) -> Option<Vec<String>> {
118    let mut digests = paths
119        .iter()
120        .map(|path| {
121            crate::tools::ctx_read::read_file_for_tool_rooted(
122                &path.to_string_lossy(),
123                root,
124                "ctx_compose",
125            )
126            .ok()
127            .map(|content| blake3::hash(content.as_bytes()).to_hex().to_string())
128        })
129        .collect::<Option<Vec<_>>>()?;
130    digests.sort();
131    Some(digests)
132}
133
134#[cfg(test)]
135mod tests {
136    use super::ComposeSectionCache;
137
138    #[test]
139    fn section_cache_hits_only_while_all_sources_match() {
140        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
141        let dir = tempfile::tempdir().unwrap();
142        let first = dir.path().join("first.rs");
143        let second = dir.path().join("second.rs");
144        std::fs::write(&first, "one").unwrap();
145        std::fs::write(&second, "two").unwrap();
146        let root = dir.path().to_string_lossy();
147        let text = "File: first.rs\nbody one\nFile: second.rs\nbody two".to_string();
148        let cache = ComposeSectionCache::default();
149        let revision = super::source_revision(&root).unwrap();
150        assert!(cache.record("task", &root, text.clone(), &revision));
151        assert_eq!(cache.check("task", &root), Some(text));
152        std::fs::write(&second, "changed").unwrap();
153        assert_eq!(cache.check("task", &root), None);
154    }
155
156    #[test]
157    fn section_cache_rejects_corpus_changes_without_file_headers() {
158        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
159        let dir = tempfile::tempdir().unwrap();
160        let source = dir.path().join("source.rs");
161        std::fs::write(&source, "fn before() {}\n").unwrap();
162        let root = dir.path().to_string_lossy();
163        let cache = ComposeSectionCache::default();
164        let revision = super::source_revision(&root).unwrap();
165        assert!(cache.record("task", &root, "old derived result".to_string(), &revision));
166        assert_eq!(
167            cache.check("task", &root).as_deref(),
168            Some("old derived result")
169        );
170        std::fs::write(&source, "fn after_policy_removal() {}\n").unwrap();
171        assert_eq!(cache.check("task", &root), None);
172        assert!(!cache.record("task", &root, "old derived result".to_string(), &revision));
173    }
174
175    #[test]
176    fn section_cache_rejects_a_changed_role_even_with_same_secret_visibility() {
177        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
178        let root = tempfile::tempdir().unwrap();
179        std::fs::write(root.path().join("source.rs"), "fn sample() {}\n").unwrap();
180        let path = root.path().to_str().unwrap();
181        let role = crate::core::roles::load_role("coder").unwrap();
182        crate::core::roles::with_test_active_role(role.clone(), || {
183            let cache = ComposeSectionCache::default();
184            let revision = super::source_revision(path).unwrap();
185            assert!(cache.record("task", path, "derived text".into(), &revision));
186            assert_eq!(cache.check("task", path).as_deref(), Some("derived text"));
187            let mut changed = role;
188            changed.tools.denied.push("ctx_symbol".into());
189            crate::core::roles::set_test_active_role(changed);
190            assert_eq!(cache.check("task", path), None);
191            assert!(!cache.record("task", path, "derived text".into(), &revision));
192        });
193    }
194}