Skip to main content

lean_ctx/core/patterns/
mod.rs

1/// Pattern engine version. Bump when output format changes to maintain
2/// shell-output determinism guarantees. Consumers (proofs, benchmarks)
3/// can embed this version to detect pattern-breaking updates.
4///
5/// v2 (#936): `json_schema::compress` now prefers the lossless `json_crush`
6/// form over the schema outline for redundant array-of-object payloads.
7pub 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 clang;
19pub mod cmake;
20pub mod composer;
21pub mod cosign;
22pub mod curl;
23pub mod dbt;
24pub mod deno;
25pub mod deploy;
26pub mod deps_cmd;
27pub mod docker;
28pub mod dotnet;
29pub mod env_filter;
30pub mod eslint;
31pub mod fd;
32pub mod find;
33pub mod flutter;
34pub mod flyway;
35pub mod gem;
36pub mod gh;
37pub mod git;
38pub mod glab;
39pub mod golang;
40pub mod grep;
41pub mod grype;
42pub mod helm;
43pub mod jj;
44pub mod json_schema;
45pub mod just;
46pub mod kubectl;
47pub mod linkerd;
48pub mod log_dedup;
49pub mod ls;
50pub mod make;
51pub mod maven;
52pub mod mise;
53pub mod mix;
54pub mod mlflow;
55pub mod mypy;
56pub mod mysql;
57pub mod next_build;
58pub mod ninja;
59pub mod npm;
60pub mod ollama;
61pub mod php;
62pub mod pip;
63pub mod playwright;
64pub mod pnpm;
65pub mod poetry;
66pub mod prettier;
67pub mod prisma;
68pub mod psql;
69pub mod pulumi;
70pub mod pytest;
71pub mod ruby;
72pub mod ruff;
73pub mod semgrep;
74pub mod spark;
75pub mod swift;
76pub mod swiftlint;
77pub mod syft;
78pub mod sysinfo;
79pub mod systemd;
80pub mod terraform;
81pub mod test;
82pub mod trivy;
83pub mod typescript;
84pub mod wget;
85pub mod zig;
86
87use crate::core::tokens::count_tokens;
88
89pub fn compress_output(command: &str, output: &str) -> Option<String> {
90    // Policy gate: protected commands (Passthrough + Verbatim) must
91    // never be pattern-compressed. The caller (compress_if_beneficial
92    // or ctx_shell::handle) should have already checked, but we
93    // defend in depth here.
94    let policy = crate::shell::output_policy::classify(command, &[]);
95    if policy.is_protected() {
96        return None;
97    }
98
99    let stripped;
100    let clean_output = {
101        let s = crate::core::compressor::strip_ansi(output);
102        if s.len() < output.len() {
103            stripped = s;
104            &stripped
105        } else {
106            output
107        }
108    };
109
110    if let Some(engine) = crate::core::filters::FilterEngine::load()
111        && let Some(filtered) = engine.apply(command, clean_output)
112    {
113        return shorter_only(filtered, output);
114    }
115
116    // VCS history (git/jj/gh/glab/hg) is owned by its dedicated compressor. Its
117    // lines look log-ish (one per commit) but are NOT application logs, so the
118    // generic json/log/test fallbacks would mis-summarize them — e.g. truncating
119    // an explicit `git log --oneline -40` to "last 15" or reading a commit
120    // subject like "fix: pending_errors" as an error line. Return the dedicated
121    // compressor's result directly — even when it is not shorter, so an already
122    // compact oneline log is preserved verbatim (full history intact) instead of
123    // being reshaped by a generic heuristic.
124    if has_vcs_owner(command) {
125        // The VCS compressor is authoritative and is kept even when it is not
126        // strictly *shorter*, so a compact `git log --oneline` is preserved
127        // verbatim (full history intact). It must still never return *more*
128        // tokens than its input, though — a tiny adversarial `git status` body
129        // could otherwise reshape into a one-token-larger summary and break the
130        // never-inflate invariant. Allow equal (verbatim), reject only growth.
131        return try_specific_pattern(command, clean_output)
132            .filter(|c| !c.trim().is_empty())
133            .filter(|c| !inflates_tokens(c, output));
134    }
135
136    if let Some(compressed) = try_specific_pattern(command, clean_output)
137        && let Some(r) = shorter_only(compressed, output)
138    {
139        return Some(r);
140    }
141
142    if let Some(r) = json_schema::compress(clean_output)
143        && let Some(r) = shorter_only(r, output)
144    {
145        return Some(r);
146    }
147
148    if let Some(r) = log_dedup::compress(clean_output)
149        && let Some(r) = shorter_only(r, output)
150    {
151        return Some(r);
152    }
153
154    if let Some(r) = test::compress(clean_output)
155        && let Some(r) = shorter_only(r, output)
156    {
157        return Some(r);
158    }
159
160    None
161}
162
163/// True for version-control commands whose output is authoritative under their
164/// own compressor and must not be reinterpreted by the generic log/test
165/// fallbacks (commit history is not application log output).
166pub(crate) fn has_vcs_owner(command: &str) -> bool {
167    let c = command.trim_start().to_ascii_lowercase();
168    c.starts_with("git ")
169        || c.starts_with("jj ")
170        || c.starts_with("gh ")
171        || c.starts_with("glab ")
172        || c.starts_with("hg ")
173}
174
175/// Collapse whitespace into single spaces so comparisons align with logical word tokens.
176fn normalize_shell_tokens(text: &str) -> String {
177    text.split_whitespace().collect::<Vec<_>>().join(" ")
178}
179
180/// True when `compressed` carries *more* tokens than the raw `original` — i.e.
181/// the transform inflated rather than compressed. Compared against the raw
182/// (pre-ANSI-strip) output so the guard matches the public `compress_output`
183/// invariant exactly: the returned text never tokenizes larger than its input.
184fn inflates_tokens(compressed: &str, original: &str) -> bool {
185    count_tokens(compressed) > count_tokens(original)
186}
187
188fn shorter_only(compressed: String, original: &str) -> Option<String> {
189    let orig_n = normalize_shell_tokens(original);
190    let comp_n = normalize_shell_tokens(&compressed);
191    let ct_c = count_tokens(&comp_n);
192    let ct_o = count_tokens(&orig_n);
193    if ct_c < ct_o || (ct_c == ct_o && comp_n.len() < orig_n.len()) {
194        Some(compressed)
195    } else {
196        None
197    }
198}
199
200type PatternMatcher = fn(&str) -> bool;
201type PatternHandler = fn(&str, &str) -> Option<String>;
202
203/// Ordered prefix → compressor dispatch table (#660 CC reduction): first
204/// matching entry wins, mirroring the previous `if c.starts_with(..) { return
205/// ...; }` cascade exactly — including that a matched entry's `None` is
206/// final, never falls through to a later entry. Registering a new CLI tool
207/// is now a one-line addition here instead of a new branch in
208/// `try_specific_pattern`.
209const PATTERNS: &[(PatternMatcher, PatternHandler)] = &[
210    (
211        |c| c.starts_with("git "),
212        |c, output| git::compress(c, output),
213    ),
214    (
215        |c| c.starts_with("gh "),
216        |c, output| gh::compress(c, output),
217    ),
218    (
219        |c| c.starts_with("glab "),
220        |c, output| glab::try_glab_pattern(c, output),
221    ),
222    (
223        |c| c == "terraform" || c.starts_with("terraform "),
224        |c, output| terraform::compress(c, output),
225    ),
226    (
227        |c| c == "make" || c.starts_with("make "),
228        |c, output| make::compress(c, output),
229    ),
230    (
231        |c| c == "just" || c.starts_with("just "),
232        |c, output| just::compress(c, output),
233    ),
234    (
235        |c| {
236            c.starts_with("mvn ")
237                || c.starts_with("./mvnw ")
238                || c.starts_with("mvnw ")
239                || c.starts_with("gradle ")
240                || c.starts_with("./gradlew ")
241                || c.starts_with("gradlew ")
242        },
243        |c, output| maven::compress(c, output),
244    ),
245    (
246        |c| c.starts_with("kubectl ") || c.starts_with("k "),
247        |c, output| kubectl::compress(c, output),
248    ),
249    (
250        |c| c.starts_with("helm "),
251        |c, output| helm::compress(c, output),
252    ),
253    (
254        |c| c.starts_with("pnpm "),
255        |c, output| pnpm::compress(c, output),
256    ),
257    (
258        |c| c.starts_with("bun ") || c.starts_with("bunx "),
259        |c, output| bun::compress(c, output),
260    ),
261    (
262        |c| c.starts_with("deno "),
263        |c, output| deno::compress(c, output),
264    ),
265    (
266        |c| c.starts_with("npm ") || c.starts_with("yarn "),
267        |c, output| npm::compress(c, output),
268    ),
269    (
270        |c| c.starts_with("cargo "),
271        |c, output| cargo::compress(c, output),
272    ),
273    (
274        |c| c.starts_with("docker ") || c.starts_with("docker-compose "),
275        |c, output| docker::compress(c, output),
276    ),
277    (
278        |c| c.starts_with("pip ") || c.starts_with("pip3 ") || c.starts_with("python -m pip"),
279        |c, output| pip::compress(c, output),
280    ),
281    (
282        |c| c.starts_with("mypy") || c.starts_with("python -m mypy") || c.starts_with("dmypy "),
283        |c, output| mypy::compress(c, output),
284    ),
285    (
286        |c| c.starts_with("pytest") || c.starts_with("python -m pytest"),
287        |c, output| pytest::compress(c, output).or_else(|| test::compress(output)),
288    ),
289    (
290        |c| c.starts_with("ruff "),
291        |c, output| ruff::compress(c, output),
292    ),
293    (
294        |c| {
295            c.starts_with("eslint")
296                || c.starts_with("npx eslint")
297                || c.starts_with("biome ")
298                || c.starts_with("stylelint")
299        },
300        |c, output| eslint::compress(c, output),
301    ),
302    (
303        |c| c.starts_with("prettier") || c.starts_with("npx prettier"),
304        |_c, output| prettier::compress(output),
305    ),
306    (
307        |c| c.starts_with("go ") || c.starts_with("golangci-lint") || c.starts_with("golint"),
308        |c, output| golang::compress(c, output),
309    ),
310    (
311        |c| {
312            c.starts_with("playwright")
313                || c.starts_with("npx playwright")
314                || c.starts_with("cypress")
315                || c.starts_with("npx cypress")
316        },
317        |c, output| playwright::compress(c, output),
318    ),
319    (
320        |c| c.starts_with("vitest") || c.starts_with("npx vitest") || c.starts_with("pnpm vitest"),
321        |_c, output| test::compress(output),
322    ),
323    (
324        |c| {
325            c.starts_with("next ")
326                || c.starts_with("npx next")
327                || c.starts_with("vite ")
328                || c.starts_with("npx vite")
329                || c.starts_with("vp ")
330                || c.starts_with("vite-plus ")
331        },
332        |c, output| next_build::compress(c, output),
333    ),
334    (
335        |c| c.starts_with("tsc") || c.contains("typescript"),
336        |_c, output| typescript::compress(output),
337    ),
338    (
339        |c| {
340            c.starts_with("rubocop")
341                || c.starts_with("bundle ")
342                || c.starts_with("rake ")
343                || c.starts_with("rails test")
344                || c.starts_with("rspec")
345        },
346        |c, output| ruby::compress(c, output),
347    ),
348    (
349        |c| c.starts_with("grep ") || c.starts_with("rg "),
350        |_c, output| grep::compress(output),
351    ),
352    (
353        |c| c.starts_with("find "),
354        |_c, output| find::compress(output),
355    ),
356    (
357        |c| c.starts_with("fd ") || c.starts_with("fdfind "),
358        |_c, output| fd::compress(output),
359    ),
360    (
361        |c| c.starts_with("ls ") || c == "ls",
362        |_c, output| ls::compress(output),
363    ),
364    (
365        |c| c.starts_with("curl "),
366        |c, output| curl::compress_with_cmd(c, output),
367    ),
368    (
369        |c| c.starts_with("wget "),
370        |_c, output| wget::compress(output),
371    ),
372    (
373        |c| c == "env" || c.starts_with("env ") || c.starts_with("printenv"),
374        |_c, output| env_filter::compress(output),
375    ),
376    (
377        |c| c.starts_with("dotnet "),
378        |c, output| dotnet::compress(c, output),
379    ),
380    (
381        |c| {
382            c.starts_with("flutter ")
383                || (c.starts_with("dart ") && (c.contains(" analyze") || c.ends_with(" analyze")))
384        },
385        |c, output| flutter::compress(c, output),
386    ),
387    (
388        |c| {
389            c.starts_with("poetry ")
390                || c.starts_with("uv ")
391                || c.starts_with("conda ")
392                || c.starts_with("mamba ")
393                || c.starts_with("pipx ")
394        },
395        |c, output| poetry::compress(c, output),
396    ),
397    (
398        |c| c.starts_with("aws "),
399        |c, output| aws::compress(c, output),
400    ),
401    (
402        |c| c.starts_with("psql ") || c.starts_with("pg_"),
403        |c, output| psql::compress(c, output),
404    ),
405    (
406        |c| c.starts_with("mysql ") || c.starts_with("mariadb "),
407        |c, output| mysql::compress(c, output),
408    ),
409    (
410        |c| c.starts_with("prisma ") || c.starts_with("npx prisma"),
411        |c, output| prisma::compress(c, output),
412    ),
413    (
414        |c| c.starts_with("swift "),
415        |c, output| swift::compress(c, output),
416    ),
417    (
418        |c| c.starts_with("zig "),
419        |c, output| zig::compress(c, output),
420    ),
421    (
422        |c| c.starts_with("cmake ") || c.starts_with("ctest"),
423        |c, output| cmake::compress(c, output),
424    ),
425    (
426        |c| c.starts_with("ninja"),
427        |c, output| ninja::compress(c, output),
428    ),
429    (
430        |c| c.starts_with("ansible") || c.starts_with("ansible-playbook"),
431        |c, output| ansible::compress(c, output),
432    ),
433    (
434        |c| c.starts_with("composer "),
435        |c, output| composer::compress(c, output),
436    ),
437    (
438        |c| c.starts_with("php artisan") || c.starts_with("artisan "),
439        |c, output| artisan::compress(c, output),
440    ),
441    (
442        |c| c.starts_with("./vendor/bin/pest") || c.starts_with("pest "),
443        |_c, output| artisan::compress("php artisan test", output),
444    ),
445    (
446        |c| c.starts_with("mix ") || c.starts_with("iex "),
447        |c, output| mix::compress(c, output),
448    ),
449    (
450        |c| c.starts_with("bazel ") || c.starts_with("blaze "),
451        |c, output| bazel::compress(c, output),
452    ),
453    (
454        |c| c.starts_with("systemctl ") || c.starts_with("journalctl"),
455        |c, output| systemd::compress(c, output),
456    ),
457    (
458        |c| c.starts_with("jest") || c.starts_with("npx jest") || c.starts_with("pnpm jest"),
459        |_c, output| test::compress(output),
460    ),
461    (
462        |c| c.starts_with("mocha") || c.starts_with("npx mocha"),
463        |_c, output| test::compress(output),
464    ),
465    (
466        |c| c.starts_with("tofu "),
467        |c, output| terraform::compress(c, output),
468    ),
469    (
470        |c| c.starts_with("ps ") || c == "ps",
471        |_c, output| sysinfo::compress_ps(output),
472    ),
473    (
474        |c| c.starts_with("df ") || c == "df",
475        |_c, output| sysinfo::compress_df(output),
476    ),
477    (
478        |c| c.starts_with("du ") || c == "du",
479        |_c, output| sysinfo::compress_du(output),
480    ),
481    (
482        |c| c.starts_with("ping "),
483        |_c, output| sysinfo::compress_ping(output),
484    ),
485    (
486        |c| c.starts_with("jq ") || c == "jq",
487        |_c, output| json_schema::compress(output),
488    ),
489    (
490        |c| c.starts_with("hadolint"),
491        |c, output| eslint::compress(c, output),
492    ),
493    (
494        |c| c.starts_with("yamllint") || c.starts_with("npx yamllint"),
495        |c, output| eslint::compress(c, output),
496    ),
497    (
498        |c| c.starts_with("markdownlint") || c.starts_with("npx markdownlint"),
499        |c, output| eslint::compress(c, output),
500    ),
501    (
502        |c| c.starts_with("oxlint") || c.starts_with("npx oxlint"),
503        |c, output| eslint::compress(c, output),
504    ),
505    (
506        |c| c.starts_with("pyright") || c.starts_with("basedpyright"),
507        |c, output| mypy::compress(c, output),
508    ),
509    (
510        |c| c.starts_with("turbo ") || c.starts_with("npx turbo"),
511        |c, output| npm::compress(c, output),
512    ),
513    (
514        |c| c.starts_with("nx ") || c.starts_with("npx nx"),
515        |c, output| npm::compress(c, output),
516    ),
517    (
518        |c| c.starts_with("clang++ ") || c.starts_with("clang "),
519        |c, output| clang::compress(c, output),
520    ),
521    (
522        |c| {
523            c.starts_with("gcc ")
524                || c.starts_with("g++ ")
525                || c.starts_with("cc ")
526                || c.starts_with("c++ ")
527        },
528        |c, output| cmake::compress(c, output),
529    ),
530    // --- data domain (#657) ---
531    (
532        |c| c == "dbt" || c.starts_with("dbt "),
533        |c, output| dbt::compress(c, output),
534    ),
535    (
536        |c| c == "alembic" || c.starts_with("alembic "),
537        |c, output| alembic::compress(c, output),
538    ),
539    (
540        |c| c == "flyway" || c.starts_with("flyway "),
541        |c, output| flyway::compress(c, output),
542    ),
543    (
544        |c| c.starts_with("spark-submit") || c.starts_with("spark-sql") || c.starts_with("pyspark"),
545        |c, output| spark::compress(c, output),
546    ),
547    // --- ai domain (#658) ---
548    (
549        |c| c == "ollama" || c.starts_with("ollama "),
550        |c, output| ollama::compress(c, output),
551    ),
552    (
553        |c| c.starts_with("mlflow "),
554        |c, output| mlflow::compress(c, output),
555    ),
556    // --- security / supply-chain (#659) ---
557    (
558        |c| c.starts_with("semgrep "),
559        |c, output| semgrep::compress(c, output),
560    ),
561    (
562        |c| c.starts_with("trivy "),
563        |c, output| trivy::compress(c, output),
564    ),
565    (
566        |c| c.starts_with("grype "),
567        |c, output| grype::compress(c, output),
568    ),
569    (
570        |c| c.starts_with("syft "),
571        |c, output| syft::compress(c, output),
572    ),
573    (
574        |c| c.starts_with("cosign "),
575        |c, output| cosign::compress(c, output),
576    ),
577    (
578        |c| c.starts_with("swiftlint"),
579        |c, output| swiftlint::compress(c, output),
580    ),
581    // --- vcs / toolchain (#660) ---
582    (
583        |c| c == "jj" || c.starts_with("jj "),
584        |c, output| jj::compress(c, output),
585    ),
586    (
587        |c| c == "mise" || c.starts_with("mise "),
588        |c, output| mise::compress(c, output),
589    ),
590    (
591        |c| c == "buf" || c.starts_with("buf "),
592        |c, output| buf::compress(c, output),
593    ),
594    (
595        |c| c.starts_with("gem "),
596        |c, output| gem::compress(c, output),
597    ),
598    // --- edge / infra (#661) ---
599    (
600        |c| c == "pulumi" || c.starts_with("pulumi "),
601        |c, output| pulumi::compress(c, output),
602    ),
603    (
604        |c| c.starts_with("linkerd "),
605        |c, output| linkerd::compress(c, output),
606    ),
607    (
608        |c| c.starts_with("argocd "),
609        |c, output| argocd::compress(c, output),
610    ),
611    (
612        |c| {
613            c == "vercel"
614                || c.starts_with("vercel ")
615                || c == "fly"
616                || c.starts_with("fly ")
617                || c.starts_with("flyctl ")
618                || c.starts_with("wrangler ")
619                || c.starts_with("skaffold ")
620                || c.starts_with("supabase ")
621        },
622        |c, output| deploy::compress(c, output),
623    ),
624];
625
626pub fn try_specific_pattern(cmd: &str, output: &str) -> Option<String> {
627    let cl = cmd.to_ascii_lowercase();
628    let c = cl.as_str();
629
630    PATTERNS
631        .iter()
632        .find(|(matches, _)| matches(c))
633        .and_then(|(_, handle)| handle(c, output))
634}
635
636#[cfg(test)]
637mod tests {
638    use super::*;
639
640    #[test]
641    fn routes_git_commands() {
642        let output = "On branch main\nnothing to commit";
643        assert!(compress_output("git status", output).is_some());
644    }
645
646    #[test]
647    fn vcs_path_never_inflates_tokens() {
648        // Regression for the `compress_output_never_inflates_tokens` property
649        // (Windows CI): the VCS branch returned the git compressor's reshaped
650        // output without the `shorter_only` guard the other paths use, so this
651        // tiny adversarial `git status` body grew 10 -> 11 tokens. The result
652        // must now never tokenize larger than its input (None == use original).
653        let output = " Abu a\nAa aa_A00A\n\n-";
654        if let Some(compressed) = compress_output("git status", output) {
655            assert!(
656                count_tokens(&compressed) <= count_tokens(output),
657                "VCS compress inflated: {} > {}",
658                count_tokens(&compressed),
659                count_tokens(output),
660            );
661        }
662    }
663
664    #[test]
665    fn routes_cargo_commands() {
666        let output = "   Compiling lean-ctx v2.1.1\n    Finished `release` profile [optimized] target(s) in 30.5s";
667        assert!(compress_output("cargo build --release", output).is_some());
668    }
669
670    #[test]
671    fn routes_npm_commands() {
672        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";
673        assert!(compress_output("npm install", output).is_some());
674    }
675
676    #[test]
677    fn routes_docker_commands() {
678        let output = "CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES";
679        // docker ps is Verbatim (via is_container_listing), so compress_output
680        // correctly returns None (policy gate). docker build should still compress.
681        assert!(compress_output("docker ps", output).is_none());
682        let build_output =
683            "Step 1/5 : FROM node:18\n ---> abc123\nStep 2/5 : COPY . .\nSuccessfully built def456";
684        assert!(compress_output("docker build .", build_output).is_some());
685    }
686
687    #[test]
688    fn routes_mypy_commands() {
689        let output = "src/main.py:10: error: Missing return  [return]\nFound 1 error in 1 file (checked 3 source files)";
690        assert!(compress_output("mypy .", output).is_some());
691        assert!(compress_output("python -m mypy src/", output).is_some());
692    }
693
694    #[test]
695    fn routes_pytest_commands() {
696        let output = "===== test session starts =====\ncollected 5 items\ntest_main.py ..... [100%]\n===== 5 passed in 0.5s =====";
697        assert!(compress_output("pytest", output).is_some());
698        assert!(compress_output("python -m pytest tests/", output).is_some());
699    }
700
701    #[test]
702    fn routes_data_domain() {
703        let dbt =
704            "20:14:02  Found 12 models\n20:14:20  Done. PASS=11 WARN=0 ERROR=1 SKIP=0 TOTAL=12";
705        assert!(
706            compress_output("dbt run", dbt).is_some(),
707            "dbt routed+compressible"
708        );
709        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";
710        assert!(compress_output("alembic upgrade head", alembic).is_some());
711        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";
712        assert!(compress_output("flyway migrate", flyway).is_some());
713        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";
714        assert!(compress_output("spark-submit app.py", spark).is_some());
715    }
716
717    #[test]
718    fn routes_ai_domain() {
719        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";
720        assert!(compress_output("ollama list", ollama).is_some());
721        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 ===";
722        assert!(compress_output("mlflow run .", mlflow).is_some());
723    }
724
725    #[test]
726    fn routes_security_domain() {
727        let trivy = "2024-01-01T12:00:00.000Z\tINFO\tscanning\nnginx:latest (debian 12.1)\n=====\nTotal: 45 (LOW: 20, HIGH: 8, CRITICAL: 2)";
728        assert!(compress_output("trivy image nginx", trivy).is_some());
729        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";
730        assert!(compress_output("grype nginx", grype).is_some());
731        let syft = "NAME       VERSION    TYPE\nadduser    3.118      deb\napt        2.6.1      deb\nlodash     4.17.21    npm";
732        assert!(compress_output("syft nginx", syft).is_some());
733        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.";
734        assert!(compress_output("semgrep scan", semgrep).is_some());
735        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.";
736        assert!(compress_output("swiftlint", swiftlint).is_some());
737    }
738
739    #[test]
740    fn routes_vcs_toolchain_domain() {
741        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~";
742        assert!(compress_output("jj log", jj).is_some());
743        let mise = "node    20.10.0  ~/.config/mise/config.toml\npython  3.12.0   ~/.tool-versions\nrust    1.75.0   ~/.config/mise/config.toml";
744        assert!(compress_output("mise ls", mise).is_some());
745        let buf_lines: Vec<String> = (0..30)
746            .map(|i| format!("proto/f{i}.proto:{i}:1:Field name should be lower_snake_case here."))
747            .collect();
748        let buf = buf_lines.join("\n");
749        assert!(compress_output("buf lint", &buf).is_some());
750        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";
751        assert!(compress_output("gem install rails", gem).is_some());
752        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";
753        assert!(compress_output("uv add pandas", uv).is_some());
754    }
755
756    #[test]
757    fn routes_edge_infra_domain() {
758        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";
759        assert!(compress_output("pulumi up", pulumi).is_some());
760        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 ×";
761        assert!(compress_output("linkerd check", linkerd).is_some());
762        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";
763        assert!(compress_output("argocd app get myapp", argocd).is_some());
764        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]";
765        assert!(compress_output("vercel deploy --prod", vercel).is_some());
766        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";
767        assert!(compress_output("wrangler deploy", wrangler).is_some());
768    }
769
770    #[test]
771    fn unknown_command_returns_none() {
772        assert!(compress_output("some-unknown-tool --version", "v1.0").is_none());
773    }
774
775    #[test]
776    fn case_insensitive_routing() {
777        let output = "On branch main\nnothing to commit";
778        assert!(compress_output("Git Status", output).is_some());
779        assert!(compress_output("GIT STATUS", output).is_some());
780    }
781
782    #[test]
783    fn routes_vp_and_vite_plus() {
784        let output = "  VITE v5.0.0  ready in 200 ms\n\n  -> Local:   http://localhost:5173/\n  -> Network: http://192.168.1.2:5173/";
785        assert!(compress_output("vp build", output).is_some());
786        assert!(compress_output("vite-plus build", output).is_some());
787    }
788
789    #[test]
790    fn routes_bunx_commands() {
791        let output = "1 pass tests\n0 fail tests\n3 skip tests\nDone 12ms\nsome extra line\nmore output here";
792        let result = compress_output("bunx test", output);
793        assert!(
794            result.is_some(),
795            "bunx should compress when output is large enough"
796        );
797        assert!(result.unwrap().contains("bun test: 1 passed"));
798    }
799
800    #[test]
801    fn routes_deno_task() {
802        let output = "Task dev deno run --allow-net server.ts\nListening on http://localhost:8000";
803        assert!(try_specific_pattern("deno task dev", output).is_some());
804    }
805
806    #[test]
807    fn routes_jest_commands() {
808        let output = "PASS  tests/main.test.js\nTest Suites: 1 passed, 1 total\nTests:       5 passed, 5 total\nTime:        2.5 s";
809        assert!(try_specific_pattern("jest", output).is_some());
810        assert!(try_specific_pattern("npx jest --coverage", output).is_some());
811    }
812
813    #[test]
814    fn routes_mocha_commands() {
815        let output = "  3 passing (50ms)\n  1 failing\n\n  1) Array #indexOf():\n     Error: expected -1 to equal 0";
816        assert!(try_specific_pattern("mocha", output).is_some());
817        assert!(try_specific_pattern("npx mocha tests/", output).is_some());
818    }
819
820    #[test]
821    fn routes_tofu_commands() {
822        let output = "Initializing the backend...\nInitializing provider plugins...\nTerraform has been successfully initialized!";
823        assert!(try_specific_pattern("tofu init", output).is_some());
824    }
825
826    #[test]
827    fn routes_ps_commands() {
828        let mut lines = vec!["USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND".to_string()];
829        for i in 0..20 {
830            lines.push(format!("user {i} 0.0 0.1 1234 123 ? S 10:00 0:00 proc_{i}"));
831        }
832        let output = lines.join("\n");
833        assert!(try_specific_pattern("ps aux", &output).is_some());
834    }
835
836    #[test]
837    fn routes_ping_commands() {
838        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";
839        assert!(try_specific_pattern("ping -c 3 google.com", output).is_some());
840    }
841
842    #[test]
843    fn routes_jq_to_json_schema() {
844        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}]}";
845        assert!(try_specific_pattern("jq '.items' data.json", output).is_some());
846    }
847
848    #[test]
849    fn routes_linting_tools() {
850        let lint_output = "src/main.py:10: error: Missing return\nsrc/main.py:20: error: Unused var\nFound 2 errors";
851        assert!(try_specific_pattern("hadolint Dockerfile", lint_output).is_some());
852        assert!(try_specific_pattern("oxlint src/", lint_output).is_some());
853        assert!(try_specific_pattern("pyright src/", lint_output).is_some());
854        assert!(try_specific_pattern("basedpyright src/", lint_output).is_some());
855    }
856
857    #[test]
858    fn routes_fd_commands() {
859        let output = "src/main.rs\nsrc/lib.rs\nsrc/util/helpers.rs\nsrc/util/math.rs\ntests/integration.rs\n";
860        assert!(try_specific_pattern("fd --extension rs", output).is_some());
861        assert!(try_specific_pattern("fdfind .rs", output).is_some());
862    }
863
864    #[test]
865    fn routes_just_commands() {
866        let output = "Available recipes:\n    build\n    test\n    lint\n";
867        assert!(try_specific_pattern("just --list", output).is_some());
868        assert!(try_specific_pattern("just build", output).is_some());
869    }
870
871    #[test]
872    fn routes_ninja_commands() {
873        let output = "[1/10] Compiling foo.c\n[10/10] Linking app\n";
874        assert!(try_specific_pattern("ninja", output).is_some());
875        assert!(try_specific_pattern("ninja -j4", output).is_some());
876    }
877
878    #[test]
879    fn routes_clang_commands() {
880        let output =
881            "src/main.c:10:5: error: use of undeclared identifier 'foo'\n1 error generated.\n";
882        assert!(try_specific_pattern("clang src/main.c", output).is_some());
883        assert!(try_specific_pattern("clang++ -std=c++17 main.cpp", output).is_some());
884    }
885
886    #[test]
887    fn routes_cargo_run() {
888        let output = "   Compiling foo v0.1.0\n    Finished `dev` profile\nHello, world!";
889        assert!(try_specific_pattern("cargo run", output).is_some());
890    }
891
892    #[test]
893    fn routes_cargo_bench() {
894        let output = "   Compiling foo v0.1.0\ntest bench_parse ... bench: 1234 ns/iter";
895        assert!(try_specific_pattern("cargo bench", output).is_some());
896    }
897
898    #[test]
899    fn routes_build_tools() {
900        let build_output = "   Compiling foo v0.1.0\n    Finished release [optimized]";
901        assert!(try_specific_pattern("gcc -o main main.c", build_output).is_some());
902        assert!(try_specific_pattern("g++ -o main main.cpp", build_output).is_some());
903    }
904
905    #[test]
906    fn routes_monorepo_tools() {
907        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";
908        assert!(try_specific_pattern("turbo install", output).is_some());
909        assert!(try_specific_pattern("nx install", output).is_some());
910    }
911
912    #[test]
913    fn gh_api_passthrough_never_compresses() {
914        let huge = "line\n".repeat(5000);
915        assert!(
916            compress_output("gh api repos/owner/repo/actions/jobs/123/logs", &huge).is_none(),
917            "gh api must never be compressed, even for large output"
918        );
919        assert!(compress_output("gh api repos/owner/repo/actions/runs/123/logs", &huge).is_none());
920    }
921
922    #[test]
923    fn gh_log_flags_passthrough() {
924        let huge = "line\n".repeat(5000);
925        assert!(compress_output("gh run view 123 --log-failed", &huge).is_none());
926        assert!(compress_output("gh run view 123 --log", &huge).is_none());
927    }
928
929    #[test]
930    fn gh_structured_commands_still_compress() {
931        let output = "On branch main\nnothing to commit";
932        assert!(try_specific_pattern("gh pr list", output).is_some());
933        assert!(try_specific_pattern("gh run list", output).is_some());
934    }
935}