1pub fn save_tee(command: &str, output: &str) -> Option<String> {
10 if crate::core::policy::runtime::is_active() {
13 return None;
14 }
15 let command = crate::core::policy::content::protect_active(command).ok()?;
17 let output = crate::core::policy::content::protect_active(output).ok()?;
18 let command = command.as_ref();
19 let output = output.as_ref();
20 let tee_dir = crate::core::paths::state_dir().ok()?.join("tee");
21 crate::core::secure_fs::private_dir(&tee_dir).ok()?;
24
25 if let Ok(now) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)
32 && TEE_CLEANUP_THROTTLE.is_due(now.as_secs())
33 {
34 cleanup_old_tee_logs(&tee_dir);
35 }
36
37 let cmd_slug: String = command
38 .chars()
39 .take(40)
40 .map(|c| {
41 if c.is_alphanumeric() || c == '-' {
42 c
43 } else {
44 '_'
45 }
46 })
47 .collect();
48 let cmd_hash = blake3::hash(command.as_bytes()).to_hex();
53 let filename = format!("{cmd_slug}_{}.log", &cmd_hash.as_str()[..8]);
54 let path = tee_dir.join(&filename);
55
56 crate::core::ccr::write_tee(&path, output)?;
57 let handle = path.to_string_lossy().to_string();
58 crate::core::relevance_tracker::register_compressed(
59 handle.clone(),
60 output,
61 "ctx_shell",
62 crate::core::tokens::count_tokens(output),
63 0,
64 );
65 Some(handle)
66}
67
68struct CleanupThrottle {
72 last_run_unix_secs: std::sync::atomic::AtomicU64,
73 interval_secs: u64,
74}
75
76impl CleanupThrottle {
77 const fn new(interval_secs: u64) -> Self {
78 Self {
79 last_run_unix_secs: std::sync::atomic::AtomicU64::new(0),
80 interval_secs,
81 }
82 }
83
84 fn is_due(&self, now_unix_secs: u64) -> bool {
87 use std::sync::atomic::Ordering;
88 let last = self.last_run_unix_secs.load(Ordering::Relaxed);
89 let due = last == 0 || now_unix_secs.saturating_sub(last) >= self.interval_secs;
90 due && self
91 .last_run_unix_secs
92 .compare_exchange(last, now_unix_secs, Ordering::Relaxed, Ordering::Relaxed)
93 .is_ok()
94 }
95}
96
97static TEE_CLEANUP_THROTTLE: CleanupThrottle = CleanupThrottle::new(10 * 60);
98
99pub(crate) fn cleanup_old_tee_logs(tee_dir: &std::path::Path) {
103 let cutoff = std::time::SystemTime::now().checked_sub(std::time::Duration::from_hours(24));
104 let Some(cutoff) = cutoff else { return };
105
106 if let Ok(entries) = std::fs::read_dir(tee_dir) {
107 for entry in entries.flatten() {
108 if let Ok(meta) = entry.metadata()
109 && let Ok(modified) = meta.modified()
110 && modified < cutoff
111 {
112 let _ = std::fs::remove_file(entry.path());
113 }
114 }
115 }
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121
122 #[test]
125 fn cleanup_throttle_gates_by_interval() {
126 let throttle = CleanupThrottle::new(600);
127 assert!(
128 throttle.is_due(1_000),
129 "never run before: first call is always due"
130 );
131 assert!(
132 !throttle.is_due(1_100),
133 "only 100s elapsed of a 600s interval"
134 );
135 assert!(!throttle.is_due(1_599), "still short of the interval by 1s");
136 assert!(
137 throttle.is_due(1_600),
138 "exactly interval-elapsed must be due again"
139 );
140 }
141
142 #[test]
143 fn cleanup_throttle_lets_only_one_racer_through_per_interval() {
144 let throttle = CleanupThrottle::new(600);
145 let hits = std::thread::scope(|scope| {
146 let handles: Vec<_> = (0..16)
147 .map(|_| scope.spawn(|| throttle.is_due(1_000)))
148 .collect();
149 handles
150 .into_iter()
151 .map(|h| h.join().unwrap())
152 .filter(|&due| due)
153 .count()
154 });
155 assert_eq!(hits, 1, "exactly one racer should win the cleanup slot");
156 }
157
158 #[test]
162 fn tee_path_is_content_addressed() {
163 let _lock = crate::core::data_dir::test_env_lock();
166 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
167 let first = save_tee("cargo test --lib", "output run 1").expect("tee saved");
168 let second = save_tee("cargo test --lib", "output run 2").expect("tee saved");
169 assert_eq!(first, second, "same command must map to the same tee path");
170
171 let other = save_tee("cargo build", "output").expect("tee saved");
172 assert_ne!(first, other, "different commands get different tee paths");
173
174 let content = std::fs::read_to_string(&second).unwrap();
176 assert!(content.contains("run 2"));
177
178 for p in [first, other] {
179 let _ = std::fs::remove_file(p);
180 }
181 }
182
183 #[cfg(unix)]
186 #[test]
187 fn tee_dir_is_owner_only() {
188 use std::os::unix::fs::PermissionsExt as _;
189 let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
190 let _isolated = crate::core::data_dir::isolated_data_dir();
191 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
192
193 let log = std::path::PathBuf::from(save_tee("echo tee-perms", "out").expect("tee saved"));
194 let dir = log.parent().unwrap().to_path_buf();
195 assert_eq!(mode(&dir), 0o700, "new tee dir must be owner-only");
196 assert_eq!(mode(&log), 0o600, "tee log must be owner-only");
197
198 std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
199 save_tee("echo tee-perms", "out 2").expect("tee saved");
200 assert_eq!(mode(&dir), 0o700, "existing wide tee dir must be tightened");
201 }
202}