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        let other_path = other.path().to_str().expect("utf-8 temp path");
524        // Each guard holds the (reentrant) test env lock and restores the
525        // previous value on drop, also when an assertion below panics.
526        let (resolved, proxy, json, shell, tee) = {
527            let _env: Vec<_> = [
528                "LEAN_CTX_DATA_DIR",
529                "LEAN_CTX_CONFIG_DIR",
530                "LEAN_CTX_CACHE_DIR",
531            ]
532            .into_iter()
533            .map(|var| crate::test_env::EnvVarGuard::set(var, other_path))
534            .chain(std::iter::once(crate::test_env::EnvVarGuard::set(
535                "LEAN_CTX_STATE_DIR",
536                state.path().to_str().expect("utf-8 temp path"),
537            )))
538            .collect();
539            let tee = state.path().join("tee");
540
541            let proxy = persist(&big("proxy line under an explicit state dir"));
542            let json = persist_json(&big("{\"k\": \"json line under an explicit state dir\"}"));
543            let resolved = proxy.as_deref().map(resolve_tee_checked);
544            let shell = crate::shell::save_tee(
545                "cargo test --lib",
546                &big("shell line under an explicit state dir"),
547            );
548            (resolved, proxy, json, shell, tee)
549        };
550
551        for (writer, handle) in [
552            ("persist", &proxy),
553            ("persist_json", &json),
554            ("save_tee", &shell),
555        ] {
556            let handle = handle
557                .as_deref()
558                .unwrap_or_else(|| panic!("{writer} must write a tee copy"));
559            assert_eq!(
560                Path::new(handle).parent(),
561                Some(tee.as_path()),
562                "{writer} must write under LEAN_CTX_STATE_DIR/tee: {handle}"
563            );
564            assert!(Path::new(handle).is_file(), "{writer}: {handle}");
565        }
566        let resolved = resolved.expect("handle").expect("resolves");
567        assert!(
568            std::fs::canonicalize(&resolved)
569                .expect("resolved file")
570                .starts_with(std::fs::canonicalize(&tee).expect("tee dir")),
571            "resolver must look under LEAN_CTX_STATE_DIR/tee: {}",
572            resolved.display()
573        );
574        assert!(
575            std::fs::read_dir(other.path().join("tee")).is_err(),
576            "nothing lands in the data/config/cache directories"
577        );
578    }
579
580    #[test]
581    fn handle_is_content_addressed_and_deterministic() {
582        let _lock = crate::core::data_dir::test_env_lock();
583        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
584        let content = big("file body line");
585        let a = persist(&content).expect("persisted");
586        let b = persist(&content).expect("persisted again");
587        assert_eq!(
588            a, b,
589            "same content must map to the same handle (cache-safe)"
590        );
591        assert!(a.contains("proxy_"), "handle is a proxy tee path: {a}");
592
593        let other = persist(&big("different body")).expect("persisted");
594        assert_ne!(a, other, "different content must get a different handle");
595    }
596
597    #[test]
598    fn persisted_original_is_recoverable() {
599        let _lock = crate::core::data_dir::test_env_lock();
600        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
601        let content = big("recoverable verbatim line");
602        let handle = persist(&content).expect("persisted");
603        let on_disk = std::fs::read_to_string(&handle).expect("tee file readable");
604        assert!(
605            on_disk.contains("recoverable verbatim line"),
606            "the verbatim original must be retrievable from the handle"
607        );
608    }
609
610    #[test]
611    fn small_content_gets_no_handle() {
612        let _lock = crate::core::data_dir::test_env_lock();
613        assert!(
614            persist("too small to bother").is_none(),
615            "below MIN_TEE_BYTES there is no handle (the caller keeps its plain stub)"
616        );
617    }
618
619    #[test]
620    #[allow(clippy::case_sensitive_file_extension_comparisons)]
621    fn conversation_handle_is_compact_and_deterministic() {
622        let _lock = crate::core::data_dir::test_env_lock();
623        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
624        let a = persist_conversation("{\"role\":\"user\",\"content\":\"hello\"}")
625            .expect("conversation handle");
626        let b = persist_conversation("{\"role\":\"user\",\"content\":\"hello\"}")
627            .expect("conversation handle");
628        assert_eq!(a, b);
629        assert!(a.starts_with("conv_") && a.ends_with(".log"));
630    }
631
632    #[test]
633    fn conversation_handle_resolves_short_messages() {
634        let _lock = crate::core::data_dir::test_env_lock();
635        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
636        let handle = persist_conversation("short conversation message").expect("handle");
637        assert!(resolve_tee(&handle).is_some());
638    }
639
640    #[test]
641    fn conversation_original_is_recoverable() {
642        let _lock = crate::core::data_dir::test_env_lock();
643        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
644        let original = "{\"role\":\"tool\",\"content\":\"recover me\"}";
645        let handle = persist_conversation(original).expect("handle");
646        let path = resolve_tee(&handle).expect("resolved handle");
647        assert_eq!(std::fs::read_to_string(path).unwrap(), original);
648    }
649
650    #[test]
651    fn resolve_tee_accepts_every_stub_form() {
652        let _lock = crate::core::data_dir::test_env_lock();
653        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
654        let content = big("resolvable tee body");
655        let handle = persist(&content).expect("persisted");
656        let hash = crate::core::hasher::hash_short(&content);
657
658        // Full path, bare file name, proxy_<hash>, and bare <hash> all resolve to
659        // the same on-disk file — whatever the agent copied out of the stub.
660        for form in [
661            handle.clone(),
662            format!("proxy_{hash}.log"),
663            format!("proxy_{hash}"),
664            hash.clone(),
665        ] {
666            let resolved = resolve_tee(&form).unwrap_or_else(|| panic!("must resolve {form}"));
667            assert_eq!(
668                resolved.to_string_lossy(),
669                handle,
670                "form {form} -> {handle}"
671            );
672        }
673    }
674
675    /// #1911: the HTML crush's `html_` handle must round-trip through the
676    /// resolver `ctx_expand` uses, in every form the footer can be copied in.
677    #[test]
678    fn persist_html_handle_resolves_in_every_form() {
679        let _lock = crate::core::data_dir::test_env_lock();
680        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
681        let content = big("<p>html crush original</p>");
682        let handle = persist_html(&content).expect("html persisted");
683        let hash = crate::core::hasher::hash_short(&content);
684        for form in [
685            handle.clone(),
686            format!("html_{hash}.log"),
687            format!("html_{hash}"),
688        ] {
689            let resolved = resolve_tee(&form).unwrap_or_else(|| panic!("must resolve {form}"));
690            assert_eq!(resolved.to_string_lossy(), handle, "form {form}");
691        }
692        assert!(
693            std::fs::read_to_string(&handle)
694                .unwrap()
695                .contains("html crush original")
696        );
697    }
698
699    /// Every prefix a producer can write is accepted by the resolver, and a
700    /// prefix without its `_` separator is not.
701    #[test]
702    fn canonical_tee_name_covers_every_producer_prefix() {
703        let hash = "0123456789abcdef";
704        for prefix in TEE_PREFIXES {
705            assert_eq!(
706                canonical_tee_name(&format!("{prefix}_{hash}.log")),
707                Some(format!("{prefix}_{hash}.log"))
708            );
709        }
710        assert_eq!(canonical_tee_name(&format!("html{hash}")), None);
711        assert_eq!(canonical_tee_name("html_nothex000000000"), None);
712    }
713
714    #[test]
715    fn resolve_tee_rejects_nontee_and_traversal_ids() {
716        let _lock = crate::core::data_dir::test_env_lock();
717        // No FS escape: a crafted path is reduced to its file name, which is not a
718        // valid proxy tee name, so it resolves to None instead of reading it.
719        assert!(resolve_tee("/etc/passwd").is_none());
720        assert!(resolve_tee("../../secret").is_none());
721        assert!(resolve_tee("proxy_nothex0000000.log").is_none());
722        // Right shape but no such file in the store.
723        assert!(resolve_tee("deadbeefdeadbeef").is_none());
724    }
725
726    #[test]
727    fn persist_json_is_distinct_prefix_and_resolvable() {
728        let _lock = crate::core::data_dir::test_env_lock();
729        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
730        let content = big("json crusher original");
731        let proxy = persist(&content).expect("proxy persisted");
732        let json = persist_json(&content).expect("json persisted");
733        assert!(
734            json.contains("json_"),
735            "json handle uses json_ prefix: {json}"
736        );
737        assert_ne!(
738            proxy, json,
739            "same content gets distinct files per producer prefix"
740        );
741
742        // The json_ handle resolves through the unified resolver in every form a
743        // stub / footer can carry: full path, bare file name, and bare json_id.
744        let hash = crate::core::hasher::hash_short(&content);
745        for form in [
746            json.clone(),
747            format!("json_{hash}.log"),
748            format!("json_{hash}"),
749        ] {
750            assert_eq!(
751                resolve_tee(&form)
752                    .expect("json form resolves")
753                    .to_string_lossy(),
754                json,
755                "json form {form} -> {json}"
756            );
757        }
758    }
759
760    #[test]
761    fn persist_tabular_is_distinct_prefix_and_resolvable() {
762        let _lock = crate::core::data_dir::test_env_lock();
763        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
764        let content = big("tabular crusher original");
765        let json = persist_json(&content).expect("json persisted");
766        let tbl = persist_tabular(&content).expect("tbl persisted");
767        assert!(
768            tbl.contains("tbl_"),
769            "tabular handle uses tbl_ prefix: {tbl}"
770        );
771        assert_ne!(
772            json, tbl,
773            "same content gets distinct files per producer prefix"
774        );
775
776        let hash = crate::core::hasher::hash_short(&content);
777        for form in [
778            tbl.clone(),
779            format!("tbl_{hash}.log"),
780            format!("tbl_{hash}"),
781        ] {
782            assert_eq!(
783                resolve_tee(&form)
784                    .expect("tbl form resolves")
785                    .to_string_lossy(),
786                tbl,
787                "tbl form {form} -> {tbl}"
788            );
789        }
790    }
791
792    #[test]
793    fn persist_yaml_is_distinct_prefix_and_resolvable() {
794        let _lock = crate::core::data_dir::test_env_lock();
795        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
796        let content = big("yaml crusher original");
797        let tbl = persist_tabular(&content).expect("tbl persisted");
798        let yaml = persist_yaml(&content).expect("yaml persisted");
799        assert!(
800            yaml.contains("yaml_"),
801            "yaml handle uses yaml_ prefix: {yaml}"
802        );
803        assert_ne!(
804            tbl, yaml,
805            "same content gets distinct files per producer prefix"
806        );
807
808        let hash = crate::core::hasher::hash_short(&content);
809        for form in [
810            yaml.clone(),
811            format!("yaml_{hash}.log"),
812            format!("yaml_{hash}"),
813        ] {
814            assert_eq!(
815                resolve_tee(&form)
816                    .expect("yaml form resolves")
817                    .to_string_lossy(),
818                yaml,
819                "yaml form {form} -> {yaml}"
820            );
821        }
822    }
823
824    #[test]
825    fn resolve_tee_resolves_shell_tee_with_underscored_slug() {
826        let _lock = crate::core::data_dir::test_env_lock();
827        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
828        // A real shell command whose slug contains underscores: the hash is the
829        // last `_`-segment (8 hex), never the first — the parsing trap. The full
830        // verbatim output the shell already teed is now surgically retrievable.
831        let path = crate::shell::save_tee("gh api /repos/foo/bar", &big("api row"))
832            .expect("shell tee saved");
833        let name = std::path::Path::new(&path)
834            .file_name()
835            .and_then(|n| n.to_str())
836            .unwrap()
837            .to_string();
838        assert!(
839            is_shell_tee_name(&name),
840            "save_tee name must be recognized as a shell tee: {name}"
841        );
842        for form in [path.clone(), name] {
843            assert_eq!(
844                resolve_tee(&form)
845                    .expect("shell tee form resolves")
846                    .to_string_lossy(),
847                path,
848                "shell tee form -> {path}"
849            );
850        }
851    }
852
853    #[test]
854    fn resolve_tee_does_not_capture_reference_ids() {
855        let _lock = crate::core::data_dir::test_env_lock();
856        // A reference-store id (`ref_<16hex>`, no `.log`) must fall through the
857        // tee resolver so ctx_expand routes it to the reference store, not the
858        // tee store — the precedence guard for the unified retrieve ladder.
859        assert!(resolve_tee("ref_deadbeefcafef00d").is_none());
860        // A bare 16-hex archive id with no backing tee file also stays None.
861        assert!(resolve_tee("0123456789abcdef").is_none());
862    }
863
864    #[test]
865    fn litellm_hash_is_24_lowercase_hex_and_extends_tee_hash() {
866        let content = big("gateway retrieval body");
867        let hash = litellm_hash(&content);
868        assert_eq!(hash.len(), LITELLM_HASH_LEN);
869        assert!(
870            hash.bytes()
871                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
872            "must match LiteLLM's [a-f0-9]{{24}} class: {hash}"
873        );
874        // Same blake3 digest as the tee name, longer prefix: the first 16 chars
875        // ARE the tee content-address, which is what makes retrieval work.
876        assert_eq!(hash[..16], crate::core::hasher::hash_short(&content));
877        // Pure function of content (#498): stable across calls.
878        assert_eq!(hash, litellm_hash(&content));
879    }
880
881    #[cfg(feature = "http-server")]
882    #[test]
883    fn retrieve_litellm_resolves_persisted_content() {
884        let _lock = crate::core::data_dir::test_env_lock();
885        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
886        let content = big("litellm retrievable original");
887        persist(&content).expect("persisted");
888        let recovered =
889            retrieve_litellm(&litellm_hash(&content)).expect("24-hex hash must resolve");
890        assert!(recovered.contains("litellm retrievable original"));
891    }
892
893    #[cfg(feature = "http-server")]
894    #[test]
895    fn retrieve_litellm_is_shape_locked_to_the_guardrail_regex() {
896        let _lock = crate::core::data_dir::test_env_lock();
897        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
898        let content = big("shape locked body");
899        persist(&content).expect("persisted");
900        let hash = litellm_hash(&content);
901
902        // 16-hex (our tee id), truncated, extended, uppercased, non-hex: all
903        // rejected — only the exact shape LiteLLM's regex captures resolves.
904        assert!(retrieve_litellm(&hash[..16]).is_none(), "16-hex rejected");
905        assert!(retrieve_litellm(&hash[..23]).is_none(), "23-hex rejected");
906        assert!(
907            retrieve_litellm(&format!("{hash}0")).is_none(),
908            "25-hex rejected"
909        );
910        assert!(
911            retrieve_litellm(&hash.to_uppercase()).is_none(),
912            "uppercase rejected (regex class is [a-f0-9])"
913        );
914        assert!(
915            retrieve_litellm("zzzzzzzzzzzzzzzzzzzzzzzz").is_none(),
916            "non-hex rejected"
917        );
918        // Traversal attempts die in resolve_tee's name canonicalization.
919        assert!(retrieve_litellm("../../etc/passwd00000000").is_none());
920        // Right shape, unknown content.
921        assert!(retrieve_litellm("0123456789abcdef01234567").is_none());
922    }
923
924    #[test]
925    fn inband_marker_is_derived_from_handle() {
926        let _lock = crate::core::data_dir::test_env_lock();
927        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
928        let content = big("inband marker body");
929        let handle = persist(&content).expect("persisted");
930        let hash = crate::core::hasher::hash_short(&content);
931        // The marker carries the same content hash the handle does, so a model can
932        // echo it and the proxy resolves it back to the very same tee file.
933        assert_eq!(inband_marker(&handle), Some(format!("<lc_expand:{hash}>")));
934        // A non-tee handle has no marker.
935        assert!(inband_marker("/tmp/not-a-tee.txt").is_none());
936    }
937
938    /// A handle a live session still carries must survive the shared 24h
939    /// cleanup: naming it again (`persist_once` on a hit, as session elision
940    /// does every turn) restarts its TTL, so a cleanup run by any process
941    /// right after leaves it in place. A copy no session named again expires.
942    #[test]
943    fn a_handle_named_again_is_not_expired_by_the_cleanup() {
944        let _data = crate::core::data_dir::isolated_data_dir();
945        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
946        let stale_time = SystemTime::now() - std::time::Duration::from_hours(30);
947        let age = |path: &Path| {
948            std::fs::OpenOptions::new()
949                .write(true)
950                .open(path)
951                .expect("tee file")
952                .set_modified(stale_time)
953                .expect("age the tee file");
954        };
955
956        let live = big("line of a session that is still running");
957        let live_handle = persist_once(&live).expect("first copy");
958        let gone = big("line of a session that ended a day ago");
959        let gone_handle = persist_once(&gone).expect("first copy");
960        age(Path::new(&live_handle));
961        age(Path::new(&gone_handle));
962
963        assert_eq!(persist_once(&live).as_deref(), Some(live_handle.as_str()));
964        let tee_dir = Path::new(&live_handle).parent().expect("tee dir");
965        crate::shell::cleanup_old_tee_logs(tee_dir);
966
967        assert!(
968            Path::new(&live_handle).is_file(),
969            "a handle named again keeps its file"
970        );
971        assert!(
972            !Path::new(&gone_handle).exists(),
973            "a copy nobody named for longer than the TTL expires"
974        );
975    }
976}