1pub fn cmd_tee(args: &[String]) {
2 let tee_dir = match crate::core::paths::state_dir() {
3 Ok(d) => d.join("tee"),
4 Err(e) => {
5 eprintln!("Cannot determine state directory: {e}");
6 std::process::exit(1);
7 }
8 };
9
10 let action = args.first().map_or("list", std::string::String::as_str);
11 if !matches!(action, "clear" | "purge") {
12 match crate::core::policy::runtime::with_source_view(
13 crate::core::policy::runtime::is_active,
14 ) {
15 Ok(false) => {}
16 Ok(true) => {
17 eprintln!(
18 "Stored shell output has no source authority; repeat the original authorized operation."
19 );
20 std::process::exit(1);
21 }
22 Err(_) => {
23 eprintln!("Current policy cannot be verified; retry the authorized operation.");
24 std::process::exit(1);
25 }
26 }
27 }
28 match action {
29 "list" | "ls" => {
30 let listing = crate::core::policy::runtime::with_source_view(|| {
33 if crate::core::policy::runtime::is_active() {
34 return Err("Stored shell output has no source authority.".to_string());
35 }
36 if !tee_dir.exists() {
37 return Ok("No tee logs found (~/.lean-ctx/tee/ does not exist)\n".to_string());
38 }
39 let mut entries: Vec<_> = std::fs::read_dir(&tee_dir)
40 .map_err(|_| "Tee metadata is unavailable".to_string())?
41 .filter_map(std::result::Result::ok)
42 .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("log"))
43 .collect();
44 entries.sort_by_key(std::fs::DirEntry::file_name);
45
46 if entries.is_empty() {
47 return Ok("No tee logs found.\n".to_string());
48 }
49
50 let mut output = format!("Tee logs ({}):\n\n", entries.len());
51 for entry in &entries {
52 let size = entry.metadata().map_or(0, |m| m.len());
53 let name = entry.file_name();
54 let size_str = if size > 1024 {
55 format!("{}K", size / 1024)
56 } else {
57 format!("{size}B")
58 };
59 output.push_str(&format!(" {:<60} {}\n", name.to_string_lossy(), size_str));
60 }
61 output.push_str("\nUse 'lean-ctx tee clear' to delete all logs.\n");
62 Ok(output)
63 })
64 .and_then(std::convert::identity);
65 if let Ok(output) = listing {
66 print!("{output}");
67 } else {
68 eprintln!("Tee metadata is unavailable or current policy cannot be verified.");
69 std::process::exit(1);
70 }
71 }
72 "clear" | "purge" => {
73 if !tee_dir.exists() {
74 println!("No tee logs to clear.");
75 return;
76 }
77 let mut count = 0u32;
78 if let Ok(entries) = std::fs::read_dir(&tee_dir) {
79 for entry in entries.flatten() {
80 if entry.path().extension().and_then(|x| x.to_str()) == Some("log")
81 && std::fs::remove_file(entry.path()).is_ok()
82 {
83 count += 1;
84 }
85 }
86 }
87 println!("Cleared {count} tee log(s) from {}", tee_dir.display());
88 }
89 "show" => {
90 let Some(filename) = args.get(1) else {
91 eprintln!("Usage: lean-ctx tee show <filename>");
92 std::process::exit(1);
93 };
94 let fname = filename.as_str();
95 let basename = std::path::Path::new(fname).file_name().unwrap_or_default();
96 if basename.is_empty()
97 || basename != fname
98 || fname == "."
99 || fname == ".."
100 || fname.contains(std::path::MAIN_SEPARATOR)
101 {
102 eprintln!("Error: filename must be a plain basename (no path separators or '..')");
103 std::process::exit(1);
104 }
105 let path = tee_dir.join(basename);
106 match crate::proxy::ccr::read_tee_detailed(&path) {
107 Ok(content) => print!("{content}"),
108 Err(reason) => {
109 eprintln!("{reason}");
110 std::process::exit(1);
111 }
112 }
113 }
114 "last" => {
115 if !tee_dir.exists() {
116 println!("No tee logs found.");
117 return;
118 }
119 let mut entries: Vec<_> = std::fs::read_dir(&tee_dir)
120 .ok()
121 .into_iter()
122 .flat_map(|d| d.filter_map(std::result::Result::ok))
123 .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("log"))
124 .collect();
125 entries.sort_by_key(|e| {
126 e.metadata()
127 .and_then(|m| m.modified())
128 .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
129 });
130 match entries.last() {
131 Some(entry) => {
132 let path = entry.path();
133 match crate::proxy::ccr::read_tee_detailed(&path) {
134 Ok(content) => println!(
135 "--- {} ---\n\n{content}",
136 path.file_name().unwrap_or_default().to_string_lossy()
137 ),
138 Err(reason) => {
139 eprintln!("{reason}");
140 std::process::exit(1);
141 }
142 }
143 }
144 None => println!("No tee logs found."),
145 }
146 }
147 _ => {
148 eprintln!("Usage: lean-ctx tee [list|clear|show <file>|last]");
149 std::process::exit(1);
150 }
151 }
152}
153
154pub fn cmd_filter(args: &[String]) {
155 let action = args.first().map_or("list", std::string::String::as_str);
156 match action {
157 "list" | "ls" => {
158 if let Some(engine) = crate::core::filters::FilterEngine::load() {
159 let rules = engine.list_rules();
160 println!("Loaded {} filter rule(s):\n", rules.len());
161 for rule in &rules {
162 println!("{rule}");
163 }
164 } else {
165 println!("No custom filters found.");
166 println!("Create one: lean-ctx filter init");
167 }
168 }
169 "validate" => {
170 let Some(path) = args.get(1) else {
171 eprintln!("Usage: lean-ctx filter validate <file.toml>");
172 std::process::exit(1);
173 };
174 match crate::core::filters::validate_filter_file(path) {
175 Ok(count) => println!("Valid: {count} rule(s) parsed successfully."),
176 Err(e) => {
177 eprintln!("Validation failed: {e}");
178 std::process::exit(1);
179 }
180 }
181 }
182 "init" => match crate::core::filters::create_example_filter() {
183 Ok(path) => {
184 println!("Created example filter: {path}");
185 println!("Edit it to add your custom compression rules.");
186 }
187 Err(e) => {
188 eprintln!("{e}");
189 std::process::exit(1);
190 }
191 },
192 _ => {
193 eprintln!("Usage: lean-ctx filter [list|validate <file>|init]");
194 std::process::exit(1);
195 }
196 }
197}
198
199pub fn cmd_slow_log(args: &[String]) {
200 use crate::core::slow_log;
201
202 let action = args.first().map_or("list", std::string::String::as_str);
203 match action {
204 "list" | "ls" | "" => println!("{}", slow_log::list()),
205 "clear" | "purge" => println!("{}", slow_log::clear()),
206 _ => {
207 eprintln!("Usage: lean-ctx slow-log [list|clear]");
208 std::process::exit(1);
209 }
210 }
211}