Skip to main content

lean_ctx_cli/cli/
tee_cmd.rs

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