Skip to main content

lean_ctx/tools/
ctx_multi_read.rs

1use crate::core::cache::{ReuseOutcome, SessionCache};
2use crate::core::heatmap;
3use crate::core::ocla::cache_types::{CacheKeyBuilder, FileReadKey};
4use crate::core::tokens::count_tokens;
5use crate::tools::CrpMode;
6use crate::tools::ctx_read;
7
8pub fn handle(cache: &mut SessionCache, paths: &[String], mode: &str, crp_mode: CrpMode) -> String {
9    handle_with_task(cache, paths, mode, crp_mode, None)
10}
11
12pub fn handle_with_task(
13    cache: &mut SessionCache,
14    paths: &[String],
15    mode: &str,
16    crp_mode: CrpMode,
17    task: Option<&str>,
18) -> String {
19    handle_with_task_fresh(cache, paths, mode, false, crp_mode, task)
20}
21
22const DEFAULT_MAX_MULTI_READ_BYTES: usize = 512 * 1024;
23
24fn max_multi_read_bytes() -> usize {
25    std::env::var("LCTX_MAX_MULTI_READ_BYTES")
26        .ok()
27        .and_then(|v| v.parse().ok())
28        .unwrap_or(DEFAULT_MAX_MULTI_READ_BYTES)
29}
30
31pub fn handle_with_task_fresh(
32    cache: &mut SessionCache,
33    paths: &[String],
34    mode: &str,
35    fresh: bool,
36    crp_mode: CrpMode,
37    task: Option<&str>,
38) -> String {
39    handle_with_task_fresh_result(cache, paths, mode, fresh, crp_mode, task).text
40}
41
42/// Batch-read result with the aggregate baseline across local and cross-agent hits.
43pub struct MultiReadResult {
44    pub text: String,
45    pub original_tokens: usize,
46}
47
48pub fn handle_with_task_fresh_result(
49    cache: &mut SessionCache,
50    paths: &[String],
51    mode: &str,
52    fresh: bool,
53    crp_mode: CrpMode,
54    task: Option<&str>,
55) -> MultiReadResult {
56    let n = paths.len();
57    if n == 0 {
58        return MultiReadResult {
59            text: "Read 0 files | 0 tokens saved".to_string(),
60            original_tokens: 0,
61        };
62    }
63
64    let max_bytes = max_multi_read_bytes();
65    let mut sections: Vec<String> = Vec::with_capacity(n);
66    let mut total_saved: usize = 0;
67    let mut total_original: usize = 0;
68    let mut accumulated_bytes: usize = 0;
69    let mut files_read = 0usize;
70    let mut truncated = false;
71
72    for path in paths {
73        let effective_mode = if ctx_read::is_instruction_file(path) {
74            "full"
75        } else {
76            mode
77        };
78        let cache_key = file_read_cache_key(path, effective_mode, crp_mode, task);
79        let current_conversation = crate::core::conversation::current_conversation_id_fresh();
80        let cross_agent = (!fresh)
81            .then(|| {
82                crate::core::ocla::cache_delivery::check(
83                    &cache_key.cache_key(),
84                    &cache_key.validator(),
85                    "ctx_multi_read",
86                )
87            })
88            .flatten()
89            .filter(|entry| {
90                crate::core::ocla::cache_delivery::entry_allows_stub(
91                    entry,
92                    current_conversation.as_deref(),
93                )
94            });
95        let (chunk, cross_agent_original, reuse_outcome) = if let Some(entry) = cross_agent {
96            (
97                crate::core::ocla::cache_delivery::stub(&entry, "file read"),
98                Some(entry.token_count as usize),
99                ReuseOutcome::CrossFileRef,
100            )
101        } else {
102            let read = if fresh {
103                ctx_read::handle_fresh_with_task_result(cache, path, effective_mode, crp_mode, task)
104            } else {
105                ctx_read::handle_with_task_result(cache, path, effective_mode, crp_mode, task)
106            };
107            let reuse_outcome = if fresh {
108                ReuseOutcome::FreshBypass
109            } else if read.is_cache_hit {
110                if matches!(read.resolved_mode.as_str(), "full" | "full-compact") {
111                    ReuseOutcome::UnchangedStub
112                } else {
113                    ReuseOutcome::RenderCacheHit
114                }
115            } else {
116                ReuseOutcome::Cold
117            };
118            let chunk = read.content;
119            if !chunk.contains("[cross-agent") {
120                crate::core::ocla::cache_delivery::record(
121                    cache_key.cache_key(),
122                    crate::core::ocla::cache_types::DeliveryKind::FileRead,
123                    cache_key.validator(),
124                    Some(cache_key.path.clone()),
125                    &chunk,
126                    "ctx_multi_read",
127                );
128            }
129            (chunk, None, reuse_outcome)
130        };
131        crate::core::cache::record_ctx_read_outcome(reuse_outcome);
132        let original = cross_agent_original
133            .or_else(|| cache.get(path).map(|entry| entry.original_tokens))
134            .unwrap_or(0);
135        let sent = count_tokens(&chunk);
136        heatmap::record_file_access(path, original, original.saturating_sub(sent));
137        // Verified ledger (#685): model-correct counts. The default O200kBase model
138        // reuses the o200k counts above (same BPE + cache key → zero extra work); a
139        // resolved Claude/Gemini/Llama model re-tokenizes the raw source (from the
140        // cache) and the sent chunk so savings match the provider's billing units.
141        {
142            use crate::core::savings_ledger as ledger;
143            let (lbase, lsaved) =
144                if ledger::ledger_family() == crate::core::tokens::TokenizerFamily::O200kBase {
145                    (original, original.saturating_sub(sent))
146                } else if let Some(raw) = cache
147                    .get(path)
148                    .and_then(crate::core::cache::CacheEntry::content)
149                {
150                    let lo = ledger::count_for_ledger(&raw);
151                    (lo, lo.saturating_sub(ledger::count_for_ledger(&chunk)))
152                } else {
153                    (original, original.saturating_sub(sent))
154                };
155            ledger::record_read_event(lbase, lsaved, None, None);
156        }
157        total_original = total_original.saturating_add(original);
158        total_saved = total_saved.saturating_add(original.saturating_sub(sent));
159
160        let chunk_bytes = chunk.len();
161        if accumulated_bytes > 0 && accumulated_bytes + chunk_bytes > max_bytes {
162            truncated = true;
163            break;
164        }
165        accumulated_bytes += chunk_bytes;
166        sections.push(chunk);
167        files_read += 1;
168    }
169
170    let body = sections.join("\n---\n");
171    let summary = if truncated {
172        let skipped = n - files_read;
173        format!(
174            "Read {files_read}/{n} files | {total_saved} tokens saved\n\
175             ⚠ Output capped at {max_bytes} bytes (LCTX_MAX_MULTI_READ_BYTES). \
176             {skipped} file(s) skipped. Use individual ctx_read calls for remaining files."
177        )
178    } else if total_saved > 0 {
179        format!("Read {n} files | {total_saved} tokens saved")
180    } else {
181        format!("Read {n} files")
182    };
183    MultiReadResult {
184        text: format!("{body}\n---\n{summary}"),
185        original_tokens: total_original,
186    }
187}
188
189fn file_read_cache_key(
190    path: &str,
191    mode: &str,
192    crp_mode: CrpMode,
193    task: Option<&str>,
194) -> FileReadKey {
195    let canonical = crate::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(path));
196    let mtime_ns = std::fs::metadata(&canonical)
197        .ok()
198        .and_then(|metadata| metadata.modified().ok())
199        .and_then(|mtime| mtime.duration_since(std::time::UNIX_EPOCH).ok())
200        .map_or(0, |duration| duration.as_nanos());
201    FileReadKey {
202        path: canonical.to_string_lossy().into_owned(),
203        mtime_ns,
204        mode: mode.into(),
205        crp_mode: format!("{crp_mode:?}").to_ascii_lowercase(),
206        task_digest: blake3::hash(task.unwrap_or_default().as_bytes())
207            .to_hex()
208            .to_string(),
209        policy_rev: env!("CARGO_PKG_VERSION").into(),
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn multi_read_deduplicates_each_file_with_cross_agent_references() {
219        let directory = tempfile::tempdir().unwrap();
220        let first = directory.path().join("first.rs");
221        let second = directory.path().join("second.rs");
222        std::fs::write(&first, "fn first_probe() {}\n").unwrap();
223        std::fs::write(&second, "fn second_probe() {}\n").unwrap();
224        let paths = vec![
225            first.to_string_lossy().into_owned(),
226            second.to_string_lossy().into_owned(),
227        ];
228
229        let mut local = SessionCache::new();
230        let initial =
231            handle_with_task_fresh_result(&mut local, &paths, "full", false, CrpMode::Off, None);
232        assert!(initial.text.contains("first_probe"));
233
234        let mut another_agent = SessionCache::new();
235        let repeated = handle_with_task_fresh_result(
236            &mut another_agent,
237            &paths,
238            "full",
239            false,
240            CrpMode::Off,
241            None,
242        );
243        assert_eq!(repeated.text.matches("[cross-agent cache").count(), 2);
244        assert!(repeated.original_tokens > 0);
245    }
246}