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    // Instruction files are served in full (see `handle_with_options_inner`),
348    // so a relayed compressed view of another agent's read must not stand in.
349    let compress_protected = (mode != "raw"
350        && !mode.starts_with("lines:")
351        && crate::core::config::Config::load()
352            .proxy
353            .is_path_compress_protected(path))
354        || super::instruction_file_forces_full(path, mode);
355
356    // Hash once for cross-agent delivery. The same snapshot is used for both
357    // the pre-read lookup and the post-read record, avoiding a second disk read.
358    let delivery_metadata = config
359        .ocla
360        .delivery_enabled()
361        .then(|| file_blake3_prefix(path))
362        .flatten();
363
364    if !effective_fresh_for_delivery
365        && !compress_protected
366        && let Some(fp) = delivery_metadata
367        && let Some(stub) = try_cross_agent_stub(path, mode, fp.hash, fp.mtime, crp_mode, tuning)
368    {
369        return stub;
370    }
371
372    if mode == "auto" {
373        let touched: Vec<String> = cache
374            .get_all_entries()
375            .iter()
376            .map(|(p, _)| (*p).clone())
377            .collect();
378        if crate::core::relevance_gate::should_gate(path, mode, task, &touched) {
379            let meta = std::fs::metadata(path);
380            let byte_count = meta.as_ref().map_or(0, std::fs::Metadata::len);
381            let line_count = preread
382                .as_ref()
383                .map_or(0, |c| bytecount::count(c.as_bytes(), b'\n'));
384            let stub = crate::core::relevance_gate::irrelevant_stub(path, line_count, byte_count);
385            let stub_tokens = count_tokens(&stub);
386            return ReadOutput {
387                content: stub,
388                resolved_mode: "auto".into(),
389                output_tokens: stub_tokens,
390                is_cache_hit: false,
391            };
392        }
393    }
394
395    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
396        bt.next_seq();
397    }
398    let mut result = handle_with_options_inner(
399        cache,
400        path,
401        mode,
402        effective_fresh_for_cache,
403        crp_mode,
404        task,
405        tuning,
406        preread,
407    );
408
409    if let Some(entry) = cache.get_mut(path) {
410        entry.last_mode.clone_from(&result.resolved_mode);
411        if matches!(result.resolved_mode.as_str(), "full" | "full-compact")
412            && entry.full_content_delivered
413            && result.is_cache_hit
414            && entry.bump_reread() >= crate::core::cache::full_degradation_threshold()
415        {
416            entry.full_content_delivered = false;
417            entry.reset_reread_count();
418            crate::core::auto_mode_resolver::count_source("full_delivery_degraded");
419        }
420        // #841: a partial/filtered read means the model's most recent view is NOT
421        // the full content. Clear the delivery flag so a subsequent mode="full"
422        // re-delivers real content instead of the [unchanged] stub. Without this,
423        // a task→full sequence returns an empty stub because the flag was set by an
424        // earlier full delivery and never cleared by the intervening non-full read.
425        if !matches!(result.resolved_mode.as_str(), "full" | "full-compact") {
426            entry.full_content_delivered = false;
427            entry.reset_reread_count();
428        }
429    }
430
431    if !result.is_cache_hit
432        && let Some(fp) = delivery_metadata
433    {
434        record_read_delivery(
435            path,
436            fp,
437            &result.resolved_mode,
438            &result.content,
439            result.output_tokens,
440            crp_mode,
441            tuning,
442        );
443    }
444
445    // SSOT via [`ReadMode`] (#528): lossy summaries may elide shared blocks.
446    let dedup_allowed = result
447        .resolved_mode
448        .parse::<ReadMode>()
449        .is_ok_and(|m| m.is_lossy_summary());
450    if dedup_allowed && let Some(deduped) = cache.apply_dedup(path, &result.content) {
451        let new_tokens = count_tokens(&deduped);
452        if new_tokens < result.output_tokens {
453            result.content = deduped;
454            result.output_tokens = new_tokens;
455        }
456    }
457
458    // R28: Kernel content dedup — detect re-reads of unchanged content.
459    if let Some(stub) = dedup_hook::maybe_dedup(path, &result.content, mode, fresh) {
460        let stub_tokens = count_tokens(&stub);
461        if stub_tokens < result.output_tokens {
462            result.content = stub;
463            result.output_tokens = stub_tokens;
464            result.is_cache_hit = true;
465        }
466    }
467
468    // R30: Feed bounce-tracker signal into adaptive compression bridge.
469    crate::core::context_kernel::adaptive_hook::update_from_bounce_tracker();
470    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
471        let original_tokens = cache.get(path).map_or(0, |e| e.original_tokens);
472        // Bounce waste is reported when a provisional bounce is committed
473        // (`BounceTracker::commit`), not here: a read-then-edit cancels it.
474        bt.record_read(
475            path,
476            &result.resolved_mode,
477            result.output_tokens,
478            original_tokens,
479        );
480    }
481
482    // Stigmergy (#540): deposit a Hot scent for this read in the background
483    // (the field file lock may briefly block; never stall the read path). The
484    // foreign-claim hint is intentionally NOT appended to the body: it carries a
485    // relative timestamp ("claimed Nm ago"), which would make the output a
486    // non-pure function of wall-clock time and defeat provider prompt caching
487    // (#498). The deposit remains so the field still reflects active work.
488    deposit_hot_scent(path);
489
490    crate::core::context_gc::maybe_gc(cache);
491
492    result
493}
494
495/// Attempt to serve a `mode="full"` cache hit (`[unchanged …]`) using only a
496/// shared borrow of the cache.
497///
498/// Returns `None` when the file is not cached, was modified on disk, full
499/// content was never delivered, or the cache policy forbids stubbing — in those
500/// cases the caller must fall back to the write path.
501///
502/// This is the read-locked fast path: it needs no `&mut SessionCache`, so the
503/// dominant "re-read an unchanged file" case proceeds under a shared lock and
504/// parallel reads of distinct files no longer serialize on a global write lock.
505pub fn try_stub_hit_readonly(cache: &SessionCache, path: &str) -> Option<ReadOutput> {
506    // Resolve the caller *fresh* (TTL-bypassed): the stub gate's concurrency
507    // detection must see a just-appeared second chat with zero lag, else a stub
508    // could leak across chats in the pre-detection window (#1042).
509    let current_conversation = crate::core::conversation::current_conversation_id_fresh();
510    try_stub_hit_readonly_scoped(cache, path, current_conversation.as_deref())
511}
512
513/// Conversation-scoped core of [`try_stub_hit_readonly`]. The current
514/// conversation id is injected (not read from the global resolver) so the
515/// conversation gate can be tested deterministically without global state.
516pub(crate) fn try_stub_hit_readonly_scoped(
517    cache: &SessionCache,
518    path: &str,
519    current_conversation: Option<&str>,
520) -> Option<ReadOutput> {
521    if !stub_policy_allows() {
522        return None;
523    }
524
525    // Warm path: a live in-memory entry is the freshest source of truth.
526    if let Some(file_ref) = cache.get_file_ref_readonly(path) {
527        let (cached_mtime, cached_hash, line_count, delivered_conv) = {
528            let entry = cache.get(path)?;
529            (
530                entry.stored_mtime,
531                entry.hash.clone(),
532                entry.line_count,
533                entry.delivered_conversation.clone(),
534            )
535        };
536        if crate::core::cache::is_cache_entry_stale_verified(path, cached_mtime, &cached_hash)
537            || !cache.is_full_delivered(path)
538        {
539            return None;
540        }
541        // Terminal poll files bypass the conversation gate: they are system
542        // infrastructure, not conversation-scoped content. The content-hash
543        // verification above already guarantees the file is unchanged.
544        let is_terminal_poll = is_terminal_poll_file(path);
545
546        if !is_terminal_poll
547            && !crate::core::conversation::conversation_allows_stub(
548                current_conversation,
549                delivered_conv.as_deref(),
550            )
551        {
552            return None;
553        }
554        let original_tokens = cache.record_cache_hit(path)?.original_tokens;
555        crate::core::telemetry::global_metrics().record_cache(true);
556        let stub = render_unchanged_stub(&file_ref, path, line_count);
557        crate::core::stats::record_reread(original_tokens.saturating_sub(stub.output_tokens));
558        return Some(stub);
559    }
560
561    // Cold fallback (#955): no live entry (e.g. after a daemon restart or idle
562    // clear). Serve the stub from the persisted index iff the file is unchanged
563    // AND the *same known* conversation is asking — a stricter gate than the warm
564    // path, because a cold stub crosses a process boundary (no "no context →
565    // legacy" escape; see `conversation_allows_cold_stub`).
566    let rec = crate::core::read_stub_index::lookup(path)?;
567    if crate::core::cache::is_cache_entry_stale_verified(path, rec.stored_mtime(), &rec.hash) {
568        return None;
569    }
570    if !is_terminal_poll_file(path)
571        && !crate::core::conversation::conversation_allows_cold_stub(
572            current_conversation,
573            rec.delivered_conversation.as_deref(),
574        )
575    {
576        return None;
577    }
578    Some(render_unchanged_stub(&rec.file_ref, path, rec.line_count))
579}
580
581/// Whether the cache policy and active profile allow serving `[unchanged …]`
582/// stubs at all. Shared by the full-content stub path and the #1287 variant
583/// stub path so the two can never diverge.
584pub(crate) fn stub_policy_allows() -> bool {
585    let no_deg = crate::core::config::Config::load().no_degrade_effective();
586    let prof = crate::core::profiles::active_profile();
587    let force_full = no_deg
588        || (prof.read.default_mode_effective() == "full"
589            && prof.compression.crp_mode.as_deref() == Some("off"));
590    crate::server::compaction_sync::effective_cache_policy() != "safe" && !force_full
591}
592
593/// Renders the `[unchanged …]` stub body shared by the warm and cold stub paths.
594///
595/// #498 determinism: the stub is a pure function of (file_ref, path, line_count),
596/// so identical re-reads stay byte-stable and provider prompt caching applies.
597/// The `fresh=true` escape is a *static* suffix (no rotating proof lines or
598/// read-count notes), so a re-reader in non-meta mode still sees how to force the
599/// content (#513) without breaking byte-stability.
600fn render_unchanged_stub(file_ref: &str, path: &str, line_count: usize) -> ReadOutput {
601    let short = protocol::shorten_path(path);
602    let out = if crate::core::protocol::meta_visible() {
603        format!(
604            "{file_ref}={short} [unchanged {line_count}L]\nUnchanged on disk. Use fresh=true to force re-read.",
605        )
606    } else {
607        format!("{file_ref}={short} [unchanged {line_count}L · fresh=true to re-read]")
608    };
609    let out = crate::core::redaction::redact_text_if_enabled(&out);
610    let sent = count_tokens(&out);
611    ReadOutput {
612        content: out,
613        resolved_mode: "full".into(),
614        output_tokens: sent,
615        is_cache_hit: true,
616    }
617}
618
619/// #1287: renders the `[unchanged <mode> view]` stub for a compressed-variant
620/// re-read — same conversation, unchanged file, same mode key. Mirrors
621/// [`render_unchanged_stub`]'s #498 determinism contract: a pure function of
622/// (file_ref, path, mode), so identical re-reads stay byte-stable and the
623/// static `fresh=true` escape survives non-meta mode.
624pub(crate) fn render_unchanged_variant_stub(file_ref: &str, path: &str, mode: &str) -> ReadOutput {
625    let short = protocol::shorten_path(path);
626    let out = if crate::core::protocol::meta_visible() {
627        format!(
628            "{file_ref}={short} [unchanged {mode} view]\nSame {mode} output you already received. Use fresh=true to re-emit.",
629        )
630    } else {
631        format!("{file_ref}={short} [unchanged {mode} view · fresh=true to re-emit]")
632    };
633    let out = crate::core::redaction::redact_text_if_enabled(&out);
634    let sent = count_tokens(&out);
635    ReadOutput {
636        content: out,
637        resolved_mode: mode.to_string(),
638        output_tokens: sent,
639        is_cache_hit: true,
640    }
641}
642
643/// Outcome of [`resolve_explicit_delta_mode`]: the (possibly rewritten) read
644/// mode plus an optional advisory note to surface to the agent.
645#[derive(Debug, Clone, PartialEq, Eq)]
646pub struct DeltaExplicitDecision {
647    /// The mode the read should proceed with (rewritten only when the feature
648    /// fires; otherwise the caller's mode, unchanged).
649    pub mode: String,
650    /// A byte-stable advisory appended to the read body when the mode was
651    /// rewritten to `diff`. `None` when nothing was rewritten or the collapse
652    /// was a silent `lines:`→`full` stub.
653    pub note: Option<String>,
654}
655
656/// Decide whether an **explicit** `full`/`lines:N-M` re-read of a session-cached
657/// file should be served as a delta instead of re-emitting content the model
658/// already holds (the `delta_explicit` opt-in; env `LCTX_DELTA_EXPLICIT`).
659///
660/// Returns the mode the read should proceed with:
661/// - **Changed on disk** (verified mtime+md5 stale) and full content is cached →
662///   `diff`, plus an advisory note. The diff carries exactly the new
663///   information in a fraction of the tokens.
664/// - **Unchanged** and the request is `lines:` of an already-fully-delivered
665///   file → `full`, so the read collapses to the ~15-token `[unchanged]` stub
666///   instead of re-extracting a window the model has seen.
667/// - Otherwise the caller's `mode` is returned untouched.
668///
669/// First reads (nothing cached) and `fresh=true` are never affected — the
670/// caller gates those before calling. Staleness uses the **verified** variant
671/// ([`crate::core::cache::is_cache_entry_stale_verified`]) so a same-second
672/// write on a coarse-granularity filesystem cannot be mistaken for "unchanged"
673/// and yield a misleading empty diff (#498 determinism).
674///
675/// Pure w.r.t. (cache, path, mode, enabled): no wall-clock, counters, or
676/// randomness enter the result, so identical inputs stay byte-stable.
677pub fn resolve_explicit_delta_mode(
678    cache: &SessionCache,
679    path: &str,
680    mode: &str,
681    explicit_mode: bool,
682    fresh: bool,
683    enabled: bool,
684) -> DeltaExplicitDecision {
685    let unchanged = DeltaExplicitDecision {
686        mode: mode.to_string(),
687        note: None,
688    };
689    if fresh
690        || !enabled
691        || !explicit_mode
692        || !(mode == "full" || mode == "full-compact" || mode.starts_with("lines:"))
693    {
694        return unchanged;
695    }
696    let Some(entry) = cache.get(path) else {
697        // First read this session — nothing to diff against.
698        return unchanged;
699    };
700    let stale =
701        crate::core::cache::is_cache_entry_stale_verified(path, entry.stored_mtime, &entry.hash);
702    if stale {
703        // Only divert to a diff when full content is actually cached: the diff
704        // base is that full content (see `handle_diff`), never a compressed
705        // view. Without it, `handle_diff` would have nothing to compare.
706        if entry.content().is_some() {
707            return DeltaExplicitDecision {
708                mode: "diff".to_string(),
709                note: Some(format!(
710                    "[delta-explicit] requested mode={mode} served as a diff: the file \
711                     changed since your last read and the diff is the new information. \
712                     Pass fresh=true if you need the full content re-emitted."
713                )),
714            };
715        }
716        return unchanged;
717    }
718    // Unchanged on disk: a `lines:` window of a file already delivered in full
719    // re-emits text the model holds — collapse to the full-mode stub
720    // (~15 tokens). A plain `full` re-read already hits that stub downstream.
721    if mode.starts_with("lines:") && cache.is_full_delivered(path) {
722        return DeltaExplicitDecision {
723            mode: "full".to_string(),
724            note: None,
725        };
726    }
727    unchanged
728}
729
730pub(crate) fn file_blake3_prefix(path: &str) -> Option<DeliveryFingerprint> {
731    let meta = std::fs::metadata(path).ok()?;
732    let mtime = meta
733        .modified()
734        .ok()?
735        .duration_since(std::time::UNIX_EPOCH)
736        .ok()?
737        .as_secs();
738    let bytes = std::fs::read(path).ok()?;
739    let hash = blake3::hash(&bytes);
740    let full = hash.as_bytes();
741    let mut prefix = [0u8; 12];
742    prefix.copy_from_slice(&full[..12]);
743    Some(DeliveryFingerprint {
744        hash: prefix,
745        mtime,
746        line_count: line_count_of(&bytes),
747    })
748}
749
750/// Content snapshot taken once per read for cross-agent delivery: the lookup
751/// and the record use the same hash, mtime and line count (#1909: records made
752/// from the MCP path previously carried a hardcoded `0L`).
753#[derive(Clone, Copy, Debug, PartialEq, Eq)]
754pub(crate) struct DeliveryFingerprint {
755    pub hash: [u8; 12],
756    pub mtime: u64,
757    pub line_count: u32,
758}
759
760/// Line count with `str::lines` semantics (the `SessionCache` convention): a
761/// trailing newline does not open an extra line.
762fn line_count_of(bytes: &[u8]) -> u32 {
763    let newlines = bytecount::count(bytes, b'\n');
764    let unterminated = usize::from(bytes.last().is_some_and(|b| *b != b'\n'));
765    u32::try_from(newlines + unterminated).unwrap_or(u32::MAX)
766}
767
768/// The agent id delivery records and lookups are keyed on: the signing
769/// profile's principal when one is configured, otherwise the stable
770/// per-process agent identity (#1916), so two agents never share one id.
771fn delivery_agent(
772    profile: Option<&crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1>,
773) -> String {
774    profile.map_or_else(
775        || crate::core::agent_identity::delivery_agent_id().to_string(),
776        |profile| profile.agent_id.clone(),
777    )
778}
779
780pub(crate) fn try_cross_agent_stub(
781    path: &str,
782    mode: &str,
783    hash: [u8; 12],
784    mtime: u64,
785    crp_mode: CrpMode,
786    tuning: ReadTuning<'_>,
787) -> Option<ReadOutput> {
788    if !crate::core::config::Config::load().ocla.delivery_enabled() {
789        return None;
790    }
791    if mode != "auto" && !RELAY_ELIGIBLE_MODES.contains(&mode) {
792        return None;
793    }
794    let profile =
795        crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1::from_environment()
796            .ok()?;
797    let current_agent = delivery_agent(profile.as_ref());
798    let current_conversation = crate::core::conversation::current_conversation_id()
799        .unwrap_or_else(|| current_agent.clone());
800    let reg = crate::core::ocla::OclaRegistry::global();
801    let record = if let Some(profile) = profile {
802        // A scoped miss/error must never reveal a legacy cache entry.
803        crate::daemon_client::scoped_delivery_check_blocking(
804            &profile,
805            path,
806            hash,
807            &current_conversation,
808        )
809        .ok()
810        .flatten()
811    } else {
812        crate::daemon_client::try_delivery_check_blocking(
813            &hash,
814            mtime,
815            path,
816            Some(&current_agent),
817            Some(&current_conversation),
818        )
819        .or_else(|| {
820            reg.delivery_registry.check_delivery(
821                &hash,
822                mtime,
823                path,
824                Some(&current_agent),
825                Some(&current_conversation),
826            )
827        })
828    }?;
829
830    render_cross_agent_relay(path, mode, &record, crp_mode, tuning)
831}
832
833fn render_cross_agent_relay(
834    path: &str,
835    mode: &str,
836    record: &crate::core::ocla::types::DeliveryRecord,
837    crp_mode: CrpMode,
838    tuning: ReadTuning<'_>,
839) -> Option<ReadOutput> {
840    let relay_mode = record.relay_mode.as_deref()?;
841    if !relay_variant_matches(mode, relay_mode, crp_mode, tuning) {
842        return None;
843    }
844    // A record of somebody else's read is not itself usable context.
845    // Until reference expansion is available, a missing payload is a miss.
846    let content = record.relay_content.as_ref()?;
847    let short = protocol::shorten_path(path);
848
849    let header = format!(
850        "{short} [relayed from {} · {relay_mode} · {}L]",
851        record.agent_id, record.line_count,
852    );
853    let body = format!("{header}\n{content}");
854    let tokens = count_tokens(&body);
855    crate::core::ocla::OclaRegistry::global()
856        .delivery_registry
857        .record_stub_served(record, tokens as u64);
858    Some(ReadOutput {
859        content: body,
860        resolved_mode: "cross-agent-relay".into(),
861        output_tokens: tokens,
862        is_cache_hit: true,
863    })
864}
865
866/// Records a completed (non-cache-hit) read for cross-agent delivery, relaying
867/// the rendered view when it is a compact, relay-eligible one. Shared by the
868/// CLI/daemon dispatch path so both record the same fingerprint and relay key.
869pub(crate) fn record_read_delivery(
870    path: &str,
871    fingerprint: DeliveryFingerprint,
872    resolved_mode: &str,
873    content: &str,
874    output_tokens: usize,
875    crp_mode: CrpMode,
876    tuning: ReadTuning<'_>,
877) {
878    let relay = relay_eligible(resolved_mode, content);
879    let relay_key = relay.1.map(|mode| {
880        super::compressed_cache_key(mode, crp_mode, None, tuning.aggressiveness, tuning.protect)
881    });
882    record_cross_agent_delivery(
883        path,
884        fingerprint.hash,
885        fingerprint.mtime,
886        fingerprint.line_count,
887        output_tokens,
888        relay.0,
889        relay_key.as_deref(),
890    );
891}
892
893pub(crate) fn record_cross_agent_delivery(
894    path: &str,
895    hash: [u8; 12],
896    mtime: u64,
897    line_count: u32,
898    tokens: usize,
899    relay_content: Option<&str>,
900    relay_mode: Option<&str>,
901) {
902    if !crate::core::config::Config::load().ocla.delivery_enabled() {
903        return;
904    }
905    let Ok(profile) =
906        crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1::from_environment()
907    else {
908        return;
909    };
910    let agent_id = delivery_agent(profile.as_ref());
911    let conversation_id =
912        crate::core::conversation::current_conversation_id().unwrap_or_else(|| agent_id.clone());
913    let mut entry = crate::core::ocla::types::DeliveryEntry {
914        access: None,
915        blake3: hash,
916        path: path.into(),
917        line_count,
918        token_count: tokens as u64,
919        agent_id,
920        conversation_id,
921        mtime,
922        relay_content: relay_content
923            .filter(|c| c.len() <= MAX_RELAY_CONTENT_BYTES)
924            .map(str::to_string),
925        relay_mode: relay_mode.map(str::to_string),
926    };
927    if let Some(profile) = profile {
928        let Ok(scope) = lean_ctx_ocla::delivery_scope::DeliveryScopeV1::new(
929            profile.tenant_id.clone(),
930            profile.project_id.clone(),
931        ) else {
932            return;
933        };
934        entry.access = Some(lean_ctx_ocla::delivery_scope::DeliveryAccessV1 {
935            scope,
936            privacy: profile.privacy,
937        });
938        let _ = crate::daemon_client::scoped_delivery_record_blocking(&profile, entry);
939        return;
940    }
941    crate::daemon_client::try_delivery_record_blocking(&entry);
942    let reg = crate::core::ocla::OclaRegistry::global();
943    reg.delivery_registry.record_delivery(entry);
944}
945
946/// Deposit a Hot scent for `path` in the request's project from a worker
947/// thread. The project is resolved here: the request scope does not reach
948/// the thread, which would otherwise have no project at all.
949fn deposit_hot_scent(path: &str) -> Option<std::thread::JoinHandle<()>> {
950    let project_root = crate::core::scent_field::current_project()?;
951    let self_agent = crate::core::scent_field::scent_agent_id();
952    let scent_path = crate::core::pathutil::normalize_tool_path(path);
953    Some(std::thread::spawn(move || {
954        crate::core::scent_field::deposit_for(
955            &project_root,
956            self_agent,
957            crate::core::scent_field::ScentKind::Hot,
958            &scent_path,
959            0.3,
960        );
961    }))
962}
963
964#[cfg(test)]
965mod tests {
966    use super::{
967        CrpMode, ReadOutput, ReadTuning, SessionCache, effective_fresh_flags,
968        is_terminal_poll_file, relay_variant_matches, render_cross_agent_relay,
969        try_cross_agent_stub, try_stub_hit_readonly_scoped,
970    };
971    use std::sync::atomic::Ordering;
972
973    #[test]
974    fn cross_agent_stub_miss_returns_none() {
975        let stub = try_cross_agent_stub(
976            "/nonexistent/file.rs",
977            "auto",
978            [0; 12],
979            0,
980            CrpMode::Off,
981            ReadTuning::default(),
982        );
983        assert!(stub.is_none());
984    }
985
986    #[test]
987    fn relay_variants_preserve_requested_read_semantics() {
988        let defaults = ReadTuning::default();
989        assert!(relay_variant_matches(
990            "map",
991            "map:v2",
992            CrpMode::Off,
993            defaults
994        ));
995        assert!(relay_variant_matches(
996            "auto",
997            "signatures:v2",
998            CrpMode::Off,
999            defaults
1000        ));
1001        for mode in [
1002            "signatures",
1003            "lines:1-5",
1004            "raw",
1005            "full",
1006            "task",
1007            "reference",
1008        ] {
1009            assert!(!relay_variant_matches(
1010                mode,
1011                "map:v2",
1012                CrpMode::Off,
1013                defaults
1014            ));
1015        }
1016        for stored in ["map", "map:v3", "mapping", "map:v2:tdd", "map:v2:unknown"] {
1017            assert!(!relay_variant_matches(
1018                "map",
1019                stored,
1020                CrpMode::Off,
1021                defaults
1022            ));
1023        }
1024        assert!(relay_variant_matches(
1025            "map",
1026            "map:v2:tdd",
1027            CrpMode::Tdd,
1028            defaults
1029        ));
1030        let protect = vec!["important".to_owned()];
1031        let tuned = ReadTuning {
1032            aggressiveness: Some(0.7),
1033            protect: &protect,
1034        };
1035        let key = super::super::compressed_cache_key(
1036            "map",
1037            CrpMode::Off,
1038            None,
1039            tuned.aggressiveness,
1040            tuned.protect,
1041        );
1042        assert!(relay_variant_matches("map", &key, CrpMode::Off, tuned));
1043        assert!(!relay_variant_matches("map", &key, CrpMode::Off, defaults));
1044        assert!(!relay_variant_matches("map", "map:v2", CrpMode::Off, tuned));
1045    }
1046
1047    #[test]
1048    fn relay_rendering_requires_matching_usable_payload() {
1049        let _isolated = crate::core::data_dir::isolated_data_dir();
1050        let mut record = crate::core::ocla::types::DeliveryRecord {
1051            access: None,
1052            blake3: [81; 12],
1053            path: "variant.rs".into(),
1054            line_count: 12,
1055            token_count: 200,
1056            agent_id: "source-agent".into(),
1057            conversation_id: "source-conversation".into(),
1058            read_at: 1,
1059            mtime: 1,
1060            relay_content: Some("fn shared_context()".into()),
1061            relay_mode: Some("map:v2".into()),
1062            fresh: true,
1063        };
1064        let render = |record: &crate::core::ocla::types::DeliveryRecord, mode| {
1065            render_cross_agent_relay(
1066                "variant.rs",
1067                mode,
1068                record,
1069                CrpMode::Off,
1070                ReadTuning::default(),
1071            )
1072        };
1073        let output = render(&record, "map").expect("matching relay");
1074        assert!(output.is_cache_hit);
1075        assert_eq!(output.resolved_mode, "cross-agent-relay");
1076        assert!(output.content.contains("fn shared_context()"));
1077        assert_eq!(output.output_tokens, super::count_tokens(&output.content));
1078        for mode in ["signatures", "lines:1-2", "raw", "full"] {
1079            assert!(render(&record, mode).is_none());
1080        }
1081        record.relay_mode = None;
1082        assert!(render(&record, "map").is_none());
1083        record.relay_mode = Some("map:v2".into());
1084        record.relay_content = None;
1085        assert!(render(&record, "map").is_none());
1086    }
1087
1088    #[test]
1089    fn invalid_signing_profile_never_reads_legacy_delivery() {
1090        const CHILD: &str = "LEAN_CTX_TEST_INVALID_DELIVERY_PROFILE";
1091        if std::env::var_os(CHILD).is_none() {
1092            let status = std::process::Command::new(std::env::current_exe().expect("test executable"))
1093                .args(["--exact", "tools::ctx_read::dispatch::tests::invalid_signing_profile_never_reads_legacy_delivery", "--nocapture"])
1094                .env(CHILD, "1")
1095                .env("LEAN_CTX_DELIVERY_PROFILE", "{invalid")
1096                .status().expect("child test");
1097            assert!(status.success());
1098            return;
1099        }
1100        let _isolated = crate::core::data_dir::isolated_data_dir();
1101        let registry = crate::core::ocla::OclaRegistry::global();
1102        let path = "/legacy-delivery-profile-regression";
1103        registry
1104            .delivery_registry
1105            .record_delivery(crate::core::ocla::types::DeliveryEntry {
1106                access: None,
1107                blake3: [93; 12],
1108                path: path.into(),
1109                line_count: 1,
1110                token_count: 100,
1111                agent_id: "legacy-owner".into(),
1112                conversation_id: "legacy-conversation".into(),
1113                mtime: 1,
1114                relay_content: Some("must not leak".into()),
1115                relay_mode: Some("map".into()),
1116            });
1117        assert!(
1118            registry
1119                .delivery_registry
1120                .check_delivery(&[93; 12], 1, path, None, None)
1121                .is_some()
1122        );
1123        assert!(
1124            try_cross_agent_stub(
1125                path,
1126                "auto",
1127                [93; 12],
1128                1,
1129                CrpMode::Off,
1130                ReadTuning::default()
1131            )
1132            .is_none()
1133        );
1134    }
1135
1136    #[test]
1137    fn subagent_delivery_policy_keeps_cache_fresh_but_allows_delivery_by_default() {
1138        let delivery_for_subagents =
1139            crate::core::config::DeliveryConfig::default().delivery_for_subagents;
1140        assert!(
1141            delivery_for_subagents,
1142            "delivery must default to enabled for subagents"
1143        );
1144        let (cache_fresh, delivery_fresh) =
1145            effective_fresh_flags(false, false, true, delivery_for_subagents);
1146        assert!(cache_fresh, "subagent cache must remain isolated");
1147        assert!(
1148            !delivery_fresh,
1149            "default policy must allow a cross-agent delivery lookup"
1150        );
1151    }
1152
1153    #[test]
1154    fn subagent_delivery_policy_can_force_fresh_delivery() {
1155        let (cache_fresh, delivery_fresh) = effective_fresh_flags(false, false, true, false);
1156        assert!(cache_fresh);
1157        assert!(delivery_fresh, "disabled policy must bypass delivery stubs");
1158    }
1159
1160    #[test]
1161    fn line_count_matches_str_lines_semantics() {
1162        for sample in ["", "a", "a\n", "a\nb", "a\nb\n", "\n\n", "a\r\nb\r\n"] {
1163            assert_eq!(
1164                super::line_count_of(sample.as_bytes()) as usize,
1165                sample.lines().count(),
1166                "line count diverged for {sample:?}"
1167            );
1168        }
1169    }
1170
1171    #[test]
1172    fn fingerprint_carries_real_line_count() {
1173        // #1909: the MCP path recorded a hardcoded 0L.
1174        let dir = tempfile::tempdir().unwrap();
1175        let file = dir.path().join("three.rs");
1176        std::fs::write(&file, "fn a() {}\nfn b() {}\nfn c() {}\n").unwrap();
1177        let fp = super::file_blake3_prefix(file.to_str().unwrap()).unwrap();
1178        assert_eq!(fp.line_count, 3);
1179    }
1180
1181    /// Records a foreign legacy delivery for a fresh file and returns its path + key.
1182    fn foreign_delivery(
1183        relay: Option<(&str, &str)>,
1184    ) -> (tempfile::TempDir, String, super::DeliveryFingerprint) {
1185        let dir = tempfile::tempdir().unwrap();
1186        let file = dir.path().join("foreign.rs");
1187        std::fs::write(&file, "pub fn foreign() {}\npub fn other() {}\n").unwrap();
1188        let path = file.to_string_lossy().to_string();
1189        let fp = super::file_blake3_prefix(&path).unwrap();
1190        crate::core::ocla::OclaRegistry::global()
1191            .delivery_registry
1192            .record_delivery(crate::core::ocla::types::DeliveryEntry {
1193                access: None,
1194                blake3: fp.hash,
1195                path: path.clone(),
1196                line_count: fp.line_count,
1197                token_count: 40,
1198                agent_id: "claude-foreign".into(),
1199                conversation_id: "conv-foreign".into(),
1200                mtime: fp.mtime,
1201                relay_content: relay.map(|(c, _)| c.to_string()),
1202                relay_mode: relay.map(|(_, m)| m.to_string()),
1203            });
1204        (dir, path, fp)
1205    }
1206
1207    fn cross_agent(path: &str, mode: &str, fp: super::DeliveryFingerprint) -> Option<ReadOutput> {
1208        try_cross_agent_stub(
1209            path,
1210            mode,
1211            fp.hash,
1212            fp.mtime,
1213            CrpMode::Off,
1214            ReadTuning::default(),
1215        )
1216    }
1217
1218    #[test]
1219    fn content_free_stub_is_never_served_for_another_agents_read() {
1220        // #1909: agent B must get content, never a stub claiming content that
1221        // only agent A's context holds.
1222        let _isolated = crate::core::data_dir::isolated_data_dir();
1223        let (_dir, path, fp) = foreign_delivery(None);
1224        for mode in ["auto", "signatures", "map", "aggressive"] {
1225            assert!(
1226                cross_agent(&path, mode, fp).is_none(),
1227                "content-free cross-agent stub leaked for mode={mode}"
1228            );
1229        }
1230    }
1231
1232    #[test]
1233    fn relay_served_only_for_matching_mode() {
1234        let _isolated = crate::core::data_dir::isolated_data_dir();
1235        let relay = "pub fn foreign() {}";
1236        let (_dir, path, fp) = foreign_delivery(Some((relay, "map:v2")));
1237        let hit = cross_agent(&path, "map", fp).expect("map request must accept a map:v2 relay");
1238        assert!(hit.content.contains(relay), "{}", hit.content);
1239        assert!(hit.content.contains("· 2L]"), "{}", hit.content);
1240        assert!(
1241            cross_agent(&path, "signatures", fp).is_none(),
1242            "a signatures request must not be answered with a map relay"
1243        );
1244        assert!(cross_agent(&path, "lines:1-2", fp).is_none());
1245    }
1246
1247    #[test]
1248    fn warm_stub_hit_records_central_telemetry() {
1249        let dir = tempfile::tempdir().unwrap();
1250        let file = dir.path().join("telemetry-hit.rs");
1251        std::fs::write(&file, "fn telemetry_hit() {}\n").unwrap();
1252        let path = file.to_string_lossy();
1253        let mut cache = SessionCache::new();
1254        cache.store(&path, "fn telemetry_hit() {}\n");
1255        cache.mark_full_delivered(&path);
1256
1257        let metrics = crate::core::telemetry::global_metrics();
1258        let before = metrics.cache_hits.load(Ordering::Relaxed);
1259        let output = try_stub_hit_readonly_scoped(&cache, &path, None);
1260        let after = metrics.cache_hits.load(Ordering::Relaxed);
1261
1262        assert!(output.is_some(), "warm re-read must use the stub cache");
1263        assert!(
1264            after > before,
1265            "stub cache hit must increment central telemetry"
1266        );
1267    }
1268
1269    #[test]
1270    fn relay_does_not_poison_session_cache() {
1271        let mut cache = SessionCache::new();
1272        let path = "/tmp/test_relay_poison.rs";
1273        cache.store(path, "original content");
1274        assert_eq!(
1275            cache
1276                .get(path)
1277                .map(|e| e.compressed_outputs.contains_key("cross-agent-relay")),
1278            Some(false),
1279            "cross-agent-relay must not exist in session cache"
1280        );
1281    }
1282    #[test]
1283    fn is_terminal_poll_file_matches_cursor_terminal_paths() {
1284        assert!(is_terminal_poll_file(
1285            "/Users/me/.cursor/projects/Users-me-proj/terminals/12345.txt"
1286        ));
1287        assert!(is_terminal_poll_file(
1288            "/home/dev/.cursor/projects/foo/terminals/857272.txt"
1289        ));
1290        assert!(!is_terminal_poll_file("/Users/me/project/src/main.rs"));
1291        assert!(!is_terminal_poll_file(
1292            "/Users/me/.cursor/projects/foo/agent-transcripts/abc.jsonl"
1293        ));
1294        assert!(!is_terminal_poll_file("/Users/me/.cursor/terminals.log"));
1295    }
1296
1297    #[test]
1298    fn terminal_poll_file_stub_bypasses_conversation_gate() {
1299        let dir = tempfile::tempdir().unwrap();
1300        let terminals_dir = dir.path().join(".cursor").join("proj").join("terminals");
1301        std::fs::create_dir_all(&terminals_dir).unwrap();
1302        let file = terminals_dir.join("252028.txt");
1303        std::fs::write(&file, "---\npid: 1234\n---\nterminal output\n").unwrap();
1304        let path = file.to_string_lossy().to_string();
1305
1306        let mut cache = SessionCache::new();
1307        cache.store(&path, "---\npid: 1234\n---\nterminal output\n");
1308        cache.mark_full_delivered(&path);
1309
1310        // Mismatched conversation normally blocks stub — but terminal files bypass
1311        let output = try_stub_hit_readonly_scoped(&cache, &path, Some("different-conv"));
1312        assert!(
1313            output.is_some(),
1314            "terminal poll file must bypass conversation gate and serve stub"
1315        );
1316    }
1317
1318    #[test]
1319    fn non_terminal_file_respects_conversation_gate() {
1320        if crate::test_env::run_with_conversation_scope(
1321            "tools::ctx_read::dispatch::tests::non_terminal_file_respects_conversation_gate",
1322            true,
1323        ) {
1324            return;
1325        }
1326        let dir = tempfile::tempdir().unwrap();
1327        let file = dir.path().join("main.rs");
1328        std::fs::write(&file, "fn main() {}\n").unwrap();
1329        let path = file.to_string_lossy().to_string();
1330
1331        let mut cache = SessionCache::new();
1332        cache.store(&path, "fn main() {}\n");
1333        cache.mark_full_delivered(&path);
1334        if let Some(entry) = cache.get_mut(&path) {
1335            entry.delivered_conversation = Some("conv-A".to_string());
1336        }
1337
1338        // Mismatched conversation on regular file must block stub
1339        let output = try_stub_hit_readonly_scoped(&cache, &path, Some("conv-B"));
1340        assert!(
1341            output.is_none(),
1342            "regular file must respect conversation gate"
1343        );
1344    }
1345
1346    /// AP05-G6 review: the read's Hot scent was deposited from a worker
1347    /// thread that resolved the project there, outside the request scope.
1348    #[test]
1349    fn hot_scent_of_a_read_lands_in_the_request_project() {
1350        let _data = crate::core::data_dir::isolated_data_dir();
1351        let project = tempfile::tempdir().unwrap();
1352        let other = tempfile::tempdir().unwrap();
1353        let root = project.path().to_str().unwrap();
1354        crate::core::policy::runtime::REQUEST_PROJECT
1355            .sync_scope(
1356                std::cell::RefCell::new(Some(project.path().to_path_buf())),
1357                || super::deposit_hot_scent("src/hot_scent_marker.rs"),
1358            )
1359            .expect("a bound request deposits")
1360            .join()
1361            .unwrap();
1362        assert!(crate::core::scent_field::sync_block(root).contains("hot_scent_marker"));
1363        assert!(crate::core::scent_field::sync_block(other.path().to_str().unwrap()).is_empty());
1364        assert!(super::deposit_hot_scent("src/unbound.rs").is_none());
1365    }
1366}