Skip to main content

lean_ctx/core/
ccr.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Content-addressed recovery (CCR) for the proxy's lossy rewrites (#482).
3//!
4//! When the proxy prunes an old `tool_result` from conversation history, the
5//! lossy stub used to say *"re-read the file"* — which is stale-unsafe by
6//! construction: in an agent session files are edited or deleted between turns,
7//! so a re-read returns the *current* bytes (or fails), not the historical
8//! version the conversation actually showed. The model could then silently
9//! reason about the wrong content.
10//!
11//! CCR fixes this by persisting the **verbatim original** to the shared,
12//! content-addressed tee store (`{state}/tee/`, reused from the shell path) and
13//! embedding a **retrieval handle** — the absolute path of that file — in the
14//! stub. These legacy copies have no source authority and are only available
15//! without an active policy. Protected file recovery uses source-bound archives.
16//!
17//! ## Cache-safety (#448)
18//! The handle is the file path, and the path is a pure function of the content
19//! hash ([`crate::core::hasher::hash_short`]). For a fixed pruned message the
20//! handle is therefore byte-identical on every later turn, so the provider
21//! prompt-cache prefix is preserved for available copies. Failed or unauthorized
22//! persistence returns no handle; a deterministic path is not proof of recovery.
23//!
24//! The proxy splices in-band markers back into requests (`proxy::ccr`); the
25//! store, its resolver and its bounded read live here, below every caller.
26
27use std::path::{Path, PathBuf};
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::time::{SystemTime, UNIX_EPOCH};
30
31/// Opening delimiter of an in-band retrieval marker: `<lc_expand:HASH>` (#493).
32pub const EXPAND_OPEN: &str = "<lc_expand:";
33/// Closing delimiter of an in-band retrieval marker.
34pub const EXPAND_CLOSE: char = '>';
35
36/// Originals smaller than this are not worth a tee file + handle; the caller
37/// keeps its plain stub. Matches the spirit of the prune length thresholds.
38pub const MIN_TEE_BYTES: usize = 512;
39
40/// Throttle the O(dir) TTL cleanup so the prune hot path does at most one
41/// directory scan per this interval.
42const CLEANUP_INTERVAL_SECS: u64 = 600;
43
44/// Length of the content hash in a proxy/json tee name ([`hash_short`]).
45const TEE_HASH_LEN: usize = 16;
46/// Length of the command hash in a shell tee name (`shell::redact::save_tee`).
47const SHELL_TEE_HASH_LEN: usize = 8;
48
49/// Deterministic tee path for `content`:
50/// `{state}/tee/{prefix}_{blake3(content)[..16]}.log`. Pure (no I/O) so a stub
51/// embedding it stays byte-stable regardless of filesystem state. `prefix`
52/// segregates the producer (`proxy` for history-prune / live-compression stubs,
53/// `conv` for conversation history messages, `json` for the JSON crusher's
54/// lossy originals, #936) yet keeps one shared
55/// store + one resolver ([`resolve_tee`]).
56fn tee_path(content: &str, prefix: &str) -> Option<PathBuf> {
57    let dir = crate::core::paths::state_dir().ok()?.join("tee");
58    let hash = crate::core::hasher::hash_short(content);
59    Some(dir.join(format!("{prefix}_{hash}.log")))
60}
61
62/// Run the shared 24h TTL cleanup at most once per [`CLEANUP_INTERVAL_SECS`].
63fn maybe_cleanup(tee_dir: &Path) {
64    static LAST: AtomicU64 = AtomicU64::new(0);
65    let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) else {
66        return;
67    };
68    let now = now.as_secs();
69    let last = LAST.load(Ordering::Relaxed);
70    if now.saturating_sub(last) < CLEANUP_INTERVAL_SECS {
71        return;
72    }
73    // Only one thread wins the slot; the rest skip until the next interval.
74    if LAST
75        .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
76        .is_ok()
77    {
78        crate::shell::cleanup_old_tee_logs(tee_dir);
79    }
80}
81
82/// Persist `content` verbatim (best-effort, secret-redacted) to the
83/// content-addressed tee store and return its retrieval handle (the absolute
84/// path). Returns `None` for protected originless data, invalid/oversized input
85/// or persistence failure. Re-persisting identical content keeps the same path;
86/// callers must preserve useful fresh output when no recovery handle is available.
87pub fn persist(content: &str) -> Option<String> {
88    persist_with(content, "proxy")
89}
90
91/// Like [`persist`], but a content-addressed copy that is already on disk is
92/// named as it is: no rewrite, no new relevance registration. A copy the TTL
93/// cleanup removed is written again (self-healing). Under protection nothing
94/// originless is named, existing or not.
95pub fn persist_once(content: &str) -> Option<String> {
96    if content.len() < MIN_TEE_BYTES
97        || crate::core::context_admission::stored::source_authority_required()
98    {
99        return None;
100    }
101    let path = tee_path(content, "proxy")?;
102    if std::fs::symlink_metadata(&path).is_ok_and(|meta| meta.file_type().is_file()) {
103        keep_alive(&path);
104        return Some(path.to_string_lossy().to_string());
105    }
106    persist(content)
107}
108
109/// Expiry rule of the tee store: the 24h TTL of the shared cleanup
110/// (`shell::cleanup_old_tee_logs`, run by every process that writes a tee)
111/// counts from the last time a handle was **handed out**, not from when the
112/// file was first written. [`persist`] already refreshes the mtime on an
113/// identical rewrite; a handle named without a rewrite ([`persist_once`] on a
114/// hit) refreshes it here. A conversation that still carries the handle
115/// re-sends it every turn, so its file stays younger than the TTL as long as
116/// the session is live — even when another process runs the cleanup. The
117/// cleanup itself is unchanged: it cannot know which sessions of other
118/// processes hold a handle, but this rule needs no such knowledge.
119///
120/// No-follow and best-effort: a link is never touched, a failure only means
121/// the copy may expire and be rewritten by the next [`persist_once`].
122fn keep_alive(path: &Path) {
123    let mut options = std::fs::OpenOptions::new();
124    options.write(true);
125    #[cfg(unix)]
126    {
127        use std::os::unix::fs::OpenOptionsExt;
128        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC);
129    }
130    #[cfg(windows)]
131    {
132        use std::os::windows::fs::OpenOptionsExt;
133        options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
134    }
135    if let Ok(file) = options.open(path)
136        && file.metadata().is_ok_and(|meta| meta.is_file())
137    {
138        let _ = file.set_modified(SystemTime::now());
139    }
140}
141
142/// Persist a dropped conversation message under a compact `conv_` handle.
143///
144/// Conversation messages may be short, so unlike tool-output tees this path has
145/// no minimum-size gate. The returned basename is sufficient for `ctx_expand` and
146/// avoids putting machine-specific absolute paths into provider prompts.
147#[cfg_attr(not(test), allow(dead_code))] // conversation tee handle for ctx_expand recovery
148pub fn persist_conversation(content: &str) -> Option<String> {
149    let path = persist_with_min(content, "conv", 1)?;
150    Path::new(&path)
151        .file_name()
152        .and_then(|name| name.to_str())
153        .map(str::to_owned)
154}
155
156/// Persist a JSON crusher's verbatim original (#936) under the `json_` prefix and
157/// return its `{state}/tee/json_{hash}.log` handle. Used by the lossy crush stage
158/// so a dropped column is always recoverable out-of-band via [`resolve_tee`] /
159/// `ctx_expand`, never reconstructed from the (lossy) text. Shares the
160/// content-address and best-effort write contract of [`persist`], so the embedded
161/// handle stays deterministic (cache-safe).
162pub fn persist_json(content: &str) -> Option<String> {
163    persist_with(content, "json")
164}
165
166/// Persist a tabular (CSV/TSV) crusher's verbatim original (#982) under the
167/// `tbl_` prefix and return its `{state}/tee/tbl_{hash}.log` handle. Used by the
168/// lossy column-drop stage so a dropped column is always recoverable out-of-band
169/// via [`resolve_tee`] / `ctx_expand`, never reconstructed from the (lossy) text.
170/// Shares the content-address and best-effort write contract of [`persist`].
171pub fn persist_tabular(content: &str) -> Option<String> {
172    persist_with(content, "tbl")
173}
174
175/// Persist a YAML crusher's verbatim original (#985) under the `yaml_` prefix and
176/// return its `{state}/tee/yaml_{hash}.log` handle. Used by the lossy column-drop
177/// stage so a dropped column is always recoverable out-of-band via [`resolve_tee`]
178/// / `ctx_expand`, never reconstructed from the (lossy) text. Shares the
179/// content-address and best-effort write contract of [`persist`].
180pub fn persist_yaml(content: &str) -> Option<String> {
181    persist_with(content, "yaml")
182}
183
184/// Persist an HTML page's verbatim original (#1124) under the `html_` prefix
185/// and return its `{state}/tee/html_{hash}.log` handle. The extracted markdown
186/// is the compressed form; the full HTML is recoverable via [`resolve_tee`] /
187/// `ctx_expand`. Shares the content-address and best-effort write contract of
188/// [`persist`].
189pub fn persist_html(content: &str) -> Option<String> {
190    persist_with(content, "html")
191}
192
193/// Persist the full definition of a tool whose description the proxy shortened
194/// (K26) under the `tool_` prefix. Returns the basename, like
195/// [`persist_conversation`]: it resolves through `ctx_expand` and keeps a
196/// machine-specific path out of the provider prompt, so the shortened tool
197/// list is the same bytes on every machine and turn.
198#[cfg(feature = "http-server")]
199pub fn persist_tool_definition(content: &str) -> Option<String> {
200    let path = persist_with_min(content, "tool", 1)?;
201    Path::new(&path)
202        .file_name()
203        .and_then(|name| name.to_str())
204        .map(str::to_owned)
205}
206
207fn persist_with(content: &str, prefix: &str) -> Option<String> {
208    persist_with_min(content, prefix, MIN_TEE_BYTES)
209}
210
211fn persist_with_min(content: &str, prefix: &str, min_bytes: usize) -> Option<String> {
212    debug_assert!(
213        TEE_PREFIXES.contains(&prefix),
214        "tee prefix {prefix} must be resolvable (add it to TEE_PREFIXES)"
215    );
216    if content.len() < min_bytes {
217        return None;
218    }
219    let path = tee_path(content, prefix)?;
220    let handle = path.to_string_lossy().to_string();
221    storage::write(&path, content)?;
222    if let Some(dir) = path.parent() {
223        maybe_cleanup(dir);
224    }
225    if path.is_file() {
226        let source_tool = match prefix {
227            "json" | "tbl" | "yaml" => "ctx_read",
228            "html" => "ctx_shell",
229            _ => "proxy",
230        };
231        crate::core::relevance_tracker::register_compressed(
232            handle.clone(),
233            content,
234            source_tool,
235            crate::core::tokens::count_tokens(content),
236            0,
237        );
238    }
239    Some(handle)
240}
241
242fn is_hex(s: &str, len: usize) -> bool {
243    s.len() == len && s.bytes().all(|b| b.is_ascii_hexdigit())
244}
245
246/// Every prefix [`persist_with_min`] writes. The resolver is driven by the same
247/// table, so a new producer can never mint a handle `ctx_expand` rejects
248/// (#1911: `html_` was persisted but unresolvable).
249const TEE_PREFIXES: &[&str] = &["proxy", "conv", "json", "tbl", "yaml", "html", "tool"];
250
251/// Canonical `{prefix}_{16hex}.log` name for a prefixed ([`TEE_PREFIXES`]) or
252/// bare-hash id, or `None`. A bare 16-hex id defaults to the `proxy_` store
253/// (back-compat: that is the only form pre-#936 stubs carry).
254fn canonical_tee_name(name: &str) -> Option<String> {
255    let stem = name.strip_suffix(".log").unwrap_or(name);
256    for prefix in TEE_PREFIXES {
257        if let Some(hash) = stem
258            .strip_prefix(prefix)
259            .and_then(|rest| rest.strip_prefix('_'))
260        {
261            return is_hex(hash, TEE_HASH_LEN).then(|| format!("{prefix}_{hash}.log"));
262        }
263    }
264    is_hex(stem, TEE_HASH_LEN).then(|| format!("proxy_{stem}.log"))
265}
266
267/// True for a shell tee basename `<slug>_<8hex>.log` (`shell::redact::save_tee`):
268/// ends in `.log`, the whole basename is safe (`[A-Za-z0-9_-]`), and the **last**
269/// `_`-segment is exactly 8 hex. The slug itself may contain `_`, so the hash is
270/// matched as the suffix — never the first segment (the documented parsing trap).
271fn is_shell_tee_name(name: &str) -> bool {
272    let Some(stem) = name.strip_suffix(".log") else {
273        return false;
274    };
275    if !stem
276        .bytes()
277        .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
278    {
279        return false;
280    }
281    match stem.rsplit_once('_') {
282        Some((slug, hash)) => !slug.is_empty() && is_hex(hash, SHELL_TEE_HASH_LEN),
283        None => false,
284    }
285}
286
287/// Why a canonical tee handle could not be resolved.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub enum TeeResolveError {
290    Malformed,
291    Missing,
292    Refused(&'static str),
293}
294
295/// Resolve a retrieval ID through the same canonical store path used by
296/// `ctx_expand`, while distinguishing malformed IDs and policy refusals.
297pub fn resolve_tee_checked(id: &str) -> Result<PathBuf, TeeResolveError> {
298    let name = Path::new(id)
299        .file_name()
300        .and_then(|n| n.to_str())
301        .unwrap_or(id);
302    let canon = canonical_tee_name(name)
303        .or_else(|| is_shell_tee_name(name).then(|| name.to_string()))
304        .ok_or(TeeResolveError::Malformed)?;
305    let state_dir = crate::core::paths::state_dir().map_err(|_| TeeResolveError::Missing)?;
306    let tee_dir = state_dir.join("tee");
307    let path = tee_dir.join(canon);
308    // The tee store itself must be a real directory: a `tee` link to another
309    // store (archives, references) would let a tee-shaped name read that store.
310    if std::fs::symlink_metadata(&tee_dir).is_ok_and(|m| m.file_type().is_symlink()) {
311        return Err(TeeResolveError::Refused(
312            "tee store is a symlink to another location",
313        ));
314    }
315
316    let link_metadata = std::fs::symlink_metadata(&path).map_err(|error| {
317        if error.kind() == std::io::ErrorKind::PermissionDenied {
318            TeeResolveError::Refused("tee metadata read refused by filesystem policy")
319        } else {
320            TeeResolveError::Missing
321        }
322    })?;
323    if link_metadata.file_type().is_symlink() {
324        return Err(TeeResolveError::Refused(
325            "tee handles cannot resolve through symlinks",
326        ));
327    }
328    if !link_metadata.is_file() {
329        return Err(TeeResolveError::Missing);
330    }
331
332    let canonical_state = std::fs::canonicalize(&state_dir).map_err(|error| {
333        if error.kind() == std::io::ErrorKind::PermissionDenied {
334            TeeResolveError::Refused("tee store access refused by filesystem policy")
335        } else {
336            TeeResolveError::Missing
337        }
338    })?;
339    let canonical_tee = std::fs::canonicalize(&tee_dir).map_err(|error| {
340        if error.kind() == std::io::ErrorKind::PermissionDenied {
341            TeeResolveError::Refused("tee store access refused by filesystem policy")
342        } else {
343            TeeResolveError::Missing
344        }
345    })?;
346    if canonical_tee != canonical_state.join("tee") {
347        return Err(TeeResolveError::Refused(
348            "tee store resolves outside the state directory",
349        ));
350    }
351
352    let canonical_file = std::fs::canonicalize(&path).map_err(|error| {
353        if error.kind() == std::io::ErrorKind::PermissionDenied {
354            TeeResolveError::Refused("tee read refused by filesystem policy")
355        } else {
356            TeeResolveError::Missing
357        }
358    })?;
359    if !canonical_file.starts_with(&canonical_tee) {
360        return Err(TeeResolveError::Refused(
361            "tee handle resolves outside the tee store",
362        ));
363    }
364    if !canonical_file.is_file() {
365        return Err(TeeResolveError::Missing);
366    }
367    Ok(path)
368}
369
370/// Back-compatible resolver used by `ctx_expand`.
371pub fn resolve_tee(id: &str) -> Option<PathBuf> {
372    resolve_tee_checked(id).ok()
373}
374
375/// The in-band retrieval marker `<lc_expand:HASH>` for a CCR `handle` (#493).
376///
377/// `HASH` is the content hash already embedded in the tee handle, so a model can
378/// echo the marker verbatim and the proxy can recover the original via
379/// [`resolve_tee`] on the next turn. Pure (no I/O, no config) so it is trivially
380/// testable; returns `None` for a handle that is not a canonical tee path.
381pub fn inband_marker(handle: &str) -> Option<String> {
382    let name = Path::new(handle).file_name().and_then(|n| n.to_str())?;
383    let hash = name.strip_prefix("proxy_")?.strip_suffix(".log")?;
384    (hash.len() == 16 && hash.bytes().all(|b| b.is_ascii_hexdigit()))
385        .then(|| format!("{EXPAND_OPEN}{hash}{EXPAND_CLOSE}"))
386}
387
388/// The in-band marker for `handle` **only when in-band CCR is enabled** (#493),
389/// else `None`. Stub sites use this to advertise an echo-able `<lc_expand:HASH>`
390/// solely in in-band mode: a normal (shared-filesystem) deployment keeps its
391/// path handle, so the model never sees a marker the proxy would not splice.
392///
393/// Reads the (process-cached) config; the surrounding stub path already does
394/// per-message tee I/O via [`persist`], so this adds no new I/O class.
395pub fn inband_locator(handle: &str) -> Option<String> {
396    crate::core::config::Config::load()
397        .proxy
398        .ccr_inband_enabled()
399        .then(|| inband_marker(handle))
400        .flatten()
401}
402
403/// Read a tee file that [`resolve_tee`] returned. One read path for every
404/// caller: bounded, no-follow and bound to the checked file, re-checked
405/// against the current policy and re-admitted by the context gateway.
406pub fn read_tee_file(path: &Path) -> Option<String> {
407    read_checked_tee(path)
408}
409
410/// Resolve and read a tee handle in one step.
411pub fn read_tee(id: &str) -> Option<String> {
412    read_tee_file(&resolve_tee(id)?)
413}
414
415pub use storage::{
416    read as read_checked_tee, read_detailed as read_tee_detailed, write as write_tee,
417};
418
419mod storage;
420
421/// Length of a LiteLLM gateway retrieval hash (#702): LiteLLM's headroom
422/// guardrail scans compressed text with `hash=([a-f0-9]{24})`
423/// (BerriAI/litellm#31681), so the marker must carry exactly 24 lowercase hex.
424pub const LITELLM_HASH_LEN: usize = 24;
425
426/// The 24-hex gateway retrieval hash for `content` (#702): the first 24 chars
427/// of the full blake3 hex. A strict extension of the 16-hex tee name
428/// ([`crate::core::hasher::hash_short`] is the same digest truncated to 16),
429/// so `hash[..16]` resolves the tee file while the extra 8 chars keep the
430/// marker collision-resistant on the gateway side. Pure — the marker embedding
431/// it stays byte-stable per content (#498).
432pub fn litellm_hash(content: &str) -> String {
433    blake3::hash(content.as_bytes()).to_hex()[..LITELLM_HASH_LEN].to_string()
434}
435
436/// Resolve a LiteLLM `hash=<24hex>` retrieval id (#702) back to the verbatim
437/// original in the tee store, for `GET /v1/retrieve/{hash}`. Shape-locked to
438/// LiteLLM's own regex (24 lowercase hex — uppercase or any other length is
439/// rejected, never coerced) so only a string the guardrail could actually have
440/// captured resolves; the first 16 chars are the `proxy_` tee content-address.
441#[cfg(feature = "http-server")]
442pub fn retrieve_litellm(hash: &str) -> Option<String> {
443    if hash.len() != LITELLM_HASH_LEN
444        || !hash
445            .bytes()
446            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
447    {
448        return None;
449    }
450    read_tee(&hash[..TEE_HASH_LEN])
451}
452
453#[cfg(any(test, feature = "test-support"))]
454/// Inputs shared by the CCR tests here and in the proxy.
455pub mod test_support {
456    /// `seed` repeated past the tee threshold.
457    pub fn big(seed: &str) -> String {
458        format!("{seed}\n").repeat(40)
459    }
460}
461
462#[cfg(test)]
463pub(crate) mod tests {
464    use super::*;
465
466    pub(crate) use super::test_support::big;
467
468    fn write_gateway_mode(mode: &str) {
469        let config = crate::core::paths::config_dir_read_only().expect("config directory");
470        std::fs::create_dir_all(&config).expect("config directory");
471        std::fs::write(
472            config.join("config.toml"),
473            format!("[context_gateway]\nmode = \"{mode}\"\n"),
474        )
475        .expect("gateway config");
476    }
477
478    /// A stored tee log has no source authority. Governed mode protects
479    /// without any policy pack: the log written in developer mode is then
480    /// neither handed back nor is a new one written, and the refusal says
481    /// nothing about the content. Developer mode keeps its recovery.
482    #[test]
483    fn governed_mode_without_a_pack_neither_serves_nor_writes_an_originless_tee() {
484        let _data = crate::core::data_dir::isolated_data_dir();
485        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
486        write_gateway_mode("developer");
487        let content = big("deploy log line with the marker tee-governed-regression");
488        let handle = persist(&content).expect("developer mode keeps a recovery copy");
489        let path = Path::new(&handle);
490        assert!(
491            read_tee_detailed(path)
492                .expect("developer mode serves it")
493                .contains("tee-governed-regression")
494        );
495
496        write_gateway_mode("governed");
497        let refusal = read_tee_detailed(path).expect_err("governed mode must not serve it");
498        assert!(refusal.contains("no source authority"), "{refusal}");
499        assert!(!refusal.contains("tee-governed-regression"));
500        assert!(read_tee(&handle).is_none());
501        assert!(
502            persist(&big("another originless log line")).is_none(),
503            "governed mode writes no originless copy"
504        );
505
506        write_gateway_mode("developer");
507        assert!(read_tee_detailed(path).is_ok(), "developer mode unchanged");
508    }
509
510    /// Every in-process tee writer resolves its store through
511    /// `paths::state_dir()`, so `LEAN_CTX_STATE_DIR` alone moves it — the
512    /// proxy/json store (`persist`), the resolver (`resolve_tee_checked`) and
513    /// the shell tee (`shell::save_tee`). A `proxy_*.log` in the real
514    /// `~/.local/state/lean-ctx/tee` while the variable is set was written by
515    /// another process: the global proxy daemon, whose LaunchAgent pins the
516    /// layout of the CLI that installed it (`tcc_guard_sandbox`).
517    #[test]
518    fn every_tee_writer_honours_lean_ctx_state_dir() {
519        let _lock = crate::core::data_dir::test_env_lock();
520        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
521        let state = tempfile::tempdir().expect("state dir");
522        let other = tempfile::tempdir().expect("other categories");
523        for var in [
524            "LEAN_CTX_DATA_DIR",
525            "LEAN_CTX_CONFIG_DIR",
526            "LEAN_CTX_CACHE_DIR",
527        ] {
528            crate::test_env::set_var(var, other.path());
529        }
530        crate::test_env::set_var("LEAN_CTX_STATE_DIR", state.path());
531        let tee = state.path().join("tee");
532
533        let proxy = persist(&big("proxy line under an explicit state dir"));
534        let json = persist_json(&big("{\"k\": \"json line under an explicit state dir\"}"));
535        let resolved = proxy.as_deref().map(resolve_tee_checked);
536        let shell = crate::shell::save_tee(
537            "cargo test --lib",
538            &big("shell line under an explicit state dir"),
539        );
540
541        for var in [
542            "LEAN_CTX_STATE_DIR",
543            "LEAN_CTX_DATA_DIR",
544            "LEAN_CTX_CONFIG_DIR",
545            "LEAN_CTX_CACHE_DIR",
546        ] {
547            crate::test_env::remove_var(var);
548        }
549
550        for (writer, handle) in [
551            ("persist", &proxy),
552            ("persist_json", &json),
553            ("save_tee", &shell),
554        ] {
555            let handle = handle
556                .as_deref()
557                .unwrap_or_else(|| panic!("{writer} must write a tee copy"));
558            assert_eq!(
559                Path::new(handle).parent(),
560                Some(tee.as_path()),
561                "{writer} must write under LEAN_CTX_STATE_DIR/tee: {handle}"
562            );
563            assert!(Path::new(handle).is_file(), "{writer}: {handle}");
564        }
565        let resolved = resolved.expect("handle").expect("resolves");
566        assert!(
567            std::fs::canonicalize(&resolved)
568                .expect("resolved file")
569                .starts_with(std::fs::canonicalize(&tee).expect("tee dir")),
570            "resolver must look under LEAN_CTX_STATE_DIR/tee: {}",
571            resolved.display()
572        );
573        assert!(
574            std::fs::read_dir(other.path().join("tee")).is_err(),
575            "nothing lands in the data/config/cache directories"
576        );
577    }
578
579    #[test]
580    fn handle_is_content_addressed_and_deterministic() {
581        let _lock = crate::core::data_dir::test_env_lock();
582        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
583        let content = big("file body line");
584        let a = persist(&content).expect("persisted");
585        let b = persist(&content).expect("persisted again");
586        assert_eq!(
587            a, b,
588            "same content must map to the same handle (cache-safe)"
589        );
590        assert!(a.contains("proxy_"), "handle is a proxy tee path: {a}");
591
592        let other = persist(&big("different body")).expect("persisted");
593        assert_ne!(a, other, "different content must get a different handle");
594    }
595
596    #[test]
597    fn persisted_original_is_recoverable() {
598        let _lock = crate::core::data_dir::test_env_lock();
599        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
600        let content = big("recoverable verbatim line");
601        let handle = persist(&content).expect("persisted");
602        let on_disk = std::fs::read_to_string(&handle).expect("tee file readable");
603        assert!(
604            on_disk.contains("recoverable verbatim line"),
605            "the verbatim original must be retrievable from the handle"
606        );
607    }
608
609    #[test]
610    fn small_content_gets_no_handle() {
611        let _lock = crate::core::data_dir::test_env_lock();
612        assert!(
613            persist("too small to bother").is_none(),
614            "below MIN_TEE_BYTES there is no handle (the caller keeps its plain stub)"
615        );
616    }
617
618    #[test]
619    #[allow(clippy::case_sensitive_file_extension_comparisons)]
620    fn conversation_handle_is_compact_and_deterministic() {
621        let _lock = crate::core::data_dir::test_env_lock();
622        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
623        let a = persist_conversation("{\"role\":\"user\",\"content\":\"hello\"}")
624            .expect("conversation handle");
625        let b = persist_conversation("{\"role\":\"user\",\"content\":\"hello\"}")
626            .expect("conversation handle");
627        assert_eq!(a, b);
628        assert!(a.starts_with("conv_") && a.ends_with(".log"));
629    }
630
631    #[test]
632    fn conversation_handle_resolves_short_messages() {
633        let _lock = crate::core::data_dir::test_env_lock();
634        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
635        let handle = persist_conversation("short conversation message").expect("handle");
636        assert!(resolve_tee(&handle).is_some());
637    }
638
639    #[test]
640    fn conversation_original_is_recoverable() {
641        let _lock = crate::core::data_dir::test_env_lock();
642        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
643        let original = "{\"role\":\"tool\",\"content\":\"recover me\"}";
644        let handle = persist_conversation(original).expect("handle");
645        let path = resolve_tee(&handle).expect("resolved handle");
646        assert_eq!(std::fs::read_to_string(path).unwrap(), original);
647    }
648
649    #[test]
650    fn resolve_tee_accepts_every_stub_form() {
651        let _lock = crate::core::data_dir::test_env_lock();
652        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
653        let content = big("resolvable tee body");
654        let handle = persist(&content).expect("persisted");
655        let hash = crate::core::hasher::hash_short(&content);
656
657        // Full path, bare file name, proxy_<hash>, and bare <hash> all resolve to
658        // the same on-disk file — whatever the agent copied out of the stub.
659        for form in [
660            handle.clone(),
661            format!("proxy_{hash}.log"),
662            format!("proxy_{hash}"),
663            hash.clone(),
664        ] {
665            let resolved = resolve_tee(&form).unwrap_or_else(|| panic!("must resolve {form}"));
666            assert_eq!(
667                resolved.to_string_lossy(),
668                handle,
669                "form {form} -> {handle}"
670            );
671        }
672    }
673
674    /// #1911: the HTML crush's `html_` handle must round-trip through the
675    /// resolver `ctx_expand` uses, in every form the footer can be copied in.
676    #[test]
677    fn persist_html_handle_resolves_in_every_form() {
678        let _lock = crate::core::data_dir::test_env_lock();
679        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
680        let content = big("<p>html crush original</p>");
681        let handle = persist_html(&content).expect("html persisted");
682        let hash = crate::core::hasher::hash_short(&content);
683        for form in [
684            handle.clone(),
685            format!("html_{hash}.log"),
686            format!("html_{hash}"),
687        ] {
688            let resolved = resolve_tee(&form).unwrap_or_else(|| panic!("must resolve {form}"));
689            assert_eq!(resolved.to_string_lossy(), handle, "form {form}");
690        }
691        assert!(
692            std::fs::read_to_string(&handle)
693                .unwrap()
694                .contains("html crush original")
695        );
696    }
697
698    /// Every prefix a producer can write is accepted by the resolver, and a
699    /// prefix without its `_` separator is not.
700    #[test]
701    fn canonical_tee_name_covers_every_producer_prefix() {
702        let hash = "0123456789abcdef";
703        for prefix in TEE_PREFIXES {
704            assert_eq!(
705                canonical_tee_name(&format!("{prefix}_{hash}.log")),
706                Some(format!("{prefix}_{hash}.log"))
707            );
708        }
709        assert_eq!(canonical_tee_name(&format!("html{hash}")), None);
710        assert_eq!(canonical_tee_name("html_nothex000000000"), None);
711    }
712
713    #[test]
714    fn resolve_tee_rejects_nontee_and_traversal_ids() {
715        let _lock = crate::core::data_dir::test_env_lock();
716        // No FS escape: a crafted path is reduced to its file name, which is not a
717        // valid proxy tee name, so it resolves to None instead of reading it.
718        assert!(resolve_tee("/etc/passwd").is_none());
719        assert!(resolve_tee("../../secret").is_none());
720        assert!(resolve_tee("proxy_nothex0000000.log").is_none());
721        // Right shape but no such file in the store.
722        assert!(resolve_tee("deadbeefdeadbeef").is_none());
723    }
724
725    #[test]
726    fn persist_json_is_distinct_prefix_and_resolvable() {
727        let _lock = crate::core::data_dir::test_env_lock();
728        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
729        let content = big("json crusher original");
730        let proxy = persist(&content).expect("proxy persisted");
731        let json = persist_json(&content).expect("json persisted");
732        assert!(
733            json.contains("json_"),
734            "json handle uses json_ prefix: {json}"
735        );
736        assert_ne!(
737            proxy, json,
738            "same content gets distinct files per producer prefix"
739        );
740
741        // The json_ handle resolves through the unified resolver in every form a
742        // stub / footer can carry: full path, bare file name, and bare json_id.
743        let hash = crate::core::hasher::hash_short(&content);
744        for form in [
745            json.clone(),
746            format!("json_{hash}.log"),
747            format!("json_{hash}"),
748        ] {
749            assert_eq!(
750                resolve_tee(&form)
751                    .expect("json form resolves")
752                    .to_string_lossy(),
753                json,
754                "json form {form} -> {json}"
755            );
756        }
757    }
758
759    #[test]
760    fn persist_tabular_is_distinct_prefix_and_resolvable() {
761        let _lock = crate::core::data_dir::test_env_lock();
762        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
763        let content = big("tabular crusher original");
764        let json = persist_json(&content).expect("json persisted");
765        let tbl = persist_tabular(&content).expect("tbl persisted");
766        assert!(
767            tbl.contains("tbl_"),
768            "tabular handle uses tbl_ prefix: {tbl}"
769        );
770        assert_ne!(
771            json, tbl,
772            "same content gets distinct files per producer prefix"
773        );
774
775        let hash = crate::core::hasher::hash_short(&content);
776        for form in [
777            tbl.clone(),
778            format!("tbl_{hash}.log"),
779            format!("tbl_{hash}"),
780        ] {
781            assert_eq!(
782                resolve_tee(&form)
783                    .expect("tbl form resolves")
784                    .to_string_lossy(),
785                tbl,
786                "tbl form {form} -> {tbl}"
787            );
788        }
789    }
790
791    #[test]
792    fn persist_yaml_is_distinct_prefix_and_resolvable() {
793        let _lock = crate::core::data_dir::test_env_lock();
794        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
795        let content = big("yaml crusher original");
796        let tbl = persist_tabular(&content).expect("tbl persisted");
797        let yaml = persist_yaml(&content).expect("yaml persisted");
798        assert!(
799            yaml.contains("yaml_"),
800            "yaml handle uses yaml_ prefix: {yaml}"
801        );
802        assert_ne!(
803            tbl, yaml,
804            "same content gets distinct files per producer prefix"
805        );
806
807        let hash = crate::core::hasher::hash_short(&content);
808        for form in [
809            yaml.clone(),
810            format!("yaml_{hash}.log"),
811            format!("yaml_{hash}"),
812        ] {
813            assert_eq!(
814                resolve_tee(&form)
815                    .expect("yaml form resolves")
816                    .to_string_lossy(),
817                yaml,
818                "yaml form {form} -> {yaml}"
819            );
820        }
821    }
822
823    #[test]
824    fn resolve_tee_resolves_shell_tee_with_underscored_slug() {
825        let _lock = crate::core::data_dir::test_env_lock();
826        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
827        // A real shell command whose slug contains underscores: the hash is the
828        // last `_`-segment (8 hex), never the first — the parsing trap. The full
829        // verbatim output the shell already teed is now surgically retrievable.
830        let path = crate::shell::save_tee("gh api /repos/foo/bar", &big("api row"))
831            .expect("shell tee saved");
832        let name = std::path::Path::new(&path)
833            .file_name()
834            .and_then(|n| n.to_str())
835            .unwrap()
836            .to_string();
837        assert!(
838            is_shell_tee_name(&name),
839            "save_tee name must be recognized as a shell tee: {name}"
840        );
841        for form in [path.clone(), name] {
842            assert_eq!(
843                resolve_tee(&form)
844                    .expect("shell tee form resolves")
845                    .to_string_lossy(),
846                path,
847                "shell tee form -> {path}"
848            );
849        }
850    }
851
852    #[test]
853    fn resolve_tee_does_not_capture_reference_ids() {
854        let _lock = crate::core::data_dir::test_env_lock();
855        // A reference-store id (`ref_<16hex>`, no `.log`) must fall through the
856        // tee resolver so ctx_expand routes it to the reference store, not the
857        // tee store — the precedence guard for the unified retrieve ladder.
858        assert!(resolve_tee("ref_deadbeefcafef00d").is_none());
859        // A bare 16-hex archive id with no backing tee file also stays None.
860        assert!(resolve_tee("0123456789abcdef").is_none());
861    }
862
863    #[test]
864    fn litellm_hash_is_24_lowercase_hex_and_extends_tee_hash() {
865        let content = big("gateway retrieval body");
866        let hash = litellm_hash(&content);
867        assert_eq!(hash.len(), LITELLM_HASH_LEN);
868        assert!(
869            hash.bytes()
870                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
871            "must match LiteLLM's [a-f0-9]{{24}} class: {hash}"
872        );
873        // Same blake3 digest as the tee name, longer prefix: the first 16 chars
874        // ARE the tee content-address, which is what makes retrieval work.
875        assert_eq!(hash[..16], crate::core::hasher::hash_short(&content));
876        // Pure function of content (#498): stable across calls.
877        assert_eq!(hash, litellm_hash(&content));
878    }
879
880    #[cfg(feature = "http-server")]
881    #[test]
882    fn retrieve_litellm_resolves_persisted_content() {
883        let _lock = crate::core::data_dir::test_env_lock();
884        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
885        let content = big("litellm retrievable original");
886        persist(&content).expect("persisted");
887        let recovered =
888            retrieve_litellm(&litellm_hash(&content)).expect("24-hex hash must resolve");
889        assert!(recovered.contains("litellm retrievable original"));
890    }
891
892    #[cfg(feature = "http-server")]
893    #[test]
894    fn retrieve_litellm_is_shape_locked_to_the_guardrail_regex() {
895        let _lock = crate::core::data_dir::test_env_lock();
896        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
897        let content = big("shape locked body");
898        persist(&content).expect("persisted");
899        let hash = litellm_hash(&content);
900
901        // 16-hex (our tee id), truncated, extended, uppercased, non-hex: all
902        // rejected — only the exact shape LiteLLM's regex captures resolves.
903        assert!(retrieve_litellm(&hash[..16]).is_none(), "16-hex rejected");
904        assert!(retrieve_litellm(&hash[..23]).is_none(), "23-hex rejected");
905        assert!(
906            retrieve_litellm(&format!("{hash}0")).is_none(),
907            "25-hex rejected"
908        );
909        assert!(
910            retrieve_litellm(&hash.to_uppercase()).is_none(),
911            "uppercase rejected (regex class is [a-f0-9])"
912        );
913        assert!(
914            retrieve_litellm("zzzzzzzzzzzzzzzzzzzzzzzz").is_none(),
915            "non-hex rejected"
916        );
917        // Traversal attempts die in resolve_tee's name canonicalization.
918        assert!(retrieve_litellm("../../etc/passwd00000000").is_none());
919        // Right shape, unknown content.
920        assert!(retrieve_litellm("0123456789abcdef01234567").is_none());
921    }
922
923    #[test]
924    fn inband_marker_is_derived_from_handle() {
925        let _lock = crate::core::data_dir::test_env_lock();
926        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
927        let content = big("inband marker body");
928        let handle = persist(&content).expect("persisted");
929        let hash = crate::core::hasher::hash_short(&content);
930        // The marker carries the same content hash the handle does, so a model can
931        // echo it and the proxy resolves it back to the very same tee file.
932        assert_eq!(inband_marker(&handle), Some(format!("<lc_expand:{hash}>")));
933        // A non-tee handle has no marker.
934        assert!(inband_marker("/tmp/not-a-tee.txt").is_none());
935    }
936
937    /// A handle a live session still carries must survive the shared 24h
938    /// cleanup: naming it again (`persist_once` on a hit, as session elision
939    /// does every turn) restarts its TTL, so a cleanup run by any process
940    /// right after leaves it in place. A copy no session named again expires.
941    #[test]
942    fn a_handle_named_again_is_not_expired_by_the_cleanup() {
943        let _data = crate::core::data_dir::isolated_data_dir();
944        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
945        let stale_time = SystemTime::now() - std::time::Duration::from_hours(30);
946        let age = |path: &Path| {
947            std::fs::OpenOptions::new()
948                .write(true)
949                .open(path)
950                .expect("tee file")
951                .set_modified(stale_time)
952                .expect("age the tee file");
953        };
954
955        let live = big("line of a session that is still running");
956        let live_handle = persist_once(&live).expect("first copy");
957        let gone = big("line of a session that ended a day ago");
958        let gone_handle = persist_once(&gone).expect("first copy");
959        age(Path::new(&live_handle));
960        age(Path::new(&gone_handle));
961
962        assert_eq!(persist_once(&live).as_deref(), Some(live_handle.as_str()));
963        let tee_dir = Path::new(&live_handle).parent().expect("tee dir");
964        crate::shell::cleanup_old_tee_logs(tee_dir);
965
966        assert!(
967            Path::new(&live_handle).is_file(),
968            "a handle named again keeps its file"
969        );
970        assert!(
971            !Path::new(&gone_handle).exists(),
972            "a copy nobody named for longer than the TTL expires"
973        );
974    }
975}