1pub const PATTERN_ENGINE_VERSION: u32 = 2;
8
9pub mod alembic;
10pub mod ansible;
11pub mod argocd;
12pub mod artisan;
13pub mod aws;
14pub mod bazel;
15pub mod buf;
16pub mod bun;
17pub mod cargo;
18pub mod cargo_diagnostics;
19pub mod clang;
20pub mod cmake;
21pub mod composer;
22pub mod cosign;
23pub mod curl;
24pub mod dbt;
25pub mod deno;
26pub mod deploy;
27pub mod deps_cmd;
28pub mod docker;
29pub mod dotnet;
30pub mod env_filter;
31pub mod eslint;
32pub mod fd;
33pub mod find;
34pub mod flutter;
35pub mod flyway;
36pub mod gem;
37pub mod gh;
38pub mod git;
39pub mod glab;
40pub mod golang;
41pub mod grep;
42pub mod grype;
43pub mod helm;
44pub mod jj;
45pub mod json_schema;
46pub mod just;
47pub mod kubectl;
48pub mod linkerd;
49pub mod log_dedup;
50pub mod ls;
51pub mod make;
52pub mod maven;
53pub mod mise;
54pub mod mix;
55pub mod mlflow;
56pub mod mypy;
57pub mod mysql;
58pub mod next_build;
59pub mod ninja;
60pub mod npm;
61pub mod ollama;
62pub mod php;
63pub mod pip;
64pub mod playwright;
65pub mod pnpm;
66pub mod poetry;
67pub mod prettier;
68pub mod prisma;
69pub mod psql;
70pub mod pulumi;
71pub mod pytest;
72pub mod ruby;
73pub mod ruff;
74pub mod semgrep;
75pub mod spark;
76pub mod swift;
77pub mod swiftlint;
78pub mod syft;
79pub mod sysinfo;
80pub mod systemd;
81pub mod terraform;
82pub mod test;
83pub mod trivy;
84pub mod typescript;
85pub mod wget;
86pub mod zig;
87
88use crate::core::tokens::count_tokens;
89
90pub fn compress_output(command: &str, output: &str) -> Option<String> {
91 let policy = crate::shell::output_policy::classify(command, &[]);
96 if policy.is_protected() {
97 return None;
98 }
99 let command = strip_leading_cd(command);
100
101 let stripped;
102 let clean_output = {
103 let s = crate::core::compressor::strip_ansi(output);
104 if s.len() < output.len() {
105 stripped = s;
106 &stripped
107 } else {
108 output
109 }
110 };
111
112 if let Some(engine) = crate::core::filters::FilterEngine::load()
113 && let Some(filtered) = engine.apply(command, clean_output)
114 {
115 return shorter_only(filtered, output);
116 }
117
118 if has_vcs_owner(command) {
127 return try_specific_pattern(command, clean_output)
134 .filter(|c| !c.trim().is_empty())
135 .filter(|c| !inflates_tokens(c, output));
136 }
137
138 if let Some(compressed) = try_specific_pattern(command, clean_output)
139 && let Some(r) = shorter_only(compressed, output)
140 {
141 return Some(r);
142 }
143
144 if let Some(r) = json_schema::compress(clean_output)
145 && let Some(r) = shorter_only(r, output)
146 {
147 return Some(r);
148 }
149
150 if let Some(r) = log_dedup::compress(clean_output)
151 && let Some(r) = shorter_only(r, output)
152 {
153 return Some(r);
154 }
155
156 if let Some(r) = test::compress(clean_output)
157 && let Some(r) = shorter_only(r, output)
158 {
159 return Some(r);
160 }
161
162 None
163}
164
165pub(crate) fn strip_leading_cd(command: &str) -> &str {
170 use crate::core::shell_allowlist::Separator;
171 let segments = crate::core::shell_allowlist::segments_with_separators(command);
172 let [(first, Some(Separator::And)), (rest, None)] = segments.as_slice() else {
173 return command;
174 };
175 let is_plain_cd = first
176 .strip_prefix("cd ")
177 .is_some_and(|dir| !dir.trim().is_empty() && !dir.contains(['$', '`', '(']));
178 if !is_plain_cd {
179 return command;
180 }
181 command
182 .rfind(rest.as_str())
183 .map_or(command, |at| &command[at..])
184}
185
186pub(crate) fn has_vcs_owner(command: &str) -> bool {
190 let c = command.trim_start().to_ascii_lowercase();
191 c.starts_with("git ")
192 || c.starts_with("jj ")
193 || c.starts_with("gh ")
194 || c.starts_with("glab ")
195 || c.starts_with("hg ")
196}
197
198fn normalize_shell_tokens(text: &str) -> String {
200 text.split_whitespace().collect::<Vec<_>>().join(" ")
201}
202
203fn inflates_tokens(compressed: &str, original: &str) -> bool {
208 count_tokens(compressed) > count_tokens(original)
209}
210
211fn shorter_only(compressed: String, original: &str) -> Option<String> {
212 let orig_n = normalize_shell_tokens(original);
213 let comp_n = normalize_shell_tokens(&compressed);
214 let ct_c = count_tokens(&comp_n);
215 let ct_o = count_tokens(&orig_n);
216 if ct_c < ct_o || (ct_c == ct_o && comp_n.len() < orig_n.len()) {
217 Some(compressed)
218 } else {
219 None
220 }
221}
222
223pub(crate) fn elision_marker(omitted: usize) -> String {
237 let plural = if omitted == 1 { "line" } else { "lines" };
238 format!("[lean-ctx: {omitted} {plural} elided — re-run with raw=true for the full output]")
239}
240
241type PatternMatcher = fn(&str) -> bool;
242type PatternHandler = fn(&str, &str) -> Option<String>;
243
244#[cfg(test)]
252pub(crate) fn pattern_count() -> usize {
253 PATTERNS.len()
254}
255
256const PATTERNS: &[(PatternMatcher, PatternHandler)] = &[
257 (
258 |c| c.starts_with("git "),
259 |c, output| git::compress(c, output),
260 ),
261 (
262 |c| c.starts_with("gh "),
263 |c, output| gh::compress(c, output),
264 ),
265 (
266 |c| c.starts_with("glab "),
267 |c, output| glab::try_glab_pattern(c, output),
268 ),
269 (
270 |c| c == "terraform" || c.starts_with("terraform "),
271 |c, output| terraform::compress(c, output),
272 ),
273 (
274 |c| c == "make" || c.starts_with("make "),
275 |c, output| make::compress(c, output),
276 ),
277 (
278 |c| c == "just" || c.starts_with("just "),
279 |c, output| just::compress(c, output),
280 ),
281 (
282 |c| {
283 c.starts_with("mvn ")
284 || c.starts_with("./mvnw ")
285 || c.starts_with("mvnw ")
286 || c.starts_with("gradle ")
287 || c.starts_with("./gradlew ")
288 || c.starts_with("gradlew ")
289 },
290 |c, output| maven::compress(c, output),
291 ),
292 (
293 |c| c.starts_with("kubectl ") || c.starts_with("k "),
294 |c, output| kubectl::compress(c, output),
295 ),
296 (
297 |c| c.starts_with("helm "),
298 |c, output| helm::compress(c, output),
299 ),
300 (
301 |c| c.starts_with("pnpm "),
302 |c, output| pnpm::compress(c, output),
303 ),
304 (
305 |c| c.starts_with("bun ") || c.starts_with("bunx "),
306 |c, output| bun::compress(c, output),
307 ),
308 (
309 |c| c.starts_with("deno "),
310 |c, output| deno::compress(c, output),
311 ),
312 (
313 |c| c.starts_with("npm ") || c.starts_with("yarn "),
314 |c, output| npm::compress(c, output),
315 ),
316 (
317 |c| c.starts_with("cargo "),
318 |c, output| cargo::compress(c, output),
319 ),
320 (
321 |c| c.starts_with("docker ") || c.starts_with("docker-compose "),
322 |c, output| docker::compress(c, output),
323 ),
324 (
325 |c| c.starts_with("pip ") || c.starts_with("pip3 ") || c.starts_with("python -m pip"),
326 |c, output| pip::compress(c, output),
327 ),
328 (
329 |c| c.starts_with("mypy") || c.starts_with("python -m mypy") || c.starts_with("dmypy "),
330 |c, output| mypy::compress(c, output),
331 ),
332 (
333 |c| c.starts_with("pytest") || c.starts_with("python -m pytest"),
334 |c, output| pytest::compress(c, output).or_else(|| test::compress(output)),
335 ),
336 (
337 |c| c.starts_with("ruff "),
338 |c, output| ruff::compress(c, output),
339 ),
340 (
341 |c| {
342 c.starts_with("eslint")
343 || c.starts_with("npx eslint")
344 || c.starts_with("biome ")
345 || c.starts_with("stylelint")
346 },
347 |c, output| eslint::compress(c, output),
348 ),
349 (
350 |c| c.starts_with("prettier") || c.starts_with("npx prettier"),
351 |_c, output| prettier::compress(output),
352 ),
353 (
354 |c| c.starts_with("go ") || c.starts_with("golangci-lint") || c.starts_with("golint"),
355 |c, output| golang::compress(c, output),
356 ),
357 (
358 |c| {
359 c.starts_with("playwright")
360 || c.starts_with("npx playwright")
361 || c.starts_with("cypress")
362 || c.starts_with("npx cypress")
363 },
364 |c, output| playwright::compress(c, output),
365 ),
366 (
367 |c| c.starts_with("vitest") || c.starts_with("npx vitest") || c.starts_with("pnpm vitest"),
368 |_c, output| test::compress(output),
369 ),
370 (
371 |c| {
372 c.starts_with("next ")
373 || c.starts_with("npx next")
374 || c.starts_with("vite ")
375 || c.starts_with("npx vite")
376 || c.starts_with("vp ")
377 || c.starts_with("vite-plus ")
378 },
379 |c, output| next_build::compress(c, output),
380 ),
381 (
382 |c| c.starts_with("tsc") || c.contains("typescript"),
383 |_c, output| typescript::compress(output),
384 ),
385 (
386 |c| {
387 c.starts_with("rubocop")
388 || c.starts_with("bundle ")
389 || c.starts_with("rake ")
390 || c.starts_with("rails test")
391 || c.starts_with("rspec")
392 },
393 |c, output| ruby::compress(c, output),
394 ),
395 (|c| is_grep_family(c), |_c, output| grep::compress(output)),
396 (
397 |c| c.starts_with("find "),
398 |_c, output| find::compress(output),
399 ),
400 (
401 |c| c.starts_with("fd ") || c.starts_with("fdfind "),
402 |_c, output| fd::compress(output),
403 ),
404 (
405 |c| c.starts_with("ls ") || c == "ls",
406 |_c, output| ls::compress(output),
407 ),
408 (
409 |c| c.starts_with("curl "),
410 |c, output| curl::compress_with_cmd(c, output),
411 ),
412 (
413 |c| c.starts_with("wget "),
414 |_c, output| wget::compress(output),
415 ),
416 (
417 |c| c == "env" || c.starts_with("env ") || c.starts_with("printenv"),
418 |_c, output| env_filter::compress(output),
419 ),
420 (
421 |c| c.starts_with("dotnet "),
422 |c, output| dotnet::compress(c, output),
423 ),
424 (
425 |c| {
426 c.starts_with("flutter ")
427 || (c.starts_with("dart ") && (c.contains(" analyze") || c.ends_with(" analyze")))
428 },
429 |c, output| flutter::compress(c, output),
430 ),
431 (
432 |c| {
433 c.starts_with("poetry ")
434 || c.starts_with("uv ")
435 || c.starts_with("conda ")
436 || c.starts_with("mamba ")
437 || c.starts_with("pipx ")
438 },
439 |c, output| poetry::compress(c, output),
440 ),
441 (
442 |c| c.starts_with("aws "),
443 |c, output| aws::compress(c, output),
444 ),
445 (
446 |c| c.starts_with("psql ") || c.starts_with("pg_"),
447 |c, output| psql::compress(c, output),
448 ),
449 (
450 |c| c.starts_with("mysql ") || c.starts_with("mariadb "),
451 |c, output| mysql::compress(c, output),
452 ),
453 (
454 |c| c.starts_with("prisma ") || c.starts_with("npx prisma"),
455 |c, output| prisma::compress(c, output),
456 ),
457 (
458 |c| c.starts_with("swift "),
459 |c, output| swift::compress(c, output),
460 ),
461 (
462 |c| c.starts_with("zig "),
463 |c, output| zig::compress(c, output),
464 ),
465 (
466 |c| c.starts_with("cmake ") || c.starts_with("ctest"),
467 |c, output| cmake::compress(c, output),
468 ),
469 (
470 |c| c.starts_with("ninja"),
471 |c, output| ninja::compress(c, output),
472 ),
473 (
474 |c| c.starts_with("ansible") || c.starts_with("ansible-playbook"),
475 |c, output| ansible::compress(c, output),
476 ),
477 (
478 |c| c.starts_with("composer "),
479 |c, output| composer::compress(c, output),
480 ),
481 (
482 |c| c.starts_with("php artisan") || c.starts_with("artisan "),
483 |c, output| artisan::compress(c, output),
484 ),
485 (
486 |c| c.starts_with("./vendor/bin/pest") || c.starts_with("pest "),
487 |_c, output| artisan::compress("php artisan test", output),
488 ),
489 (
490 |c| c.starts_with("mix ") || c.starts_with("iex "),
491 |c, output| mix::compress(c, output),
492 ),
493 (
494 |c| c.starts_with("bazel ") || c.starts_with("blaze "),
495 |c, output| bazel::compress(c, output),
496 ),
497 (
498 |c| c.starts_with("systemctl ") || c.starts_with("journalctl"),
499 |c, output| systemd::compress(c, output),
500 ),
501 (
502 |c| c.starts_with("jest") || c.starts_with("npx jest") || c.starts_with("pnpm jest"),
503 |_c, output| test::compress(output),
504 ),
505 (
506 |c| c.starts_with("mocha") || c.starts_with("npx mocha"),
507 |_c, output| test::compress(output),
508 ),
509 (
510 |c| c.starts_with("tofu "),
511 |c, output| terraform::compress(c, output),
512 ),
513 (
514 |c| c.starts_with("ps ") || c == "ps",
515 |_c, output| sysinfo::compress_ps(output),
516 ),
517 (
518 |c| c.starts_with("df ") || c == "df",
519 |_c, output| sysinfo::compress_df(output),
520 ),
521 (
522 |c| c.starts_with("du ") || c == "du",
523 |_c, output| sysinfo::compress_du(output),
524 ),
525 (
526 |c| c.starts_with("ping "),
527 |_c, output| sysinfo::compress_ping(output),
528 ),
529 (
530 |c| c.starts_with("jq ") || c == "jq",
531 |_c, output| json_schema::compress(output),
532 ),
533 (
534 |c| c.starts_with("hadolint"),
535 |c, output| eslint::compress(c, output),
536 ),
537 (
538 |c| c.starts_with("yamllint") || c.starts_with("npx yamllint"),
539 |c, output| eslint::compress(c, output),
540 ),
541 (
542 |c| c.starts_with("markdownlint") || c.starts_with("npx markdownlint"),
543 |c, output| eslint::compress(c, output),
544 ),
545 (
546 |c| c.starts_with("oxlint") || c.starts_with("npx oxlint"),
547 |c, output| eslint::compress(c, output),
548 ),
549 (
550 |c| c.starts_with("pyright") || c.starts_with("basedpyright"),
551 |c, output| mypy::compress(c, output),
552 ),
553 (
554 |c| c.starts_with("turbo ") || c.starts_with("npx turbo"),
555 |c, output| npm::compress(c, output),
556 ),
557 (
558 |c| c.starts_with("nx ") || c.starts_with("npx nx"),
559 |c, output| npm::compress(c, output),
560 ),
561 (
562 |c| c.starts_with("clang++ ") || c.starts_with("clang "),
563 |c, output| clang::compress(c, output),
564 ),
565 (
566 |c| {
567 c.starts_with("gcc ")
568 || c.starts_with("g++ ")
569 || c.starts_with("cc ")
570 || c.starts_with("c++ ")
571 },
572 |c, output| cmake::compress(c, output),
573 ),
574 (
576 |c| c == "dbt" || c.starts_with("dbt "),
577 |c, output| dbt::compress(c, output),
578 ),
579 (
580 |c| c == "alembic" || c.starts_with("alembic "),
581 |c, output| alembic::compress(c, output),
582 ),
583 (
584 |c| c == "flyway" || c.starts_with("flyway "),
585 |c, output| flyway::compress(c, output),
586 ),
587 (
588 |c| c.starts_with("spark-submit") || c.starts_with("spark-sql") || c.starts_with("pyspark"),
589 |c, output| spark::compress(c, output),
590 ),
591 (
593 |c| c == "ollama" || c.starts_with("ollama "),
594 |c, output| ollama::compress(c, output),
595 ),
596 (
597 |c| c.starts_with("mlflow "),
598 |c, output| mlflow::compress(c, output),
599 ),
600 (
602 |c| c.starts_with("semgrep "),
603 |c, output| semgrep::compress(c, output),
604 ),
605 (
606 |c| c.starts_with("trivy "),
607 |c, output| trivy::compress(c, output),
608 ),
609 (
610 |c| c.starts_with("grype "),
611 |c, output| grype::compress(c, output),
612 ),
613 (
614 |c| c.starts_with("syft "),
615 |c, output| syft::compress(c, output),
616 ),
617 (
618 |c| c.starts_with("cosign "),
619 |c, output| cosign::compress(c, output),
620 ),
621 (
622 |c| c.starts_with("swiftlint"),
623 |c, output| swiftlint::compress(c, output),
624 ),
625 (
627 |c| c == "jj" || c.starts_with("jj "),
628 |c, output| jj::compress(c, output),
629 ),
630 (
631 |c| c == "mise" || c.starts_with("mise "),
632 |c, output| mise::compress(c, output),
633 ),
634 (
635 |c| c == "buf" || c.starts_with("buf "),
636 |c, output| buf::compress(c, output),
637 ),
638 (
639 |c| c.starts_with("gem "),
640 |c, output| gem::compress(c, output),
641 ),
642 (
644 |c| c == "pulumi" || c.starts_with("pulumi "),
645 |c, output| pulumi::compress(c, output),
646 ),
647 (
648 |c| c.starts_with("linkerd "),
649 |c, output| linkerd::compress(c, output),
650 ),
651 (
652 |c| c.starts_with("argocd "),
653 |c, output| argocd::compress(c, output),
654 ),
655 (
656 |c| {
657 c == "vercel"
658 || c.starts_with("vercel ")
659 || c == "fly"
660 || c.starts_with("fly ")
661 || c.starts_with("flyctl ")
662 || c.starts_with("wrangler ")
663 || c.starts_with("skaffold ")
664 || c.starts_with("supabase ")
665 },
666 |c, output| deploy::compress(c, output),
667 ),
668];
669
670fn is_grep_family(cmd: &str) -> bool {
677 let first = cmd.split_whitespace().next().unwrap_or("");
678 let base = first.rsplit('/').next().unwrap_or(first);
679 matches!(
680 base,
681 "grep" | "egrep" | "fgrep" | "rg" | "ag" | "ack" | "ugrep" | "sift"
682 )
683}
684
685pub fn try_specific_pattern(cmd: &str, output: &str) -> Option<String> {
686 let cl = cmd.to_ascii_lowercase();
687 let c = cl.as_str();
688
689 PATTERNS
690 .iter()
691 .find(|(matches, _)| matches(c))
692 .and_then(|(_, handle)| handle(c, output))
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698
699 #[test]
700 fn routes_git_commands() {
701 let output = "On branch main\nnothing to commit";
702 assert!(compress_output("git status", output).is_some());
703 }
704
705 #[test]
706 fn vcs_path_never_inflates_tokens() {
707 let output = " Abu a\nAa aa_A00A\n\n-";
713 if let Some(compressed) = compress_output("git status", output) {
714 assert!(
715 count_tokens(&compressed) <= count_tokens(output),
716 "VCS compress inflated: {} > {}",
717 count_tokens(&compressed),
718 count_tokens(output),
719 );
720 }
721 }
722
723 #[test]
724 fn routes_cargo_commands() {
725 let output = " Compiling lean-ctx v2.1.1\n Finished `release` profile [optimized] target(s) in 30.5s";
726 assert!(compress_output("cargo build --release", output).is_some());
727 }
728
729 #[test]
730 fn routes_npm_commands() {
731 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";
732 assert!(compress_output("npm install", output).is_some());
733 }
734
735 #[test]
736 fn routes_docker_commands() {
737 let output = "CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES";
738 assert!(compress_output("docker ps", output).is_none());
741 let build_output =
742 "Step 1/5 : FROM node:18\n ---> abc123\nStep 2/5 : COPY . .\nSuccessfully built def456";
743 assert!(compress_output("docker build .", build_output).is_some());
744 }
745
746 #[test]
747 fn routes_mypy_commands() {
748 let output = "src/main.py:10: error: Missing return [return]\nFound 1 error in 1 file (checked 3 source files)";
749 assert!(compress_output("mypy .", output).is_some());
750 assert!(compress_output("python -m mypy src/", output).is_some());
751 }
752
753 #[test]
754 fn routes_pytest_commands() {
755 let output = "===== test session starts =====\ncollected 5 items\ntest_main.py ..... [100%]\n===== 5 passed in 0.5s =====";
756 assert!(compress_output("pytest", output).is_some());
757 assert!(compress_output("python -m pytest tests/", output).is_some());
758 }
759
760 #[test]
761 fn routes_data_domain() {
762 let dbt =
763 "20:14:02 Found 12 models\n20:14:20 Done. PASS=11 WARN=0 ERROR=1 SKIP=0 TOTAL=12";
764 assert!(
765 compress_output("dbt run", dbt).is_some(),
766 "dbt routed+compressible"
767 );
768 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";
769 assert!(compress_output("alembic upgrade head", alembic).is_some());
770 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";
771 assert!(compress_output("flyway migrate", flyway).is_some());
772 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";
773 assert!(compress_output("spark-submit app.py", spark).is_some());
774 }
775
776 #[test]
777 fn routes_ai_domain() {
778 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";
779 assert!(compress_output("ollama list", ollama).is_some());
780 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 ===";
781 assert!(compress_output("mlflow run .", mlflow).is_some());
782 }
783
784 #[test]
785 fn routes_security_domain() {
786 let trivy = "2024-01-01T12:00:00.000Z\tINFO\tscanning\nnginx:latest (debian 12.1)\n=====\nTotal: 45 (LOW: 20, HIGH: 8, CRITICAL: 2)";
787 assert!(compress_output("trivy image nginx", trivy).is_some());
788 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";
789 assert!(compress_output("grype nginx", grype).is_some());
790 let syft = "NAME VERSION TYPE\nadduser 3.118 deb\napt 2.6.1 deb\nlodash 4.17.21 npm";
791 assert!(compress_output("syft nginx", syft).is_some());
792 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.";
793 assert!(compress_output("semgrep scan", semgrep).is_some());
794 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.";
795 assert!(compress_output("swiftlint", swiftlint).is_some());
796 }
797
798 #[test]
799 fn routes_vcs_toolchain_domain() {
800 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~";
801 assert!(compress_output("jj log", jj).is_some());
802 let mise = "node 20.10.0 ~/.config/mise/config.toml\npython 3.12.0 ~/.tool-versions\nrust 1.75.0 ~/.config/mise/config.toml";
803 assert!(compress_output("mise ls", mise).is_some());
804 let buf_lines: Vec<String> = (0..30)
805 .map(|i| format!("proto/f{i}.proto:{i}:1:Field name should be lower_snake_case here."))
806 .collect();
807 let buf = buf_lines.join("\n");
808 assert!(compress_output("buf lint", &buf).is_some());
809 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";
810 assert!(compress_output("gem install rails", gem).is_some());
811 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";
812 assert!(compress_output("uv add pandas", uv).is_some());
813 }
814
815 #[test]
816 fn routes_edge_infra_domain() {
817 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";
818 assert!(compress_output("pulumi up", pulumi).is_some());
819 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 ×";
820 assert!(compress_output("linkerd check", linkerd).is_some());
821 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";
822 assert!(compress_output("argocd app get myapp", argocd).is_some());
823 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]";
824 assert!(compress_output("vercel deploy --prod", vercel).is_some());
825 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";
826 assert!(compress_output("wrangler deploy", wrangler).is_some());
827 }
828
829 #[test]
830 fn unknown_command_returns_none() {
831 assert!(compress_output("some-unknown-tool --version", "v1.0").is_none());
832 }
833
834 #[test]
835 fn case_insensitive_routing() {
836 let output = "On branch main\nnothing to commit";
837 assert!(compress_output("Git Status", output).is_some());
838 assert!(compress_output("GIT STATUS", output).is_some());
839 }
840
841 #[test]
842 fn routes_vp_and_vite_plus() {
843 let output = " VITE v5.0.0 ready in 200 ms\n\n -> Local: http://localhost:5173/\n -> Network: http://192.168.1.2:5173/";
844 assert!(compress_output("vp build", output).is_some());
845 assert!(compress_output("vite-plus build", output).is_some());
846 }
847
848 #[test]
849 fn routes_bunx_commands() {
850 let output = "1 pass tests\n0 fail tests\n3 skip tests\nDone 12ms\nsome extra line\nmore output here";
851 let result = compress_output("bunx test", output);
852 assert!(
853 result.is_some(),
854 "bunx should compress when output is large enough"
855 );
856 assert!(result.unwrap().contains("bun test: 1 passed"));
857 }
858
859 #[test]
860 fn routes_deno_task() {
861 let output = "Task dev deno run --allow-net server.ts\nListening on http://localhost:8000";
862 assert!(try_specific_pattern("deno task dev", output).is_some());
863 }
864
865 #[test]
866 fn routes_jest_commands() {
867 let output = "PASS tests/main.test.js\nTest Suites: 1 passed, 1 total\nTests: 5 passed, 5 total\nTime: 2.5 s";
868 assert!(try_specific_pattern("jest", output).is_some());
869 assert!(try_specific_pattern("npx jest --coverage", output).is_some());
870 }
871
872 #[test]
873 fn routes_mocha_commands() {
874 let output = " 3 passing (50ms)\n 1 failing\n\n 1) Array #indexOf():\n Error: expected -1 to equal 0";
875 assert!(try_specific_pattern("mocha", output).is_some());
876 assert!(try_specific_pattern("npx mocha tests/", output).is_some());
877 }
878
879 #[test]
880 fn routes_tofu_commands() {
881 let output = "Initializing the backend...\nInitializing provider plugins...\nTerraform has been successfully initialized!";
882 assert!(try_specific_pattern("tofu init", output).is_some());
883 }
884
885 #[test]
886 fn routes_ps_commands() {
887 let mut lines = vec!["USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND".to_string()];
888 for i in 0..20 {
889 lines.push(format!("user {i} 0.0 0.1 1234 123 ? S 10:00 0:00 proc_{i}"));
890 }
891 let output = lines.join("\n");
892 assert!(try_specific_pattern("ps aux", &output).is_some());
893 }
894
895 #[test]
896 fn routes_ping_commands() {
897 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";
898 assert!(try_specific_pattern("ping -c 3 google.com", output).is_some());
899 }
900
901 #[test]
902 fn routes_jq_to_json_schema() {
903 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}]}";
904 assert!(try_specific_pattern("jq '.items' data.json", output).is_some());
905 }
906
907 #[test]
908 fn routes_linting_tools() {
909 let lint_output = "src/main.py:10: error: Missing return\nsrc/main.py:20: error: Unused var\nFound 2 errors";
910 assert!(try_specific_pattern("hadolint Dockerfile", lint_output).is_some());
911 assert!(try_specific_pattern("oxlint src/", lint_output).is_some());
912 assert!(try_specific_pattern("pyright src/", lint_output).is_some());
913 assert!(try_specific_pattern("basedpyright src/", lint_output).is_some());
914 }
915
916 #[test]
917 fn routes_fd_commands() {
918 let output = "src/main.rs\nsrc/lib.rs\nsrc/util/helpers.rs\nsrc/util/math.rs\ntests/integration.rs\n";
919 assert!(try_specific_pattern("fd --extension rs", output).is_some());
920 assert!(try_specific_pattern("fdfind .rs", output).is_some());
921 }
922
923 #[test]
924 fn routes_just_commands() {
925 let output = "Available recipes:\n build\n test\n lint\n";
926 assert!(try_specific_pattern("just --list", output).is_some());
927 assert!(try_specific_pattern("just build", output).is_some());
928 }
929
930 #[test]
931 fn routes_ninja_commands() {
932 let output = "[1/10] Compiling foo.c\n[10/10] Linking app\n";
933 assert!(try_specific_pattern("ninja", output).is_some());
934 assert!(try_specific_pattern("ninja -j4", output).is_some());
935 }
936
937 #[test]
938 fn routes_clang_commands() {
939 let output =
940 "src/main.c:10:5: error: use of undeclared identifier 'foo'\n1 error generated.\n";
941 assert!(try_specific_pattern("clang src/main.c", output).is_some());
942 assert!(try_specific_pattern("clang++ -std=c++17 main.cpp", output).is_some());
943 }
944
945 #[test]
946 fn routes_cargo_run() {
947 let output = " Compiling foo v0.1.0\n Finished `dev` profile\nHello, world!";
948 assert!(try_specific_pattern("cargo run", output).is_some());
949 }
950
951 #[test]
952 fn routes_cargo_bench() {
953 let output = " Compiling foo v0.1.0\ntest bench_parse ... bench: 1234 ns/iter";
954 assert!(try_specific_pattern("cargo bench", output).is_some());
955 }
956
957 #[test]
958 fn routes_build_tools() {
959 let build_output = " Compiling foo v0.1.0\n Finished release [optimized]";
960 assert!(try_specific_pattern("gcc -o main main.c", build_output).is_some());
961 assert!(try_specific_pattern("g++ -o main main.cpp", build_output).is_some());
962 }
963
964 #[test]
965 fn routes_monorepo_tools() {
966 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";
967 assert!(try_specific_pattern("turbo install", output).is_some());
968 assert!(try_specific_pattern("nx install", output).is_some());
969 }
970
971 #[test]
972 fn gh_api_passthrough_never_compresses() {
973 let huge = "line\n".repeat(5000);
974 assert!(
975 compress_output("gh api repos/owner/repo/actions/jobs/123/logs", &huge).is_none(),
976 "gh api must never be compressed, even for large output"
977 );
978 assert!(compress_output("gh api repos/owner/repo/actions/runs/123/logs", &huge).is_none());
979 }
980
981 #[test]
982 fn gh_log_flags_passthrough() {
983 let huge = "line\n".repeat(5000);
984 assert!(compress_output("gh run view 123 --log-failed", &huge).is_none());
985 assert!(compress_output("gh run view 123 --log", &huge).is_none());
986 }
987
988 #[test]
989 fn strip_leading_cd_unwraps_only_plain_two_segment_cd() {
990 assert_eq!(strip_leading_cd("cd /x && git log -5"), "git log -5");
991 assert_eq!(strip_leading_cd("cd 'a b' && git status"), "git status");
992 assert_eq!(strip_leading_cd("git log -5"), "git log -5");
993 for kept in [
994 "cd /x && git log && git status",
995 "cd /x; git log",
996 "cd /x || git log",
997 "cd $HOME && git log",
998 "cd $(pwd) && git log",
999 "pushd /x && git log",
1000 ] {
1001 assert_eq!(strip_leading_cd(kept), kept, "{kept}");
1002 }
1003 }
1004
1005 #[test]
1006 fn cd_prefixed_git_log_uses_git_pattern() {
1007 let mut out = String::new();
1008 for i in 0..30 {
1009 out.push_str(&format!(
1010 "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"
1011 ));
1012 }
1013 let plain = compress_output("git -C /x log --stat -30", &out);
1014 let cd = compress_output("cd /x && git log --stat -30", &out);
1015 assert!(plain.is_some());
1016 assert_eq!(cd, plain);
1017 assert!(cd.unwrap().contains("+60/-60 total"));
1018 }
1019
1020 #[test]
1021 fn gh_structured_commands_still_compress() {
1022 let output = "On branch main\nnothing to commit";
1023 assert!(try_specific_pattern("gh pr list", output).is_some());
1024 assert!(try_specific_pattern("gh run list", output).is_some());
1025 }
1026}
1027
1028#[cfg(test)]
1029mod gh1679 {
1030 use super::*;
1031
1032 #[test]
1039 fn an_elision_announces_itself_as_ours() {
1040 let marker = elision_marker(34);
1041
1042 assert!(
1043 marker.starts_with("[lean-ctx:"),
1044 "must be unmistakably ours, not content-shaped: {marker}"
1045 );
1046 assert!(
1047 !marker.contains("more lines)"),
1048 "the old content-shaped wording must be gone: {marker}"
1049 );
1050 assert!(marker.contains("34"), "{marker}");
1051 }
1052
1053 #[test]
1057 fn the_marker_names_a_recovery_that_always_exists() {
1058 assert!(
1059 elision_marker(1).contains("raw=true"),
1060 "{}",
1061 elision_marker(1)
1062 );
1063 }
1064
1065 #[test]
1066 fn one_line_is_not_called_lines() {
1067 assert!(
1068 elision_marker(1).contains("1 line elided"),
1069 "{}",
1070 elision_marker(1)
1071 );
1072 assert!(
1073 elision_marker(2).contains("2 lines elided"),
1074 "{}",
1075 elision_marker(2)
1076 );
1077 }
1078
1079 #[test]
1083 fn no_compressor_hand_rolls_the_old_marker() {
1084 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/core/patterns");
1085 let mut offenders = Vec::new();
1086
1087 for entry in std::fs::read_dir(&dir).expect("patterns dir") {
1088 let path = entry.expect("dir entry").path();
1089 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
1090 continue;
1091 }
1092 let source = std::fs::read_to_string(&path).expect("read pattern source");
1093 let production = source
1096 .split_once("#[cfg(test)]")
1097 .map_or(source.as_str(), |(head, _)| head);
1098 if production.contains("more lines)")
1099 && path.file_name().and_then(|n| n.to_str()) != Some("mod.rs")
1100 {
1101 offenders.push(path.display().to_string());
1102 }
1103 }
1104
1105 assert!(
1106 offenders.is_empty(),
1107 "these compressors elide with the old content-shaped marker; \
1108 use super::elision_marker() instead: {offenders:?}"
1109 );
1110 }
1111}