1pub use lean_ctx_patterns::*;
9
10pub fn output_class(command: &str) -> crate::core::context_admission::origin::SourceClass {
15 crate::core::context_admission::tool_output::classify(command).map_or(
16 crate::core::context_admission::origin::SourceClass::Project,
17 |found| found.class(),
18 )
19}
20
21pub fn compress_output(command: &str, output: &str) -> Option<String> {
24 let policy = crate::shell::output_policy::classify(command, &[]);
29 if policy.is_protected() {
30 return None;
31 }
32 let command = strip_leading_cd(command);
33
34 let stripped;
35 let clean_output = {
36 let s = crate::core::compressor::strip_ansi(output);
37 if s.len() < output.len() {
38 stripped = s;
39 &stripped
40 } else {
41 output
42 }
43 };
44
45 if let Some(engine) = crate::core::filters::FilterEngine::load()
46 && let Some(filtered) = engine.apply(command, clean_output)
47 {
48 return shorter_only(filtered, output);
49 }
50
51 compress_clean(&EngineEnv, command, clean_output, output)
52}
53
54pub fn try_specific_pattern(cmd: &str, output: &str) -> Option<String> {
56 try_specific_pattern_with(&EngineEnv, cmd, output)
57}
58
59pub(crate) fn strip_leading_cd(command: &str) -> &str {
64 use crate::core::shell_allowlist::Separator;
65 let segments = crate::core::shell_allowlist::segments_with_separators(command);
66 let [(first, Some(Separator::And)), (rest, None)] = segments.as_slice() else {
67 return command;
68 };
69 let is_plain_cd = first
70 .strip_prefix("cd ")
71 .is_some_and(|dir| !dir.trim().is_empty() && !dir.contains(['$', '`', '(']));
72 if !is_plain_cd {
73 return command;
74 }
75 command
76 .rfind(rest.as_str())
77 .map_or(command, |at| &command[at..])
78}
79
80struct EngineEnv;
83
84impl PatternEnv for EngineEnv {
85 fn is_curl_passthrough(&self, command: &str) -> bool {
86 let cfg = crate::core::config::Config::load();
87 curl::is_passthrough(command, &cfg.passthrough_urls)
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use super::*;
94 use crate::core::tokens::count_tokens;
95
96 #[test]
97 fn routes_git_commands() {
98 let output = "On branch main\nnothing to commit";
99 assert!(compress_output("git status", output).is_some());
100 }
101
102 #[test]
103 fn vcs_path_never_inflates_tokens() {
104 let output = " Abu a\nAa aa_A00A\n\n-";
110 if let Some(compressed) = compress_output("git status", output) {
111 assert!(
112 count_tokens(&compressed) <= count_tokens(output),
113 "VCS compress inflated: {} > {}",
114 count_tokens(&compressed),
115 count_tokens(output),
116 );
117 }
118 }
119
120 #[test]
121 fn routes_cargo_commands() {
122 let output = " Compiling lean-ctx v2.1.1\n Finished `release` profile [optimized] target(s) in 30.5s";
123 assert!(compress_output("cargo build --release", output).is_some());
124 }
125
126 #[test]
127 fn routes_npm_commands() {
128 let output = "added 150 packages, and audited 151 packages in 5s\n\n25 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities";
129 assert!(compress_output("npm install", output).is_some());
130 }
131
132 #[test]
133 fn routes_docker_commands() {
134 let output = "CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES";
135 assert!(compress_output("docker ps", output).is_none());
138 let build_output =
139 "Step 1/5 : FROM node:18\n ---> abc123\nStep 2/5 : COPY . .\nSuccessfully built def456";
140 assert!(compress_output("docker build .", build_output).is_some());
141 }
142
143 #[test]
144 fn routes_mypy_commands() {
145 let output = "src/main.py:10: error: Missing return [return]\nFound 1 error in 1 file (checked 3 source files)";
146 assert!(compress_output("mypy .", output).is_some());
147 assert!(compress_output("python -m mypy src/", output).is_some());
148 }
149
150 #[test]
151 fn routes_pytest_commands() {
152 let output = "===== test session starts =====\ncollected 5 items\ntest_main.py ..... [100%]\n===== 5 passed in 0.5s =====";
153 assert!(compress_output("pytest", output).is_some());
154 assert!(compress_output("python -m pytest tests/", output).is_some());
155 }
156
157 #[test]
158 fn routes_data_domain() {
159 let dbt =
160 "20:14:02 Found 12 models\n20:14:20 Done. PASS=11 WARN=0 ERROR=1 SKIP=0 TOTAL=12";
161 assert!(
162 compress_output("dbt run", dbt).is_some(),
163 "dbt routed+compressible"
164 );
165 let alembic = "INFO [alembic.runtime.migration] Context impl PostgresqlImpl.\nINFO [alembic.runtime.migration] Running upgrade -> a1b2c3, create users table\nINFO [alembic.runtime.migration] Running upgrade a1b2c3 -> d4e5f6, add email index";
166 assert!(compress_output("alembic upgrade head", alembic).is_some());
167 let flyway = "Flyway Community Edition 9.22.0 by Redgate\nDatabase: jdbc:postgresql://localhost/db\nMigrating schema \"public\" to version \"5 - add orders\"\nSuccessfully applied 1 migration to schema \"public\", now at version v5";
168 assert!(compress_output("flyway migrate", flyway).is_some());
169 let spark = "23/01/01 12:00:00 INFO SparkContext: Running Spark version 3.4.0\n23/01/01 12:00:01 INFO ResourceUtils: none configured\n23/01/01 12:00:10 INFO DAGScheduler: Job 0 finished: collect, took 5.1 s\n23/01/01 12:00:15 ERROR Executor: Exception in task 0.0";
170 assert!(compress_output("spark-submit app.py", spark).is_some());
171 }
172
173 #[test]
174 fn routes_ai_domain() {
175 let ollama = "NAME ID SIZE MODIFIED\nllama3.2:latest a80c4f17acd5 2.0 GB 3 days ago\nqwen2.5-coder:7b 2b0496514337 4.7 GB 2 weeks ago";
176 assert!(compress_output("ollama list", ollama).is_some());
177 let mlflow = "2024/01/01 12:00:01 INFO mlflow.projects.backend.local: === Running command 'python train.py' ===\nCollecting numpy==1.26.0\nDownloading numpy-1.26.0.whl (18.2 MB)\n2024/01/01 12:00:30 INFO mlflow.projects: === Run (ID 'abc123def456') succeeded ===";
178 assert!(compress_output("mlflow run .", mlflow).is_some());
179 }
180
181 #[test]
182 fn routes_security_domain() {
183 let trivy = "2024-01-01T12:00:00.000Z\tINFO\tscanning\nnginx:latest (debian 12.1)\n=====\nTotal: 45 (LOW: 20, HIGH: 8, CRITICAL: 2)";
184 assert!(compress_output("trivy image nginx", trivy).is_some());
185 let grype = "NAME INSTALLED FIXED-IN TYPE VULNERABILITY SEVERITY\nlibssl1.1 1.1.1n 1.1.1w deb CVE-2023-1234 Critical\nzlib1g 1.2.11 1.2.13 deb CVE-2022-5678 High";
186 assert!(compress_output("grype nginx", grype).is_some());
187 let syft = "NAME VERSION TYPE\nadduser 3.118 deb\napt 2.6.1 deb\nlodash 4.17.21 npm";
188 assert!(compress_output("syft nginx", syft).is_some());
189 let semgrep = "Scanning 120 files.\n src/app.py\n python.security.dangerous-subprocess-use\n Detected subprocess.\n 42┆ subprocess.call(x)\nRan 450 rules on 120 files: 1 findings.";
190 assert!(compress_output("semgrep scan", semgrep).is_some());
191 let swiftlint = "Linting Swift files in current working directory\nLinting 'A.swift' (1/3)\nLinting 'B.swift' (2/3)\nLinting 'C.swift' (3/3)\n/path/A.swift:10:5: warning: Line Length Violation: Line should be 120 chars or less (line_length)\n/path/A.swift:22:1: warning: Trailing Whitespace Violation: no trailing whitespace (trailing_whitespace)\n/path/B.swift:5:1: error: Force Cast Violation: avoid force casts (force_cast)\n/path/C.swift:8:3: warning: Todo Violation: resolve TODOs (todo)\nDone linting! Found 4 violations, 1 serious in 3 files.";
192 assert!(compress_output("swiftlint", swiftlint).is_some());
193 }
194
195 #[test]
196 fn routes_vcs_toolchain_domain() {
197 let jj = "@ qpvuntsm user@host.com 2024-01-01 12:00:00 1234abcd\n│ add feature x\n○ zzzzmmmm user@host.com 2024-01-01 11:00:00 main 5678efab\n│ initial commit\n~";
198 assert!(compress_output("jj log", jj).is_some());
199 let mise = "node 20.10.0 ~/.config/mise/config.toml\npython 3.12.0 ~/.tool-versions\nrust 1.75.0 ~/.config/mise/config.toml";
200 assert!(compress_output("mise ls", mise).is_some());
201 let buf_lines: Vec<String> = (0..30)
202 .map(|i| format!("proto/f{i}.proto:{i}:1:Field name should be lower_snake_case here."))
203 .collect();
204 let buf = buf_lines.join("\n");
205 assert!(compress_output("buf lint", &buf).is_some());
206 let gem = "Fetching rails-7.1.0.gem\nSuccessfully installed activesupport-7.1.0\nSuccessfully installed rails-7.1.0\nParsing documentation for rails-7.1.0\nInstalling ri documentation for rails-7.1.0\nDone installing documentation for rails after 3 seconds\n2 gems installed";
207 assert!(compress_output("gem install rails", gem).is_some());
208 let uv = "Resolved 42 packages in 120ms\nDownloading numpy (18.2MiB)\n 100%|████████| 18.2M/18.2M [00:01<00:00, 15.3MiB/s]\nDownloading pandas (12.1MiB)\n 100%|████████| 12.1M/12.1M [00:00<00:00, 14.1MiB/s]\nPrepared 5 packages in 1.2s\nInstalled 5 packages in 30ms\n + numpy==1.26.0\n + pandas==2.1.0";
209 assert!(compress_output("uv add pandas", uv).is_some());
210 }
211
212 #[test]
213 fn routes_edge_infra_domain() {
214 let pulumi = "Updating (dev):\n Type Name Status\n + pulumi:pulumi:Stack proj created\n + aws:s3:Bucket b1 created\n + aws:s3:Bucket b2 created\n + aws:s3:Bucket b3 created\n + aws:lambda:Function fn created\n\nOutputs:\n url: \"https://x.example.com\"\n\nResources:\n + 5 created\n 10 unchanged\n\nDuration: 35s";
215 assert!(compress_output("pulumi up", pulumi).is_some());
216 let linkerd = "kubernetes-api\n--------------\n√ can initialize the client\n√ can query the Kubernetes API\n√ is running the minimum kubectl version\n\nlinkerd-existence\n-----------------\n√ 'linkerd-config' config map exists\n× control plane pods are ready\n some pods are not ready\n\nStatus check results are ×";
217 assert!(compress_output("linkerd check", linkerd).is_some());
218 let argocd = "Name: argocd/myapp\nProject: default\nSync Status: Synced\nHealth Status: Healthy\n\nGROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE\n Service ns s1 Synced Healthy\n Service ns s2 Synced Healthy\n Service ns s3 Synced Healthy\napps Deployment ns d1 OutOfSync Progressing";
219 assert!(compress_output("argocd app get myapp", argocd).is_some());
220 let vercel = "Vercel CLI 33.0.0\nInstalling dependencies...\nadded 420 packages in 12s\nBuilding...\nCompiling pages\nCollecting page data\nGenerating static pages\nProduction: https://my-app.vercel.app [45s]";
221 assert!(compress_output("vercel deploy --prod", vercel).is_some());
222 let wrangler = "wrangler 3.0.0\n-------------------\nyour worker has access to the following bindings:\n- KV Namespaces:\n - CACHE: abc123\nTotal Upload: 1.2 MiB / gzip: 0.4 MiB\nUploaded my-worker (3.5 sec)\nPublished my-worker (1.2 sec)\n https://my-worker.example.workers.dev";
223 assert!(compress_output("wrangler deploy", wrangler).is_some());
224 }
225
226 #[test]
227 fn unknown_command_returns_none() {
228 assert!(compress_output("some-unknown-tool --version", "v1.0").is_none());
229 }
230
231 #[test]
232 fn case_insensitive_routing() {
233 let output = "On branch main\nnothing to commit";
234 assert!(compress_output("Git Status", output).is_some());
235 assert!(compress_output("GIT STATUS", output).is_some());
236 }
237
238 #[test]
239 fn routes_vp_and_vite_plus() {
240 let output = " VITE v5.0.0 ready in 200 ms\n\n -> Local: http://localhost:5173/\n -> Network: http://192.168.1.2:5173/";
241 assert!(compress_output("vp build", output).is_some());
242 assert!(compress_output("vite-plus build", output).is_some());
243 }
244
245 #[test]
246 fn routes_bunx_commands() {
247 let output = "1 pass tests\n0 fail tests\n3 skip tests\nDone 12ms\nsome extra line\nmore output here";
248 let result = compress_output("bunx test", output);
249 assert!(
250 result.is_some(),
251 "bunx should compress when output is large enough"
252 );
253 assert!(result.unwrap().contains("bun test: 1 passed"));
254 }
255
256 #[test]
257 fn routes_deno_task() {
258 let output = "Task dev deno run --allow-net server.ts\nListening on http://localhost:8000";
259 assert!(try_specific_pattern("deno task dev", output).is_some());
260 }
261
262 #[test]
263 fn routes_jest_commands() {
264 let output = "PASS tests/main.test.js\nTest Suites: 1 passed, 1 total\nTests: 5 passed, 5 total\nTime: 2.5 s";
265 assert!(try_specific_pattern("jest", output).is_some());
266 assert!(try_specific_pattern("npx jest --coverage", output).is_some());
267 }
268
269 #[test]
270 fn routes_mocha_commands() {
271 let output = " 3 passing (50ms)\n 1 failing\n\n 1) Array #indexOf():\n Error: expected -1 to equal 0";
272 assert!(try_specific_pattern("mocha", output).is_some());
273 assert!(try_specific_pattern("npx mocha tests/", output).is_some());
274 }
275
276 #[test]
277 fn routes_tofu_commands() {
278 let output = "Initializing the backend...\nInitializing provider plugins...\nTerraform has been successfully initialized!";
279 assert!(try_specific_pattern("tofu init", output).is_some());
280 }
281
282 #[test]
283 fn routes_ps_commands() {
284 let mut lines = vec!["USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND".to_string()];
285 for i in 0..20 {
286 lines.push(format!("user {i} 0.0 0.1 1234 123 ? S 10:00 0:00 proc_{i}"));
287 }
288 let output = lines.join("\n");
289 assert!(try_specific_pattern("ps aux", &output).is_some());
290 }
291
292 #[test]
293 fn routes_ping_commands() {
294 let output = "PING google.com (1.2.3.4): 56 data bytes\n64 bytes from 1.2.3.4: icmp_seq=0 ttl=116 time=12ms\n3 packets transmitted, 3 packets received, 0.0% packet loss\nrtt min/avg/max/stddev = 11/12/13/1 ms";
295 assert!(try_specific_pattern("ping -c 3 google.com", output).is_some());
296 }
297
298 #[test]
299 fn routes_jq_to_json_schema() {
300 let output = "{\"name\": \"test\", \"version\": \"1.0\", \"items\": [{\"id\": 1}, {\"id\": 2}, {\"id\": 3}, {\"id\": 4}, {\"id\": 5}, {\"id\": 6}, {\"id\": 7}, {\"id\": 8}, {\"id\": 9}, {\"id\": 10}]}";
301 assert!(try_specific_pattern("jq '.items' data.json", output).is_some());
302 }
303
304 #[test]
305 fn routes_linting_tools() {
306 let lint_output = "src/main.py:10: error: Missing return\nsrc/main.py:20: error: Unused var\nFound 2 errors";
307 assert!(try_specific_pattern("hadolint Dockerfile", lint_output).is_some());
308 assert!(try_specific_pattern("oxlint src/", lint_output).is_some());
309 assert!(try_specific_pattern("pyright src/", lint_output).is_some());
310 assert!(try_specific_pattern("basedpyright src/", lint_output).is_some());
311 }
312
313 #[test]
314 fn routes_fd_commands() {
315 let output = "src/main.rs\nsrc/lib.rs\nsrc/util/helpers.rs\nsrc/util/math.rs\ntests/integration.rs\n";
316 assert!(try_specific_pattern("fd --extension rs", output).is_some());
317 assert!(try_specific_pattern("fdfind .rs", output).is_some());
318 }
319
320 #[test]
321 fn routes_just_commands() {
322 let output = "Available recipes:\n build\n test\n lint\n";
323 assert!(try_specific_pattern("just --list", output).is_some());
324 assert!(try_specific_pattern("just build", output).is_some());
325 }
326
327 #[test]
328 fn routes_ninja_commands() {
329 let output = "[1/10] Compiling foo.c\n[10/10] Linking app\n";
330 assert!(try_specific_pattern("ninja", output).is_some());
331 assert!(try_specific_pattern("ninja -j4", output).is_some());
332 }
333
334 #[test]
335 fn routes_clang_commands() {
336 let output =
337 "src/main.c:10:5: error: use of undeclared identifier 'foo'\n1 error generated.\n";
338 assert!(try_specific_pattern("clang src/main.c", output).is_some());
339 assert!(try_specific_pattern("clang++ -std=c++17 main.cpp", output).is_some());
340 }
341
342 #[test]
343 fn routes_cargo_run() {
344 let output = " Compiling foo v0.1.0\n Finished `dev` profile\nHello, world!";
345 assert!(try_specific_pattern("cargo run", output).is_some());
346 }
347
348 #[test]
349 fn routes_cargo_bench() {
350 let output = " Compiling foo v0.1.0\ntest bench_parse ... bench: 1234 ns/iter";
351 assert!(try_specific_pattern("cargo bench", output).is_some());
352 }
353
354 #[test]
355 fn routes_build_tools() {
356 let build_output = " Compiling foo v0.1.0\n Finished release [optimized]";
357 assert!(try_specific_pattern("gcc -o main main.c", build_output).is_some());
358 assert!(try_specific_pattern("g++ -o main main.cpp", build_output).is_some());
359 }
360
361 #[test]
362 fn routes_monorepo_tools() {
363 let output = "npm warn deprecated inflight@1.0.6\nnpm warn deprecated rimraf@3.0.2\nadded 150 packages, and audited 151 packages in 5s\n\n25 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities";
364 assert!(try_specific_pattern("turbo install", output).is_some());
365 assert!(try_specific_pattern("nx install", output).is_some());
366 }
367
368 #[test]
369 fn gh_api_passthrough_never_compresses() {
370 let huge = "line\n".repeat(5000);
371 assert!(
372 compress_output("gh api repos/owner/repo/actions/jobs/123/logs", &huge).is_none(),
373 "gh api must never be compressed, even for large output"
374 );
375 assert!(compress_output("gh api repos/owner/repo/actions/runs/123/logs", &huge).is_none());
376 }
377
378 #[test]
379 fn gh_log_flags_passthrough() {
380 let huge = "line\n".repeat(5000);
381 assert!(compress_output("gh run view 123 --log-failed", &huge).is_none());
382 assert!(compress_output("gh run view 123 --log", &huge).is_none());
383 }
384
385 #[test]
386 fn strip_leading_cd_unwraps_only_plain_two_segment_cd() {
387 assert_eq!(strip_leading_cd("cd /x && git log -5"), "git log -5");
388 assert_eq!(strip_leading_cd("cd 'a b' && git status"), "git status");
389 assert_eq!(strip_leading_cd("git log -5"), "git log -5");
390 for kept in [
391 "cd /x && git log && git status",
392 "cd /x; git log",
393 "cd /x || git log",
394 "cd $HOME && git log",
395 "cd $(pwd) && git log",
396 "pushd /x && git log",
397 ] {
398 assert_eq!(strip_leading_cd(kept), kept, "{kept}");
399 }
400 }
401
402 #[test]
403 fn cd_prefixed_git_log_uses_git_pattern() {
404 let mut out = String::new();
405 for i in 0..30 {
406 out.push_str(&format!(
407 "commit {i:040x}\nAuthor: A <a@b.c>\nDate: Mon Jan 1 00:00:00 2026 +0000\n\n subject {i}\n\n - bullet body line\n\n src/f{i}.rs | 4 ++--\n 1 file changed, 2 insertions(+), 2 deletions(-)\n\n"
408 ));
409 }
410 let plain = compress_output("git -C /x log --stat -30", &out);
411 let cd = compress_output("cd /x && git log --stat -30", &out);
412 assert!(plain.is_some());
413 assert_eq!(cd, plain);
414 assert!(cd.unwrap().contains("+60/-60 total"));
415 }
416
417 #[test]
418 fn gh_structured_commands_still_compress() {
419 let output = "On branch main\nnothing to commit";
420 assert!(try_specific_pattern("gh pr list", output).is_some());
421 assert!(try_specific_pattern("gh run list", output).is_some());
422 }
423}