1use std::path::{Path, PathBuf};
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::time::{SystemTime, UNIX_EPOCH};
30
31pub const EXPAND_OPEN: &str = "<lc_expand:";
33pub const EXPAND_CLOSE: char = '>';
35
36pub const MIN_TEE_BYTES: usize = 512;
39
40const CLEANUP_INTERVAL_SECS: u64 = 600;
43
44const TEE_HASH_LEN: usize = 16;
46const SHELL_TEE_HASH_LEN: usize = 8;
48
49fn 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
62fn 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 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
82pub fn persist(content: &str) -> Option<String> {
88 persist_with(content, "proxy")
89}
90
91pub 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
109fn 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); }
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#[cfg_attr(not(test), allow(dead_code))] pub 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
156pub fn persist_json(content: &str) -> Option<String> {
163 persist_with(content, "json")
164}
165
166pub fn persist_tabular(content: &str) -> Option<String> {
172 persist_with(content, "tbl")
173}
174
175pub fn persist_yaml(content: &str) -> Option<String> {
181 persist_with(content, "yaml")
182}
183
184pub fn persist_html(content: &str) -> Option<String> {
190 persist_with(content, "html")
191}
192
193#[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
246const TEE_PREFIXES: &[&str] = &["proxy", "conv", "json", "tbl", "yaml", "html", "tool"];
250
251fn 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
267fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub enum TeeResolveError {
290 Malformed,
291 Missing,
292 Refused(&'static str),
293}
294
295pub 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 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
370pub fn resolve_tee(id: &str) -> Option<PathBuf> {
372 resolve_tee_checked(id).ok()
373}
374
375pub 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
388pub 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
403pub fn read_tee_file(path: &Path) -> Option<String> {
407 read_checked_tee(path)
408}
409
410pub 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
421pub const LITELLM_HASH_LEN: usize = 24;
425
426pub fn litellm_hash(content: &str) -> String {
433 blake3::hash(content.as_bytes()).to_hex()[..LITELLM_HASH_LEN].to_string()
434}
435
436#[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"))]
454pub mod test_support {
456 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 #[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 #[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 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 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 #[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 #[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 assert!(resolve_tee("/etc/passwd").is_none());
720 assert!(resolve_tee("../../secret").is_none());
721 assert!(resolve_tee("proxy_nothex0000000.log").is_none());
722 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 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 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 assert!(resolve_tee("ref_deadbeefcafef00d").is_none());
860 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 assert_eq!(hash[..16], crate::core::hasher::hash_short(&content));
877 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 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 assert!(retrieve_litellm("../../etc/passwd00000000").is_none());
920 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 assert_eq!(inband_marker(&handle), Some(format!("<lc_expand:{hash}>")));
934 assert!(inband_marker("/tmp/not-a-tee.txt").is_none());
936 }
937
938 #[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}