/// Pattern engine version. Bump when output format changes to maintain
/// shell-output determinism guarantees. Consumers (proofs, benchmarks)
/// can embed this version to detect pattern-breaking updates.
///
/// v2 (#936): `json_schema::compress` now prefers the lossless `json_crush`
/// form over the schema outline for redundant array-of-object payloads.
pub const PATTERN_ENGINE_VERSION: u32 = 2;
pub mod alembic;
pub mod ansible;
pub mod argocd;
pub mod artisan;
pub mod aws;
pub mod bazel;
pub mod buf;
pub mod bun;
pub mod cargo;
pub mod cargo_diagnostics;
pub mod clang;
pub mod cmake;
pub mod composer;
pub mod cosign;
pub mod curl;
pub mod dbt;
pub mod deno;
pub mod deploy;
pub mod deps_cmd;
pub mod docker;
pub mod dotnet;
pub mod env_filter;
pub mod eslint;
pub mod fd;
pub mod find;
pub mod flutter;
pub mod flyway;
pub mod gem;
pub mod gh;
pub mod git;
pub mod glab;
pub mod golang;
pub mod grep;
pub mod grype;
pub mod helm;
pub mod jj;
pub mod json_schema;
pub mod just;
pub mod kubectl;
pub mod linkerd;
pub mod log_dedup;
pub mod ls;
pub mod make;
pub mod maven;
pub mod mise;
pub mod mix;
pub mod mlflow;
pub mod mypy;
pub mod mysql;
pub mod next_build;
pub mod ninja;
pub mod npm;
pub mod ollama;
pub mod php;
pub mod pip;
pub mod playwright;
pub mod pnpm;
pub mod poetry;
pub mod prettier;
pub mod prisma;
pub mod psql;
pub mod pulumi;
pub mod pytest;
pub mod ruby;
pub mod ruff;
pub mod semgrep;
pub mod spark;
pub mod swift;
pub mod swiftlint;
pub mod syft;
pub mod sysinfo;
pub mod systemd;
pub mod terraform;
pub mod test;
pub mod trivy;
pub mod typescript;
pub mod wget;
pub mod zig;
use crate::core::tokens::count_tokens;
pub fn compress_output(command: &str, output: &str) -> Option<String> {
// Policy gate: protected commands (Passthrough + Verbatim) must
// never be pattern-compressed. The caller (compress_if_beneficial
// or ctx_shell::handle) should have already checked, but we
// defend in depth here.
let policy = crate::shell::output_policy::classify(command, &[]);
if policy.is_protected() {
return None;
}
let stripped;
let clean_output = {
let s = crate::core::compressor::strip_ansi(output);
if s.len() < output.len() {
stripped = s;
&stripped
} else {
output
}
};
if let Some(engine) = crate::core::filters::FilterEngine::load()
&& let Some(filtered) = engine.apply(command, clean_output)
{
return shorter_only(filtered, output);
}
// VCS history (git/jj/gh/glab/hg) is owned by its dedicated compressor. Its
// lines look log-ish (one per commit) but are NOT application logs, so the
// generic json/log/test fallbacks would mis-summarize them — e.g. truncating
// an explicit `git log --oneline -40` to "last 15" or reading a commit
// subject like "fix: pending_errors" as an error line. Return the dedicated
// compressor's result directly — even when it is not shorter, so an already
// compact oneline log is preserved verbatim (full history intact) instead of
// being reshaped by a generic heuristic.
if has_vcs_owner(command) {
// The VCS compressor is authoritative and is kept even when it is not
// strictly *shorter*, so a compact `git log --oneline` is preserved
// verbatim (full history intact). It must still never return *more*
// tokens than its input, though — a tiny adversarial `git status` body
// could otherwise reshape into a one-token-larger summary and break the
// never-inflate invariant. Allow equal (verbatim), reject only growth.
return try_specific_pattern(command, clean_output)
.filter(|c| !c.trim().is_empty())
.filter(|c| !inflates_tokens(c, output));
}
if let Some(compressed) = try_specific_pattern(command, clean_output)
&& let Some(r) = shorter_only(compressed, output)
{
return Some(r);
}
if let Some(r) = json_schema::compress(clean_output)
&& let Some(r) = shorter_only(r, output)
{
return Some(r);
}
if let Some(r) = log_dedup::compress(clean_output)
&& let Some(r) = shorter_only(r, output)
{
return Some(r);
}
if let Some(r) = test::compress(clean_output)
&& let Some(r) = shorter_only(r, output)
{
return Some(r);
}
None
}
/// True for version-control commands whose output is authoritative under their
/// own compressor and must not be reinterpreted by the generic log/test
/// fallbacks (commit history is not application log output).
pub(crate) fn has_vcs_owner(command: &str) -> bool {
let c = command.trim_start().to_ascii_lowercase();
c.starts_with("git ")
|| c.starts_with("jj ")
|| c.starts_with("gh ")
|| c.starts_with("glab ")
|| c.starts_with("hg ")
}
/// Collapse whitespace into single spaces so comparisons align with logical word tokens.
fn normalize_shell_tokens(text: &str) -> String {
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// True when `compressed` carries *more* tokens than the raw `original` — i.e.
/// the transform inflated rather than compressed. Compared against the raw
/// (pre-ANSI-strip) output so the guard matches the public `compress_output`
/// invariant exactly: the returned text never tokenizes larger than its input.
fn inflates_tokens(compressed: &str, original: &str) -> bool {
count_tokens(compressed) > count_tokens(original)
}
fn shorter_only(compressed: String, original: &str) -> Option<String> {
let orig_n = normalize_shell_tokens(original);
let comp_n = normalize_shell_tokens(&compressed);
let ct_c = count_tokens(&comp_n);
let ct_o = count_tokens(&orig_n);
if ct_c < ct_o || (ct_c == ct_o && comp_n.len() < orig_n.len()) {
Some(compressed)
} else {
None
}
}
type PatternMatcher = fn(&str) -> bool;
type PatternHandler = fn(&str, &str) -> Option<String>;
/// Ordered prefix → compressor dispatch table (#660 CC reduction): first
/// matching entry wins, mirroring the previous `if c.starts_with(..) { return
/// ...; }` cascade exactly — including that a matched entry's `None` is
/// final, never falls through to a later entry. Registering a new CLI tool
/// is now a one-line addition here instead of a new branch in
/// `try_specific_pattern`.
const PATTERNS: &[(PatternMatcher, PatternHandler)] = &[
(
|c| c.starts_with("git "),
|c, output| git::compress(c, output),
),
(
|c| c.starts_with("gh "),
|c, output| gh::compress(c, output),
),
(
|c| c.starts_with("glab "),
|c, output| glab::try_glab_pattern(c, output),
),
(
|c| c == "terraform" || c.starts_with("terraform "),
|c, output| terraform::compress(c, output),
),
(
|c| c == "make" || c.starts_with("make "),
|c, output| make::compress(c, output),
),
(
|c| c == "just" || c.starts_with("just "),
|c, output| just::compress(c, output),
),
(
|c| {
c.starts_with("mvn ")
|| c.starts_with("./mvnw ")
|| c.starts_with("mvnw ")
|| c.starts_with("gradle ")
|| c.starts_with("./gradlew ")
|| c.starts_with("gradlew ")
},
|c, output| maven::compress(c, output),
),
(
|c| c.starts_with("kubectl ") || c.starts_with("k "),
|c, output| kubectl::compress(c, output),
),
(
|c| c.starts_with("helm "),
|c, output| helm::compress(c, output),
),
(
|c| c.starts_with("pnpm "),
|c, output| pnpm::compress(c, output),
),
(
|c| c.starts_with("bun ") || c.starts_with("bunx "),
|c, output| bun::compress(c, output),
),
(
|c| c.starts_with("deno "),
|c, output| deno::compress(c, output),
),
(
|c| c.starts_with("npm ") || c.starts_with("yarn "),
|c, output| npm::compress(c, output),
),
(
|c| c.starts_with("cargo "),
|c, output| cargo::compress(c, output),
),
(
|c| c.starts_with("docker ") || c.starts_with("docker-compose "),
|c, output| docker::compress(c, output),
),
(
|c| c.starts_with("pip ") || c.starts_with("pip3 ") || c.starts_with("python -m pip"),
|c, output| pip::compress(c, output),
),
(
|c| c.starts_with("mypy") || c.starts_with("python -m mypy") || c.starts_with("dmypy "),
|c, output| mypy::compress(c, output),
),
(
|c| c.starts_with("pytest") || c.starts_with("python -m pytest"),
|c, output| pytest::compress(c, output).or_else(|| test::compress(output)),
),
(
|c| c.starts_with("ruff "),
|c, output| ruff::compress(c, output),
),
(
|c| {
c.starts_with("eslint")
|| c.starts_with("npx eslint")
|| c.starts_with("biome ")
|| c.starts_with("stylelint")
},
|c, output| eslint::compress(c, output),
),
(
|c| c.starts_with("prettier") || c.starts_with("npx prettier"),
|_c, output| prettier::compress(output),
),
(
|c| c.starts_with("go ") || c.starts_with("golangci-lint") || c.starts_with("golint"),
|c, output| golang::compress(c, output),
),
(
|c| {
c.starts_with("playwright")
|| c.starts_with("npx playwright")
|| c.starts_with("cypress")
|| c.starts_with("npx cypress")
},
|c, output| playwright::compress(c, output),
),
(
|c| c.starts_with("vitest") || c.starts_with("npx vitest") || c.starts_with("pnpm vitest"),
|_c, output| test::compress(output),
),
(
|c| {
c.starts_with("next ")
|| c.starts_with("npx next")
|| c.starts_with("vite ")
|| c.starts_with("npx vite")
|| c.starts_with("vp ")
|| c.starts_with("vite-plus ")
},
|c, output| next_build::compress(c, output),
),
(
|c| c.starts_with("tsc") || c.contains("typescript"),
|_c, output| typescript::compress(output),
),
(
|c| {
c.starts_with("rubocop")
|| c.starts_with("bundle ")
|| c.starts_with("rake ")
|| c.starts_with("rails test")
|| c.starts_with("rspec")
},
|c, output| ruby::compress(c, output),
),
(|c| is_grep_family(c), |_c, output| grep::compress(output)),
(
|c| c.starts_with("find "),
|_c, output| find::compress(output),
),
(
|c| c.starts_with("fd ") || c.starts_with("fdfind "),
|_c, output| fd::compress(output),
),
(
|c| c.starts_with("ls ") || c == "ls",
|_c, output| ls::compress(output),
),
(
|c| c.starts_with("curl "),
|c, output| curl::compress_with_cmd(c, output),
),
(
|c| c.starts_with("wget "),
|_c, output| wget::compress(output),
),
(
|c| c == "env" || c.starts_with("env ") || c.starts_with("printenv"),
|_c, output| env_filter::compress(output),
),
(
|c| c.starts_with("dotnet "),
|c, output| dotnet::compress(c, output),
),
(
|c| {
c.starts_with("flutter ")
|| (c.starts_with("dart ") && (c.contains(" analyze") || c.ends_with(" analyze")))
},
|c, output| flutter::compress(c, output),
),
(
|c| {
c.starts_with("poetry ")
|| c.starts_with("uv ")
|| c.starts_with("conda ")
|| c.starts_with("mamba ")
|| c.starts_with("pipx ")
},
|c, output| poetry::compress(c, output),
),
(
|c| c.starts_with("aws "),
|c, output| aws::compress(c, output),
),
(
|c| c.starts_with("psql ") || c.starts_with("pg_"),
|c, output| psql::compress(c, output),
),
(
|c| c.starts_with("mysql ") || c.starts_with("mariadb "),
|c, output| mysql::compress(c, output),
),
(
|c| c.starts_with("prisma ") || c.starts_with("npx prisma"),
|c, output| prisma::compress(c, output),
),
(
|c| c.starts_with("swift "),
|c, output| swift::compress(c, output),
),
(
|c| c.starts_with("zig "),
|c, output| zig::compress(c, output),
),
(
|c| c.starts_with("cmake ") || c.starts_with("ctest"),
|c, output| cmake::compress(c, output),
),
(
|c| c.starts_with("ninja"),
|c, output| ninja::compress(c, output),
),
(
|c| c.starts_with("ansible") || c.starts_with("ansible-playbook"),
|c, output| ansible::compress(c, output),
),
(
|c| c.starts_with("composer "),
|c, output| composer::compress(c, output),
),
(
|c| c.starts_with("php artisan") || c.starts_with("artisan "),
|c, output| artisan::compress(c, output),
),
(
|c| c.starts_with("./vendor/bin/pest") || c.starts_with("pest "),
|_c, output| artisan::compress("php artisan test", output),
),
(
|c| c.starts_with("mix ") || c.starts_with("iex "),
|c, output| mix::compress(c, output),
),
(
|c| c.starts_with("bazel ") || c.starts_with("blaze "),
|c, output| bazel::compress(c, output),
),
(
|c| c.starts_with("systemctl ") || c.starts_with("journalctl"),
|c, output| systemd::compress(c, output),
),
(
|c| c.starts_with("jest") || c.starts_with("npx jest") || c.starts_with("pnpm jest"),
|_c, output| test::compress(output),
),
(
|c| c.starts_with("mocha") || c.starts_with("npx mocha"),
|_c, output| test::compress(output),
),
(
|c| c.starts_with("tofu "),
|c, output| terraform::compress(c, output),
),
(
|c| c.starts_with("ps ") || c == "ps",
|_c, output| sysinfo::compress_ps(output),
),
(
|c| c.starts_with("df ") || c == "df",
|_c, output| sysinfo::compress_df(output),
),
(
|c| c.starts_with("du ") || c == "du",
|_c, output| sysinfo::compress_du(output),
),
(
|c| c.starts_with("ping "),
|_c, output| sysinfo::compress_ping(output),
),
(
|c| c.starts_with("jq ") || c == "jq",
|_c, output| json_schema::compress(output),
),
(
|c| c.starts_with("hadolint"),
|c, output| eslint::compress(c, output),
),
(
|c| c.starts_with("yamllint") || c.starts_with("npx yamllint"),
|c, output| eslint::compress(c, output),
),
(
|c| c.starts_with("markdownlint") || c.starts_with("npx markdownlint"),
|c, output| eslint::compress(c, output),
),
(
|c| c.starts_with("oxlint") || c.starts_with("npx oxlint"),
|c, output| eslint::compress(c, output),
),
(
|c| c.starts_with("pyright") || c.starts_with("basedpyright"),
|c, output| mypy::compress(c, output),
),
(
|c| c.starts_with("turbo ") || c.starts_with("npx turbo"),
|c, output| npm::compress(c, output),
),
(
|c| c.starts_with("nx ") || c.starts_with("npx nx"),
|c, output| npm::compress(c, output),
),
(
|c| c.starts_with("clang++ ") || c.starts_with("clang "),
|c, output| clang::compress(c, output),
),
(
|c| {
c.starts_with("gcc ")
|| c.starts_with("g++ ")
|| c.starts_with("cc ")
|| c.starts_with("c++ ")
},
|c, output| cmake::compress(c, output),
),
// --- data domain (#657) ---
(
|c| c == "dbt" || c.starts_with("dbt "),
|c, output| dbt::compress(c, output),
),
(
|c| c == "alembic" || c.starts_with("alembic "),
|c, output| alembic::compress(c, output),
),
(
|c| c == "flyway" || c.starts_with("flyway "),
|c, output| flyway::compress(c, output),
),
(
|c| c.starts_with("spark-submit") || c.starts_with("spark-sql") || c.starts_with("pyspark"),
|c, output| spark::compress(c, output),
),
// --- ai domain (#658) ---
(
|c| c == "ollama" || c.starts_with("ollama "),
|c, output| ollama::compress(c, output),
),
(
|c| c.starts_with("mlflow "),
|c, output| mlflow::compress(c, output),
),
// --- security / supply-chain (#659) ---
(
|c| c.starts_with("semgrep "),
|c, output| semgrep::compress(c, output),
),
(
|c| c.starts_with("trivy "),
|c, output| trivy::compress(c, output),
),
(
|c| c.starts_with("grype "),
|c, output| grype::compress(c, output),
),
(
|c| c.starts_with("syft "),
|c, output| syft::compress(c, output),
),
(
|c| c.starts_with("cosign "),
|c, output| cosign::compress(c, output),
),
(
|c| c.starts_with("swiftlint"),
|c, output| swiftlint::compress(c, output),
),
// --- vcs / toolchain (#660) ---
(
|c| c == "jj" || c.starts_with("jj "),
|c, output| jj::compress(c, output),
),
(
|c| c == "mise" || c.starts_with("mise "),
|c, output| mise::compress(c, output),
),
(
|c| c == "buf" || c.starts_with("buf "),
|c, output| buf::compress(c, output),
),
(
|c| c.starts_with("gem "),
|c, output| gem::compress(c, output),
),
// --- edge / infra (#661) ---
(
|c| c == "pulumi" || c.starts_with("pulumi "),
|c, output| pulumi::compress(c, output),
),
(
|c| c.starts_with("linkerd "),
|c, output| linkerd::compress(c, output),
),
(
|c| c.starts_with("argocd "),
|c, output| argocd::compress(c, output),
),
(
|c| {
c == "vercel"
|| c.starts_with("vercel ")
|| c == "fly"
|| c.starts_with("fly ")
|| c.starts_with("flyctl ")
|| c.starts_with("wrangler ")
|| c.starts_with("skaffold ")
|| c.starts_with("supabase ")
},
|c, output| deploy::compress(c, output),
),
];
/// A grep-family search command, bare or with arguments (#980, #985).
///
/// The bare form matters: `proxy::compress::infer_command` synthesises `grep`
/// (no arguments) from tool names like `search_files`. The old `starts_with("grep ")`
/// required a trailing space and never matched, so those results fell through to the
/// terse pipeline which corrupted source identifiers.
fn is_grep_family(cmd: &str) -> bool {
let first = cmd.split_whitespace().next().unwrap_or("");
let base = first.rsplit('/').next().unwrap_or(first);
matches!(
base,
"grep" | "egrep" | "fgrep" | "rg" | "ag" | "ack" | "ugrep" | "sift"
)
}
pub fn try_specific_pattern(cmd: &str, output: &str) -> Option<String> {
let cl = cmd.to_ascii_lowercase();
let c = cl.as_str();
PATTERNS
.iter()
.find(|(matches, _)| matches(c))
.and_then(|(_, handle)| handle(c, output))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn routes_git_commands() {
let output = "On branch main\nnothing to commit";
assert!(compress_output("git status", output).is_some());
}
#[test]
fn vcs_path_never_inflates_tokens() {
// Regression for the `compress_output_never_inflates_tokens` property
// (Windows CI): the VCS branch returned the git compressor's reshaped
// output without the `shorter_only` guard the other paths use, so this
// tiny adversarial `git status` body grew 10 -> 11 tokens. The result
// must now never tokenize larger than its input (None == use original).
let output = " Abu a\nAa aa_A00A\n\n-";
if let Some(compressed) = compress_output("git status", output) {
assert!(
count_tokens(&compressed) <= count_tokens(output),
"VCS compress inflated: {} > {}",
count_tokens(&compressed),
count_tokens(output),
);
}
}
#[test]
fn routes_cargo_commands() {
let output = " Compiling lean-ctx v2.1.1\n Finished `release` profile [optimized] target(s) in 30.5s";
assert!(compress_output("cargo build --release", output).is_some());
}
#[test]
fn routes_npm_commands() {
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";
assert!(compress_output("npm install", output).is_some());
}
#[test]
fn routes_docker_commands() {
let output = "CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES";
// docker ps is Verbatim (via is_container_listing), so compress_output
// correctly returns None (policy gate). docker build should still compress.
assert!(compress_output("docker ps", output).is_none());
let build_output =
"Step 1/5 : FROM node:18\n ---> abc123\nStep 2/5 : COPY . .\nSuccessfully built def456";
assert!(compress_output("docker build .", build_output).is_some());
}
#[test]
fn routes_mypy_commands() {
let output = "src/main.py:10: error: Missing return [return]\nFound 1 error in 1 file (checked 3 source files)";
assert!(compress_output("mypy .", output).is_some());
assert!(compress_output("python -m mypy src/", output).is_some());
}
#[test]
fn routes_pytest_commands() {
let output = "===== test session starts =====\ncollected 5 items\ntest_main.py ..... [100%]\n===== 5 passed in 0.5s =====";
assert!(compress_output("pytest", output).is_some());
assert!(compress_output("python -m pytest tests/", output).is_some());
}
#[test]
fn routes_data_domain() {
let dbt =
"20:14:02 Found 12 models\n20:14:20 Done. PASS=11 WARN=0 ERROR=1 SKIP=0 TOTAL=12";
assert!(
compress_output("dbt run", dbt).is_some(),
"dbt routed+compressible"
);
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";
assert!(compress_output("alembic upgrade head", alembic).is_some());
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";
assert!(compress_output("flyway migrate", flyway).is_some());
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";
assert!(compress_output("spark-submit app.py", spark).is_some());
}
#[test]
fn routes_ai_domain() {
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";
assert!(compress_output("ollama list", ollama).is_some());
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 ===";
assert!(compress_output("mlflow run .", mlflow).is_some());
}
#[test]
fn routes_security_domain() {
let trivy = "2024-01-01T12:00:00.000Z\tINFO\tscanning\nnginx:latest (debian 12.1)\n=====\nTotal: 45 (LOW: 20, HIGH: 8, CRITICAL: 2)";
assert!(compress_output("trivy image nginx", trivy).is_some());
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";
assert!(compress_output("grype nginx", grype).is_some());
let syft = "NAME VERSION TYPE\nadduser 3.118 deb\napt 2.6.1 deb\nlodash 4.17.21 npm";
assert!(compress_output("syft nginx", syft).is_some());
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.";
assert!(compress_output("semgrep scan", semgrep).is_some());
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.";
assert!(compress_output("swiftlint", swiftlint).is_some());
}
#[test]
fn routes_vcs_toolchain_domain() {
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~";
assert!(compress_output("jj log", jj).is_some());
let mise = "node 20.10.0 ~/.config/mise/config.toml\npython 3.12.0 ~/.tool-versions\nrust 1.75.0 ~/.config/mise/config.toml";
assert!(compress_output("mise ls", mise).is_some());
let buf_lines: Vec<String> = (0..30)
.map(|i| format!("proto/f{i}.proto:{i}:1:Field name should be lower_snake_case here."))
.collect();
let buf = buf_lines.join("\n");
assert!(compress_output("buf lint", &buf).is_some());
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";
assert!(compress_output("gem install rails", gem).is_some());
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";
assert!(compress_output("uv add pandas", uv).is_some());
}
#[test]
fn routes_edge_infra_domain() {
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";
assert!(compress_output("pulumi up", pulumi).is_some());
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 ×";
assert!(compress_output("linkerd check", linkerd).is_some());
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";
assert!(compress_output("argocd app get myapp", argocd).is_some());
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]";
assert!(compress_output("vercel deploy --prod", vercel).is_some());
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";
assert!(compress_output("wrangler deploy", wrangler).is_some());
}
#[test]
fn unknown_command_returns_none() {
assert!(compress_output("some-unknown-tool --version", "v1.0").is_none());
}
#[test]
fn case_insensitive_routing() {
let output = "On branch main\nnothing to commit";
assert!(compress_output("Git Status", output).is_some());
assert!(compress_output("GIT STATUS", output).is_some());
}
#[test]
fn routes_vp_and_vite_plus() {
let output = " VITE v5.0.0 ready in 200 ms\n\n -> Local: http://localhost:5173/\n -> Network: http://192.168.1.2:5173/";
assert!(compress_output("vp build", output).is_some());
assert!(compress_output("vite-plus build", output).is_some());
}
#[test]
fn routes_bunx_commands() {
let output = "1 pass tests\n0 fail tests\n3 skip tests\nDone 12ms\nsome extra line\nmore output here";
let result = compress_output("bunx test", output);
assert!(
result.is_some(),
"bunx should compress when output is large enough"
);
assert!(result.unwrap().contains("bun test: 1 passed"));
}
#[test]
fn routes_deno_task() {
let output = "Task dev deno run --allow-net server.ts\nListening on http://localhost:8000";
assert!(try_specific_pattern("deno task dev", output).is_some());
}
#[test]
fn routes_jest_commands() {
let output = "PASS tests/main.test.js\nTest Suites: 1 passed, 1 total\nTests: 5 passed, 5 total\nTime: 2.5 s";
assert!(try_specific_pattern("jest", output).is_some());
assert!(try_specific_pattern("npx jest --coverage", output).is_some());
}
#[test]
fn routes_mocha_commands() {
let output = " 3 passing (50ms)\n 1 failing\n\n 1) Array #indexOf():\n Error: expected -1 to equal 0";
assert!(try_specific_pattern("mocha", output).is_some());
assert!(try_specific_pattern("npx mocha tests/", output).is_some());
}
#[test]
fn routes_tofu_commands() {
let output = "Initializing the backend...\nInitializing provider plugins...\nTerraform has been successfully initialized!";
assert!(try_specific_pattern("tofu init", output).is_some());
}
#[test]
fn routes_ps_commands() {
let mut lines = vec!["USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND".to_string()];
for i in 0..20 {
lines.push(format!("user {i} 0.0 0.1 1234 123 ? S 10:00 0:00 proc_{i}"));
}
let output = lines.join("\n");
assert!(try_specific_pattern("ps aux", &output).is_some());
}
#[test]
fn routes_ping_commands() {
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";
assert!(try_specific_pattern("ping -c 3 google.com", output).is_some());
}
#[test]
fn routes_jq_to_json_schema() {
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}]}";
assert!(try_specific_pattern("jq '.items' data.json", output).is_some());
}
#[test]
fn routes_linting_tools() {
let lint_output = "src/main.py:10: error: Missing return\nsrc/main.py:20: error: Unused var\nFound 2 errors";
assert!(try_specific_pattern("hadolint Dockerfile", lint_output).is_some());
assert!(try_specific_pattern("oxlint src/", lint_output).is_some());
assert!(try_specific_pattern("pyright src/", lint_output).is_some());
assert!(try_specific_pattern("basedpyright src/", lint_output).is_some());
}
#[test]
fn routes_fd_commands() {
let output = "src/main.rs\nsrc/lib.rs\nsrc/util/helpers.rs\nsrc/util/math.rs\ntests/integration.rs\n";
assert!(try_specific_pattern("fd --extension rs", output).is_some());
assert!(try_specific_pattern("fdfind .rs", output).is_some());
}
#[test]
fn routes_just_commands() {
let output = "Available recipes:\n build\n test\n lint\n";
assert!(try_specific_pattern("just --list", output).is_some());
assert!(try_specific_pattern("just build", output).is_some());
}
#[test]
fn routes_ninja_commands() {
let output = "[1/10] Compiling foo.c\n[10/10] Linking app\n";
assert!(try_specific_pattern("ninja", output).is_some());
assert!(try_specific_pattern("ninja -j4", output).is_some());
}
#[test]
fn routes_clang_commands() {
let output =
"src/main.c:10:5: error: use of undeclared identifier 'foo'\n1 error generated.\n";
assert!(try_specific_pattern("clang src/main.c", output).is_some());
assert!(try_specific_pattern("clang++ -std=c++17 main.cpp", output).is_some());
}
#[test]
fn routes_cargo_run() {
let output = " Compiling foo v0.1.0\n Finished `dev` profile\nHello, world!";
assert!(try_specific_pattern("cargo run", output).is_some());
}
#[test]
fn routes_cargo_bench() {
let output = " Compiling foo v0.1.0\ntest bench_parse ... bench: 1234 ns/iter";
assert!(try_specific_pattern("cargo bench", output).is_some());
}
#[test]
fn routes_build_tools() {
let build_output = " Compiling foo v0.1.0\n Finished release [optimized]";
assert!(try_specific_pattern("gcc -o main main.c", build_output).is_some());
assert!(try_specific_pattern("g++ -o main main.cpp", build_output).is_some());
}
#[test]
fn routes_monorepo_tools() {
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";
assert!(try_specific_pattern("turbo install", output).is_some());
assert!(try_specific_pattern("nx install", output).is_some());
}
#[test]
fn gh_api_passthrough_never_compresses() {
let huge = "line\n".repeat(5000);
assert!(
compress_output("gh api repos/owner/repo/actions/jobs/123/logs", &huge).is_none(),
"gh api must never be compressed, even for large output"
);
assert!(compress_output("gh api repos/owner/repo/actions/runs/123/logs", &huge).is_none());
}
#[test]
fn gh_log_flags_passthrough() {
let huge = "line\n".repeat(5000);
assert!(compress_output("gh run view 123 --log-failed", &huge).is_none());
assert!(compress_output("gh run view 123 --log", &huge).is_none());
}
#[test]
fn gh_structured_commands_still_compress() {
let output = "On branch main\nnothing to commit";
assert!(try_specific_pattern("gh pr list", output).is_some());
assert!(try_specific_pattern("gh run list", output).is_some());
}
}