Skip to main content

lean_ctx/tools/
ctx_multi_read.rs

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