Skip to main content

lean_ctx/tools/ctx_read/
dispatch.rs

1use super::{
2    CrpMode, ReadMode, ReadOutput, ReadTuning, SessionCache, count_tokens, dedup_hook,
3    handle_with_options_inner, kernel, protocol,
4};
5const MAX_RELAY_CONTENT_BYTES: usize = 8192;
6
7/// Cursor writes terminal output to `.cursor/projects/*/terminals/*.txt` and
8/// polls these files every ~3s. Without special handling, each poll triggers a
9/// full re-read because the conversation gate blocks stubs under concurrency
10/// (#1040). Terminal files are system infrastructure — not conversation-scoped
11/// — so they safely bypass the gate while the content-hash check still
12/// guarantees correctness.
13fn is_terminal_poll_file(path: &str) -> bool {
14    (path.contains("/.cursor/") || path.contains("\\.cursor\\"))
15        && (path.contains("/terminals/") || path.contains("\\terminals\\"))
16        && std::path::Path::new(path)
17            .extension()
18            .is_some_and(|ext| ext.eq_ignore_ascii_case("txt"))
19}
20
21/// Modes whose compressed output is useful for cross-agent relay.
22const RELAY_ELIGIBLE_MODES: &[&str] = &["map", "map:v2", "signatures", "signatures:v2"];
23
24/// Extract relay-eligible content from a read result.
25fn relay_eligible_content(result: &ReadOutput) -> (Option<&str>, Option<&str>) {
26    let mode = result.resolved_mode.as_str();
27    if RELAY_ELIGIBLE_MODES.iter().any(|m| mode.starts_with(m))
28        && result.content.len() <= MAX_RELAY_CONTENT_BYTES
29    {
30        (Some(&result.content), Some(mode))
31    } else {
32        (None, None)
33    }
34}
35/// Reads a file through the cache and applies the requested compression mode.
36pub fn handle(cache: &mut SessionCache, path: &str, mode: &str, crp_mode: CrpMode) -> String {
37    handle_with_options(cache, path, mode, false, crp_mode, None)
38}
39
40/// Like `handle`, but invalidates the cache first to force a fresh disk read.
41pub fn handle_fresh(cache: &mut SessionCache, path: &str, mode: &str, crp_mode: CrpMode) -> String {
42    handle_with_options(cache, path, mode, true, crp_mode, None)
43}
44
45/// Reads a file with task-aware filtering to prioritize task-relevant content.
46pub fn handle_with_task(
47    cache: &mut SessionCache,
48    path: &str,
49    mode: &str,
50    crp_mode: CrpMode,
51    task: Option<&str>,
52) -> String {
53    handle_with_task_result(cache, path, mode, crp_mode, task).content
54}
55
56/// Task-aware read with the structural cache-hit result retained for callers
57/// that need to account for each file in a batch independently.
58pub fn handle_with_task_result(
59    cache: &mut SessionCache,
60    path: &str,
61    mode: &str,
62    crp_mode: CrpMode,
63    task: Option<&str>,
64) -> ReadOutput {
65    let mut result = handle_with_options_resolved(
66        cache,
67        path,
68        mode,
69        false,
70        crp_mode,
71        task,
72        ReadTuning::resolve(None, &[]),
73    );
74    kernel::enrich_with_kernel(&mut result.content, task);
75    result.output_tokens = count_tokens(&result.content);
76    result
77}
78
79/// Like `handle_with_task`, also returns the resolved mode name and pre-counted tokens.
80pub fn handle_with_task_resolved(
81    cache: &mut SessionCache,
82    path: &str,
83    mode: &str,
84    crp_mode: CrpMode,
85    task: Option<&str>,
86) -> ReadOutput {
87    handle_with_options_resolved(
88        cache,
89        path,
90        mode,
91        false,
92        crp_mode,
93        task,
94        ReadTuning::resolve(None, &[]),
95    )
96}
97
98/// Like [`handle_with_task_resolved`] but with an explicit per-call
99/// aggressiveness (the `ctx_read` `aggressiveness` arg, #714). `None` falls back
100/// to the `LEAN_CTX_AGGRESSIVENESS` env var / config field.
101pub fn handle_with_task_resolved_tuned(
102    cache: &mut SessionCache,
103    path: &str,
104    mode: &str,
105    crp_mode: CrpMode,
106    task: Option<&str>,
107    aggressiveness: Option<f64>,
108    protect: &[String],
109) -> ReadOutput {
110    handle_with_options_resolved(
111        cache,
112        path,
113        mode,
114        false,
115        crp_mode,
116        task,
117        ReadTuning::resolve(aggressiveness, protect),
118    )
119}
120
121/// Like [`handle_with_task_resolved_tuned`] but accepts pre-read file content,
122/// avoiding disk I/O under the cache write-lock (Two-Phase Read pattern, #1098).
123#[allow(clippy::too_many_arguments)]
124pub fn handle_with_preread(
125    cache: &mut SessionCache,
126    path: &str,
127    mode: &str,
128    fresh: bool,
129    crp_mode: CrpMode,
130    task: Option<&str>,
131    aggressiveness: Option<f64>,
132    protect: &[String],
133    preread: String,
134) -> ReadOutput {
135    handle_with_options_resolved_preread(
136        cache,
137        path,
138        mode,
139        fresh,
140        crp_mode,
141        task,
142        ReadTuning::resolve(aggressiveness, protect),
143        Some(preread),
144    )
145}
146
147/// Fresh read with task-aware filtering (invalidates cache first).
148pub fn handle_fresh_with_task(
149    cache: &mut SessionCache,
150    path: &str,
151    mode: &str,
152    crp_mode: CrpMode,
153    task: Option<&str>,
154) -> String {
155    handle_fresh_with_task_result(cache, path, mode, crp_mode, task).content
156}
157
158/// Fresh task-aware read with the structural cache-hit result retained.
159pub fn handle_fresh_with_task_result(
160    cache: &mut SessionCache,
161    path: &str,
162    mode: &str,
163    crp_mode: CrpMode,
164    task: Option<&str>,
165) -> ReadOutput {
166    handle_with_options_resolved(
167        cache,
168        path,
169        mode,
170        true,
171        crp_mode,
172        task,
173        ReadTuning::resolve(None, &[]),
174    )
175}
176
177/// Fresh read with task-aware filtering, also returns the resolved mode name and pre-counted tokens.
178pub fn handle_fresh_with_task_resolved(
179    cache: &mut SessionCache,
180    path: &str,
181    mode: &str,
182    crp_mode: CrpMode,
183    task: Option<&str>,
184) -> ReadOutput {
185    handle_with_options_resolved(
186        cache,
187        path,
188        mode,
189        true,
190        crp_mode,
191        task,
192        ReadTuning::resolve(None, &[]),
193    )
194}
195
196/// Fresh-read variant of [`handle_with_task_resolved_tuned`] (#714).
197pub fn handle_fresh_with_task_resolved_tuned(
198    cache: &mut SessionCache,
199    path: &str,
200    mode: &str,
201    crp_mode: CrpMode,
202    task: Option<&str>,
203    aggressiveness: Option<f64>,
204    protect: &[String],
205) -> ReadOutput {
206    handle_with_options_resolved(
207        cache,
208        path,
209        mode,
210        true,
211        crp_mode,
212        task,
213        ReadTuning::resolve(aggressiveness, protect),
214    )
215}
216
217fn handle_with_options(
218    cache: &mut SessionCache,
219    path: &str,
220    mode: &str,
221    fresh: bool,
222    crp_mode: CrpMode,
223    task: Option<&str>,
224) -> String {
225    handle_with_options_resolved(
226        cache,
227        path,
228        mode,
229        fresh,
230        crp_mode,
231        task,
232        ReadTuning::resolve(None, &[]),
233    )
234    .content
235}
236
237/// `LEAN_CTX_FORCE_FRESH=1` — an explicit operator override that always forces a
238/// cold full read, independent of conversation scoping.
239pub(crate) fn force_fresh_env() -> bool {
240    static FORCE_FRESH: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
241    *FORCE_FRESH.get_or_init(|| {
242        std::env::var("LEAN_CTX_FORCE_FRESH").is_ok_and(|v| v == "1" || v == "true")
243    })
244}
245
246/// Detects a subagent (forked agent) execution context.
247///
248/// A subagent must never be served a stub for content only the parent received.
249/// That used to be enforced by force-freshing *every* subagent read; with
250/// conversation scoping (#954/#955) the subagent instead runs under its own scope
251/// (`conversation::current_conversation_id` → `task:{id}` or `proc:{id}`), so
252/// the stub gate withholds cross-agent stubs precisely while restoring the
253/// subagent's *own* cheap re-reads. The blanket force-fresh is therefore kept
254/// only as the fallback when scoping is disabled (#956).
255///
256/// Checks `CURSOR_TASK_ID` (Cursor) and `CLAUDE_CODE_ENTRYPOINT=local-agent`
257/// (future Claude Code subagent marker). Current Claude Code is handled by
258/// per-process scoping in [`crate::core::conversation`] (#1292).
259pub(crate) fn is_subagent_context() -> bool {
260    static IS_SUBAGENT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
261    *IS_SUBAGENT.get_or_init(|| {
262        std::env::var("CURSOR_TASK_ID").is_ok_and(|v| !v.is_empty())
263            || std::env::var("CLAUDE_CODE_ENTRYPOINT")
264                .ok()
265                .as_deref()
266                .map(str::trim)
267                == Some("local-agent")
268    })
269}
270
271/// Keeps subagent cache isolation while independently deciding whether a
272/// cross-agent delivery lookup may return a stub.
273#[allow(clippy::fn_params_excessive_bools)]
274pub(crate) fn effective_fresh_flags(
275    fresh: bool,
276    force_fresh: bool,
277    subagent_context: bool,
278    delivery_for_subagents: bool,
279) -> (bool, bool) {
280    let effective_fresh_for_cache = fresh || force_fresh || subagent_context;
281    let effective_fresh_for_delivery =
282        fresh || force_fresh || (subagent_context && !delivery_for_subagents);
283    (effective_fresh_for_cache, effective_fresh_for_delivery)
284}
285
286pub(crate) fn effective_fresh_for_delivery(fresh: bool) -> bool {
287    let config = crate::core::config::Config::load();
288    effective_fresh_flags(
289        fresh,
290        force_fresh_env(),
291        is_subagent_context(),
292        config.ocla.delivery.delivery_for_subagents,
293    )
294    .1
295}
296
297fn handle_with_options_resolved(
298    cache: &mut SessionCache,
299    path: &str,
300    mode: &str,
301    fresh: bool,
302    crp_mode: CrpMode,
303    task: Option<&str>,
304    tuning: ReadTuning<'_>,
305) -> ReadOutput {
306    handle_with_options_resolved_preread(cache, path, mode, fresh, crp_mode, task, tuning, None)
307}
308
309fn handle_with_options_resolved_preread(
310    cache: &mut SessionCache,
311    path: &str,
312    mode: &str,
313    fresh: bool,
314    crp_mode: CrpMode,
315    task: Option<&str>,
316    tuning: ReadTuning<'_>,
317    preread: Option<String>,
318) -> ReadOutput {
319    // Subagents retain isolated session caches, but can use delivery stubs when
320    // configured because those stubs explicitly identify another agent's read.
321    let config = crate::core::config::Config::load();
322    let (effective_fresh_for_cache, effective_fresh_for_delivery) = effective_fresh_flags(
323        fresh,
324        force_fresh_env(),
325        is_subagent_context(),
326        config.ocla.delivery.delivery_for_subagents,
327    );
328
329    let compress_protected = mode != "raw"
330        && !mode.starts_with("lines:")
331        && crate::core::config::Config::load()
332            .proxy
333            .is_path_compress_protected(path);
334
335    // Hash once for cross-agent delivery. The same snapshot is used for both
336    // the pre-read lookup and the post-read record, avoiding a second disk read.
337    let delivery_metadata = config
338        .ocla
339        .delivery_enabled()
340        .then(|| file_blake3_prefix(path))
341        .flatten();
342
343    if !effective_fresh_for_delivery
344        && !compress_protected
345        && let Some((hash, mtime)) = delivery_metadata
346        && let Some(stub) = try_cross_agent_stub(path, mode, hash, mtime)
347    {
348        return stub;
349    }
350
351    if mode == "auto" {
352        let touched: Vec<String> = cache
353            .get_all_entries()
354            .iter()
355            .map(|(p, _)| (*p).clone())
356            .collect();
357        if crate::core::relevance_gate::should_gate(path, mode, task, &touched) {
358            let meta = std::fs::metadata(path);
359            let byte_count = meta.as_ref().map_or(0, std::fs::Metadata::len);
360            let line_count = preread
361                .as_ref()
362                .map_or(0, |c| bytecount::count(c.as_bytes(), b'\n'));
363            let stub = crate::core::relevance_gate::irrelevant_stub(path, line_count, byte_count);
364            let stub_tokens = count_tokens(&stub);
365            return ReadOutput {
366                content: stub,
367                resolved_mode: "auto".into(),
368                output_tokens: stub_tokens,
369                is_cache_hit: false,
370            };
371        }
372    }
373
374    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
375        bt.next_seq();
376    }
377    let mut result = handle_with_options_inner(
378        cache,
379        path,
380        mode,
381        effective_fresh_for_cache,
382        crp_mode,
383        task,
384        tuning,
385        preread,
386    );
387
388    if let Some(entry) = cache.get_mut(path) {
389        entry.last_mode.clone_from(&result.resolved_mode);
390        if matches!(result.resolved_mode.as_str(), "full" | "full-compact")
391            && entry.full_content_delivered
392            && result.is_cache_hit
393            && entry.bump_reread() >= crate::core::cache::full_degradation_threshold()
394        {
395            entry.full_content_delivered = false;
396            entry.reset_reread_count();
397            crate::core::auto_mode_resolver::count_source("full_delivery_degraded");
398        }
399        // #841: a partial/filtered read means the model's most recent view is NOT
400        // the full content. Clear the delivery flag so a subsequent mode="full"
401        // re-delivers real content instead of the [unchanged] stub. Without this,
402        // a task→full sequence returns an empty stub because the flag was set by an
403        // earlier full delivery and never cleared by the intervening non-full read.
404        if !matches!(result.resolved_mode.as_str(), "full" | "full-compact") {
405            entry.full_content_delivered = false;
406            entry.reset_reread_count();
407        }
408    }
409
410    if !result.is_cache_hit
411        && let Some((hash, mtime)) = delivery_metadata
412    {
413        let line_count = cache.get(path).map_or(0, |entry| entry.line_count as u32);
414        let relay = relay_eligible_content(&result);
415        record_cross_agent_delivery(
416            path,
417            hash,
418            mtime,
419            line_count,
420            result.output_tokens,
421            relay.0,
422            relay.1,
423        );
424    }
425
426    // SSOT via [`ReadMode`] (#528): lossy summaries may elide shared blocks.
427    let dedup_allowed = result
428        .resolved_mode
429        .parse::<ReadMode>()
430        .is_ok_and(|m| m.is_lossy_summary());
431    if dedup_allowed && let Some(deduped) = cache.apply_dedup(path, &result.content) {
432        let new_tokens = count_tokens(&deduped);
433        if new_tokens < result.output_tokens {
434            result.content = deduped;
435            result.output_tokens = new_tokens;
436        }
437    }
438
439    // R28: Kernel content dedup — detect re-reads of unchanged content.
440    if let Some(stub) = dedup_hook::maybe_dedup(path, &result.content, mode, fresh) {
441        let stub_tokens = count_tokens(&stub);
442        if stub_tokens < result.output_tokens {
443            result.content = stub;
444            result.output_tokens = stub_tokens;
445            result.is_cache_hit = true;
446            crate::core::anti_interrupt::spawn_redundant_read(path);
447        }
448    }
449
450    // R30: Feed bounce-tracker signal into adaptive compression bridge.
451    crate::core::context_kernel::adaptive_hook::update_from_bounce_tracker();
452    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
453        let original_tokens = cache.get(path).map_or(0, |e| e.original_tokens);
454        let bounces_before = bt.total_bounces();
455        let output_tokens = result.output_tokens;
456        bt.record_read(path, &result.resolved_mode, output_tokens, original_tokens);
457
458        if bt.total_bounces() > bounces_before {
459            crate::core::anti_interrupt::spawn_bounce_waste(output_tokens as u64);
460        }
461
462        // Quality signals (#538): compressed reads count as clean until a
463        // bounce proves otherwise (the bounce signal outweighs 6:1); large
464        // full reads of never-bouncing extensions are wasted compression
465        // opportunities and push the learned threshold up.
466        // SSOT via [`ReadMode`] (#528): only verbatim `full` and the `diff`
467        // delta are uncompressed. A resolved window is always the canonical
468        // `lines:N-M` (parses to `Lines` ⇒ compressed); the default of `true`
469        // for the unreachable bare `"lines"` keeps prior behaviour everywhere a
470        // real resolved mode can occur.
471        let compressed = result
472            .resolved_mode
473            .parse::<ReadMode>()
474            .map_or(true, |m| m.counts_as_compressed());
475        if compressed {
476            crate::core::adaptive_thresholds::record_quality_signal(
477                path,
478                crate::core::threshold_learning::QualitySignal::CleanCompressed,
479            );
480        } else if result.resolved_mode == "full"
481            && result.output_tokens > 2000
482            && bt.bounce_rate_for_extension(path).unwrap_or(0.0) < 0.05
483        {
484            crate::core::adaptive_thresholds::record_quality_signal(
485                path,
486                crate::core::threshold_learning::QualitySignal::WastedFull,
487            );
488        }
489    }
490
491    // Stigmergy (#540): deposit a Hot scent for this read in the background
492    // (the field file lock may briefly block; never stall the read path). The
493    // foreign-claim hint is intentionally NOT appended to the body: it carries a
494    // relative timestamp ("claimed Nm ago"), which would make the output a
495    // non-pure function of wall-clock time and defeat provider prompt caching
496    // (#498). The deposit remains so the field still reflects active work.
497    {
498        let self_agent = crate::core::scent_field::scent_agent_id();
499        let scent_path = crate::core::pathutil::normalize_tool_path(path);
500        std::thread::spawn(move || {
501            crate::core::scent_field::deposit(
502                self_agent,
503                crate::core::scent_field::ScentKind::Hot,
504                &scent_path,
505                0.3,
506            );
507        });
508    }
509
510    crate::core::context_gc::maybe_gc(cache);
511
512    result
513}
514
515/// Attempt to serve a `mode="full"` cache hit (`[unchanged …]`) using only a
516/// shared borrow of the cache.
517///
518/// Returns `None` when the file is not cached, was modified on disk, full
519/// content was never delivered, or the cache policy forbids stubbing — in those
520/// cases the caller must fall back to the write path.
521///
522/// This is the read-locked fast path: it needs no `&mut SessionCache`, so the
523/// dominant "re-read an unchanged file" case proceeds under a shared lock and
524/// parallel reads of distinct files no longer serialize on a global write lock.
525pub fn try_stub_hit_readonly(cache: &SessionCache, path: &str) -> Option<ReadOutput> {
526    // Resolve the caller *fresh* (TTL-bypassed): the stub gate's concurrency
527    // detection must see a just-appeared second chat with zero lag, else a stub
528    // could leak across chats in the pre-detection window (#1042).
529    let current_conversation = crate::core::conversation::current_conversation_id_fresh();
530    try_stub_hit_readonly_scoped(cache, path, current_conversation.as_deref())
531}
532
533/// Conversation-scoped core of [`try_stub_hit_readonly`]. The current
534/// conversation id is injected (not read from the global resolver) so the
535/// conversation gate can be tested deterministically without global state.
536pub(crate) fn try_stub_hit_readonly_scoped(
537    cache: &SessionCache,
538    path: &str,
539    current_conversation: Option<&str>,
540) -> Option<ReadOutput> {
541    if !stub_policy_allows() {
542        return None;
543    }
544
545    // Warm path: a live in-memory entry is the freshest source of truth.
546    if let Some(file_ref) = cache.get_file_ref_readonly(path) {
547        let (cached_mtime, cached_hash, line_count, delivered_conv) = {
548            let entry = cache.get(path)?;
549            (
550                entry.stored_mtime,
551                entry.hash.clone(),
552                entry.line_count,
553                entry.delivered_conversation.clone(),
554            )
555        };
556        if crate::core::cache::is_cache_entry_stale_verified(path, cached_mtime, &cached_hash)
557            || !cache.is_full_delivered(path)
558        {
559            return None;
560        }
561        // Terminal poll files bypass the conversation gate: they are system
562        // infrastructure, not conversation-scoped content. The content-hash
563        // verification above already guarantees the file is unchanged.
564        let is_terminal_poll = is_terminal_poll_file(path);
565
566        if !is_terminal_poll
567            && !crate::core::conversation::conversation_allows_stub(
568                current_conversation,
569                delivered_conv.as_deref(),
570            )
571        {
572            crate::core::cache_telemetry::record_conversation_mismatch();
573            return None;
574        }
575        let original_tokens = cache.record_cache_hit(path)?.original_tokens;
576        crate::core::telemetry::global_metrics().record_cache(true);
577        let stub = render_unchanged_stub(&file_ref, path, line_count);
578        crate::core::stats::record_reread(original_tokens.saturating_sub(stub.output_tokens));
579        return Some(stub);
580    }
581
582    // Cold fallback (#955): no live entry (e.g. after a daemon restart or idle
583    // clear). Serve the stub from the persisted index iff the file is unchanged
584    // AND the *same known* conversation is asking — a stricter gate than the warm
585    // path, because a cold stub crosses a process boundary (no "no context →
586    // legacy" escape; see `conversation_allows_cold_stub`).
587    let rec = crate::core::read_stub_index::lookup(path)?;
588    if crate::core::cache::is_cache_entry_stale_verified(path, rec.stored_mtime(), &rec.hash) {
589        return None;
590    }
591    if !is_terminal_poll_file(path)
592        && !crate::core::conversation::conversation_allows_cold_stub(
593            current_conversation,
594            rec.delivered_conversation.as_deref(),
595        )
596    {
597        crate::core::cache_telemetry::record_conversation_mismatch();
598        return None;
599    }
600    Some(render_unchanged_stub(&rec.file_ref, path, rec.line_count))
601}
602
603/// Whether the cache policy and active profile allow serving `[unchanged …]`
604/// stubs at all. Shared by the full-content stub path and the #1287 variant
605/// stub path so the two can never diverge.
606pub(crate) fn stub_policy_allows() -> bool {
607    let no_deg = crate::core::config::Config::load().no_degrade_effective();
608    let prof = crate::core::profiles::active_profile();
609    let force_full = no_deg
610        || (prof.read.default_mode_effective() == "full"
611            && prof.compression.crp_mode_effective() == "off");
612    crate::server::compaction_sync::effective_cache_policy() != "safe" && !force_full
613}
614
615/// Renders the `[unchanged …]` stub body shared by the warm and cold stub paths.
616///
617/// #498 determinism: the stub is a pure function of (file_ref, path, line_count),
618/// so identical re-reads stay byte-stable and provider prompt caching applies.
619/// The `fresh=true` escape is a *static* suffix (no rotating proof lines or
620/// read-count notes), so a re-reader in non-meta mode still sees how to force the
621/// content (#513) without breaking byte-stability.
622fn render_unchanged_stub(file_ref: &str, path: &str, line_count: usize) -> ReadOutput {
623    let short = protocol::shorten_path(path);
624    let out = if crate::core::protocol::meta_visible() {
625        format!(
626            "{file_ref}={short} [unchanged {line_count}L]\nUnchanged on disk. Use fresh=true to force re-read.",
627        )
628    } else {
629        format!("{file_ref}={short} [unchanged {line_count}L · fresh=true to re-read]")
630    };
631    let out = crate::core::redaction::redact_text_if_enabled(&out);
632    let sent = count_tokens(&out);
633    ReadOutput {
634        content: out,
635        resolved_mode: "full".into(),
636        output_tokens: sent,
637        is_cache_hit: true,
638    }
639}
640
641/// #1287: renders the `[unchanged <mode> view]` stub for a compressed-variant
642/// re-read — same conversation, unchanged file, same mode key. Mirrors
643/// [`render_unchanged_stub`]'s #498 determinism contract: a pure function of
644/// (file_ref, path, mode), so identical re-reads stay byte-stable and the
645/// static `fresh=true` escape survives non-meta mode.
646pub(crate) fn render_unchanged_variant_stub(file_ref: &str, path: &str, mode: &str) -> ReadOutput {
647    let short = protocol::shorten_path(path);
648    let out = if crate::core::protocol::meta_visible() {
649        format!(
650            "{file_ref}={short} [unchanged {mode} view]\nSame {mode} output you already received. Use fresh=true to re-emit.",
651        )
652    } else {
653        format!("{file_ref}={short} [unchanged {mode} view · fresh=true to re-emit]")
654    };
655    let out = crate::core::redaction::redact_text_if_enabled(&out);
656    let sent = count_tokens(&out);
657    ReadOutput {
658        content: out,
659        resolved_mode: mode.to_string(),
660        output_tokens: sent,
661        is_cache_hit: true,
662    }
663}
664
665/// Outcome of [`resolve_explicit_delta_mode`]: the (possibly rewritten) read
666/// mode plus an optional advisory note to surface to the agent.
667#[derive(Debug, Clone, PartialEq, Eq)]
668pub struct DeltaExplicitDecision {
669    /// The mode the read should proceed with (rewritten only when the feature
670    /// fires; otherwise the caller's mode, unchanged).
671    pub mode: String,
672    /// A byte-stable advisory appended to the read body when the mode was
673    /// rewritten to `diff`. `None` when nothing was rewritten or the collapse
674    /// was a silent `lines:`→`full` stub.
675    pub note: Option<String>,
676}
677
678/// Decide whether an **explicit** `full`/`lines:N-M` re-read of a session-cached
679/// file should be served as a delta instead of re-emitting content the model
680/// already holds (the `delta_explicit` opt-in; env `LCTX_DELTA_EXPLICIT`).
681///
682/// Returns the mode the read should proceed with:
683/// - **Changed on disk** (verified mtime+md5 stale) and full content is cached →
684///   `diff`, plus an advisory note. The diff carries exactly the new
685///   information in a fraction of the tokens.
686/// - **Unchanged** and the request is `lines:` of an already-fully-delivered
687///   file → `full`, so the read collapses to the ~15-token `[unchanged]` stub
688///   instead of re-extracting a window the model has seen.
689/// - Otherwise the caller's `mode` is returned untouched.
690///
691/// First reads (nothing cached) and `fresh=true` are never affected — the
692/// caller gates those before calling. Staleness uses the **verified** variant
693/// ([`crate::core::cache::is_cache_entry_stale_verified`]) so a same-second
694/// write on a coarse-granularity filesystem cannot be mistaken for "unchanged"
695/// and yield a misleading empty diff (#498 determinism).
696///
697/// Pure w.r.t. (cache, path, mode, enabled): no wall-clock, counters, or
698/// randomness enter the result, so identical inputs stay byte-stable.
699pub fn resolve_explicit_delta_mode(
700    cache: &SessionCache,
701    path: &str,
702    mode: &str,
703    explicit_mode: bool,
704    fresh: bool,
705    enabled: bool,
706) -> DeltaExplicitDecision {
707    let unchanged = DeltaExplicitDecision {
708        mode: mode.to_string(),
709        note: None,
710    };
711    if fresh
712        || !enabled
713        || !explicit_mode
714        || !(mode == "full" || mode == "full-compact" || mode.starts_with("lines:"))
715    {
716        return unchanged;
717    }
718    let Some(entry) = cache.get(path) else {
719        // First read this session — nothing to diff against.
720        return unchanged;
721    };
722    let stale =
723        crate::core::cache::is_cache_entry_stale_verified(path, entry.stored_mtime, &entry.hash);
724    if stale {
725        // Only divert to a diff when full content is actually cached: the diff
726        // base is that full content (see `handle_diff`), never a compressed
727        // view. Without it, `handle_diff` would have nothing to compare.
728        if entry.content().is_some() {
729            return DeltaExplicitDecision {
730                mode: "diff".to_string(),
731                note: Some(format!(
732                    "[delta-explicit] requested mode={mode} served as a diff: the file \
733                     changed since your last read and the diff is the new information. \
734                     Pass fresh=true if you need the full content re-emitted."
735                )),
736            };
737        }
738        return unchanged;
739    }
740    // Unchanged on disk: a `lines:` window of a file already delivered in full
741    // re-emits text the model holds — collapse to the full-mode stub
742    // (~15 tokens). A plain `full` re-read already hits that stub downstream.
743    if mode.starts_with("lines:") && cache.is_full_delivered(path) {
744        return DeltaExplicitDecision {
745            mode: "full".to_string(),
746            note: None,
747        };
748    }
749    unchanged
750}
751
752pub(crate) fn file_blake3_prefix(path: &str) -> Option<([u8; 12], u64)> {
753    let meta = std::fs::metadata(path).ok()?;
754    let mtime = meta
755        .modified()
756        .ok()?
757        .duration_since(std::time::UNIX_EPOCH)
758        .ok()?
759        .as_secs();
760    let bytes = std::fs::read(path).ok()?;
761    let hash = blake3::hash(&bytes);
762    let full = hash.as_bytes();
763    let mut prefix = [0u8; 12];
764    prefix.copy_from_slice(&full[..12]);
765    Some((prefix, mtime))
766}
767
768pub(crate) fn try_cross_agent_stub(
769    path: &str,
770    mode: &str,
771    hash: [u8; 12],
772    mtime: u64,
773) -> Option<ReadOutput> {
774    if !crate::core::config::Config::load().ocla.delivery_enabled() {
775        return None;
776    }
777    if matches!(mode, "full" | "raw" | "diff") {
778        return None;
779    }
780    let current_agent = std::env::var("CURSOR_TASK_ID")
781        .or_else(|_| std::env::var("CLAUDECODE"))
782        .unwrap_or_else(|_| format!("local-{}", std::process::id()));
783    let current_conversation = crate::core::conversation::current_conversation_id()
784        .unwrap_or_else(|| current_agent.clone());
785    let reg = crate::core::ocla::OclaRegistry::global();
786    let record = crate::daemon_client::try_delivery_check_blocking(
787        &hash,
788        mtime,
789        path,
790        Some(&current_agent),
791        Some(&current_conversation),
792    )
793    .or_else(|| {
794        reg.delivery_registry.check_delivery(
795            &hash,
796            mtime,
797            path,
798            Some(&current_agent),
799            Some(&current_conversation),
800        )
801    })?;
802
803    let short = protocol::shorten_path(path);
804
805    if let Some(ref content) = record.relay_content {
806        let relay_mode = record.relay_mode.as_deref().unwrap_or("map");
807        let header = format!(
808            "{short} [relayed from {} · {relay_mode} · {}L]",
809            record.agent_id, record.line_count,
810        );
811        let body = format!("{header}\n{content}");
812        let tokens = count_tokens(&body);
813        reg.delivery_registry
814            .record_stub_served(&record, tokens as u64);
815        return Some(ReadOutput {
816            content: body,
817            resolved_mode: "cross-agent-relay".into(),
818            output_tokens: tokens,
819            is_cache_hit: true,
820        });
821    }
822
823    let stub = format!(
824        "{short} [cross-agent · {lines}L · read by {agent} · use fresh=true to force]",
825        lines = record.line_count,
826        agent = record.agent_id,
827    );
828    let tokens = count_tokens(&stub);
829    reg.delivery_registry
830        .record_stub_served(&record, tokens as u64);
831    Some(ReadOutput {
832        content: stub,
833        resolved_mode: "cross-agent-stub".into(),
834        output_tokens: tokens,
835        is_cache_hit: true,
836    })
837}
838
839pub(crate) fn record_cross_agent_delivery(
840    path: &str,
841    hash: [u8; 12],
842    mtime: u64,
843    line_count: u32,
844    tokens: usize,
845    relay_content: Option<&str>,
846    relay_mode: Option<&str>,
847) {
848    if !crate::core::config::Config::load().ocla.delivery_enabled() {
849        return;
850    }
851    let agent_id = std::env::var("CURSOR_TASK_ID")
852        .or_else(|_| std::env::var("CLAUDECODE"))
853        .unwrap_or_else(|_| format!("local-{}", std::process::id()));
854    let conversation_id =
855        crate::core::conversation::current_conversation_id().unwrap_or_else(|| agent_id.clone());
856    let entry = crate::core::ocla::types::DeliveryEntry {
857        blake3: hash,
858        path: path.into(),
859        line_count,
860        token_count: tokens as u64,
861        agent_id,
862        conversation_id,
863        mtime,
864        relay_content: relay_content
865            .filter(|c| c.len() <= MAX_RELAY_CONTENT_BYTES)
866            .map(str::to_string),
867        relay_mode: relay_mode.map(str::to_string),
868    };
869    crate::daemon_client::try_delivery_record_blocking(&entry);
870    let reg = crate::core::ocla::OclaRegistry::global();
871    reg.delivery_registry.record_delivery(entry);
872}
873
874#[cfg(test)]
875mod tests {
876    use super::{
877        SessionCache, effective_fresh_flags, is_terminal_poll_file, try_cross_agent_stub,
878        try_stub_hit_readonly_scoped,
879    };
880    use std::sync::atomic::Ordering;
881
882    #[test]
883    fn cross_agent_stub_miss_returns_none() {
884        let stub = try_cross_agent_stub("/nonexistent/file.rs", "auto", [0; 12], 0);
885        assert!(stub.is_none());
886    }
887
888    #[test]
889    fn subagent_delivery_policy_keeps_cache_fresh_but_allows_delivery_by_default() {
890        let delivery_for_subagents =
891            crate::core::config::DeliveryConfig::default().delivery_for_subagents;
892        assert!(
893            delivery_for_subagents,
894            "delivery must default to enabled for subagents"
895        );
896        let (cache_fresh, delivery_fresh) =
897            effective_fresh_flags(false, false, true, delivery_for_subagents);
898        assert!(cache_fresh, "subagent cache must remain isolated");
899        assert!(
900            !delivery_fresh,
901            "default policy must allow a cross-agent delivery lookup"
902        );
903    }
904
905    #[test]
906    fn subagent_delivery_policy_can_force_fresh_delivery() {
907        let (cache_fresh, delivery_fresh) = effective_fresh_flags(false, false, true, false);
908        assert!(cache_fresh);
909        assert!(delivery_fresh, "disabled policy must bypass delivery stubs");
910    }
911
912    #[test]
913    fn cross_agent_fallback_is_deterministic() {
914        // When no CURSOR_TASK_ID or CLAUDECODE env var is set, the fallback
915        // must be deterministic (not PID-based) for provider cache stability.
916        let _lock = crate::core::data_dir::test_env_lock();
917        crate::test_env::remove_var("CURSOR_TASK_ID");
918        crate::test_env::remove_var("CLAUDECODE");
919        let id1 = std::env::var("CURSOR_TASK_ID")
920            .or_else(|_| std::env::var("CLAUDECODE"))
921            .unwrap_or_else(|_| format!("local-{}", std::process::id()));
922        let id2 = std::env::var("CURSOR_TASK_ID")
923            .or_else(|_| std::env::var("CLAUDECODE"))
924            .unwrap_or_else(|_| format!("local-{}", std::process::id()));
925        assert_eq!(id1, id2, "fallback agent ID must be deterministic");
926        assert!(!id1.contains("proc:"), "must not contain PID");
927    }
928
929    #[test]
930    fn warm_stub_hit_records_central_telemetry() {
931        let dir = tempfile::tempdir().unwrap();
932        let file = dir.path().join("telemetry-hit.rs");
933        std::fs::write(&file, "fn telemetry_hit() {}\n").unwrap();
934        let path = file.to_string_lossy();
935        let mut cache = SessionCache::new();
936        cache.store(&path, "fn telemetry_hit() {}\n");
937        cache.mark_full_delivered(&path);
938
939        let metrics = crate::core::telemetry::global_metrics();
940        let before = metrics.cache_hits.load(Ordering::Relaxed);
941        let output = try_stub_hit_readonly_scoped(&cache, &path, None);
942        let after = metrics.cache_hits.load(Ordering::Relaxed);
943
944        assert!(output.is_some(), "warm re-read must use the stub cache");
945        assert!(
946            after > before,
947            "stub cache hit must increment central telemetry"
948        );
949    }
950
951    #[test]
952    fn relay_does_not_poison_session_cache() {
953        let mut cache = SessionCache::new();
954        let path = "/tmp/test_relay_poison.rs";
955        cache.store(path, "original content");
956        assert_eq!(
957            cache
958                .get(path)
959                .map(|e| e.compressed_outputs.contains_key("cross-agent-relay")),
960            Some(false),
961            "cross-agent-relay must not exist in session cache"
962        );
963    }
964    #[test]
965    fn is_terminal_poll_file_matches_cursor_terminal_paths() {
966        assert!(is_terminal_poll_file(
967            "/Users/me/.cursor/projects/Users-me-proj/terminals/12345.txt"
968        ));
969        assert!(is_terminal_poll_file(
970            "/home/dev/.cursor/projects/foo/terminals/857272.txt"
971        ));
972        assert!(!is_terminal_poll_file("/Users/me/project/src/main.rs"));
973        assert!(!is_terminal_poll_file(
974            "/Users/me/.cursor/projects/foo/agent-transcripts/abc.jsonl"
975        ));
976        assert!(!is_terminal_poll_file("/Users/me/.cursor/terminals.log"));
977    }
978
979    #[test]
980    fn terminal_poll_file_stub_bypasses_conversation_gate() {
981        let dir = tempfile::tempdir().unwrap();
982        let terminals_dir = dir.path().join(".cursor").join("proj").join("terminals");
983        std::fs::create_dir_all(&terminals_dir).unwrap();
984        let file = terminals_dir.join("252028.txt");
985        std::fs::write(&file, "---\npid: 1234\n---\nterminal output\n").unwrap();
986        let path = file.to_string_lossy().to_string();
987
988        let mut cache = SessionCache::new();
989        cache.store(&path, "---\npid: 1234\n---\nterminal output\n");
990        cache.mark_full_delivered(&path);
991
992        // Mismatched conversation normally blocks stub — but terminal files bypass
993        let output = try_stub_hit_readonly_scoped(&cache, &path, Some("different-conv"));
994        assert!(
995            output.is_some(),
996            "terminal poll file must bypass conversation gate and serve stub"
997        );
998    }
999
1000    #[test]
1001    fn non_terminal_file_respects_conversation_gate() {
1002        let dir = tempfile::tempdir().unwrap();
1003        let file = dir.path().join("main.rs");
1004        std::fs::write(&file, "fn main() {}\n").unwrap();
1005        let path = file.to_string_lossy().to_string();
1006
1007        let mut cache = SessionCache::new();
1008        cache.store(&path, "fn main() {}\n");
1009        cache.mark_full_delivered(&path);
1010        if let Some(entry) = cache.get_mut(&path) {
1011            entry.delivered_conversation = Some("conv-A".to_string());
1012        }
1013
1014        // Mismatched conversation on regular file must block stub
1015        let output = try_stub_hit_readonly_scoped(&cache, &path, Some("conv-B"));
1016        assert!(
1017            output.is_none(),
1018            "regular file must respect conversation gate"
1019        );
1020    }
1021}