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, 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", "signatures"];
23
24/// Extract relay-eligible content from a rendered read.
25fn relay_eligible<'a>(mode: &'a str, content: &'a str) -> (Option<&'a str>, Option<&'a str>) {
26    if RELAY_ELIGIBLE_MODES.contains(&mode) && content.len() <= MAX_RELAY_CONTENT_BYTES {
27        (Some(content), Some(mode))
28    } else {
29        (None, None)
30    }
31}
32
33fn relay_variant_matches(
34    mode: &str,
35    stored: &str,
36    crp_mode: CrpMode,
37    tuning: ReadTuning<'_>,
38) -> bool {
39    RELAY_ELIGIBLE_MODES.iter().any(|candidate| {
40        (mode == "auto" || mode == *candidate)
41            && stored
42                == super::compressed_cache_key(
43                    candidate,
44                    crp_mode,
45                    None,
46                    tuning.aggressiveness,
47                    tuning.protect,
48                )
49    })
50}
51/// Reads a file through the cache and applies the requested compression mode.
52pub fn handle(cache: &mut SessionCache, path: &str, mode: &str, crp_mode: CrpMode) -> String {
53    handle_with_options(cache, path, mode, false, crp_mode, None)
54}
55
56/// Like `handle`, but invalidates the cache first to force a fresh disk read.
57pub fn handle_fresh(cache: &mut SessionCache, path: &str, mode: &str, crp_mode: CrpMode) -> String {
58    handle_with_options(cache, path, mode, true, crp_mode, None)
59}
60
61/// Reads a file with task-aware filtering to prioritize task-relevant content.
62pub fn handle_with_task(
63    cache: &mut SessionCache,
64    path: &str,
65    mode: &str,
66    crp_mode: CrpMode,
67    task: Option<&str>,
68) -> String {
69    handle_with_task_result(cache, path, mode, crp_mode, task).content
70}
71
72/// Task-aware read with the structural cache-hit result retained for callers
73/// that need to account for each file in a batch independently.
74pub fn handle_with_task_result(
75    cache: &mut SessionCache,
76    path: &str,
77    mode: &str,
78    crp_mode: CrpMode,
79    task: Option<&str>,
80) -> ReadOutput {
81    let mut result = handle_with_options_resolved(
82        cache,
83        path,
84        mode,
85        false,
86        crp_mode,
87        task,
88        ReadTuning::resolve(None, &[]),
89    );
90    // #1993: a file's section carries the file and nothing else. Kernel
91    // context is task-scoped, not file-scoped, so a batch appends it once as
92    // its own trailer (see `kernel_trailer`) instead of inside file 1.
93    result.output_tokens = count_tokens(&result.content);
94    result
95}
96
97/// Like `handle_with_task`, also returns the resolved mode name and pre-counted tokens.
98pub fn handle_with_task_resolved(
99    cache: &mut SessionCache,
100    path: &str,
101    mode: &str,
102    crp_mode: CrpMode,
103    task: Option<&str>,
104) -> ReadOutput {
105    handle_with_options_resolved(
106        cache,
107        path,
108        mode,
109        false,
110        crp_mode,
111        task,
112        ReadTuning::resolve(None, &[]),
113    )
114}
115
116/// Like [`handle_with_task_resolved`] but with an explicit per-call
117/// aggressiveness (the `ctx_read` `aggressiveness` arg, #714). `None` falls back
118/// to the `LEAN_CTX_AGGRESSIVENESS` env var / config field.
119pub fn handle_with_task_resolved_tuned(
120    cache: &mut SessionCache,
121    path: &str,
122    mode: &str,
123    crp_mode: CrpMode,
124    task: Option<&str>,
125    aggressiveness: Option<f64>,
126    protect: &[String],
127) -> ReadOutput {
128    handle_with_options_resolved(
129        cache,
130        path,
131        mode,
132        false,
133        crp_mode,
134        task,
135        ReadTuning::resolve(aggressiveness, protect),
136    )
137}
138
139/// Like [`handle_with_task_resolved_tuned`] but accepts pre-read file content,
140/// avoiding disk I/O under the cache write-lock (Two-Phase Read pattern, #1098).
141#[allow(clippy::too_many_arguments)]
142pub fn handle_with_preread(
143    cache: &mut SessionCache,
144    path: &str,
145    mode: &str,
146    fresh: bool,
147    crp_mode: CrpMode,
148    task: Option<&str>,
149    aggressiveness: Option<f64>,
150    protect: &[String],
151    preread: String,
152) -> ReadOutput {
153    handle_with_options_resolved_preread(
154        cache,
155        path,
156        mode,
157        fresh,
158        crp_mode,
159        task,
160        ReadTuning::resolve(aggressiveness, protect),
161        Some(preread),
162    )
163}
164
165/// Fresh read with task-aware filtering (invalidates cache first).
166pub fn handle_fresh_with_task(
167    cache: &mut SessionCache,
168    path: &str,
169    mode: &str,
170    crp_mode: CrpMode,
171    task: Option<&str>,
172) -> String {
173    handle_fresh_with_task_result(cache, path, mode, crp_mode, task).content
174}
175
176/// Fresh task-aware read with the structural cache-hit result retained.
177pub fn handle_fresh_with_task_result(
178    cache: &mut SessionCache,
179    path: &str,
180    mode: &str,
181    crp_mode: CrpMode,
182    task: Option<&str>,
183) -> ReadOutput {
184    handle_with_options_resolved(
185        cache,
186        path,
187        mode,
188        true,
189        crp_mode,
190        task,
191        ReadTuning::resolve(None, &[]),
192    )
193}
194
195/// Fresh read with task-aware filtering, also returns the resolved mode name and pre-counted tokens.
196pub fn handle_fresh_with_task_resolved(
197    cache: &mut SessionCache,
198    path: &str,
199    mode: &str,
200    crp_mode: CrpMode,
201    task: Option<&str>,
202) -> ReadOutput {
203    handle_with_options_resolved(
204        cache,
205        path,
206        mode,
207        true,
208        crp_mode,
209        task,
210        ReadTuning::resolve(None, &[]),
211    )
212}
213
214/// Fresh-read variant of [`handle_with_task_resolved_tuned`] (#714).
215pub fn handle_fresh_with_task_resolved_tuned(
216    cache: &mut SessionCache,
217    path: &str,
218    mode: &str,
219    crp_mode: CrpMode,
220    task: Option<&str>,
221    aggressiveness: Option<f64>,
222    protect: &[String],
223) -> ReadOutput {
224    handle_with_options_resolved(
225        cache,
226        path,
227        mode,
228        true,
229        crp_mode,
230        task,
231        ReadTuning::resolve(aggressiveness, protect),
232    )
233}
234
235fn handle_with_options(
236    cache: &mut SessionCache,
237    path: &str,
238    mode: &str,
239    fresh: bool,
240    crp_mode: CrpMode,
241    task: Option<&str>,
242) -> String {
243    handle_with_options_resolved(
244        cache,
245        path,
246        mode,
247        fresh,
248        crp_mode,
249        task,
250        ReadTuning::resolve(None, &[]),
251    )
252    .content
253}
254
255/// `LEAN_CTX_FORCE_FRESH=1` — an explicit operator override that always forces a
256/// cold full read, independent of conversation scoping.
257pub(crate) fn force_fresh_env() -> bool {
258    static FORCE_FRESH: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
259    *FORCE_FRESH.get_or_init(|| {
260        std::env::var("LEAN_CTX_FORCE_FRESH").is_ok_and(|v| v == "1" || v == "true")
261    })
262}
263
264/// Detects a subagent (forked agent) execution context.
265///
266/// A subagent must never be served a stub for content only the parent received.
267/// That used to be enforced by force-freshing *every* subagent read; with
268/// conversation scoping (#954/#955) the subagent instead runs under its own scope
269/// (`conversation::current_conversation_id` → `task:{id}` or `proc:{id}`), so
270/// the stub gate withholds cross-agent stubs precisely while restoring the
271/// subagent's *own* cheap re-reads. The blanket force-fresh is therefore kept
272/// only as the fallback when scoping is disabled (#956).
273///
274/// Checks `CURSOR_TASK_ID` (Cursor) and `CLAUDE_CODE_ENTRYPOINT=local-agent`
275/// (future Claude Code subagent marker). Current Claude Code is handled by
276/// per-process scoping in [`crate::core::conversation`] (#1292).
277pub(crate) fn is_subagent_context() -> bool {
278    static IS_SUBAGENT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
279    *IS_SUBAGENT.get_or_init(|| {
280        std::env::var("CURSOR_TASK_ID").is_ok_and(|v| !v.is_empty())
281            || std::env::var("CLAUDE_CODE_ENTRYPOINT")
282                .ok()
283                .as_deref()
284                .map(str::trim)
285                == Some("local-agent")
286    })
287}
288
289/// Keeps subagent cache isolation while independently deciding whether a
290/// cross-agent delivery lookup may return a stub.
291#[allow(clippy::fn_params_excessive_bools)]
292pub(crate) fn effective_fresh_flags(
293    fresh: bool,
294    force_fresh: bool,
295    subagent_context: bool,
296    delivery_for_subagents: bool,
297) -> (bool, bool) {
298    let effective_fresh_for_cache = fresh || force_fresh || subagent_context;
299    let effective_fresh_for_delivery =
300        fresh || force_fresh || (subagent_context && !delivery_for_subagents);
301    (effective_fresh_for_cache, effective_fresh_for_delivery)
302}
303
304pub(crate) fn effective_fresh_for_delivery(fresh: bool) -> bool {
305    let config = crate::core::config::Config::load();
306    effective_fresh_flags(
307        fresh,
308        force_fresh_env(),
309        is_subagent_context(),
310        config.ocla.delivery.delivery_for_subagents,
311    )
312    .1
313}
314
315fn handle_with_options_resolved(
316    cache: &mut SessionCache,
317    path: &str,
318    mode: &str,
319    fresh: bool,
320    crp_mode: CrpMode,
321    task: Option<&str>,
322    tuning: ReadTuning<'_>,
323) -> ReadOutput {
324    handle_with_options_resolved_preread(cache, path, mode, fresh, crp_mode, task, tuning, None)
325}
326
327fn handle_with_options_resolved_preread(
328    cache: &mut SessionCache,
329    path: &str,
330    mode: &str,
331    fresh: bool,
332    crp_mode: CrpMode,
333    task: Option<&str>,
334    tuning: ReadTuning<'_>,
335    preread: Option<String>,
336) -> ReadOutput {
337    // Subagents retain isolated session caches, but can use delivery stubs when
338    // configured because those stubs explicitly identify another agent's read.
339    let config = crate::core::config::Config::load();
340    let (effective_fresh_for_cache, effective_fresh_for_delivery) = effective_fresh_flags(
341        fresh,
342        force_fresh_env(),
343        is_subagent_context(),
344        config.ocla.delivery.delivery_for_subagents,
345    );
346
347    let compress_protected = mode != "raw"
348        && !mode.starts_with("lines:")
349        && crate::core::config::Config::load()
350            .proxy
351            .is_path_compress_protected(path);
352
353    // Hash once for cross-agent delivery. The same snapshot is used for both
354    // the pre-read lookup and the post-read record, avoiding a second disk read.
355    let delivery_metadata = config
356        .ocla
357        .delivery_enabled()
358        .then(|| file_blake3_prefix(path))
359        .flatten();
360
361    if !effective_fresh_for_delivery
362        && !compress_protected
363        && let Some(fp) = delivery_metadata
364        && let Some(stub) = try_cross_agent_stub(path, mode, fp.hash, fp.mtime, crp_mode, tuning)
365    {
366        return stub;
367    }
368
369    if mode == "auto" {
370        let touched: Vec<String> = cache
371            .get_all_entries()
372            .iter()
373            .map(|(p, _)| (*p).clone())
374            .collect();
375        if crate::core::relevance_gate::should_gate(path, mode, task, &touched) {
376            let meta = std::fs::metadata(path);
377            let byte_count = meta.as_ref().map_or(0, std::fs::Metadata::len);
378            let line_count = preread
379                .as_ref()
380                .map_or(0, |c| bytecount::count(c.as_bytes(), b'\n'));
381            let stub = crate::core::relevance_gate::irrelevant_stub(path, line_count, byte_count);
382            let stub_tokens = count_tokens(&stub);
383            return ReadOutput {
384                content: stub,
385                resolved_mode: "auto".into(),
386                output_tokens: stub_tokens,
387                is_cache_hit: false,
388            };
389        }
390    }
391
392    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
393        bt.next_seq();
394    }
395    let mut result = handle_with_options_inner(
396        cache,
397        path,
398        mode,
399        effective_fresh_for_cache,
400        crp_mode,
401        task,
402        tuning,
403        preread,
404    );
405
406    if let Some(entry) = cache.get_mut(path) {
407        entry.last_mode.clone_from(&result.resolved_mode);
408        if matches!(result.resolved_mode.as_str(), "full" | "full-compact")
409            && entry.full_content_delivered
410            && result.is_cache_hit
411            && entry.bump_reread() >= crate::core::cache::full_degradation_threshold()
412        {
413            entry.full_content_delivered = false;
414            entry.reset_reread_count();
415            crate::core::auto_mode_resolver::count_source("full_delivery_degraded");
416        }
417        // #841: a partial/filtered read means the model's most recent view is NOT
418        // the full content. Clear the delivery flag so a subsequent mode="full"
419        // re-delivers real content instead of the [unchanged] stub. Without this,
420        // a task→full sequence returns an empty stub because the flag was set by an
421        // earlier full delivery and never cleared by the intervening non-full read.
422        if !matches!(result.resolved_mode.as_str(), "full" | "full-compact") {
423            entry.full_content_delivered = false;
424            entry.reset_reread_count();
425        }
426    }
427
428    if !result.is_cache_hit
429        && let Some(fp) = delivery_metadata
430    {
431        record_read_delivery(
432            path,
433            fp,
434            &result.resolved_mode,
435            &result.content,
436            result.output_tokens,
437            crp_mode,
438            tuning,
439        );
440    }
441
442    // SSOT via [`ReadMode`] (#528): lossy summaries may elide shared blocks.
443    let dedup_allowed = result
444        .resolved_mode
445        .parse::<ReadMode>()
446        .is_ok_and(|m| m.is_lossy_summary());
447    if dedup_allowed && let Some(deduped) = cache.apply_dedup(path, &result.content) {
448        let new_tokens = count_tokens(&deduped);
449        if new_tokens < result.output_tokens {
450            result.content = deduped;
451            result.output_tokens = new_tokens;
452        }
453    }
454
455    // R28: Kernel content dedup — detect re-reads of unchanged content.
456    if let Some(stub) = dedup_hook::maybe_dedup(path, &result.content, mode, fresh) {
457        let stub_tokens = count_tokens(&stub);
458        if stub_tokens < result.output_tokens {
459            result.content = stub;
460            result.output_tokens = stub_tokens;
461            result.is_cache_hit = true;
462            crate::core::anti_interrupt::spawn_redundant_read(path);
463        }
464    }
465
466    // R30: Feed bounce-tracker signal into adaptive compression bridge.
467    crate::core::context_kernel::adaptive_hook::update_from_bounce_tracker();
468    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
469        let original_tokens = cache.get(path).map_or(0, |e| e.original_tokens);
470        let bounces_before = bt.total_bounces();
471        let output_tokens = result.output_tokens;
472        bt.record_read(path, &result.resolved_mode, output_tokens, original_tokens);
473
474        if bt.total_bounces() > bounces_before {
475            crate::core::anti_interrupt::spawn_bounce_waste(output_tokens as u64);
476        }
477
478        // Quality signals (#538): compressed reads count as clean until a
479        // bounce proves otherwise (the bounce signal outweighs 6:1); large
480        // full reads of never-bouncing extensions are wasted compression
481        // opportunities and push the learned threshold up.
482        // SSOT via [`ReadMode`] (#528): only verbatim `full` and the `diff`
483        // delta are uncompressed. A resolved window is always the canonical
484        // `lines:N-M` (parses to `Lines` ⇒ compressed); the default of `true`
485        // for the unreachable bare `"lines"` keeps prior behaviour everywhere a
486        // real resolved mode can occur.
487        let compressed = result
488            .resolved_mode
489            .parse::<ReadMode>()
490            .map_or(true, |m| m.counts_as_compressed());
491        if compressed {
492            crate::core::adaptive_thresholds::record_quality_signal(
493                path,
494                crate::core::threshold_learning::QualitySignal::CleanCompressed,
495            );
496        } else if result.resolved_mode == "full"
497            && result.output_tokens > 2000
498            && bt.bounce_rate_for_extension(path).unwrap_or(0.0) < 0.05
499        {
500            crate::core::adaptive_thresholds::record_quality_signal(
501                path,
502                crate::core::threshold_learning::QualitySignal::WastedFull,
503            );
504        }
505    }
506
507    // Stigmergy (#540): deposit a Hot scent for this read in the background
508    // (the field file lock may briefly block; never stall the read path). The
509    // foreign-claim hint is intentionally NOT appended to the body: it carries a
510    // relative timestamp ("claimed Nm ago"), which would make the output a
511    // non-pure function of wall-clock time and defeat provider prompt caching
512    // (#498). The deposit remains so the field still reflects active work.
513    {
514        let self_agent = crate::core::scent_field::scent_agent_id();
515        let scent_path = crate::core::pathutil::normalize_tool_path(path);
516        std::thread::spawn(move || {
517            crate::core::scent_field::deposit(
518                self_agent,
519                crate::core::scent_field::ScentKind::Hot,
520                &scent_path,
521                0.3,
522            );
523        });
524    }
525
526    crate::core::context_gc::maybe_gc(cache);
527
528    result
529}
530
531/// Attempt to serve a `mode="full"` cache hit (`[unchanged …]`) using only a
532/// shared borrow of the cache.
533///
534/// Returns `None` when the file is not cached, was modified on disk, full
535/// content was never delivered, or the cache policy forbids stubbing — in those
536/// cases the caller must fall back to the write path.
537///
538/// This is the read-locked fast path: it needs no `&mut SessionCache`, so the
539/// dominant "re-read an unchanged file" case proceeds under a shared lock and
540/// parallel reads of distinct files no longer serialize on a global write lock.
541pub fn try_stub_hit_readonly(cache: &SessionCache, path: &str) -> Option<ReadOutput> {
542    // Resolve the caller *fresh* (TTL-bypassed): the stub gate's concurrency
543    // detection must see a just-appeared second chat with zero lag, else a stub
544    // could leak across chats in the pre-detection window (#1042).
545    let current_conversation = crate::core::conversation::current_conversation_id_fresh();
546    try_stub_hit_readonly_scoped(cache, path, current_conversation.as_deref())
547}
548
549/// Conversation-scoped core of [`try_stub_hit_readonly`]. The current
550/// conversation id is injected (not read from the global resolver) so the
551/// conversation gate can be tested deterministically without global state.
552pub(crate) fn try_stub_hit_readonly_scoped(
553    cache: &SessionCache,
554    path: &str,
555    current_conversation: Option<&str>,
556) -> Option<ReadOutput> {
557    if !stub_policy_allows() {
558        return None;
559    }
560
561    // Warm path: a live in-memory entry is the freshest source of truth.
562    if let Some(file_ref) = cache.get_file_ref_readonly(path) {
563        let (cached_mtime, cached_hash, line_count, delivered_conv) = {
564            let entry = cache.get(path)?;
565            (
566                entry.stored_mtime,
567                entry.hash.clone(),
568                entry.line_count,
569                entry.delivered_conversation.clone(),
570            )
571        };
572        if crate::core::cache::is_cache_entry_stale_verified(path, cached_mtime, &cached_hash)
573            || !cache.is_full_delivered(path)
574        {
575            return None;
576        }
577        // Terminal poll files bypass the conversation gate: they are system
578        // infrastructure, not conversation-scoped content. The content-hash
579        // verification above already guarantees the file is unchanged.
580        let is_terminal_poll = is_terminal_poll_file(path);
581
582        if !is_terminal_poll
583            && !crate::core::conversation::conversation_allows_stub(
584                current_conversation,
585                delivered_conv.as_deref(),
586            )
587        {
588            crate::core::cache_telemetry::record_conversation_mismatch();
589            return None;
590        }
591        let original_tokens = cache.record_cache_hit(path)?.original_tokens;
592        crate::core::telemetry::global_metrics().record_cache(true);
593        let stub = render_unchanged_stub(&file_ref, path, line_count);
594        crate::core::stats::record_reread(original_tokens.saturating_sub(stub.output_tokens));
595        return Some(stub);
596    }
597
598    // Cold fallback (#955): no live entry (e.g. after a daemon restart or idle
599    // clear). Serve the stub from the persisted index iff the file is unchanged
600    // AND the *same known* conversation is asking — a stricter gate than the warm
601    // path, because a cold stub crosses a process boundary (no "no context →
602    // legacy" escape; see `conversation_allows_cold_stub`).
603    let rec = crate::core::read_stub_index::lookup(path)?;
604    if crate::core::cache::is_cache_entry_stale_verified(path, rec.stored_mtime(), &rec.hash) {
605        return None;
606    }
607    if !is_terminal_poll_file(path)
608        && !crate::core::conversation::conversation_allows_cold_stub(
609            current_conversation,
610            rec.delivered_conversation.as_deref(),
611        )
612    {
613        crate::core::cache_telemetry::record_conversation_mismatch();
614        return None;
615    }
616    Some(render_unchanged_stub(&rec.file_ref, path, rec.line_count))
617}
618
619/// Whether the cache policy and active profile allow serving `[unchanged …]`
620/// stubs at all. Shared by the full-content stub path and the #1287 variant
621/// stub path so the two can never diverge.
622pub(crate) fn stub_policy_allows() -> bool {
623    let no_deg = crate::core::config::Config::load().no_degrade_effective();
624    let prof = crate::core::profiles::active_profile();
625    let force_full = no_deg
626        || (prof.read.default_mode_effective() == "full"
627            && prof.compression.crp_mode.as_deref() == Some("off"));
628    crate::server::compaction_sync::effective_cache_policy() != "safe" && !force_full
629}
630
631/// Renders the `[unchanged …]` stub body shared by the warm and cold stub paths.
632///
633/// #498 determinism: the stub is a pure function of (file_ref, path, line_count),
634/// so identical re-reads stay byte-stable and provider prompt caching applies.
635/// The `fresh=true` escape is a *static* suffix (no rotating proof lines or
636/// read-count notes), so a re-reader in non-meta mode still sees how to force the
637/// content (#513) without breaking byte-stability.
638fn render_unchanged_stub(file_ref: &str, path: &str, line_count: usize) -> ReadOutput {
639    let short = protocol::shorten_path(path);
640    let out = if crate::core::protocol::meta_visible() {
641        format!(
642            "{file_ref}={short} [unchanged {line_count}L]\nUnchanged on disk. Use fresh=true to force re-read.",
643        )
644    } else {
645        format!("{file_ref}={short} [unchanged {line_count}L · fresh=true to re-read]")
646    };
647    let out = crate::core::redaction::redact_text_if_enabled(&out);
648    let sent = count_tokens(&out);
649    ReadOutput {
650        content: out,
651        resolved_mode: "full".into(),
652        output_tokens: sent,
653        is_cache_hit: true,
654    }
655}
656
657/// #1287: renders the `[unchanged <mode> view]` stub for a compressed-variant
658/// re-read — same conversation, unchanged file, same mode key. Mirrors
659/// [`render_unchanged_stub`]'s #498 determinism contract: a pure function of
660/// (file_ref, path, mode), so identical re-reads stay byte-stable and the
661/// static `fresh=true` escape survives non-meta mode.
662pub(crate) fn render_unchanged_variant_stub(file_ref: &str, path: &str, mode: &str) -> ReadOutput {
663    let short = protocol::shorten_path(path);
664    let out = if crate::core::protocol::meta_visible() {
665        format!(
666            "{file_ref}={short} [unchanged {mode} view]\nSame {mode} output you already received. Use fresh=true to re-emit.",
667        )
668    } else {
669        format!("{file_ref}={short} [unchanged {mode} view · fresh=true to re-emit]")
670    };
671    let out = crate::core::redaction::redact_text_if_enabled(&out);
672    let sent = count_tokens(&out);
673    ReadOutput {
674        content: out,
675        resolved_mode: mode.to_string(),
676        output_tokens: sent,
677        is_cache_hit: true,
678    }
679}
680
681/// Outcome of [`resolve_explicit_delta_mode`]: the (possibly rewritten) read
682/// mode plus an optional advisory note to surface to the agent.
683#[derive(Debug, Clone, PartialEq, Eq)]
684pub struct DeltaExplicitDecision {
685    /// The mode the read should proceed with (rewritten only when the feature
686    /// fires; otherwise the caller's mode, unchanged).
687    pub mode: String,
688    /// A byte-stable advisory appended to the read body when the mode was
689    /// rewritten to `diff`. `None` when nothing was rewritten or the collapse
690    /// was a silent `lines:`→`full` stub.
691    pub note: Option<String>,
692}
693
694/// Decide whether an **explicit** `full`/`lines:N-M` re-read of a session-cached
695/// file should be served as a delta instead of re-emitting content the model
696/// already holds (the `delta_explicit` opt-in; env `LCTX_DELTA_EXPLICIT`).
697///
698/// Returns the mode the read should proceed with:
699/// - **Changed on disk** (verified mtime+md5 stale) and full content is cached →
700///   `diff`, plus an advisory note. The diff carries exactly the new
701///   information in a fraction of the tokens.
702/// - **Unchanged** and the request is `lines:` of an already-fully-delivered
703///   file → `full`, so the read collapses to the ~15-token `[unchanged]` stub
704///   instead of re-extracting a window the model has seen.
705/// - Otherwise the caller's `mode` is returned untouched.
706///
707/// First reads (nothing cached) and `fresh=true` are never affected — the
708/// caller gates those before calling. Staleness uses the **verified** variant
709/// ([`crate::core::cache::is_cache_entry_stale_verified`]) so a same-second
710/// write on a coarse-granularity filesystem cannot be mistaken for "unchanged"
711/// and yield a misleading empty diff (#498 determinism).
712///
713/// Pure w.r.t. (cache, path, mode, enabled): no wall-clock, counters, or
714/// randomness enter the result, so identical inputs stay byte-stable.
715pub fn resolve_explicit_delta_mode(
716    cache: &SessionCache,
717    path: &str,
718    mode: &str,
719    explicit_mode: bool,
720    fresh: bool,
721    enabled: bool,
722) -> DeltaExplicitDecision {
723    let unchanged = DeltaExplicitDecision {
724        mode: mode.to_string(),
725        note: None,
726    };
727    if fresh
728        || !enabled
729        || !explicit_mode
730        || !(mode == "full" || mode == "full-compact" || mode.starts_with("lines:"))
731    {
732        return unchanged;
733    }
734    let Some(entry) = cache.get(path) else {
735        // First read this session — nothing to diff against.
736        return unchanged;
737    };
738    let stale =
739        crate::core::cache::is_cache_entry_stale_verified(path, entry.stored_mtime, &entry.hash);
740    if stale {
741        // Only divert to a diff when full content is actually cached: the diff
742        // base is that full content (see `handle_diff`), never a compressed
743        // view. Without it, `handle_diff` would have nothing to compare.
744        if entry.content().is_some() {
745            return DeltaExplicitDecision {
746                mode: "diff".to_string(),
747                note: Some(format!(
748                    "[delta-explicit] requested mode={mode} served as a diff: the file \
749                     changed since your last read and the diff is the new information. \
750                     Pass fresh=true if you need the full content re-emitted."
751                )),
752            };
753        }
754        return unchanged;
755    }
756    // Unchanged on disk: a `lines:` window of a file already delivered in full
757    // re-emits text the model holds — collapse to the full-mode stub
758    // (~15 tokens). A plain `full` re-read already hits that stub downstream.
759    if mode.starts_with("lines:") && cache.is_full_delivered(path) {
760        return DeltaExplicitDecision {
761            mode: "full".to_string(),
762            note: None,
763        };
764    }
765    unchanged
766}
767
768pub(crate) fn file_blake3_prefix(path: &str) -> Option<DeliveryFingerprint> {
769    let meta = std::fs::metadata(path).ok()?;
770    let mtime = meta
771        .modified()
772        .ok()?
773        .duration_since(std::time::UNIX_EPOCH)
774        .ok()?
775        .as_secs();
776    let bytes = std::fs::read(path).ok()?;
777    let hash = blake3::hash(&bytes);
778    let full = hash.as_bytes();
779    let mut prefix = [0u8; 12];
780    prefix.copy_from_slice(&full[..12]);
781    Some(DeliveryFingerprint {
782        hash: prefix,
783        mtime,
784        line_count: line_count_of(&bytes),
785    })
786}
787
788/// Content snapshot taken once per read for cross-agent delivery: the lookup
789/// and the record use the same hash, mtime and line count (#1909: records made
790/// from the MCP path previously carried a hardcoded `0L`).
791#[derive(Clone, Copy, Debug, PartialEq, Eq)]
792pub(crate) struct DeliveryFingerprint {
793    pub hash: [u8; 12],
794    pub mtime: u64,
795    pub line_count: u32,
796}
797
798/// Line count with `str::lines` semantics (the `SessionCache` convention): a
799/// trailing newline does not open an extra line.
800fn line_count_of(bytes: &[u8]) -> u32 {
801    let newlines = bytecount::count(bytes, b'\n');
802    let unterminated = usize::from(bytes.last().is_some_and(|b| *b != b'\n'));
803    u32::try_from(newlines + unterminated).unwrap_or(u32::MAX)
804}
805
806/// The agent id delivery records and lookups are keyed on: the signing
807/// profile's principal when one is configured, otherwise the stable
808/// per-process agent identity (#1916), so two agents never share one id.
809fn delivery_agent(
810    profile: Option<&crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1>,
811) -> String {
812    profile.map_or_else(
813        || crate::core::agent_identity::delivery_agent_id().to_string(),
814        |profile| profile.agent_id.clone(),
815    )
816}
817
818pub(crate) fn try_cross_agent_stub(
819    path: &str,
820    mode: &str,
821    hash: [u8; 12],
822    mtime: u64,
823    crp_mode: CrpMode,
824    tuning: ReadTuning<'_>,
825) -> Option<ReadOutput> {
826    if !crate::core::config::Config::load().ocla.delivery_enabled() {
827        return None;
828    }
829    if mode != "auto" && !RELAY_ELIGIBLE_MODES.contains(&mode) {
830        return None;
831    }
832    let profile =
833        crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1::from_environment()
834            .ok()?;
835    let current_agent = delivery_agent(profile.as_ref());
836    let current_conversation = crate::core::conversation::current_conversation_id()
837        .unwrap_or_else(|| current_agent.clone());
838    let reg = crate::core::ocla::OclaRegistry::global();
839    let record = if let Some(profile) = profile {
840        // A scoped miss/error must never reveal a legacy cache entry.
841        crate::daemon_client::scoped_delivery_check_blocking(
842            &profile,
843            path,
844            hash,
845            &current_conversation,
846        )
847        .ok()
848        .flatten()
849    } else {
850        crate::daemon_client::try_delivery_check_blocking(
851            &hash,
852            mtime,
853            path,
854            Some(&current_agent),
855            Some(&current_conversation),
856        )
857        .or_else(|| {
858            reg.delivery_registry.check_delivery(
859                &hash,
860                mtime,
861                path,
862                Some(&current_agent),
863                Some(&current_conversation),
864            )
865        })
866    }?;
867
868    render_cross_agent_relay(path, mode, &record, crp_mode, tuning)
869}
870
871fn render_cross_agent_relay(
872    path: &str,
873    mode: &str,
874    record: &crate::core::ocla::types::DeliveryRecord,
875    crp_mode: CrpMode,
876    tuning: ReadTuning<'_>,
877) -> Option<ReadOutput> {
878    let relay_mode = record.relay_mode.as_deref()?;
879    if !relay_variant_matches(mode, relay_mode, crp_mode, tuning) {
880        return None;
881    }
882    // A record of somebody else's read is not itself usable context.
883    // Until reference expansion is available, a missing payload is a miss.
884    let content = record.relay_content.as_ref()?;
885    let short = protocol::shorten_path(path);
886
887    let header = format!(
888        "{short} [relayed from {} · {relay_mode} · {}L]",
889        record.agent_id, record.line_count,
890    );
891    let body = format!("{header}\n{content}");
892    let tokens = count_tokens(&body);
893    crate::core::ocla::OclaRegistry::global()
894        .delivery_registry
895        .record_stub_served(record, tokens as u64);
896    Some(ReadOutput {
897        content: body,
898        resolved_mode: "cross-agent-relay".into(),
899        output_tokens: tokens,
900        is_cache_hit: true,
901    })
902}
903
904/// Records a completed (non-cache-hit) read for cross-agent delivery, relaying
905/// the rendered view when it is a compact, relay-eligible one. Shared by the
906/// CLI/daemon dispatch path so both record the same fingerprint and relay key.
907pub(crate) fn record_read_delivery(
908    path: &str,
909    fingerprint: DeliveryFingerprint,
910    resolved_mode: &str,
911    content: &str,
912    output_tokens: usize,
913    crp_mode: CrpMode,
914    tuning: ReadTuning<'_>,
915) {
916    let relay = relay_eligible(resolved_mode, content);
917    let relay_key = relay.1.map(|mode| {
918        super::compressed_cache_key(mode, crp_mode, None, tuning.aggressiveness, tuning.protect)
919    });
920    record_cross_agent_delivery(
921        path,
922        fingerprint.hash,
923        fingerprint.mtime,
924        fingerprint.line_count,
925        output_tokens,
926        relay.0,
927        relay_key.as_deref(),
928    );
929}
930
931pub(crate) fn record_cross_agent_delivery(
932    path: &str,
933    hash: [u8; 12],
934    mtime: u64,
935    line_count: u32,
936    tokens: usize,
937    relay_content: Option<&str>,
938    relay_mode: Option<&str>,
939) {
940    if !crate::core::config::Config::load().ocla.delivery_enabled() {
941        return;
942    }
943    let Ok(profile) =
944        crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1::from_environment()
945    else {
946        return;
947    };
948    let agent_id = delivery_agent(profile.as_ref());
949    let conversation_id =
950        crate::core::conversation::current_conversation_id().unwrap_or_else(|| agent_id.clone());
951    let mut entry = crate::core::ocla::types::DeliveryEntry {
952        access: None,
953        blake3: hash,
954        path: path.into(),
955        line_count,
956        token_count: tokens as u64,
957        agent_id,
958        conversation_id,
959        mtime,
960        relay_content: relay_content
961            .filter(|c| c.len() <= MAX_RELAY_CONTENT_BYTES)
962            .map(str::to_string),
963        relay_mode: relay_mode.map(str::to_string),
964    };
965    if let Some(profile) = profile {
966        let Ok(scope) = lean_ctx_ocla::delivery_scope::DeliveryScopeV1::new(
967            profile.tenant_id.clone(),
968            profile.project_id.clone(),
969        ) else {
970            return;
971        };
972        entry.access = Some(lean_ctx_ocla::delivery_scope::DeliveryAccessV1 {
973            scope,
974            privacy: profile.privacy,
975        });
976        let _ = crate::daemon_client::scoped_delivery_record_blocking(&profile, entry);
977        return;
978    }
979    crate::daemon_client::try_delivery_record_blocking(&entry);
980    let reg = crate::core::ocla::OclaRegistry::global();
981    reg.delivery_registry.record_delivery(entry);
982}
983
984#[cfg(test)]
985mod tests {
986    use super::{
987        CrpMode, ReadOutput, ReadTuning, SessionCache, effective_fresh_flags,
988        is_terminal_poll_file, relay_variant_matches, render_cross_agent_relay,
989        try_cross_agent_stub, try_stub_hit_readonly_scoped,
990    };
991    use std::sync::atomic::Ordering;
992
993    #[test]
994    fn cross_agent_stub_miss_returns_none() {
995        let stub = try_cross_agent_stub(
996            "/nonexistent/file.rs",
997            "auto",
998            [0; 12],
999            0,
1000            CrpMode::Off,
1001            ReadTuning::default(),
1002        );
1003        assert!(stub.is_none());
1004    }
1005
1006    #[test]
1007    fn relay_variants_preserve_requested_read_semantics() {
1008        let defaults = ReadTuning::default();
1009        assert!(relay_variant_matches(
1010            "map",
1011            "map:v2",
1012            CrpMode::Off,
1013            defaults
1014        ));
1015        assert!(relay_variant_matches(
1016            "auto",
1017            "signatures:v2",
1018            CrpMode::Off,
1019            defaults
1020        ));
1021        for mode in [
1022            "signatures",
1023            "lines:1-5",
1024            "raw",
1025            "full",
1026            "task",
1027            "reference",
1028        ] {
1029            assert!(!relay_variant_matches(
1030                mode,
1031                "map:v2",
1032                CrpMode::Off,
1033                defaults
1034            ));
1035        }
1036        for stored in ["map", "map:v3", "mapping", "map:v2:tdd", "map:v2:unknown"] {
1037            assert!(!relay_variant_matches(
1038                "map",
1039                stored,
1040                CrpMode::Off,
1041                defaults
1042            ));
1043        }
1044        assert!(relay_variant_matches(
1045            "map",
1046            "map:v2:tdd",
1047            CrpMode::Tdd,
1048            defaults
1049        ));
1050        let protect = vec!["important".to_owned()];
1051        let tuned = ReadTuning {
1052            aggressiveness: Some(0.7),
1053            protect: &protect,
1054        };
1055        let key = super::super::compressed_cache_key(
1056            "map",
1057            CrpMode::Off,
1058            None,
1059            tuned.aggressiveness,
1060            tuned.protect,
1061        );
1062        assert!(relay_variant_matches("map", &key, CrpMode::Off, tuned));
1063        assert!(!relay_variant_matches("map", &key, CrpMode::Off, defaults));
1064        assert!(!relay_variant_matches("map", "map:v2", CrpMode::Off, tuned));
1065    }
1066
1067    #[test]
1068    fn relay_rendering_requires_matching_usable_payload() {
1069        let _isolated = crate::core::data_dir::isolated_data_dir();
1070        let mut record = crate::core::ocla::types::DeliveryRecord {
1071            access: None,
1072            blake3: [81; 12],
1073            path: "variant.rs".into(),
1074            line_count: 12,
1075            token_count: 200,
1076            agent_id: "source-agent".into(),
1077            conversation_id: "source-conversation".into(),
1078            read_at: 1,
1079            mtime: 1,
1080            relay_content: Some("fn shared_context()".into()),
1081            relay_mode: Some("map:v2".into()),
1082            fresh: true,
1083        };
1084        let render = |record: &crate::core::ocla::types::DeliveryRecord, mode| {
1085            render_cross_agent_relay(
1086                "variant.rs",
1087                mode,
1088                record,
1089                CrpMode::Off,
1090                ReadTuning::default(),
1091            )
1092        };
1093        let output = render(&record, "map").expect("matching relay");
1094        assert!(output.is_cache_hit);
1095        assert_eq!(output.resolved_mode, "cross-agent-relay");
1096        assert!(output.content.contains("fn shared_context()"));
1097        assert_eq!(output.output_tokens, super::count_tokens(&output.content));
1098        for mode in ["signatures", "lines:1-2", "raw", "full"] {
1099            assert!(render(&record, mode).is_none());
1100        }
1101        record.relay_mode = None;
1102        assert!(render(&record, "map").is_none());
1103        record.relay_mode = Some("map:v2".into());
1104        record.relay_content = None;
1105        assert!(render(&record, "map").is_none());
1106    }
1107
1108    #[test]
1109    fn invalid_signing_profile_never_reads_legacy_delivery() {
1110        const CHILD: &str = "LEAN_CTX_TEST_INVALID_DELIVERY_PROFILE";
1111        if std::env::var_os(CHILD).is_none() {
1112            let status = std::process::Command::new(std::env::current_exe().expect("test executable"))
1113                .args(["--exact", "tools::ctx_read::dispatch::tests::invalid_signing_profile_never_reads_legacy_delivery", "--nocapture"])
1114                .env(CHILD, "1")
1115                .env("LEAN_CTX_DELIVERY_PROFILE", "{invalid")
1116                .status().expect("child test");
1117            assert!(status.success());
1118            return;
1119        }
1120        let _isolated = crate::core::data_dir::isolated_data_dir();
1121        let registry = crate::core::ocla::OclaRegistry::global();
1122        let path = "/legacy-delivery-profile-regression";
1123        registry
1124            .delivery_registry
1125            .record_delivery(crate::core::ocla::types::DeliveryEntry {
1126                access: None,
1127                blake3: [93; 12],
1128                path: path.into(),
1129                line_count: 1,
1130                token_count: 100,
1131                agent_id: "legacy-owner".into(),
1132                conversation_id: "legacy-conversation".into(),
1133                mtime: 1,
1134                relay_content: Some("must not leak".into()),
1135                relay_mode: Some("map".into()),
1136            });
1137        assert!(
1138            registry
1139                .delivery_registry
1140                .check_delivery(&[93; 12], 1, path, None, None)
1141                .is_some()
1142        );
1143        assert!(
1144            try_cross_agent_stub(
1145                path,
1146                "auto",
1147                [93; 12],
1148                1,
1149                CrpMode::Off,
1150                ReadTuning::default()
1151            )
1152            .is_none()
1153        );
1154    }
1155
1156    #[test]
1157    fn subagent_delivery_policy_keeps_cache_fresh_but_allows_delivery_by_default() {
1158        let delivery_for_subagents =
1159            crate::core::config::DeliveryConfig::default().delivery_for_subagents;
1160        assert!(
1161            delivery_for_subagents,
1162            "delivery must default to enabled for subagents"
1163        );
1164        let (cache_fresh, delivery_fresh) =
1165            effective_fresh_flags(false, false, true, delivery_for_subagents);
1166        assert!(cache_fresh, "subagent cache must remain isolated");
1167        assert!(
1168            !delivery_fresh,
1169            "default policy must allow a cross-agent delivery lookup"
1170        );
1171    }
1172
1173    #[test]
1174    fn subagent_delivery_policy_can_force_fresh_delivery() {
1175        let (cache_fresh, delivery_fresh) = effective_fresh_flags(false, false, true, false);
1176        assert!(cache_fresh);
1177        assert!(delivery_fresh, "disabled policy must bypass delivery stubs");
1178    }
1179
1180    #[test]
1181    fn line_count_matches_str_lines_semantics() {
1182        for sample in ["", "a", "a\n", "a\nb", "a\nb\n", "\n\n", "a\r\nb\r\n"] {
1183            assert_eq!(
1184                super::line_count_of(sample.as_bytes()) as usize,
1185                sample.lines().count(),
1186                "line count diverged for {sample:?}"
1187            );
1188        }
1189    }
1190
1191    #[test]
1192    fn fingerprint_carries_real_line_count() {
1193        // #1909: the MCP path recorded a hardcoded 0L.
1194        let dir = tempfile::tempdir().unwrap();
1195        let file = dir.path().join("three.rs");
1196        std::fs::write(&file, "fn a() {}\nfn b() {}\nfn c() {}\n").unwrap();
1197        let fp = super::file_blake3_prefix(file.to_str().unwrap()).unwrap();
1198        assert_eq!(fp.line_count, 3);
1199    }
1200
1201    /// Records a foreign legacy delivery for a fresh file and returns its path + key.
1202    fn foreign_delivery(
1203        relay: Option<(&str, &str)>,
1204    ) -> (tempfile::TempDir, String, super::DeliveryFingerprint) {
1205        let dir = tempfile::tempdir().unwrap();
1206        let file = dir.path().join("foreign.rs");
1207        std::fs::write(&file, "pub fn foreign() {}\npub fn other() {}\n").unwrap();
1208        let path = file.to_string_lossy().to_string();
1209        let fp = super::file_blake3_prefix(&path).unwrap();
1210        crate::core::ocla::OclaRegistry::global()
1211            .delivery_registry
1212            .record_delivery(crate::core::ocla::types::DeliveryEntry {
1213                access: None,
1214                blake3: fp.hash,
1215                path: path.clone(),
1216                line_count: fp.line_count,
1217                token_count: 40,
1218                agent_id: "claude-foreign".into(),
1219                conversation_id: "conv-foreign".into(),
1220                mtime: fp.mtime,
1221                relay_content: relay.map(|(c, _)| c.to_string()),
1222                relay_mode: relay.map(|(_, m)| m.to_string()),
1223            });
1224        (dir, path, fp)
1225    }
1226
1227    fn cross_agent(path: &str, mode: &str, fp: super::DeliveryFingerprint) -> Option<ReadOutput> {
1228        try_cross_agent_stub(
1229            path,
1230            mode,
1231            fp.hash,
1232            fp.mtime,
1233            CrpMode::Off,
1234            ReadTuning::default(),
1235        )
1236    }
1237
1238    #[test]
1239    fn content_free_stub_is_never_served_for_another_agents_read() {
1240        // #1909: agent B must get content, never a stub claiming content that
1241        // only agent A's context holds.
1242        let _isolated = crate::core::data_dir::isolated_data_dir();
1243        let (_dir, path, fp) = foreign_delivery(None);
1244        for mode in ["auto", "signatures", "map", "aggressive"] {
1245            assert!(
1246                cross_agent(&path, mode, fp).is_none(),
1247                "content-free cross-agent stub leaked for mode={mode}"
1248            );
1249        }
1250    }
1251
1252    #[test]
1253    fn relay_served_only_for_matching_mode() {
1254        let _isolated = crate::core::data_dir::isolated_data_dir();
1255        let relay = "pub fn foreign() {}";
1256        let (_dir, path, fp) = foreign_delivery(Some((relay, "map:v2")));
1257        let hit = cross_agent(&path, "map", fp).expect("map request must accept a map:v2 relay");
1258        assert!(hit.content.contains(relay), "{}", hit.content);
1259        assert!(hit.content.contains("· 2L]"), "{}", hit.content);
1260        assert!(
1261            cross_agent(&path, "signatures", fp).is_none(),
1262            "a signatures request must not be answered with a map relay"
1263        );
1264        assert!(cross_agent(&path, "lines:1-2", fp).is_none());
1265    }
1266
1267    #[test]
1268    fn warm_stub_hit_records_central_telemetry() {
1269        let dir = tempfile::tempdir().unwrap();
1270        let file = dir.path().join("telemetry-hit.rs");
1271        std::fs::write(&file, "fn telemetry_hit() {}\n").unwrap();
1272        let path = file.to_string_lossy();
1273        let mut cache = SessionCache::new();
1274        cache.store(&path, "fn telemetry_hit() {}\n");
1275        cache.mark_full_delivered(&path);
1276
1277        let metrics = crate::core::telemetry::global_metrics();
1278        let before = metrics.cache_hits.load(Ordering::Relaxed);
1279        let output = try_stub_hit_readonly_scoped(&cache, &path, None);
1280        let after = metrics.cache_hits.load(Ordering::Relaxed);
1281
1282        assert!(output.is_some(), "warm re-read must use the stub cache");
1283        assert!(
1284            after > before,
1285            "stub cache hit must increment central telemetry"
1286        );
1287    }
1288
1289    #[test]
1290    fn relay_does_not_poison_session_cache() {
1291        let mut cache = SessionCache::new();
1292        let path = "/tmp/test_relay_poison.rs";
1293        cache.store(path, "original content");
1294        assert_eq!(
1295            cache
1296                .get(path)
1297                .map(|e| e.compressed_outputs.contains_key("cross-agent-relay")),
1298            Some(false),
1299            "cross-agent-relay must not exist in session cache"
1300        );
1301    }
1302    #[test]
1303    fn is_terminal_poll_file_matches_cursor_terminal_paths() {
1304        assert!(is_terminal_poll_file(
1305            "/Users/me/.cursor/projects/Users-me-proj/terminals/12345.txt"
1306        ));
1307        assert!(is_terminal_poll_file(
1308            "/home/dev/.cursor/projects/foo/terminals/857272.txt"
1309        ));
1310        assert!(!is_terminal_poll_file("/Users/me/project/src/main.rs"));
1311        assert!(!is_terminal_poll_file(
1312            "/Users/me/.cursor/projects/foo/agent-transcripts/abc.jsonl"
1313        ));
1314        assert!(!is_terminal_poll_file("/Users/me/.cursor/terminals.log"));
1315    }
1316
1317    #[test]
1318    fn terminal_poll_file_stub_bypasses_conversation_gate() {
1319        let dir = tempfile::tempdir().unwrap();
1320        let terminals_dir = dir.path().join(".cursor").join("proj").join("terminals");
1321        std::fs::create_dir_all(&terminals_dir).unwrap();
1322        let file = terminals_dir.join("252028.txt");
1323        std::fs::write(&file, "---\npid: 1234\n---\nterminal output\n").unwrap();
1324        let path = file.to_string_lossy().to_string();
1325
1326        let mut cache = SessionCache::new();
1327        cache.store(&path, "---\npid: 1234\n---\nterminal output\n");
1328        cache.mark_full_delivered(&path);
1329
1330        // Mismatched conversation normally blocks stub — but terminal files bypass
1331        let output = try_stub_hit_readonly_scoped(&cache, &path, Some("different-conv"));
1332        assert!(
1333            output.is_some(),
1334            "terminal poll file must bypass conversation gate and serve stub"
1335        );
1336    }
1337
1338    #[test]
1339    fn non_terminal_file_respects_conversation_gate() {
1340        if crate::test_env::run_with_conversation_scope(
1341            "tools::ctx_read::dispatch::tests::non_terminal_file_respects_conversation_gate",
1342            true,
1343        ) {
1344            return;
1345        }
1346        let dir = tempfile::tempdir().unwrap();
1347        let file = dir.path().join("main.rs");
1348        std::fs::write(&file, "fn main() {}\n").unwrap();
1349        let path = file.to_string_lossy().to_string();
1350
1351        let mut cache = SessionCache::new();
1352        cache.store(&path, "fn main() {}\n");
1353        cache.mark_full_delivered(&path);
1354        if let Some(entry) = cache.get_mut(&path) {
1355            entry.delivered_conversation = Some("conv-A".to_string());
1356        }
1357
1358        // Mismatched conversation on regular file must block stub
1359        let output = try_stub_hit_readonly_scoped(&cache, &path, Some("conv-B"));
1360        assert!(
1361            output.is_none(),
1362            "regular file must respect conversation gate"
1363        );
1364    }
1365}