Skip to main content

aft_base/compress/
mod.rs

1//! Output compression for hoisted bash.
2//!
3//! Compression has five tiers, tried in this order:
4//!
5//! 1. **Specific Rust [`Compressor`] modules** — hand-written parsers for
6//!    specific tools identified by tool tokens (for example `vitest`, `eslint`,
7//!    `cargo`, `git`). These win before broad package-manager compressors.
8//! 2. **Output-shape [`Compressor`] sniffers** — inner-tool parsers that can
9//!    recognize their own private summaries even when invoked through wrappers
10//!    such as `npm test`, `make test`, or `./scripts/check.sh`.
11//! 3. **Package-manager [`Compressor`] modules** — broad head-token matchers
12//!    (`npm`, `pnpm`, `bun`) that compress unclaimed package-manager output.
13//! 4. **TOML filters** — declarative strip + truncate + cap + shortcircuit
14//!    rules for the long tail of CLI tools. Loaded from builtin / user /
15//!    project sources via [`toml_filter::build_registry`]. See
16//!    [`toml_filter`] and [`trust`] for the trust model.
17//! 5. **[`generic`] fallback** — ANSI strip + consecutive-dedup. The
18//!    background bash registry owns the shared final output cap.
19
20pub mod biome;
21pub mod builtin_filters;
22pub mod bun;
23pub mod caps;
24pub mod cargo;
25pub mod eslint;
26pub mod find;
27pub mod generic;
28pub mod git;
29pub mod go;
30pub mod line_cut;
31pub mod listing_fold;
32pub mod ls;
33pub mod mypy;
34pub mod next;
35pub mod npm;
36pub mod playwright;
37pub mod pnpm;
38pub mod prettier;
39pub mod pytest;
40pub mod ruff;
41pub mod toml_filter;
42pub mod tree;
43pub mod trust;
44pub mod tsc;
45pub mod vitest;
46
47use crate::harness::Harness;
48use biome::BiomeCompressor;
49use bun::BunCompressor;
50use caps::DropClass;
51use cargo::CargoCompressor;
52use eslint::EslintCompressor;
53use find::FindCompressor;
54use generic::GenericCompressor;
55use git::GitCompressor;
56use go::{GoCompressor, GolangciLintCompressor};
57use ls::LsCompressor;
58use mypy::MypyCompressor;
59use next::NextCompressor;
60use npm::NpmCompressor;
61use playwright::PlaywrightCompressor;
62use pnpm::PnpmCompressor;
63use prettier::PrettierCompressor;
64use pytest::PytestCompressor;
65use ruff::RuffCompressor;
66use std::cell::OnceCell;
67use std::collections::{BTreeMap, HashSet};
68use std::fs;
69use std::path::{Path, PathBuf};
70use std::sync::{Arc, RwLock};
71use toml_filter::{apply_filter_with_exit_code_prestripped, FilterRegistry};
72use tree::TreeCompressor;
73use tsc::TscCompressor;
74use vitest::VitestCompressor;
75
76/// Thread-safe handle to the TOML filter registry. Shared between
77/// `AppContext::filter_registry()` (for direct use in command handlers) and
78/// `BgTaskRegistry`'s output compression closure (for use from the watchdog
79/// thread).
80pub type SharedFilterRegistry = Arc<RwLock<FilterRegistry>>;
81
82/// How specifically a compressor identifies a command.
83///
84/// `Specific` matchers (vitest, eslint, biome, tsc, pytest, cargo, git)
85/// claim a command by recognising a SPECIFIC tool name as a token anywhere
86/// in the command line — `npx vitest`, `pnpm exec eslint --fix`,
87/// `bun run vitest`, etc.
88///
89/// `PackageManager` matchers (npm, pnpm, bun) claim a command by its
90/// HEAD token alone (e.g. `npm`, `bun`) regardless of what subcommand
91/// follows. They are intentionally broad — when a `bun run vitest` is
92/// not claimed by VitestCompressor, BunCompressor still wants the chance
93/// to compress generic bun output for unknown subcommands.
94///
95/// Dispatch order: Specific command tier first, then output-shape sniffers
96/// (Specific before PackageManager), then PackageManager command tier, then
97/// TOML filters, then GenericCompressor.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum Specificity {
100    Specific,
101    PackageManager,
102}
103
104/// Shared, per-dispatch view of command output for output-shape matchers.
105///
106/// Several matchers recognize JSON by inspecting different top-level keys. A
107/// probe lets them share one lazy parse while leaving each matcher's decision
108/// and dispatch priority unchanged.
109pub struct OutputProbe<'a> {
110    output: &'a str,
111    json: OnceCell<Option<serde_json::Value>>,
112    strict_json_input: OnceCell<bool>,
113}
114
115impl<'a> OutputProbe<'a> {
116    pub fn new(output: &'a str) -> Self {
117        Self {
118            output,
119            json: OnceCell::new(),
120            strict_json_input: OnceCell::new(),
121        }
122    }
123
124    pub fn output(&self) -> &'a str {
125        self.output
126    }
127
128    /// Parse plausible JSON at most once for all matchers in this dispatch.
129    pub fn json(&self) -> Option<&serde_json::Value> {
130        // Matchers historically accepted JSON's ASCII trailing whitespace, not
131        // every Unicode whitespace character that Rust's trim removes.
132        if !self.strict_json_input.get_or_init(|| {
133            let trimmed = self.output.trim_start();
134            matches!(trimmed.as_bytes().first(), Some(b'{') | Some(b'['))
135                && trimmed.trim_end().len()
136                    == trimmed.trim_end_matches([' ', '\n', '\r', '\t']).len()
137        }) {
138            return None;
139        }
140        self.json_trimmed()
141    }
142
143    /// Ruff's command renderer trims both ends before parsing. Share that parse
144    /// without broadening the stricter output-shape matchers' accepted input.
145    pub(crate) fn json_trimmed(&self) -> Option<&serde_json::Value> {
146        self.json
147            .get_or_init(|| {
148                let trimmed = self.output.trim();
149                if !matches!(trimmed.as_bytes().first(), Some(b'{') | Some(b'[')) {
150                    return None;
151                }
152                record_output_probe_json_parse();
153                serde_json::from_str(trimmed).ok()
154            })
155            .as_ref()
156    }
157}
158
159#[cfg(debug_assertions)]
160thread_local! {
161    static OUTPUT_PROBE_JSON_PARSE_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
162}
163
164#[cfg(debug_assertions)]
165fn record_output_probe_json_parse() {
166    OUTPUT_PROBE_JSON_PARSE_COUNT.with(|count| count.set(count.get() + 1));
167}
168
169#[cfg(not(debug_assertions))]
170fn record_output_probe_json_parse() {}
171
172#[cfg(all(debug_assertions, any(test, feature = "test-support")))]
173#[cfg_attr(not(test), allow(dead_code))]
174fn reset_output_probe_json_parse_count() {
175    OUTPUT_PROBE_JSON_PARSE_COUNT.with(|count| count.set(0));
176}
177
178#[cfg(all(debug_assertions, any(test, feature = "test-support")))]
179#[cfg_attr(not(test), allow(dead_code))]
180fn output_probe_json_parse_count() -> usize {
181    OUTPUT_PROBE_JSON_PARSE_COUNT.with(std::cell::Cell::get)
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct CompressionResult {
186    pub text: String,
187    pub dropped_by_class: BTreeMap<DropClass, usize>,
188    pub had_inner_drop: bool,
189    pub offset_hint_eligible: bool,
190    pub offset_start_line: Option<usize>,
191    pub input_line_count: usize,
192    // Only cargo's bounded panic sections may omit detail after retaining the
193    // complete failure-name list and every test result.
194    #[cfg(any(test, feature = "test-support"))]
195    pub bounded_cargo_test_details: bool,
196    #[cfg(not(any(test, feature = "test-support")))]
197    bounded_cargo_test_details: bool,
198}
199
200impl CompressionResult {
201    pub fn new(text: impl Into<String>) -> Self {
202        let text = text.into();
203        let input_line_count = text.lines().count();
204        Self {
205            text,
206            dropped_by_class: BTreeMap::new(),
207            had_inner_drop: false,
208            offset_hint_eligible: true,
209            offset_start_line: None,
210            input_line_count,
211            bounded_cargo_test_details: false,
212        }
213    }
214
215    pub fn with_class_drops(
216        text: impl Into<String>,
217        dropped_by_class: BTreeMap<DropClass, usize>,
218    ) -> Self {
219        let text = text.into();
220        let input_line_count = text.lines().count();
221        let had_inner_drop = !dropped_by_class.is_empty();
222        Self {
223            text,
224            dropped_by_class,
225            had_inner_drop,
226            offset_hint_eligible: !had_inner_drop,
227            offset_start_line: None,
228            input_line_count,
229            bounded_cargo_test_details: false,
230        }
231    }
232
233    pub fn with_inner_drop(text: impl Into<String>, offset_hint_eligible: bool) -> Self {
234        let text = text.into();
235        let input_line_count = text.lines().count();
236        Self {
237            text,
238            dropped_by_class: BTreeMap::new(),
239            had_inner_drop: true,
240            offset_hint_eligible,
241            offset_start_line: None,
242            input_line_count,
243            bounded_cargo_test_details: false,
244        }
245    }
246
247    pub fn with_prefix_drop(text: impl Into<String>, offset_start_line: usize) -> Self {
248        let text = text.into();
249        let input_line_count = text.lines().count();
250        Self {
251            text,
252            dropped_by_class: BTreeMap::new(),
253            had_inner_drop: true,
254            offset_hint_eligible: true,
255            offset_start_line: Some(offset_start_line),
256            input_line_count,
257            bounded_cargo_test_details: false,
258        }
259    }
260
261    pub fn with_input_line_count(mut self, count: usize) -> Self {
262        self.input_line_count = count;
263        self
264    }
265
266    pub fn input_line_count(&self) -> usize {
267        self.input_line_count
268    }
269
270    pub fn has_semantic_drops(&self) -> bool {
271        !self.dropped_by_class.is_empty()
272    }
273
274    pub fn has_any_drop(&self) -> bool {
275        self.had_inner_drop || self.has_semantic_drops()
276    }
277
278    pub fn map_text<F>(mut self, f: F) -> Self
279    where
280        F: FnOnce(&str) -> String,
281    {
282        self.text = f(&self.text);
283        self
284    }
285}
286
287impl std::fmt::Display for CompressionResult {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        f.write_str(&self.text)
290    }
291}
292
293impl std::ops::Deref for CompressionResult {
294    type Target = str;
295
296    fn deref(&self) -> &Self::Target {
297        &self.text
298    }
299}
300
301impl PartialEq<&str> for CompressionResult {
302    fn eq(&self, other: &&str) -> bool {
303        self.text == *other
304    }
305}
306
307impl PartialEq<String> for CompressionResult {
308    fn eq(&self, other: &String) -> bool {
309        self.text == *other
310    }
311}
312
313impl From<String> for CompressionResult {
314    fn from(text: String) -> Self {
315        Self::new(text)
316    }
317}
318
319impl From<&str> for CompressionResult {
320    fn from(text: &str) -> Self {
321        Self::new(text)
322    }
323}
324
325/// A `Compressor` knows how to reduce one specific command's output to fewer
326/// tokens while preserving the information the agent needs.
327pub trait Compressor: Send + Sync {
328    /// Returns true if this compressor handles the given command head + args.
329    /// Called after generic detection (ANSI strip, dedup) so this is per-command logic only.
330    fn matches(&self, command: &str) -> bool;
331
332    /// Compress the output when the process exit code is unknown.
333    fn compress(&self, command: &str, output: &str) -> CompressionResult {
334        self.compress_with_exit_code(command, output, None)
335    }
336
337    /// Compress the output. Original is left untouched if compression fails.
338    fn compress_with_exit_code(
339        &self,
340        command: &str,
341        output: &str,
342        exit_code: Option<i64>,
343    ) -> CompressionResult;
344
345    fn specificity(&self) -> Specificity {
346        Specificity::Specific
347    }
348
349    /// Returns true when this compressor recognizes output produced by its
350    /// inner tool even if the command head was a wrapper (`npm test`,
351    /// `make test`, `./scripts/check.sh`, etc.). Wrapper compressors should
352    /// not override this; they remain command-only.
353    fn matches_output(&self, _output: &str) -> bool {
354        false
355    }
356
357    /// Probe-aware output matching. Matchers that need shared derived data can
358    /// override this; all other matchers retain their existing implementation.
359    fn matches_output_probe(&self, probe: &OutputProbe<'_>) -> bool {
360        self.matches_output(probe.output())
361    }
362
363    /// Reuse the probe's ANSI-stripped text and lazy JSON parse for a
364    /// command-selected compressor, not only for output-shape matching.
365    fn compress_with_output_probe(
366        &self,
367        command: &str,
368        probe: &OutputProbe<'_>,
369        exit_code: Option<i64>,
370    ) -> CompressionResult {
371        self.compress_with_exit_code(command, probe.output(), exit_code)
372    }
373
374    fn compress_output_probe_match(
375        &self,
376        probe: &OutputProbe<'_>,
377        exit_code: Option<i64>,
378    ) -> CompressionResult {
379        self.compress_output_match_with_exit_code(probe.output(), exit_code)
380    }
381
382    /// Compress output after an output-shape match when the process exit code is unknown.
383    fn compress_output_match(&self, output: &str) -> CompressionResult {
384        self.compress_output_match_with_exit_code(output, None)
385    }
386
387    /// Compress output after an output-shape match. Compressors that branch by
388    /// subcommand override this to jump directly to the matched branch.
389    fn compress_output_match_with_exit_code(
390        &self,
391        output: &str,
392        exit_code: Option<i64>,
393    ) -> CompressionResult {
394        self.compress_with_exit_code("", output, exit_code)
395    }
396}
397/// Top-level dispatch: try specific Rust modules, output-shape sniffers, package-manager modules, TOML filters, then generic fallback.
398///
399/// The caller supplies the compression gate and the current filter snapshot.
400pub fn compress(
401    command: &str,
402    output: String,
403    enabled: bool,
404    registry: &FilterRegistry,
405) -> CompressionResult {
406    compress_with_exit_code(command, output, None, enabled, registry)
407}
408
409pub fn compress_with_exit_code(
410    command: &str,
411    output: String,
412    exit_code: Option<i64>,
413    enabled: bool,
414    registry: &FilterRegistry,
415) -> CompressionResult {
416    if !enabled {
417        let count = output.lines().count();
418        return CompressionResult::new(output).with_input_line_count(count);
419    }
420    compress_with_registry_exit_code(command, &output, exit_code, registry)
421}
422
423/// Thread-safe dispatch that does not need `AppContext`. Caller is responsible
424/// for the `experimental_bash_compress` gate (the registry has no opinion).
425///
426/// Used from background threads (notably the `BgTaskRegistry` watchdog and
427/// completion-frame emitter) where lock-free access is required.
428pub fn compress_with_registry(
429    command: &str,
430    output: &str,
431    registry: &FilterRegistry,
432) -> CompressionResult {
433    compress_with_registry_exit_code(command, output, None, registry)
434}
435
436pub fn compress_with_registry_exit_code(
437    command: &str,
438    output: &str,
439    exit_code: Option<i64>,
440    registry: &FilterRegistry,
441) -> CompressionResult {
442    let input_line_count = output.lines().count();
443    let mut result = compress_with_registry_exit_code_inner(command, output, exit_code, registry);
444    result.input_line_count = input_line_count;
445    result
446}
447
448fn compress_with_registry_exit_code_inner(
449    command: &str,
450    output: &str,
451    exit_code: Option<i64>,
452    registry: &FilterRegistry,
453) -> CompressionResult {
454    let stripped_for_generic = generic::strip_ansi_cow(output);
455
456    // Resolve what to dispatch on: peel shell-prefix idioms (`cd /path && bun
457    // test`, `env FOO=bar npm install`, `timeout 30 cargo build`, `(cd /path;
458    // cmd)`) so head-token matchers see the real command. Any top-level pipe
459    // must stay generic: the shell already ran the user's pipeline verbatim, so
460    // the captured output belongs to the pipeline result, not necessarily to the
461    // runner that appeared before `|`.
462    let dispatch_owned = match resolve_dispatch_target(command) {
463        DispatchTarget::Pipeline(_) | DispatchTarget::ForceGeneric => {
464            return GenericCompressor::compress_stripped_output(&stripped_for_generic).into();
465        }
466        DispatchTarget::Command(cmd) => cmd,
467    };
468    let dispatch_cmd = dispatch_owned.as_str();
469
470    let compressors = compressors_in_dispatch_order();
471    let output_probe = OutputProbe::new(&stripped_for_generic);
472
473    // Tier 1a: Specific command compressors win first.
474    for compressor in compressors
475        .iter()
476        .filter(|c| c.specificity() == Specificity::Specific)
477    {
478        if compressor.matches(dispatch_cmd) {
479            let result =
480                compressor.compress_with_output_probe(dispatch_cmd, &output_probe, exit_code);
481            return failure_preserving_result(command, &stripped_for_generic, result, exit_code);
482        }
483    }
484
485    // Tier 1b: Output-shape sniffers handle wrapped inner tools before broad
486    // package managers or TOML filters can consume `npm test`, `make test`,
487    // `just test`, etc. Collision order is deterministic: Specific compressors
488    // in registry order win before PackageManager sniffers (currently Bun's
489    // test-output signature).
490    for specificity in [Specificity::Specific, Specificity::PackageManager] {
491        for compressor in compressors
492            .iter()
493            .filter(|c| c.specificity() == specificity)
494        {
495            if compressor.matches_output_probe(&output_probe) {
496                let result = compressor.compress_output_probe_match(&output_probe, exit_code);
497                return failure_preserving_result(
498                    command,
499                    &stripped_for_generic,
500                    result,
501                    exit_code,
502                );
503            }
504        }
505    }
506
507    // Tier 1c: PackageManager compressors get unclaimed commands.
508    for compressor in compressors
509        .iter()
510        .filter(|c| c.specificity() == Specificity::PackageManager)
511    {
512        if compressor.matches(dispatch_cmd) {
513            let result =
514                compressor.compress_with_output_probe(dispatch_cmd, &output_probe, exit_code);
515            return failure_preserving_result(command, &stripped_for_generic, result, exit_code);
516        }
517    }
518
519    // Tier 2: TOML filters. Pass raw output so `[ansi].strip = false` filters
520    // can intentionally match escape sequences; `apply_filter` owns ANSI policy.
521    if let Some(filter) = registry.lookup(dispatch_cmd) {
522        let result = apply_filter_with_exit_code_prestripped(
523            filter,
524            output,
525            &stripped_for_generic,
526            exit_code,
527        );
528        return failure_preserving_result(command, &stripped_for_generic, result, exit_code);
529    }
530
531    // Tier 3: generic fallback.
532    GenericCompressor::compress_stripped_output(&stripped_for_generic).into()
533}
534
535fn compressors_in_dispatch_order() -> [&'static dyn Compressor; 20] {
536    [
537        &GitCompressor,
538        &CargoCompressor,
539        &TscCompressor,
540        &NpmCompressor,
541        &BunCompressor,
542        &PnpmCompressor,
543        &PytestCompressor,
544        &EslintCompressor,
545        &VitestCompressor,
546        &BiomeCompressor,
547        &PrettierCompressor,
548        &RuffCompressor,
549        &MypyCompressor,
550        &GoCompressor,
551        &GolangciLintCompressor,
552        &PlaywrightCompressor,
553        &NextCompressor,
554        &LsCompressor,
555        &FindCompressor,
556        &TreeCompressor,
557    ]
558}
559
560fn failure_preserving_result(
561    command: &str,
562    stripped_raw_output: &str,
563    result: CompressionResult,
564    exit_code: Option<i64>,
565) -> CompressionResult {
566    if !matches!(exit_code, Some(code) if code != 0) {
567        return result;
568    }
569
570    if result.bounded_cargo_test_details {
571        if result
572            .dropped_by_class
573            .get(&DropClass::Error)
574            .copied()
575            .unwrap_or(0)
576            == 0
577            && cargo::failure_summary_preserved(stripped_raw_output, &result.text)
578        {
579            return result;
580        }
581        return GenericCompressor.compress_with_exit_code(command, stripped_raw_output, exit_code);
582    }
583
584    if dropped_failure_or_error_blocks(&result)
585        || !text_has_failure_signal(&result.text)
586        || result_looks_successful(&result.text)
587    {
588        return GenericCompressor.compress_with_exit_code(command, stripped_raw_output, exit_code);
589    }
590
591    let missing = missing_raw_failure_signal_lines(stripped_raw_output, &result.text);
592    if missing.is_empty() {
593        result
594    } else {
595        append_missing_failure_lines(result, stripped_raw_output, &missing)
596    }
597}
598
599fn dropped_failure_or_error_blocks(result: &CompressionResult) -> bool {
600    [DropClass::Error, DropClass::Failure]
601        .into_iter()
602        .any(|class| result.dropped_by_class.get(&class).copied().unwrap_or(0) > 0)
603}
604
605/// The line that introduces failure lines AFT kept from output it otherwise
606/// shortened, so the agent can tell them from the command's own lines.
607pub const PRESERVED_FAILURES_LABEL: &str = "[raw failure lines preserved by AFT]";
608
609fn append_missing_failure_lines(
610    mut result: CompressionResult,
611    raw_output: &str,
612    missing_failure_lines: &[String],
613) -> CompressionResult {
614    let mut text = result.text.trim_end().to_string();
615    // When the result ends with the command's own final line (a test summary,
616    // a script's verdict), the preserved block goes just before that line so
617    // the output still ends the way the command ended.
618    let raw_last = raw_output
619        .lines()
620        .map(str::trim_end)
621        .rfind(|line| !line.is_empty());
622    let (before, last) = text.rsplit_once('\n').unwrap_or(("", text.as_str()));
623    let final_line = match raw_last {
624        Some(raw_last) if last.trim_end() == raw_last => Some(last.to_string()),
625        _ => None,
626    };
627    if final_line.is_some() {
628        text = before.to_string();
629    }
630    if !text.is_empty() {
631        text.push('\n');
632    }
633    text.push_str(PRESERVED_FAILURES_LABEL);
634    text.push('\n');
635    text.push_str(&missing_failure_lines.join("\n"));
636    if let Some(final_line) = final_line {
637        text.push('\n');
638        text.push_str(&final_line);
639    }
640    result.text = text;
641    result
642}
643
644pub(crate) fn missing_raw_failure_signal_lines(
645    raw_output: &str,
646    compressed_text: &str,
647) -> Vec<String> {
648    let compressed_lower = compressed_text.to_ascii_lowercase();
649    let compressed_lines: HashSet<&str> = compressed_text
650        .lines()
651        .zip(compressed_lower.lines())
652        .filter_map(|(line, lower)| {
653            let trimmed = line.trim();
654            (!trimmed.is_empty() && line_has_failure_signal_lower(trimmed, lower.trim()))
655                .then_some(trimmed)
656        })
657        .collect();
658    let raw_lower = raw_output.to_ascii_lowercase();
659    let mut seen = HashSet::new();
660    let mut missing = Vec::new();
661
662    for (line, lower) in raw_output.lines().zip(raw_lower.lines()) {
663        let trimmed = line.trim();
664        if trimmed.is_empty() || !line_has_failure_signal_lower(trimmed, lower.trim()) {
665            continue;
666        }
667        if compressed_lines.contains(trimmed) || !seen.insert(trimmed) {
668            continue;
669        }
670        missing.push(trimmed.to_string());
671    }
672
673    missing
674}
675
676fn result_looks_successful(text: &str) -> bool {
677    let lower = text.to_ascii_lowercase();
678    lower.contains("clean")
679        || lower.contains(" ok")
680        || lower.contains(":ok")
681        || lower.contains(": ok")
682        || lower.contains("passed")
683        || lower.contains("succeeded")
684        || lower.contains("no errors")
685        || lower.contains("0 errors")
686        || lower.contains("no issues")
687        || lower.contains("no diagnostics")
688        || lower.contains("all checks passed")
689        || lower.contains("formatted")
690        || lower.contains("0 fail")
691        || lower.contains("found 0")
692        || lower.contains("up to date")
693        || lower.contains("up-to-date")
694}
695
696pub(crate) fn text_has_failure_signal(text: &str) -> bool {
697    let lower = text.to_ascii_lowercase();
698    text.lines()
699        .zip(lower.lines())
700        .any(|(line, lower)| line_has_failure_signal_lower(line.trim(), lower.trim()))
701}
702
703pub fn line_has_failure_signal_lower(line: &str, lower: &str) -> bool {
704    line.contains("error[")
705        || lower.contains("error:")
706        || line.contains("Error")
707        || line.contains("ERROR")
708        || lower.contains("internalerror")
709        || lower.contains("traceback")
710        || lower.contains("exception")
711        || lower.contains("no module named")
712        || lower.contains("undefined reference")
713        || lower.contains("linker command failed")
714        || lower.contains("undefined:")
715        || lower.contains("expected declaration")
716        || lower.contains("collect2: error")
717        || lower.contains("ld: error")
718        || lower.contains("fatal error")
719        || line.contains("FAILED")
720        || line.contains("FAIL")
721        || contains_nonzero_failure_word_lower(lower)
722        || lower.contains("panic")
723        || lower.contains("cannot find")
724        || lower.contains("not found")
725        || lower.contains("no such")
726}
727
728fn contains_nonzero_failure_word_lower(lower: &str) -> bool {
729    for (index, _) in lower.match_indices("fail") {
730        let tail = &lower[index + "fail".len()..];
731        for suffix in ["ures", "ure", "ed", ""] {
732            let Some(after_suffix) = tail.strip_prefix(suffix) else {
733                continue;
734            };
735            let before_is_word = lower[..index].chars().next_back().is_some_and(is_word_char);
736            let after_is_word = after_suffix.chars().next().is_some_and(is_word_char);
737            if before_is_word || after_is_word {
738                continue;
739            }
740
741            let prefix = lower[..index].trim_end();
742            let digits_start = prefix
743                .char_indices()
744                .rev()
745                .take_while(|(_, ch)| ch.is_ascii_digit())
746                .last()
747                .map(|(idx, _)| idx);
748            let Some(digits_start) = digits_start else {
749                return true;
750            };
751            let digits = &prefix[digits_start..];
752            if digits.parse::<usize>().ok() != Some(0) {
753                return true;
754            }
755        }
756    }
757    false
758}
759
760fn is_word_char(ch: char) -> bool {
761    ch.is_ascii_alphanumeric() || ch == '_'
762}
763
764/// Build the registry of TOML filters from the standard sources for the
765/// selected harness and configuration paths.
766///
767/// Layering (highest priority first):
768/// 1. Project filters at `<project_root>/.cortexkit/aft/filters/*.toml` — loaded only
769///    when the project is in the trusted set (see [`trust`]).
770/// 2. User filters at `<storage_dir>/<harness>/filters/*.toml`.
771/// 3. Builtin filters compiled into the binary via [`builtin_filters`].
772pub fn build_registry_for_paths(
773    harness: Harness,
774    storage_dir: Option<&Path>,
775    project_root: Option<&Path>,
776) -> FilterRegistry {
777    let user_dir = storage_dir.map(|dir| {
778        repair_legacy_user_filter_dir(dir, harness.clone());
779        user_filter_dir(dir, harness)
780    });
781    let project_dir = match (project_root, storage_dir) {
782        (Some(root), Some(storage)) => {
783            if trust::is_project_trusted(Some(storage), root) {
784                Some(project_filter_dir(root))
785            } else {
786                None
787            }
788        }
789        _ => None,
790    };
791
792    toml_filter::build_standard_registry(user_dir.as_deref(), project_dir.as_deref())
793}
794
795/// Normalize a shell command for compressor dispatch by walking past
796/// common shell-prefix idioms so the REAL command head is what matchers
797/// see. Returns `Some(normalized)` if a prefix was stripped, `None` if
798/// the input was already a bare command.
799///
800/// Handles:
801///   - `cd /path && cmd ...`            → `cmd ...`
802///   - `cd /path; cmd ...`              → `cmd ...`
803///   - `env FOO=bar [BAR=baz ...] cmd`  → `cmd ...`
804///   - `FOO=bar [BAR=baz ...] cmd`      → `cmd ...`
805///   - `timeout 30 cmd ...`             → `cmd ...`
806///   - `nohup cmd ...`                  → `cmd ...`
807///   - `(cd /path && cmd ...)`          → `cmd ...`   (trailing `)` is kept; harmless for matchers)
808///
809/// Real agent invocations almost always wrap their actual command in
810/// `cd "$ROOT" && ...`. Without this normalization, BunCompressor /
811/// NpmCompressor / PnpmCompressor (head-token matchers) and the
812/// pkg-manager filters silently fall through to GenericCompressor for
813/// the majority of agent bash calls.
814///
815/// The normalizer is conservative: it only strips well-defined idioms
816/// and bails on anything ambiguous, so a malformed command degrades to
817/// the same dispatch behaviour as before this helper existed.
818pub fn normalize_command_for_dispatch(command: &str) -> Option<String> {
819    match resolve_dispatch_target(command) {
820        // Ambiguous or unsafe pipelines must not be claimed by specific
821        // compressors, so return None to make callers use generic dispatch.
822        DispatchTarget::ForceGeneric => None,
823        DispatchTarget::Command(resolved) | DispatchTarget::Pipeline(resolved) => {
824            if resolved == command.trim_start() {
825                None
826            } else {
827                Some(resolved)
828            }
829        }
830    }
831}
832
833/// Normalize commands for structured-output detection, where a top-level pipe
834/// must suppress structured handling instead of falling back to the raw command.
835pub fn plain_command_for_structured_output(command: &str) -> Option<String> {
836    match resolve_dispatch_target(command) {
837        DispatchTarget::Command(resolved) => Some(resolved),
838        DispatchTarget::Pipeline(_) | DispatchTarget::ForceGeneric => None,
839    }
840}
841
842/// What compressor dispatch should target for a command, after peeling shell
843/// prefixes and resolving any top-level pipeline.
844enum DispatchTarget {
845    /// Match compressors against this command string (peeled, and/or the last
846    /// pipeline stage whose stdout was captured).
847    Command(String),
848    /// A clean top-level pipeline was found. The contained string is the last
849    /// stage for callers that only need a normalized command, but compression
850    /// dispatch treats the original command as generic raw pipeline output.
851    Pipeline(String),
852    /// An unsafe pipeline was detected (a `|` is present but the command could
853    /// not be parsed safely). Skip all specific compressors and use generic —
854    /// a head-token compressor claiming `cargo test | …` would drop the output.
855    ForceGeneric,
856}
857
858fn resolve_dispatch_target(command: &str) -> DispatchTarget {
859    // Strip top-level comments FIRST. A `#` comment's text otherwise reaches the
860    // head-token matchers, which scan the whole string for their tool name — so
861    // `printf keep # cargo test` would let CargoCompressor claim the printf
862    // command's output and drop it (issue #137), with or without a pipe.
863    let decommented = strip_top_level_comment(command);
864    let peeled = peel_shell_prefixes(&decommented);
865    let base = peeled
866        .as_deref()
867        .unwrap_or_else(|| decommented.trim_start());
868    match split_top_level_pipe(base) {
869        PipeSplit::LastStage(last) => DispatchTarget::Pipeline(last),
870        PipeSplit::Unsafe => DispatchTarget::ForceGeneric,
871        PipeSplit::None => DispatchTarget::Command(base.to_string()),
872    }
873}
874
875/// Remove top-level shell comments (`#` to end of line) from a command so the
876/// comment text can't fool head-token compressor matchers (which scan the whole
877/// command string for their tool name). Quote/backtick/substitution aware: a `#`
878/// inside quotes, inside `$(`/`` ` ``, or not at a word boundary is literal.
879/// Copies byte ranges (UTF-8 safe — every decision point is an ASCII byte) and
880/// preserves newlines so any later top-level structure stays visible to the
881/// pipeline scanner.
882fn strip_top_level_comment(command: &str) -> String {
883    let bytes = command.as_bytes();
884    let mut result = String::with_capacity(command.len());
885    let mut seg_start = 0usize;
886    let mut in_single = false;
887    let mut in_double = false;
888    let mut in_backtick = false;
889    let mut paren_depth: u32 = 0;
890    let mut escaped = false;
891    let mut prev = b' '; // start-of-string counts as a word boundary
892
893    let mut i = 0;
894    while i < bytes.len() {
895        let ch = bytes[i];
896        if escaped {
897            escaped = false;
898            prev = ch;
899            i += 1;
900            continue;
901        }
902        if in_single {
903            if ch == b'\'' {
904                in_single = false;
905            }
906            prev = ch;
907            i += 1;
908            continue;
909        }
910        if in_backtick {
911            if ch == b'\\' {
912                escaped = true;
913            } else if ch == b'`' {
914                in_backtick = false;
915            }
916            prev = ch;
917            i += 1;
918            continue;
919        }
920        if ch == b'\\' {
921            escaped = true;
922            prev = ch;
923            i += 1;
924            continue;
925        }
926        if ch == b'`' {
927            in_backtick = true;
928            prev = ch;
929            i += 1;
930            continue;
931        }
932        if ch == b'$' && bytes.get(i + 1) == Some(&b'(') {
933            paren_depth += 1;
934            prev = b'(';
935            i += 2;
936            continue;
937        }
938        if in_double {
939            if ch == b'"' {
940                in_double = false;
941            }
942            prev = ch;
943            i += 1;
944            continue;
945        }
946        if ch == b'#'
947            && paren_depth == 0
948            && matches!(prev, b' ' | b'\t' | b'\n' | b';' | b'&' | b'|' | b'(')
949        {
950            result.push_str(&command[seg_start..i]);
951            while i < bytes.len() && bytes[i] != b'\n' {
952                i += 1;
953            }
954            seg_start = i; // resume at the newline (kept) or EOL
955            prev = b'\n';
956            continue;
957        }
958        match ch {
959            b'\'' => in_single = true,
960            b'"' => in_double = true,
961            b'<' | b'>' if bytes.get(i + 1) == Some(&b'(') => {
962                paren_depth += 1;
963                prev = b'(';
964                i += 2;
965                continue;
966            }
967            b'(' => paren_depth += 1,
968            b')' => paren_depth = paren_depth.saturating_sub(1),
969            _ => {}
970        }
971        prev = ch;
972        i += 1;
973    }
974    result.push_str(&command[seg_start..]);
975    result
976}
977
978/// Peel known shell-prefix idioms (`cd … &&`, `env VAR=v`, `VAR=v`, `timeout N`,
979/// `nohup`, leading `(`) so the REAL command head is exposed to matchers.
980/// Returns `Some(peeled)` when something was stripped, `None` otherwise.
981fn peel_shell_prefixes(command: &str) -> Option<String> {
982    let trimmed = command.trim_start();
983    if trimmed.is_empty() {
984        return None;
985    }
986
987    // Step 1: peel a leading `(` from group-expression idioms.
988    let (open_paren, after_paren) = if let Some(rest) = trimmed.strip_prefix('(') {
989        (true, rest.trim_start())
990    } else {
991        (false, trimmed)
992    };
993
994    let mut current = after_paren.to_string();
995    let mut changed = open_paren;
996
997    // Step 2: iteratively peel known shell prefixes.
998    loop {
999        // `VAR=value cmd ...` (possibly multiple assignment words). This must
1000        // run before head-token matching so package-manager/Rust compressors
1001        // still see the real command for `NODE_ENV=production npm install`.
1002        if let Some(stripped) = strip_leading_assignment_prefix(&current) {
1003            current = stripped;
1004            changed = true;
1005            continue;
1006        }
1007
1008        let head: String = current.split_whitespace().next().unwrap_or("").to_string();
1009
1010        // `cd <path> && ...` or `cd <path>; ...`
1011        if head == "cd" {
1012            // Find the next `&&` or `;` token; everything after that is the real command.
1013            // Use char-level scan because `&&` is two chars not separated by whitespace.
1014            if let Some(stripped) = strip_cd_prefix(&current) {
1015                current = stripped;
1016                changed = true;
1017                continue;
1018            }
1019        }
1020
1021        // `env VAR=val [VAR=val ...] cmd ...`
1022        if head == "env" {
1023            if let Some(stripped) = strip_env_prefix(&current) {
1024                current = stripped;
1025                changed = true;
1026                continue;
1027            }
1028        }
1029
1030        // `timeout <N> cmd ...` or `timeout <duration-with-unit> cmd ...`
1031        if head == "timeout" {
1032            if let Some(stripped) = strip_timeout_prefix(&current) {
1033                current = stripped;
1034                changed = true;
1035                continue;
1036            }
1037        }
1038
1039        // `nohup cmd ...`
1040        if head == "nohup" {
1041            if let Some(rest) = current.strip_prefix("nohup").and_then(|s| {
1042                let trimmed = s.trim_start();
1043                if trimmed.is_empty() {
1044                    None
1045                } else {
1046                    Some(trimmed.to_string())
1047                }
1048            }) {
1049                current = rest;
1050                changed = true;
1051                continue;
1052            }
1053        }
1054
1055        break;
1056    }
1057
1058    if changed {
1059        Some(current)
1060    } else {
1061        None
1062    }
1063}
1064
1065/// Returns true if the token is a shell metacharacter that acts as a
1066/// command boundary. Subcommand parsers use this to avoid returning a
1067/// redirect/operator token as a subcommand name. Covers control operators
1068/// (`|`, `|&`, `;`, `&`, `&&`, `||`), and every redirect shape — bare
1069/// (`>`, `>>`, `<`, `<<`, `<<<`, `&>`, `&>>`), fd-prefixed (`2>`, `2>>`,
1070/// `2>&1`, `1>&2`), and glued (`>file`, `2>/dev/null`).
1071pub fn is_shell_boundary(token: &str) -> bool {
1072    matches!(token, "|" | "|&" | ";" | "&" | "&&" | "||" | "&>" | "&>>") || is_redirect_token(token)
1073}
1074
1075/// A redirect operator token: an optional leading fd (`2` in `2>&1`) followed
1076/// by a `>`/`<` redirect, or an `&>`/`&>>` merge redirect. Real subcommands
1077/// (`test`, `log`, `build`) never match, so this can't suppress a true one.
1078fn is_redirect_token(token: &str) -> bool {
1079    let rest = token.trim_start_matches(|c: char| c.is_ascii_digit());
1080    rest.starts_with('>') || rest.starts_with('<') || rest.starts_with("&>")
1081}
1082
1083/// Outcome of scanning a command for a top-level pipeline.
1084#[derive(Debug, PartialEq, Eq)]
1085enum PipeSplit {
1086    /// No top-level `|` and no top-level separator — dispatch on the
1087    /// command as-is.
1088    None,
1089    /// A top-level pipeline; the captured stdout is this last stage's output.
1090    LastStage(String),
1091    /// The command cannot be safely dispatched to a head-token compressor.
1092    /// Either a pipe coexists with other top-level structure (so the
1093    /// captured output isn't just the last stage's), or a top-level
1094    /// separator (`;`, `&&`, `||`, bare `&`, newline) means multiple
1095    /// commands' output is interleaved — a head-token compressor would
1096    /// delete the other commands' output. Force generic instead.
1097    Unsafe,
1098}
1099
1100/// A clean, single top-level pipeline as seen by the shell scanner. The segment
1101/// labels are derived while scanning so completion warnings do not need to
1102/// perform a second, less-capable parse of the user's command.
1103#[cfg(unix)]
1104#[derive(Debug, Clone, PartialEq, Eq)]
1105pub struct PipelineInfo {
1106    pub segments: Vec<PipelineSegment>,
1107}
1108
1109#[cfg(unix)]
1110#[derive(Debug, Clone, PartialEq, Eq)]
1111pub struct PipelineSegment {
1112    pub label: String,
1113}
1114
1115#[derive(Debug, Default)]
1116struct PipelineScan {
1117    stages: Vec<String>,
1118    saw_top_pipe: bool,
1119    saw_top_separator: bool,
1120    saw_unmatched_close: bool,
1121    in_single: bool,
1122    in_double: bool,
1123    in_backtick: bool,
1124    paren_depth: u32,
1125    escaped: bool,
1126}
1127
1128/// Return the scanner's segment list only for a single, clean top-level
1129/// pipeline. Instrumentation deliberately rejects comments here: appending a
1130/// capture program to a command that ends in a comment is otherwise easy for
1131/// the comment to swallow. Heredocs and other multi-statement forms are already
1132/// rejected by the scanner's top-level newline/separator handling.
1133#[cfg(unix)]
1134pub fn single_top_level_pipeline(command: &str) -> Option<PipelineInfo> {
1135    if strip_top_level_comment(command) != command {
1136        return None;
1137    }
1138
1139    let scan = scan_top_level_pipe(command);
1140    let stages = clean_pipeline_stages(scan)?;
1141    if stages.len() < 2 {
1142        return None;
1143    }
1144
1145    Some(PipelineInfo {
1146        segments: stages
1147            .iter()
1148            .map(|stage| PipelineSegment {
1149                label: pipeline_segment_label(stage),
1150            })
1151            .collect(),
1152    })
1153}
1154
1155#[cfg(unix)]
1156fn pipeline_segment_label(stage: &str) -> String {
1157    let stage = strip_leading_assignment_prefix(stage).unwrap_or_else(|| stage.trim().to_string());
1158    let start = skip_whitespace(&stage, 0);
1159    let Some(first_end) = shell_word_end(&stage, start) else {
1160        return stage;
1161    };
1162    if first_end == stage.len() {
1163        return stage[start..first_end].to_string();
1164    }
1165
1166    let first_word = &stage[start..first_end];
1167    if first_word != "git" {
1168        return first_word.to_string();
1169    }
1170
1171    // Git's subcommand is part of the user-facing command name (`git rebase`)
1172    // and makes the warning substantially more useful than a bare `git` label.
1173    let second_start = skip_whitespace(&stage, first_end);
1174    let second_end = shell_word_end(&stage, second_start).unwrap_or(second_start);
1175    if second_end > second_start {
1176        format!("{} {}", first_word, &stage[second_start..second_end])
1177    } else {
1178        first_word.to_string()
1179    }
1180}
1181
1182/// Depth-aware pipeline scanner that FAILS CLOSED. Tracks single/double quotes,
1183/// backslash escapes, backtick substitution, and `(`/`$(`/`<(`/`>(` nesting so a
1184/// `|` inside any of them is not treated as a stage boundary. Splits on a
1185/// top-level `|`/`|&` (never `||`) and returns the LAST stage — but ONLY when the
1186/// command is a clean single pipeline. The caller captured the WHOLE command's
1187/// stdout, so "last stage == captured output" holds only when no other top-level
1188/// structure exists; otherwise a head-token compressor could claim the command
1189/// and drop the output (issue #137). Therefore, whenever a top-level pipe
1190/// coexists with ANY of {a top-level separator `;`/`&&`/`||`/bare `&`/newline,
1191/// an unbalanced quote/paren/backtick/escape, an unmatched `)`, or an empty
1192/// trailing stage}, we return `Unsafe` so the caller forces generic compression.
1193/// The same `Unsafe` result applies when there is NO pipe but a top-level
1194/// separator IS present: the captured transcript interleaves multiple commands'
1195/// output, so per-head specialized compression would delete the other commands'
1196/// output. Top-level comments must already be removed by
1197/// `strip_top_level_comment`. Redirects (`>`, `2>&1`, `&>`, …) are NOT separators.
1198fn split_top_level_pipe(command: &str) -> PipeSplit {
1199    let scan = scan_top_level_pipe(command);
1200    if scan.saw_top_pipe {
1201        if let Some(stages) = clean_pipeline_stages(scan) {
1202            return PipeSplit::LastStage(stages.last().cloned().unwrap_or_default());
1203        }
1204        return PipeSplit::Unsafe;
1205    }
1206
1207    if (scan.imbalance() && command.contains('|')) || scan.saw_top_separator {
1208        PipeSplit::Unsafe
1209    } else {
1210        PipeSplit::None
1211    }
1212}
1213
1214fn clean_pipeline_stages(scan: PipelineScan) -> Option<Vec<String>> {
1215    if !scan.saw_top_pipe || scan.imbalance() || scan.saw_top_separator {
1216        return None;
1217    }
1218    if scan.stages.iter().any(|stage| stage.trim().is_empty()) {
1219        return None;
1220    }
1221    Some(scan.stages)
1222}
1223
1224impl PipelineScan {
1225    fn imbalance(&self) -> bool {
1226        self.in_single
1227            || self.in_double
1228            || self.in_backtick
1229            || self.escaped
1230            || self.paren_depth != 0
1231            || self.saw_unmatched_close
1232    }
1233}
1234
1235fn scan_top_level_pipe(command: &str) -> PipelineScan {
1236    let bytes = command.as_bytes();
1237    let mut scan = PipelineScan::default();
1238    let mut stage_start = 0usize;
1239    let mut i = 0;
1240
1241    while i < bytes.len() {
1242        let ch = bytes[i];
1243
1244        if scan.escaped {
1245            scan.escaped = false;
1246            i += 1;
1247            continue;
1248        }
1249        if scan.in_single {
1250            if ch == b'\'' {
1251                scan.in_single = false;
1252            }
1253            i += 1;
1254            continue;
1255        }
1256        if scan.in_backtick {
1257            // Backtick substitution is opaque for splitting. A backslash still
1258            // escapes the next byte so an escaped backtick does not close it.
1259            if ch == b'\\' {
1260                scan.escaped = true;
1261            } else if ch == b'`' {
1262                scan.in_backtick = false;
1263            }
1264            i += 1;
1265            continue;
1266        }
1267        if ch == b'\\' {
1268            scan.escaped = true;
1269            i += 1;
1270            continue;
1271        }
1272        if ch == b'`' {
1273            scan.in_backtick = true;
1274            i += 1;
1275            continue;
1276        }
1277        // `$(` opens command substitution even inside double quotes.
1278        if ch == b'$' && bytes.get(i + 1) == Some(&b'(') {
1279            scan.paren_depth += 1;
1280            i += 2;
1281            continue;
1282        }
1283        if scan.in_double {
1284            if ch == b'"' {
1285                scan.in_double = false;
1286            }
1287            i += 1;
1288            continue;
1289        }
1290
1291        // Below here: outside single/double quotes and backticks. Top-level
1292        // comments are already removed by `strip_top_level_comment` before the
1293        // compression scanner runs, so no `#` handling is needed here.
1294        let prev_raw = if i > 0 { bytes[i - 1] } else { b' ' };
1295
1296        match ch {
1297            b'\'' => scan.in_single = true,
1298            b'"' => scan.in_double = true,
1299            // process substitution `<(` / `>(`
1300            b'<' | b'>' if bytes.get(i + 1) == Some(&b'(') => {
1301                scan.paren_depth += 1;
1302                i += 2;
1303                continue;
1304            }
1305            b'(' => scan.paren_depth += 1,
1306            b')' => {
1307                if scan.paren_depth == 0 {
1308                    scan.saw_unmatched_close = true;
1309                } else {
1310                    scan.paren_depth -= 1;
1311                }
1312            }
1313            b'|' if scan.paren_depth == 0 => {
1314                if bytes.get(i + 1) == Some(&b'|') {
1315                    scan.saw_top_separator = true; // `||` logical OR
1316                    i += 2;
1317                    continue;
1318                }
1319                scan.saw_top_pipe = true;
1320                scan.stages.push(command[stage_start..i].trim().to_string());
1321                let delimiter_len = if bytes.get(i + 1) == Some(&b'&') {
1322                    2 // `|&` (stdout+stderr)
1323                } else {
1324                    1
1325                };
1326                stage_start = i + delimiter_len;
1327                i += delimiter_len;
1328                continue;
1329            }
1330            b'&' if scan.paren_depth == 0 => {
1331                if bytes.get(i + 1) == Some(&b'&') {
1332                    scan.saw_top_separator = true; // `&&`
1333                    i += 2;
1334                    continue;
1335                }
1336                // `&>`/`&>>` redirect, or `>&`/`2>&1` fd-dup: NOT a separator.
1337                // A bare `&` is the background control operator.
1338                if bytes.get(i + 1) != Some(&b'>') && prev_raw != b'>' {
1339                    scan.saw_top_separator = true;
1340                }
1341            }
1342            b';' | b'\n' if scan.paren_depth == 0 => scan.saw_top_separator = true,
1343            _ => {}
1344        }
1345        i += 1;
1346    }
1347
1348    if scan.saw_top_pipe {
1349        scan.stages.push(command[stage_start..].trim().to_string());
1350    }
1351    scan
1352}
1353
1354fn strip_cd_prefix(command: &str) -> Option<String> {
1355    // Look for `&&` or `;` outside of quotes.
1356    let bytes = command.as_bytes();
1357    let mut in_single = false;
1358    let mut in_double = false;
1359    let mut i = 0;
1360    while i < bytes.len() {
1361        let ch = bytes[i] as char;
1362        if !in_double && ch == '\'' {
1363            in_single = !in_single;
1364        } else if !in_single && ch == '"' {
1365            in_double = !in_double;
1366        } else if !in_single && !in_double {
1367            if ch == '&' && i + 1 < bytes.len() && bytes[i + 1] as char == '&' {
1368                let rest = command[i + 2..].trim_start();
1369                if rest.is_empty() {
1370                    return None;
1371                }
1372                return Some(rest.to_string());
1373            }
1374            if ch == ';' {
1375                let rest = command[i + 1..].trim_start();
1376                if rest.is_empty() {
1377                    return None;
1378                }
1379                return Some(rest.to_string());
1380            }
1381        }
1382        i += 1;
1383    }
1384    None
1385}
1386
1387fn strip_env_prefix(command: &str) -> Option<String> {
1388    // env <ASSIGN>... <cmd> ...
1389    let rest = command.strip_prefix("env")?.trim_start();
1390    strip_leading_assignment_prefix(rest)
1391}
1392
1393fn strip_leading_assignment_prefix(command: &str) -> Option<String> {
1394    let mut index = 0usize;
1395    let mut consumed_assignment = false;
1396
1397    loop {
1398        index = skip_whitespace(command, index);
1399        if index >= command.len() {
1400            break;
1401        }
1402
1403        let word_end = shell_word_end(command, index)?;
1404        if word_end == index {
1405            break;
1406        }
1407
1408        let word = &command[index..word_end];
1409        if !is_env_assignment(word) {
1410            break;
1411        }
1412
1413        consumed_assignment = true;
1414        index = word_end;
1415    }
1416
1417    if !consumed_assignment {
1418        return None;
1419    }
1420
1421    let after = command[index..].trim_start();
1422    if after.is_empty() {
1423        None
1424    } else {
1425        Some(after.to_string())
1426    }
1427}
1428
1429fn skip_whitespace(input: &str, mut index: usize) -> usize {
1430    while index < input.len() {
1431        let Some(ch) = input[index..].chars().next() else {
1432            break;
1433        };
1434        if !ch.is_whitespace() {
1435            break;
1436        }
1437        index += ch.len_utf8();
1438    }
1439    index
1440}
1441
1442fn shell_word_end(command: &str, start: usize) -> Option<usize> {
1443    let mut in_single = false;
1444    let mut in_double = false;
1445    let mut escaped = false;
1446
1447    for (offset, ch) in command[start..].char_indices() {
1448        let index = start + offset;
1449
1450        if escaped {
1451            escaped = false;
1452            continue;
1453        }
1454
1455        if ch == '\\' && !in_single {
1456            escaped = true;
1457            continue;
1458        }
1459
1460        if ch == '\'' && !in_double {
1461            in_single = !in_single;
1462            continue;
1463        }
1464
1465        if ch == '"' && !in_single {
1466            in_double = !in_double;
1467            continue;
1468        }
1469
1470        if !in_single && !in_double && (ch.is_whitespace() || matches!(ch, ';' | '&' | '|')) {
1471            return Some(index);
1472        }
1473    }
1474
1475    if in_single || in_double || escaped {
1476        None
1477    } else {
1478        Some(command.len())
1479    }
1480}
1481
1482fn is_env_assignment(token: &str) -> bool {
1483    if token.starts_with('-') {
1484        return false;
1485    }
1486    let Some((name, _value)) = token.split_once('=') else {
1487        return false;
1488    };
1489    let mut chars = name.chars();
1490    let Some(first) = chars.next() else {
1491        return false;
1492    };
1493    (first.is_ascii_alphabetic() || first == '_')
1494        && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
1495}
1496
1497fn strip_timeout_prefix(command: &str) -> Option<String> {
1498    let rest = command.strip_prefix("timeout")?.trim_start();
1499    // Next token must look like a duration (digits, optional trailing unit s/m/h).
1500    let mut iter = rest.splitn(2, char::is_whitespace);
1501    let duration = iter.next()?;
1502    let after = iter.next()?.trim_start();
1503    if after.is_empty() || !looks_like_duration(duration) {
1504        return None;
1505    }
1506    Some(after.to_string())
1507}
1508
1509fn looks_like_duration(token: &str) -> bool {
1510    if token.is_empty() {
1511        return false;
1512    }
1513    let mut chars = token.chars().peekable();
1514    let mut saw_digit = false;
1515    while let Some(&ch) = chars.peek() {
1516        if ch.is_ascii_digit() {
1517            saw_digit = true;
1518            chars.next();
1519        } else {
1520            break;
1521        }
1522    }
1523    if !saw_digit {
1524        return false;
1525    }
1526    match chars.next() {
1527        None => true,
1528        Some(unit) => matches!(unit, 's' | 'm' | 'h' | 'd') && chars.next().is_none(),
1529    }
1530}
1531
1532/// Resolve the harness-scoped user-filter directory for an arbitrary storage_dir.
1533/// Used by `aft doctor filters` to inspect filters without needing a live AppContext.
1534pub fn user_filter_dir(storage_dir: &Path, harness: Harness) -> PathBuf {
1535    storage_dir.join(harness.storage_segment()).join("filters")
1536}
1537
1538fn legacy_user_filter_dir(storage_dir: &Path) -> PathBuf {
1539    storage_dir.join("filters")
1540}
1541
1542/// Move filters written by the short-lived root-scoped v0.27 layout into the
1543/// active harness directory. Existing harness files win; colliding root files
1544/// are left in place so we never overwrite user-authored filters.
1545pub fn repair_legacy_user_filter_dir(storage_dir: &Path, harness: Harness) {
1546    let legacy_dir = legacy_user_filter_dir(storage_dir);
1547    if !legacy_dir.exists() {
1548        return;
1549    }
1550
1551    let entries = match fs::read_dir(&legacy_dir) {
1552        Ok(entries) => entries.filter_map(Result::ok).collect::<Vec<_>>(),
1553        Err(_) => return,
1554    };
1555    if entries.is_empty() {
1556        let _ = fs::remove_dir(&legacy_dir);
1557        return;
1558    }
1559
1560    let harness_dir = user_filter_dir(storage_dir, harness);
1561    if crate::private_storage::create_dir_all(&harness_dir).is_err() {
1562        return;
1563    }
1564
1565    for entry in entries {
1566        let target = harness_dir.join(entry.file_name());
1567        if target.exists() {
1568            continue;
1569        }
1570        // The harness folder and the root normally share a volume, but a move
1571        // that crosses volumes falls back to a copy instead of failing.
1572        match crate::cross_volume::move_path(&entry.path(), &target) {
1573            Ok(moved) => moved.warn_if_incomplete(&entry.path(), &target),
1574            Err(error) => {
1575                // A filter that cannot be moved stays in the root `filters/`
1576                // folder; log the move failure instead of dropping it.
1577                crate::slog_warn!(
1578                    "legacy filter {} kept in place: cannot move it to {}: {}",
1579                    entry.path().display(),
1580                    target.display(),
1581                    error
1582                );
1583            }
1584        }
1585    }
1586
1587    if fs::read_dir(&legacy_dir)
1588        .map(|mut entries| entries.next().is_none())
1589        .unwrap_or(false)
1590    {
1591        let _ = fs::remove_dir(&legacy_dir);
1592    }
1593}
1594
1595/// Resolve the project-filter directory for an arbitrary project root.
1596/// Returns the directory regardless of trust state — caller must check trust
1597/// separately if it wants to gate loading.
1598pub fn project_filter_dir(project_root: &Path) -> PathBuf {
1599    project_root.join(".cortexkit").join("aft").join("filters")
1600}
1601
1602#[cfg(test)]
1603mod tests {
1604    use super::*;
1605
1606    #[cfg(unix)]
1607    #[test]
1608    fn single_pipeline_scanner_returns_segment_labels() {
1609        let pipeline = single_top_level_pipeline("git rebase upstream/main | tail -3").unwrap();
1610        assert_eq!(
1611            pipeline
1612                .segments
1613                .iter()
1614                .map(|segment| segment.label.as_str())
1615                .collect::<Vec<_>>(),
1616            ["git rebase", "tail"]
1617        );
1618    }
1619
1620    #[cfg(unix)]
1621    #[test]
1622    fn single_pipeline_scanner_rejects_unsafe_shapes() {
1623        for command in [
1624            "false | tail -1; true | cat",
1625            "false | tail -1 &",
1626            "false | tail -1 # trailing comment",
1627            "cat <<EOF | tail -1\nbody\nEOF",
1628        ] {
1629            assert!(
1630                single_top_level_pipeline(command).is_none(),
1631                "scanner should reject {command:?}"
1632            );
1633        }
1634    }
1635
1636    #[cfg(unix)]
1637    #[test]
1638    fn single_pipeline_scanner_accepts_pipe_without_top_level_newline() {
1639        let pipeline = single_top_level_pipeline("false | tail -1").unwrap();
1640        assert_eq!(pipeline.segments.len(), 2);
1641    }
1642
1643    #[test]
1644    fn dispatch_strips_ansi_once_for_generic_and_toml_tiers() {
1645        let registry = toml_filter::build_registry(builtin_filters::ALL, None, None);
1646        for (command, output) in [
1647            ("custom-runner", "\u{1b}[32mline\u{1b}[0m\n"),
1648            (
1649                "docker build .",
1650                "\u{1b}[32m#1 DONE 0.1s\u{1b}[0m\nretained line\n",
1651            ),
1652        ] {
1653            generic::reset_ansi_strip_count();
1654            let result = compress_with_registry(command, output, &registry);
1655            assert!(!result.is_empty());
1656            assert_eq!(generic::ansi_strip_count(), 1, "command: {command}");
1657        }
1658    }
1659
1660    #[test]
1661    fn user_and_project_filter_dir_helpers() {
1662        let storage = Path::new("/tmp/aft-storage");
1663        assert_eq!(
1664            user_filter_dir(storage, Harness::Opencode),
1665            Path::new("/tmp/aft-storage/opencode/filters")
1666        );
1667
1668        let project = Path::new("/repo");
1669        assert_eq!(
1670            project_filter_dir(project),
1671            Path::new("/repo/.cortexkit/aft/filters")
1672        );
1673    }
1674
1675    #[test]
1676    fn repair_legacy_user_filter_dir_moves_root_filters_without_overwrite() {
1677        let temp = tempfile::tempdir().unwrap();
1678        let storage = temp.path();
1679        fs::create_dir_all(storage.join("filters")).unwrap();
1680        fs::create_dir_all(storage.join("opencode/filters")).unwrap();
1681        fs::write(storage.join("filters/root-only.toml"), "root").unwrap();
1682        fs::write(storage.join("filters/collides.toml"), "root").unwrap();
1683        fs::write(storage.join("opencode/filters/collides.toml"), "harness").unwrap();
1684
1685        repair_legacy_user_filter_dir(storage, Harness::Opencode);
1686
1687        assert_eq!(
1688            fs::read_to_string(storage.join("opencode/filters/root-only.toml")).unwrap(),
1689            "root"
1690        );
1691        assert_eq!(
1692            fs::read_to_string(storage.join("opencode/filters/collides.toml")).unwrap(),
1693            "harness"
1694        );
1695        assert_eq!(
1696            fs::read_to_string(storage.join("filters/collides.toml")).unwrap(),
1697            "root"
1698        );
1699        assert!(!storage.join("filters/root-only.toml").exists());
1700    }
1701
1702    #[test]
1703    fn repair_legacy_user_filter_dir_moves_filters_into_a_harness_folder_on_another_volume() {
1704        let temp = tempfile::tempdir().unwrap();
1705        let storage = temp.path();
1706        fs::create_dir_all(storage.join("filters")).unwrap();
1707        fs::create_dir_all(storage.join("opencode/filters")).unwrap();
1708        fs::write(storage.join("filters/root-only.toml"), "root").unwrap();
1709        // Every rename from the root into the harness folder now fails with EXDEV.
1710        let _volume = crate::walk_boundary::simulated_volumes::simulate(
1711            &storage.join("opencode"),
1712            u64::MAX - 23,
1713        );
1714
1715        repair_legacy_user_filter_dir(storage, Harness::Opencode);
1716
1717        assert_eq!(
1718            fs::read_to_string(storage.join("opencode/filters/root-only.toml")).unwrap(),
1719            "root"
1720        );
1721        assert!(!storage.join("filters").exists());
1722    }
1723}
1724
1725/// Cargo output of 1 KiB or less is passed through raw. A dispatch test that
1726/// must see the cargo summary at work pads its fixture with per-test progress
1727/// lines, which the summary drops.
1728#[cfg(any(test, feature = "test-support"))]
1729#[cfg_attr(not(test), allow(dead_code))]
1730fn cargo_test_progress_padding() -> String {
1731    "test padding_case ... ok\n".repeat(50)
1732}
1733
1734/// Cargo build counterpart of [`cargo_test_progress_padding`]: status lines the
1735/// build summary drops.
1736#[cfg(any(test, feature = "test-support"))]
1737#[cfg_attr(not(test), allow(dead_code))]
1738fn cargo_build_progress_padding() -> String {
1739    "   Compiling padding v0.1.0\n".repeat(40)
1740}
1741
1742#[cfg(test)]
1743mod output_probe_tests {
1744    use super::generic::strip_ansi;
1745    use super::*;
1746    use serde::Deserialize;
1747
1748    #[cfg(debug_assertions)]
1749    #[test]
1750    fn a02_plain_dispatch_borrows_stripped_input() {
1751        for command in ["./unknown", "unknown | cat"] {
1752            let input = "ordinary output\n".repeat(1000);
1753            generic::reset_ansi_strip_alloc_bytes();
1754            let _ = compress_with_registry(command, &input, &FilterRegistry::default());
1755            assert_eq!(
1756                generic::ansi_strip_alloc_bytes(),
1757                0,
1758                "plain dispatch must not allocate a stripped copy"
1759            );
1760        }
1761    }
1762
1763    #[derive(Deserialize)]
1764    struct CorpusEntry {
1765        file: String,
1766    }
1767
1768    #[derive(Debug, PartialEq, Eq)]
1769    struct MatchPhaseResult {
1770        selected: Option<usize>,
1771        output: CompressionResult,
1772    }
1773
1774    fn legacy_match_phase(output: &str) -> MatchPhaseResult {
1775        let compressors = compressors_in_dispatch_order();
1776        let selected = [Specificity::Specific, Specificity::PackageManager]
1777            .into_iter()
1778            .find_map(|specificity| {
1779                compressors
1780                    .iter()
1781                    .enumerate()
1782                    .filter(|(_, compressor)| compressor.specificity() == specificity)
1783                    .find_map(|(index, compressor)| {
1784                        compressor.matches_output(output).then_some(index)
1785                    })
1786            });
1787        match_phase_result(&compressors, selected, output)
1788    }
1789
1790    fn probe_match_phase(output: &str) -> MatchPhaseResult {
1791        let compressors = compressors_in_dispatch_order();
1792        let probe = OutputProbe::new(output);
1793        let selected = [Specificity::Specific, Specificity::PackageManager]
1794            .into_iter()
1795            .find_map(|specificity| {
1796                compressors
1797                    .iter()
1798                    .enumerate()
1799                    .filter(|(_, compressor)| compressor.specificity() == specificity)
1800                    .find_map(|(index, compressor)| {
1801                        compressor.matches_output_probe(&probe).then_some(index)
1802                    })
1803            });
1804        MatchPhaseResult {
1805            selected,
1806            output: selected
1807                .map(|index| compressors[index].compress_output_probe_match(&probe, None))
1808                .unwrap_or_else(|| GenericCompressor::compress_stripped_output(output).into()),
1809        }
1810    }
1811
1812    fn match_phase_result(
1813        compressors: &[&dyn Compressor],
1814        selected: Option<usize>,
1815        output: &str,
1816    ) -> MatchPhaseResult {
1817        let output = selected.map_or_else(
1818            || GenericCompressor.compress_with_exit_code("", output, None),
1819            |index| compressors[index].compress_output_match_with_exit_code(output, None),
1820        );
1821        MatchPhaseResult { selected, output }
1822    }
1823
1824    fn repository_root() -> PathBuf {
1825        Path::new(crate::test_support::manifest_dir())
1826            .parent()
1827            .and_then(Path::parent)
1828            .expect("aft crate should be nested under the repository root")
1829            .to_path_buf()
1830    }
1831
1832    fn benchmark_corpus() -> Vec<(String, String)> {
1833        let fixtures = repository_root().join("benchmarks/compression-tokens/fixtures");
1834        let manifest_text = fs::read_to_string(fixtures.join("manifest.json"))
1835            .expect("compression corpus manifest should be readable");
1836        let manifest: Vec<CorpusEntry> =
1837            serde_json::from_str(&manifest_text).expect("compression corpus manifest should parse");
1838        manifest
1839            .into_iter()
1840            .map(|entry| {
1841                let output = fs::read_to_string(fixtures.join(&entry.file))
1842                    .unwrap_or_else(|error| panic!("failed to read {}: {error}", entry.file));
1843                (format!("compression corpus {}", entry.file), output)
1844            })
1845            .collect()
1846    }
1847
1848    fn integration_filter_inputs() -> Vec<(String, String)> {
1849        let root = Path::new(crate::test_support::manifest_dir())
1850            .join("../aft/tests/integration/fixtures/compress_filters");
1851        let mut paths = Vec::new();
1852        collect_named_files(&root, "input.txt", &mut paths);
1853        paths.sort();
1854        paths
1855            .into_iter()
1856            .map(|path| {
1857                let output = fs::read_to_string(&path)
1858                    .unwrap_or_else(|error| panic!("failed to read {}: {error}", path.display()));
1859                (format!("filter fixture {}", path.display()), output)
1860            })
1861            .collect()
1862    }
1863
1864    fn collect_named_files(root: &Path, wanted_name: &str, paths: &mut Vec<PathBuf>) {
1865        let entries = fs::read_dir(root)
1866            .unwrap_or_else(|error| panic!("failed to read {}: {error}", root.display()));
1867        for entry in entries {
1868            let path = entry
1869                .expect("fixture directory entry should be readable")
1870                .path();
1871            if path.is_dir() {
1872                collect_named_files(&path, wanted_name, paths);
1873            } else if path.file_name().is_some_and(|name| name == wanted_name) {
1874                paths.push(path);
1875            }
1876        }
1877    }
1878
1879    fn hostile_outputs() -> Vec<(String, String)> {
1880        let huge_json_array = format!(
1881            "[{}]",
1882            (0..20_000)
1883                .map(|index| format!(r#"{{"index":{index},"value":"payload"}}"#))
1884                .collect::<Vec<_>>()
1885                .join(",")
1886        );
1887        let ansi_heavy = (0..2_000)
1888            .map(|index| format!("\u{1b}[31mordinary output {index}\u{1b}[0m"))
1889            .collect::<Vec<_>>()
1890            .join("\n");
1891        vec![
1892            (
1893                "valid non-tool JSON object".to_string(),
1894                r#" {"payload":{"nested":[1,2,3]},"ok":true}"#.to_string(),
1895            ),
1896            ("huge JSON array".to_string(), huge_json_array),
1897            (
1898                "almost JSON".to_string(),
1899                r#"{"payload":[1,2,3],"unterminated":true"#.to_string(),
1900            ),
1901            ("empty output".to_string(), String::new()),
1902            ("ANSI-heavy output".to_string(), ansi_heavy),
1903        ]
1904    }
1905
1906    #[test]
1907    fn shared_probe_preserves_match_selection_and_output_across_corpora() {
1908        let cases = benchmark_corpus()
1909            .into_iter()
1910            .chain(integration_filter_inputs())
1911            .chain(hostile_outputs());
1912
1913        for (label, raw_output) in cases {
1914            let output = strip_ansi(&raw_output);
1915            let legacy = legacy_match_phase(&output);
1916            let probed = probe_match_phase(&output);
1917            assert_eq!(legacy, probed, "output-shape dispatch changed for {label}");
1918        }
1919    }
1920
1921    #[cfg(debug_assertions)]
1922    #[test]
1923    fn unmatched_json_object_is_parsed_once_across_match_phase() {
1924        let output = r#"{"payload":{"nested":[1,2,3]},"ok":true}"#;
1925        reset_output_probe_json_parse_count();
1926
1927        let result = probe_match_phase(output);
1928
1929        assert_eq!(result.selected, None);
1930        assert_eq!(output_probe_json_parse_count(), 1);
1931    }
1932
1933    #[cfg(debug_assertions)]
1934    #[test]
1935    fn a02_json_arrays_share_one_parse_through_rendering() {
1936        for command in ["./check.sh", "eslint", "ruff"] {
1937            for output in [
1938                "[]",
1939                "[{\"payload\":true}]",
1940                "[not JSON",
1941                "[]\u{a0}",
1942                r#"[{"filePath":"a.js","messages":[]}]"#,
1943                r#"[{"code":"F401","filename":"a.py","location":{"row":1,"column":2},"message":"unused"}]"#,
1944            ] {
1945                reset_output_probe_json_parse_count();
1946                let _ = compress_with_registry_exit_code(
1947                    command,
1948                    output,
1949                    Some(0),
1950                    &FilterRegistry::default(),
1951                );
1952                assert!(
1953                    output_probe_json_parse_count() <= 1,
1954                    "{command}: {} JSON parses for {output}",
1955                    output_probe_json_parse_count()
1956                );
1957            }
1958        }
1959    }
1960
1961    #[test]
1962    fn a02_ruff_command_preserves_unicode_trailing_whitespace() {
1963        let result = compress_with_registry("ruff", "[]\u{a0}", &FilterRegistry::default());
1964        assert_eq!(result.text, "ruff: clean");
1965        assert!(!RuffCompressor.matches_output_probe(&OutputProbe::new("[]\u{a0}")));
1966    }
1967}
1968
1969#[cfg(test)]
1970mod dispatch_specificity_tests {
1971    use super::*;
1972    use crate::compress::toml_filter::FilterRegistry;
1973
1974    fn empty_registry() -> FilterRegistry {
1975        FilterRegistry::default()
1976    }
1977
1978    /// Helper: assert that a given command would be claimed by a specific
1979    /// compressor by reading the output marker the compressor produces.
1980    /// (We can't easily compare Compressor instances by identity, so we
1981    /// dispatch and check for module-distinctive markers in the output.)
1982    fn dispatch(cmd: &str, output: &str) -> String {
1983        compress_with_registry(cmd, output, &empty_registry()).text
1984    }
1985
1986    #[test]
1987    fn generic_dispatch_does_not_classify_error_or_warning_words() {
1988        let result = compress_with_registry(
1989            "unknown-tool",
1990            "error: this is just a log line\nwarning: this too",
1991            &empty_registry(),
1992        );
1993
1994        assert!(result.dropped_by_class.is_empty());
1995        assert!(!result.had_inner_drop);
1996        assert!(result.text.contains("error: this is just a log line"));
1997    }
1998
1999    #[test]
2000    fn bun_run_vitest_routes_to_vitest_not_generic() {
2001        // VitestCompressor preserves PASS/FAIL markers and "Tests:" summary.
2002        // BunCompressor's `Some("run")` arm currently goes to generic which
2003        // would middle-truncate. Use a small vitest-shaped output and assert
2004        // the vitest formatter's output marker is present.
2005        let output = "Test Files  1 passed (1)\n     Tests  4 passed (4)\n  Start at  10:00:00\n  Duration  120ms\n";
2006        let compressed = dispatch("bun run vitest", output);
2007        // Assert vitest path took it: the vitest text summary keeps "Tests" / "Test Files" lines
2008        assert!(compressed.contains("Tests") || compressed.contains("Test Files"));
2009    }
2010
2011    #[test]
2012    fn npm_test_routes_to_vitest_when_output_is_vitest_shaped() {
2013        // `npm test` has no vitest token, so this proves the output-shape
2014        // tier runs before the broad NpmCompressor PackageManager tier.
2015        let output = "RERUN src/foo.test.ts x1\nFAIL src/foo.test.ts\nTest Files  1 failed (1)\nDuration    120ms\n";
2016        let compressed = dispatch("npm test", output);
2017        assert!(compressed.contains("FAIL src/foo.test.ts"));
2018        assert!(compressed.contains("Duration    120ms"));
2019        assert!(!compressed.contains("RERUN"));
2020    }
2021
2022    #[test]
2023    fn bun_run_vitest_token_match_wins_over_bun_head_match() {
2024        // Concrete proof the new dispatch works: a command where Bun would
2025        // otherwise have claimed it.
2026        let output = "PASS src/a.test.ts (1)\n PASS src/b.test.ts (1)\nTest Files  2 passed (2)\n     Tests  4 passed (4)\n";
2027        let compressed = dispatch("bun run vitest run", output);
2028        // Vitest preserves PASS lines and "Tests:" summary.
2029        assert!(compressed.contains("Test Files") || compressed.contains("PASS"));
2030    }
2031
2032    #[test]
2033    fn bunx_jest_routes_to_vitest_module() {
2034        let output = "PASS src/foo.test.js (1.2s)\nTest Suites: 1 passed, 1 total\nTests:       3 passed, 3 total\n";
2035        let compressed = dispatch("bunx jest --json", output);
2036        assert!(compressed.contains("Tests:") && compressed.contains("Test Suites"));
2037    }
2038
2039    #[test]
2040    fn pnpm_run_vitest_routes_to_vitest() {
2041        let output = "Test Files  1 passed (1)\n     Tests  10 passed (10)\n";
2042        let compressed = dispatch("pnpm run vitest", output);
2043        assert!(compressed.contains("Tests") || compressed.contains("Test Files"));
2044    }
2045
2046    #[test]
2047    fn npx_eslint_routes_to_eslint_not_generic() {
2048        let output = "\n/tmp/a.js\n  1:1  error  'foo' is defined but never used  no-unused-vars\n\n✖ 1 problem (1 error, 0 warnings)\n";
2049        let compressed = dispatch("npx eslint .", output);
2050        // EslintCompressor preserves rule IDs and the ✖ summary.
2051        assert!(compressed.contains("no-unused-vars") || compressed.contains("✖"));
2052    }
2053
2054    #[test]
2055    fn npm_run_lint_without_linter_output_shape_falls_back() {
2056        // `npm run lint` has no eslint token, and this output has no eslint
2057        // summary signature, so it should remain package-manager generic.
2058        let output = "> my-project@1.0.0 lint\n> eslint .\n\nAll good.\n";
2059        let compressed = dispatch("npm run lint", output);
2060        assert!(compressed.contains("All good."));
2061    }
2062
2063    #[test]
2064    fn bun_test_still_routes_to_bun_test_compressor() {
2065        // Bun.test is the v0.28.2 fix — make sure specificity dispatch
2066        // doesn't accidentally break it. The Bun module's `Some("test")`
2067        // arm should still claim this when no Specific matcher does.
2068        // BunTestCompressor doesn't exist as a separate module — the
2069        // BunCompressor.compress() routes Some("test") to its inner
2070        // compress_test() function. The relevant assertion: this still
2071        // produces bun-test-shaped output, not generic-truncated output.
2072        let output = "bun test v1.3.14\n\nsrc/foo.test.ts:\n(pass) my test [0.5ms]\n\n 1 pass\n 0 fail\n 1 expect() calls\nRan 1 tests across 1 files. [1.00ms]\n";
2073        let compressed = dispatch("bun test", output);
2074        assert!(compressed.contains("(pass)") || compressed.contains("1 pass"));
2075    }
2076
2077    #[test]
2078    fn bunx_vitest_routes_to_vitest() {
2079        let output = "Test Files  1 passed (1)\n     Tests  3 passed (3)\n";
2080        let compressed = dispatch("bunx vitest run", output);
2081        assert!(compressed.contains("Tests") || compressed.contains("Test Files"));
2082    }
2083
2084    #[test]
2085    fn cargo_test_still_routes_to_cargo() {
2086        // Regression: specificity reordering must not break commands that
2087        // already worked. Cargo is Specific tier.
2088        let output = "running 5 tests\ntest foo ... ok\ntest bar ... FAILED\n\nfailures:\n\ntest result: FAILED. 4 passed; 1 failed\n";
2089        let compressed = dispatch("cargo test", output);
2090        // Cargo's test compressor preserves PASS/FAIL semantics.
2091        assert!(compressed.contains("failed") || compressed.contains("FAILED"));
2092    }
2093
2094    #[test]
2095    fn top_level_piped_cargo_test_uses_generic_output() {
2096        let output = "running 1 test\ntest ok_test ... ok\n\ntest result: ok. 1 passed; 0 failed\n";
2097
2098        let compressed = compress_with_registry("cargo test | cat", output, &empty_registry());
2099
2100        assert!(
2101            compressed.text.contains("test ok_test ... ok"),
2102            "piped cargo output must stay generic/raw, got: {}",
2103            compressed.text
2104        );
2105    }
2106
2107    /// A gate script's verdicts followed by four cargo test binaries, as one
2108    /// finished command printed them (417 bytes).
2109    const SHORT_GATE_OUTPUT: &str = "fmt-ok\nwin-check rc=0\ntest result: ok. 803 passed; 0 failed; 19 ignored; 0 measured; 8977 filtered out; finished in 23.38s\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2592 filtered out; finished in 0.12s\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2592 filtered out; finished in 0.16s\ntest result: ok. 114 passed; 0 failed; 3 ignored; 0 measured; 2476 filtered out; finished in 11.74s\n";
2110
2111    #[test]
2112    fn short_cargo_test_output_passes_through_raw_without_a_cap_trailer() {
2113        for output in [
2114            SHORT_GATE_OUTPUT.to_string(),
2115            SHORT_GATE_OUTPUT.replace("win-check rc=0", "win-check rc=101"),
2116        ] {
2117            for command in ["./scripts/gate.sh", "cargo test"] {
2118                let compressed =
2119                    compress_with_registry_exit_code(command, &output, Some(0), &empty_registry());
2120
2121                assert_eq!(compressed.text, output, "{command}");
2122                assert!(
2123                    crate::list_surfaces::bash::build_envelope_from_output(
2124                        &compressed.text,
2125                        compressed.input_line_count()
2126                    )
2127                    .is_none(),
2128                    "{command}: nothing was cut, so no `shown N of M` trailer"
2129                );
2130            }
2131        }
2132    }
2133
2134    #[test]
2135    fn long_sniffed_cargo_test_output_keeps_gate_verdicts() {
2136        let mut output = String::from("fmt-ok\nwin-check rc=101\nrunning 40 tests\n");
2137        for index in 0..40 {
2138            output.push_str(&format!("test tests::case_{index} ... ok\n"));
2139        }
2140        output.push_str("\ntest result: ok. 40 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s\n");
2141        assert!(
2142            output.len() > 1024,
2143            "fixture must be past the raw passthrough size"
2144        );
2145
2146        let compressed = compress_with_registry_exit_code(
2147            "./scripts/gate.sh",
2148            &output,
2149            Some(0),
2150            &empty_registry(),
2151        );
2152
2153        assert_eq!(
2154            compressed.text,
2155            "fmt-ok\nwin-check rc=101\nrunning 40 tests\ntest result: ok. 40 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s"
2156        );
2157    }
2158
2159    #[test]
2160    fn non_piped_cargo_test_still_uses_cargo_compressor() {
2161        let output = format!(
2162            "running 1 test\ntest ok_test ... ok\n{}\ntest result: ok. 1 passed; 0 failed\n",
2163            cargo_test_progress_padding()
2164        );
2165
2166        let compressed = compress_with_registry("cargo test", &output, &empty_registry());
2167
2168        assert!(compressed.text.contains("running 1 test"));
2169        assert!(compressed.text.contains("test result: ok"));
2170        assert!(
2171            !compressed.text.contains("test ok_test ... ok"),
2172            "non-piped cargo test should keep using the cargo compressor, got: {}",
2173            compressed.text
2174        );
2175    }
2176
2177    #[test]
2178    fn git_status_still_routes_to_git() {
2179        // Regression: git is Specific tier.
2180        let output =
2181            "On branch main\nYour branch is up to date.\n\nnothing to commit, working tree clean\n";
2182        let compressed = dispatch("git status", output);
2183        assert!(compressed.contains("branch") || compressed.contains("clean"));
2184    }
2185
2186    #[test]
2187    fn pnpm_install_still_routes_to_pnpm() {
2188        // Regression: pnpm install was handled before this change.
2189        let output = "Progress: resolved 100, downloaded 50, added 50\nAdded 50 packages\n";
2190        let compressed = dispatch("pnpm install", output);
2191        // PnpmCompressor's compress_package keeps "+ pkg" or "Added X packages" type lines.
2192        assert!(compressed.contains("Added") || compressed.contains("Progress"));
2193    }
2194}
2195
2196#[cfg(test)]
2197mod exit_code_safety_tests {
2198    use super::*;
2199    use crate::compress::toml_filter::{build_registry, FilterRegistry};
2200
2201    fn empty_registry() -> FilterRegistry {
2202        FilterRegistry::default()
2203    }
2204
2205    #[test]
2206    fn go_build_failure_signal_preserved_even_when_exit_zero_masks_failure() {
2207        let output = "go: go.mod file not found in current directory or any parent directory; see 'go help modules'\n";
2208
2209        let failed =
2210            compress_with_registry_exit_code("go build ./...", output, Some(1), &empty_registry());
2211        assert!(!failed.text.contains("go build: ok"));
2212        assert!(failed.text.contains("go.mod file not found"));
2213
2214        let masked =
2215            compress_with_registry_exit_code("go build ./...", output, Some(0), &empty_registry());
2216        assert!(!masked.text.contains("go build: ok"));
2217        assert!(masked.text.contains("go.mod file not found"));
2218    }
2219
2220    #[test]
2221    fn playwright_nonzero_crash_does_not_become_passed_summary() {
2222        let output = r#"Running 4 tests using 2 workers
2223
2224  ✓  1 [chromium] › example.spec.ts:5:1 › has title (2.3s)
2225  ✓  2 [chromium] › example.spec.ts:9:1 › get started link (1.8s)
2226  ✓  3 [chromium] › nav.spec.ts:3:1 › navigates (1.2s)
2227  ✓  4 [chromium] › auth.spec.ts:7:1 › logs out (1.0s)
2228
2229  4 passed (6.3s)
2230Error: browserType.launch: Target page, context or browser has been closed
2231"#;
2232
2233        let failed = compress_with_registry_exit_code(
2234            "npx playwright test",
2235            output,
2236            Some(1),
2237            &empty_registry(),
2238        );
2239        assert!(!failed.text.starts_with("playwright: 4 tests passed"));
2240        assert!(failed.text.contains("browserType.launch"));
2241    }
2242
2243    #[test]
2244    fn cargo_test_compile_error_nonzero_preserves_error_code_diagnostic() {
2245        let output = r#"   Compiling demo v0.1.0 (/tmp/demo)
2246error[E0432]: unresolved import `crate::missing`
2247 --> src/lib.rs:1:5
2248  |
22491 | use crate::missing;
2250  |     ^^^^^^^^^^^^^^ no `missing` in the root
2251
2252error: could not compile `demo` (lib test) due to 1 previous error
2253"#;
2254
2255        let failed =
2256            compress_with_registry_exit_code("cargo test", output, Some(101), &empty_registry());
2257        assert!(failed.text.contains("error[E0432]"));
2258        assert!(failed.text.contains("unresolved import"));
2259        assert!(failed.text.contains("error: could not compile"));
2260    }
2261
2262    #[test]
2263    fn chained_mypy_success_then_later_failure_uses_failure_preserving_output() {
2264        let output = "Success: no issues found in 1 source file\nError: node process exploded\n";
2265
2266        let failed = compress_with_registry_exit_code(
2267            "mypy src && node fail.js",
2268            output,
2269            Some(1),
2270            &empty_registry(),
2271        );
2272        assert_ne!(failed.text, "mypy: clean");
2273        assert!(failed.text.contains("Error: node process exploded"));
2274    }
2275
2276    #[test]
2277    fn toml_shortcircuit_is_skipped_for_nonzero_exit() {
2278        let registry = build_registry(
2279            &[(
2280                "wget",
2281                r#"[filter]
2282matches = ["wget"]
2283
2284[shortcircuit]
2285when = '(?s).*'
2286replacement = "wget: ok"
2287"#,
2288            )],
2289            None,
2290            None,
2291        );
2292        let output = "Connecting to example.invalid\nerror: connection refused\n";
2293
2294        let failed = compress_with_registry_exit_code(
2295            "wget https://example.invalid",
2296            output,
2297            Some(1),
2298            &registry,
2299        );
2300        assert_ne!(failed.text, "wget: ok");
2301        assert!(failed.text.contains("error: connection refused"));
2302    }
2303
2304    #[test]
2305    fn unknown_exit_code_keeps_byte_identical_legacy_compressor_output() {
2306        // Use a clean single command (no separator) so this tests the
2307        // unknown-exit-code path, not the separator-forces-generic path.
2308        let output = "Success: no issues found in 1 source file\n";
2309
2310        let legacy = compress_with_registry_exit_code("mypy src", output, None, &empty_registry());
2311        assert_eq!(legacy.text, "mypy: clean");
2312    }
2313
2314    #[test]
2315    fn killed_exit_sentinel_rejects_clean_legacy_summary() {
2316        let output = "Success: no issues found in 1 source file
2317Error: later chained command failed
2318";
2319
2320        let killed = compress_with_registry_exit_code(
2321            "mypy src && node fail.js",
2322            output,
2323            Some(137),
2324            &empty_registry(),
2325        );
2326        assert_ne!(killed.text, "mypy: clean");
2327        assert!(killed.text.contains("Error: later chained command failed"));
2328    }
2329
2330    #[test]
2331    fn nonzero_clean_eslint_json_summary_falls_back_to_raw_output() {
2332        let output =
2333            r#"[{"filePath":"/repo/src/main.ts","messages":[],"errorCount":0,"warningCount":0}]"#;
2334
2335        let failed = compress_with_registry_exit_code(
2336            "eslint -f json .",
2337            output,
2338            Some(1),
2339            &empty_registry(),
2340        );
2341
2342        assert_ne!(failed.text, "eslint: no issues");
2343        assert!(failed.text.contains(r#""messages":[]"#));
2344    }
2345
2346    #[test]
2347    fn nonzero_appends_distinct_missing_raw_failure_lines() {
2348        let raw = "Error: first failure
2349progress
2350Error: second failure
2351";
2352        let compressed = CompressionResult::new("Error: first failure");
2353
2354        let preserved = failure_preserving_result("tool", raw, compressed, Some(1));
2355
2356        assert!(preserved.text.contains("Error: first failure"));
2357        assert!(preserved.text.contains("Error: second failure"));
2358        assert!(preserved
2359            .text
2360            .contains("[raw failure lines preserved by AFT]"));
2361    }
2362
2363    #[test]
2364    fn preserved_failure_lines_go_before_the_commands_final_line() {
2365        let raw = "Error: first failure\nprogress\nError: second failure\nGATE RED: lint\n";
2366        let compressed = CompressionResult::new("Error: first failure\nGATE RED: lint");
2367
2368        let preserved = failure_preserving_result("tool", raw, compressed, Some(1));
2369
2370        assert_eq!(
2371            preserved.text,
2372            "Error: first failure\n[raw failure lines preserved by AFT]\nError: second failure\nGATE RED: lint"
2373        );
2374    }
2375
2376    #[test]
2377    fn nonzero_cargo_failure_detail_cap_keeps_all_names_without_generic_fallback() {
2378        let mut output = String::from(
2379            "running 40 tests
2380
2381failures:
2382
2383",
2384        );
2385        for index in 0..40 {
2386            output.push_str(&format!(
2387                "---- case_{index} stdout ----
2388thread 'case_{index}' panicked at src/lib.rs:{index}:1
2389
2390"
2391            ));
2392        }
2393        output.push_str(
2394            "failures:
2395",
2396        );
2397        for index in 0..40 {
2398            output.push_str(&format!(
2399                "    case_{index}
2400"
2401            ));
2402        }
2403        output.push_str(
2404            "
2405test result: FAILED. 0 passed; 40 failed; 0 ignored; 0 measured; 0 filtered out
2406",
2407        );
2408
2409        let failed =
2410            compress_with_registry_exit_code("cargo test", &output, Some(101), &empty_registry());
2411
2412        assert!(failed.text.contains("---- case_0 stdout ----"));
2413        assert!(!failed.text.contains("---- case_39 stdout ----"));
2414        assert!(failed.dropped_by_class.contains_key(&DropClass::Failure));
2415        for index in 0..40 {
2416            assert!(failed
2417                .text
2418                .lines()
2419                .any(|line| line == format!("    case_{index}")));
2420        }
2421    }
2422
2423    #[test]
2424    fn non_cargo_failure_omission_still_falls_back_to_generic() {
2425        let raw = "Error: first failure\nError: second failure\n";
2426        let compressed = CompressionResult::with_class_drops(
2427            "Error: first failure",
2428            [(DropClass::Failure, 1)].into_iter().collect(),
2429        );
2430        let result = failure_preserving_result("other-tool", raw, compressed, Some(1));
2431        let generic = GenericCompressor.compress_with_exit_code("other-tool", raw, Some(1));
2432        assert_eq!(result, generic);
2433        assert!(result.text.contains("Error: second failure"));
2434    }
2435
2436    #[test]
2437    fn cargo_summary_missing_name_or_result_still_falls_back_to_generic() {
2438        let raw = include_str!("../../../aft/tests/integration/fixtures/compress_filters/cargo-test/host-supervisor-two-failures.stdout");
2439        let compressed = CargoCompressor.compress_with_exit_code("cargo test", raw, Some(101));
2440        assert!(compressed.bounded_cargo_test_details);
2441        let generic = GenericCompressor.compress_with_exit_code("cargo test", raw, Some(101));
2442        for prefix in ["    holders::a_hosts_output", "test result:"] {
2443            let mut missing = compressed.clone();
2444            missing.text = missing
2445                .text
2446                .lines()
2447                .filter(|line| !line.starts_with(prefix))
2448                .collect::<Vec<_>>()
2449                .join("\n");
2450            let result = failure_preserving_result("cargo test", raw, missing, Some(101));
2451            assert_eq!(result, generic, "missing {prefix}");
2452        }
2453    }
2454
2455    #[test]
2456    fn toml_shortcircuit_is_skipped_for_unknown_exit_when_failure_signal_exists() {
2457        let registry = build_registry(
2458            &[(
2459                "make",
2460                r#"[filter]
2461matches = ["make"]
2462
2463[shortcircuit]
2464when = '(?s).*'
2465replacement = "make: ok"
2466"#,
2467            )],
2468            None,
2469            None,
2470        );
2471        let output = "build step
2472ERROR: compiler crashed
2473";
2474
2475        let failed = compress_with_registry_exit_code("make", output, None, &registry);
2476
2477        assert_ne!(failed.text, "make: ok");
2478        assert!(failed.text.contains("ERROR: compiler crashed"));
2479    }
2480
2481    // aft:expected-duplicate -- the frozen implementation is the independent differential oracle.
2482    fn frozen_contains_nonzero_failure_word(line: &str, word: &str) -> bool {
2483        let lower = line.to_ascii_lowercase();
2484        for (index, _) in lower.match_indices(word) {
2485            let end = index + word.len();
2486            let before_is_word = lower[..index].chars().next_back().is_some_and(is_word_char);
2487            let after_is_word = lower[end..].chars().next().is_some_and(is_word_char);
2488            if before_is_word || after_is_word {
2489                continue;
2490            }
2491
2492            let prefix = lower[..index].trim_end();
2493            let digits_start = prefix
2494                .char_indices()
2495                .rev()
2496                .take_while(|(_, ch)| ch.is_ascii_digit())
2497                .last()
2498                .map(|(idx, _)| idx);
2499            let Some(digits_start) = digits_start else {
2500                return true;
2501            };
2502            let digits = &prefix[digits_start..];
2503            if digits.parse::<usize>().ok() != Some(0) {
2504                return true;
2505            }
2506        }
2507        false
2508    }
2509
2510    fn frozen_line_has_failure_signal(line: &str) -> bool {
2511        let lower = line.to_ascii_lowercase();
2512        line.contains("error[")
2513            || lower.contains("error:")
2514            || line.contains("Error")
2515            || line.contains("ERROR")
2516            || lower.contains("internalerror")
2517            || lower.contains("traceback")
2518            || lower.contains("exception")
2519            || lower.contains("no module named")
2520            || lower.contains("undefined reference")
2521            || lower.contains("linker command failed")
2522            || lower.contains("undefined:")
2523            || lower.contains("expected declaration")
2524            || lower.contains("collect2: error")
2525            || lower.contains("ld: error")
2526            || lower.contains("fatal error")
2527            || line.contains("FAILED")
2528            || line.contains("FAIL")
2529            || frozen_contains_nonzero_failure_word(line, "fail")
2530            || frozen_contains_nonzero_failure_word(line, "failed")
2531            || frozen_contains_nonzero_failure_word(line, "failure")
2532            || frozen_contains_nonzero_failure_word(line, "failures")
2533            || lower.contains("panic")
2534            || lower.contains("cannot find")
2535            || lower.contains("not found")
2536            || lower.contains("no such")
2537    }
2538
2539    fn frozen_missing_failure_lines_reference(
2540        raw_output: &str,
2541        compressed_text: &str,
2542    ) -> Vec<String> {
2543        let compressed_lines: std::collections::BTreeSet<String> = compressed_text
2544            .lines()
2545            .map(str::trim)
2546            .filter(|line| !line.is_empty())
2547            .map(ToString::to_string)
2548            .collect();
2549        let mut seen = std::collections::BTreeSet::new();
2550        let mut missing = Vec::new();
2551
2552        for line in raw_output.lines() {
2553            let trimmed = line.trim();
2554            if trimmed.is_empty() || !frozen_line_has_failure_signal(trimmed) {
2555                continue;
2556            }
2557            if compressed_lines.contains(trimmed) || !seen.insert(trimmed.to_string()) {
2558                continue;
2559            }
2560            missing.push(trimmed.to_string());
2561        }
2562
2563        missing
2564    }
2565
2566    #[test]
2567    fn failure_line_index_is_byte_equivalent_to_frozen_reference() {
2568        let signals = [
2569            "Error: ordinary failure",
2570            "ERROR: uppercase failure",
2571            "error[E0432]: unresolved import",
2572            "eRrOr: mixed case",
2573            "0 fail",
2574            "00 failed",
2575            "1 failed",
2576            "0 failures",
2577            "01 failure",
2578            "2 failures",
2579            "failed_extra",
2580            "prefix_failure_suffix",
2581            "failures!",
2582            "thread panicked at src/lib.rs:1",
2583            "undefined reference to `main`",
2584            "例外ではない unicode status",
2585        ];
2586        for signal in signals {
2587            assert_eq!(
2588                line_has_failure_signal_lower(signal, &signal.to_ascii_lowercase()),
2589                frozen_line_has_failure_signal(signal),
2590                "classifier diverged for {signal:?}"
2591            );
2592        }
2593        for prefix in ["", "0 ", "00 ", "1 ", "01 ", "pre", "_", "2 errors and "] {
2594            for word in [
2595                "fail",
2596                "failed",
2597                "failure",
2598                "failures",
2599                "failing",
2600                "failuresx",
2601            ] {
2602                for suffix in ["", "!", "_tail", "x", " then continue"] {
2603                    let line = format!("{prefix}{word}{suffix}");
2604                    assert_eq!(
2605                        line_has_failure_signal_lower(&line, &line.to_ascii_lowercase()),
2606                        frozen_line_has_failure_signal(&line),
2607                        "classifier diverged for {line:?}"
2608                    );
2609                }
2610            }
2611        }
2612
2613        let mut raw = String::new();
2614        let mut compressed = String::new();
2615        for (index, signal) in signals.iter().enumerate() {
2616            raw.push_str("ordinary progress\n");
2617            raw.push_str("  ");
2618            raw.push_str(signal);
2619            raw.push_str("  \n");
2620            if index % 2 == 0 {
2621                compressed.push_str(signal);
2622                compressed.push('\n');
2623            }
2624            if index % 3 == 0 {
2625                raw.push_str(signal);
2626                raw.push('\n');
2627            }
2628        }
2629
2630        let expected = frozen_missing_failure_lines_reference(&raw, &compressed);
2631        let actual = missing_raw_failure_signal_lines(&raw, &compressed);
2632        assert_eq!(actual, expected);
2633
2634        let render_raw = "Error: first failure\nprogress\nError: second failure\n";
2635        let render_compressed = "Error: first failure";
2636        let render_missing = frozen_missing_failure_lines_reference(render_raw, render_compressed);
2637        let expected_text = format!(
2638            "{render_compressed}\n[raw failure lines preserved by AFT]\n{}",
2639            render_missing.join("\n")
2640        );
2641        let actual_result = failure_preserving_result(
2642            "cargo test",
2643            render_raw,
2644            CompressionResult::new(render_compressed),
2645            Some(101),
2646        );
2647        assert_eq!(actual_result.text.as_bytes(), expected_text.as_bytes());
2648    }
2649
2650    #[test]
2651    fn failure_line_index_allocations_do_not_scale_with_progress_lines() {
2652        use std::fmt::Write as _;
2653
2654        let mut output = String::new();
2655        for index in 0..5_000 {
2656            writeln!(
2657                output,
2658                "worker-{index:05}: processed /workspace/src/file-{index:05}.rs"
2659            )
2660            .expect("writing to String cannot fail");
2661        }
2662        output.push_str("ERROR: linker command failed for target app\n");
2663
2664        let (missing, allocations) =
2665            crate::test_allocations::count(|| missing_raw_failure_signal_lines(&output, &output));
2666
2667        assert!(missing.is_empty());
2668        assert!(
2669            allocations <= 8,
2670            "failure-line membership should borrow progress lines; got {allocations} allocations"
2671        );
2672    }
2673
2674    #[test]
2675    fn successful_exit_still_gets_concise_success_summary() {
2676        let output = r#"Running 4 tests using 2 workers
2677
2678  ✓  1 [chromium] › example.spec.ts:5:1 › has title (2.3s)
2679  ✓  2 [chromium] › example.spec.ts:9:1 › get started link (1.8s)
2680  ✓  3 [chromium] › nav.spec.ts:3:1 › navigates (1.2s)
2681  ✓  4 [chromium] › auth.spec.ts:7:1 › logs out (1.0s)
2682
2683  4 passed (6.3s)
2684"#;
2685
2686        let successful =
2687            compress_with_registry_exit_code("playwright test", output, Some(0), &empty_registry());
2688        assert_eq!(successful.text, "playwright: 4 tests passed (6.3s)");
2689    }
2690}
2691
2692#[cfg(test)]
2693mod normalize_command_tests {
2694    use super::*;
2695
2696    #[test]
2697    fn passes_bare_commands_unchanged() {
2698        assert_eq!(normalize_command_for_dispatch("bun test"), None);
2699        assert_eq!(normalize_command_for_dispatch("cargo build"), None);
2700        assert_eq!(normalize_command_for_dispatch("git status"), None);
2701    }
2702
2703    #[test]
2704    fn strips_cd_and_amp_prefix() {
2705        assert_eq!(
2706            normalize_command_for_dispatch("cd /repo && bun test").as_deref(),
2707            Some("bun test")
2708        );
2709        assert_eq!(
2710            normalize_command_for_dispatch("cd /repo/packages/aft && cargo test --release")
2711                .as_deref(),
2712            Some("cargo test --release")
2713        );
2714    }
2715
2716    #[test]
2717    fn strips_cd_and_semicolon_prefix() {
2718        assert_eq!(
2719            normalize_command_for_dispatch("cd /repo; bun test").as_deref(),
2720            Some("bun test")
2721        );
2722    }
2723
2724    #[test]
2725    fn strips_cd_with_quoted_path() {
2726        assert_eq!(
2727            normalize_command_for_dispatch("cd \"/path with space\" && npm install").as_deref(),
2728            Some("npm install")
2729        );
2730    }
2731
2732    #[test]
2733    fn strips_env_assignments() {
2734        assert_eq!(
2735            normalize_command_for_dispatch("env FOO=bar npm install").as_deref(),
2736            Some("npm install")
2737        );
2738        assert_eq!(
2739            normalize_command_for_dispatch("env FOO=bar BAZ=qux RUST_LOG=info cargo test")
2740                .as_deref(),
2741            Some("cargo test")
2742        );
2743    }
2744
2745    #[test]
2746    fn strips_bare_assignment_prefixes() {
2747        assert_eq!(
2748            normalize_command_for_dispatch("NODE_ENV=production npm install").as_deref(),
2749            Some("npm install")
2750        );
2751        assert_eq!(
2752            normalize_command_for_dispatch("FOO=1 BAR=2 cargo test").as_deref(),
2753            Some("cargo test")
2754        );
2755        assert_eq!(
2756            normalize_command_for_dispatch("RUSTFLAGS='-C debug' cargo build").as_deref(),
2757            Some("cargo build")
2758        );
2759    }
2760
2761    #[test]
2762    fn does_not_strip_later_assignment_arguments() {
2763        assert_eq!(normalize_command_for_dispatch("npm install foo=bar"), None);
2764    }
2765
2766    #[test]
2767    fn env_without_assignments_returns_none() {
2768        // `env` alone is the env-listing command, not a prefix.
2769        assert_eq!(
2770            normalize_command_for_dispatch("env npm install").as_deref(),
2771            None
2772        );
2773    }
2774
2775    #[test]
2776    fn strips_timeout_prefix() {
2777        assert_eq!(
2778            normalize_command_for_dispatch("timeout 30 cargo test").as_deref(),
2779            Some("cargo test")
2780        );
2781        assert_eq!(
2782            normalize_command_for_dispatch("timeout 5m bun test").as_deref(),
2783            Some("bun test")
2784        );
2785    }
2786
2787    #[test]
2788    fn strips_nohup_prefix() {
2789        assert_eq!(
2790            normalize_command_for_dispatch("nohup ./long-running-script.sh").as_deref(),
2791            Some("./long-running-script.sh")
2792        );
2793    }
2794
2795    #[test]
2796    fn strips_paren_then_cd_and_amp() {
2797        assert_eq!(
2798            normalize_command_for_dispatch("(cd /repo && bun test").as_deref(),
2799            Some("bun test")
2800        );
2801    }
2802
2803    #[test]
2804    fn chains_multiple_prefixes() {
2805        // env then timeout then real command.
2806        assert_eq!(
2807            normalize_command_for_dispatch("env FOO=bar timeout 30 cargo test").as_deref(),
2808            Some("cargo test")
2809        );
2810        // cd then env then real command.
2811        assert_eq!(
2812            normalize_command_for_dispatch("cd /repo && env FOO=bar npm install").as_deref(),
2813            Some("npm install")
2814        );
2815    }
2816
2817    // -------- end-to-end dispatch via normalize() --------
2818
2819    fn empty_registry() -> FilterRegistry {
2820        FilterRegistry::default()
2821    }
2822
2823    #[test]
2824    fn cd_prefix_bun_test_still_routes_to_bun_test() {
2825        let output = "bun test v1.3.14\n\nsrc/a.test.ts:\n(pass) ok [0.1ms]\n\n 1 pass\n 0 fail\n 1 expect() calls\nRan 1 tests across 1 files. [1.00ms]\n";
2826        let compressed = compress_with_registry("cd /repo && bun test", output, &empty_registry());
2827        // The bun test compressor produces (pass) / "1 pass" / "Ran ..." in
2828        // the pass-only path. Generic middle-truncate would drop these and
2829        // keep the original. Asserting their presence proves the normalizer
2830        // succeeded.
2831        assert!(compressed.contains("(pass)") || compressed.contains("1 pass"));
2832    }
2833
2834    #[test]
2835    fn cd_prefix_cargo_test_still_routes_to_cargo() {
2836        let output = "running 5 tests\ntest foo ... ok\ntest bar ... FAILED\n\nfailures:\n\ntest result: FAILED. 4 passed; 1 failed\n";
2837        let compressed =
2838            compress_with_registry("cd /repo && cargo test", output, &empty_registry());
2839        assert!(compressed.contains("FAILED") || compressed.contains("failed"));
2840    }
2841
2842    #[test]
2843    fn env_prefix_npm_install_still_routes_to_npm() {
2844        let output = "added 50 packages, and audited 100 packages in 3s\n";
2845        let compressed = compress_with_registry(
2846            "env NODE_ENV=production npm install",
2847            output,
2848            &empty_registry(),
2849        );
2850        // NpmCompressor's install path keeps "added N packages" / "audited" markers.
2851        assert!(compressed.contains("added") || compressed.contains("audited"));
2852    }
2853
2854    #[test]
2855    fn bare_assignment_prefix_npm_install_routes_to_npm() {
2856        let output = "npm http fetch GET 200 https://registry.npmjs.org/foo 123ms\nnpm WARN deprecated old-pkg@1.0.0: use new-pkg instead\n\nadded 42 packages in 2s\n\naudited 100 packages in 2s\n\nfound 0 vulnerabilities\n";
2857        let compressed =
2858            compress_with_registry("NODE_ENV=production npm install", output, &empty_registry());
2859        assert!(!compressed.contains("npm http fetch"));
2860        assert!(compressed.contains("audited 100 packages"));
2861    }
2862
2863    #[test]
2864    fn bare_assignment_prefix_cargo_test_routes_to_cargo() {
2865        let output = format!("running 1 test\ntest foo ... ok\n{}\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n", cargo_test_progress_padding());
2866        let compressed =
2867            compress_with_registry("FOO=1 BAR=2 cargo test", &output, &empty_registry());
2868        assert!(compressed.contains("running 1 test"));
2869        assert!(compressed.contains("test result: ok"));
2870        assert!(!compressed.contains("test foo ... ok"));
2871    }
2872
2873    #[test]
2874    fn quoted_assignment_prefix_cargo_build_routes_to_cargo() {
2875        let output = format!("{}   Compiling foo v0.1.0\nwarning: unused variable: `x`\n --> src/lib.rs:1:9\n  |\n1 |     let x = 1;\n  |         ^ help: if this is intentional, prefix it with an underscore: `_x`\n\n    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.12s\n", cargo_build_progress_padding());
2876        let compressed = compress_with_registry(
2877            "RUSTFLAGS='-C debug' cargo build",
2878            &output,
2879            &empty_registry(),
2880        );
2881        assert!(!compressed.contains("Compiling foo"));
2882        assert!(compressed.contains("warning: unused variable"));
2883        assert!(compressed.contains("Finished `dev` profile"));
2884    }
2885
2886    #[test]
2887    fn timeout_prefix_cargo_build_still_routes_to_cargo() {
2888        let output =
2889            "   Compiling foo v0.1.0\n    Finished `dev` profile [unoptimized] target(s) in 5s\n";
2890        let compressed =
2891            compress_with_registry("timeout 30 cargo build", output, &empty_registry());
2892        // CargoCompressor for build/check/run preserves the structure.
2893        assert!(compressed.contains("Compiling") || compressed.contains("Finished"));
2894    }
2895
2896    #[test]
2897    fn normalize_splits_pipe_and_takes_last_stage() {
2898        assert_eq!(
2899            normalize_command_for_dispatch("git log | grep fix").as_deref(),
2900            Some("grep fix")
2901        );
2902    }
2903
2904    #[test]
2905    fn normalize_cd_prefix_then_pipe_takes_last_stage() {
2906        assert_eq!(
2907            normalize_command_for_dispatch("cd /repo && git log | grep fix").as_deref(),
2908            Some("grep fix")
2909        );
2910    }
2911
2912    #[test]
2913    fn normalize_no_pipe_returns_none() {
2914        assert_eq!(normalize_command_for_dispatch("git log"), None);
2915    }
2916
2917    #[test]
2918    fn normalize_quoted_pipe_not_split() {
2919        assert_eq!(
2920            normalize_command_for_dispatch("grep \"a|b\" file.txt"),
2921            None
2922        );
2923    }
2924
2925    #[test]
2926    fn normalize_balanced_command_substitution_splits_top_level_pipe() {
2927        // The inner `|` is inside $(...) (depth > 0) and must be ignored; the
2928        // real top-level `| grep x` splits to the last stage. The OLD code
2929        // bailed to None here and fell back to head-token dispatch on the full
2930        // command — exactly the data-loss path issue #137 is about.
2931        assert_eq!(
2932            normalize_command_for_dispatch("echo $(cmd | cmd) | grep x").as_deref(),
2933            Some("grep x")
2934        );
2935    }
2936
2937    #[test]
2938    fn normalize_inner_pipe_in_substitution_without_top_level_pipe_is_none() {
2939        // No top-level pipe at all — the only `|` is inside $(...).
2940        assert_eq!(
2941            normalize_command_for_dispatch("echo $(cargo test | cat)"),
2942            None
2943        );
2944    }
2945
2946    #[test]
2947    fn normalize_double_pipe_not_split() {
2948        assert_eq!(normalize_command_for_dispatch("git log || echo fail"), None);
2949    }
2950
2951    #[test]
2952    fn normalize_multi_pipe_returns_last_stage() {
2953        assert_eq!(
2954            normalize_command_for_dispatch("git log | grep fix | head -5").as_deref(),
2955            Some("head -5")
2956        );
2957    }
2958
2959    #[test]
2960    fn normalize_process_substitution_splits_top_level_pipe() {
2961        // `<(...)` inner pipe ignored; top-level `| grep x` splits to last stage.
2962        assert_eq!(
2963            normalize_command_for_dispatch("cat <(echo a | cat) | grep x").as_deref(),
2964            Some("grep x")
2965        );
2966    }
2967
2968    #[test]
2969    fn normalize_pipe_ampersand_splits_last_stage() {
2970        // `|&` pipes stdout+stderr; it is a real pipe boundary, not `|` + `&`.
2971        assert_eq!(
2972            normalize_command_for_dispatch("cargo test |& grep FAIL").as_deref(),
2973            Some("grep FAIL")
2974        );
2975    }
2976
2977    #[test]
2978    fn piped_cargo_test_grep_preserves_failed() {
2979        let grep_output = "test foo ... FAILED\n";
2980        let compressed =
2981            compress_with_registry("cargo test | grep FAIL", grep_output, &empty_registry());
2982        assert!(
2983            compressed.text.contains("FAILED"),
2984            "grep-filtered FAILED must survive, got: {}",
2985            compressed.text
2986        );
2987    }
2988
2989    #[test]
2990    fn unsafe_piped_command_forces_generic_and_preserves_output() {
2991        // Unbalanced quote → the scanner can't trust the parse. A `|` is
2992        // present, so it must force generic rather than let CargoCompressor
2993        // claim `cargo test | …` and drop the single grep-filtered line.
2994        let grep_output = "test foo ... FAILED\n";
2995        let compressed =
2996            compress_with_registry("cargo test | grep \"FAIL", grep_output, &empty_registry());
2997        assert!(
2998            compressed.text.contains("FAILED"),
2999            "unsafe pipe must not drop output, got: {}",
3000            compressed.text
3001        );
3002    }
3003
3004    #[test]
3005    fn split_top_level_pipe_variants() {
3006        assert_eq!(split_top_level_pipe("git log"), PipeSplit::None);
3007        assert_eq!(
3008            split_top_level_pipe("git log | grep fix"),
3009            PipeSplit::LastStage("grep fix".to_string())
3010        );
3011        // `||` is logical-or, not a pipe — but it IS a top-level separator,
3012        // so the no-pipe exit forces generic (multiple commands' output).
3013        assert_eq!(split_top_level_pipe("a || b"), PipeSplit::Unsafe);
3014        // inner pipe inside a subshell is not a top-level boundary.
3015        assert_eq!(split_top_level_pipe("(a | b)"), PipeSplit::None);
3016        // inner pipe inside $() is not a top-level boundary.
3017        assert_eq!(split_top_level_pipe("echo $(a | b)"), PipeSplit::None);
3018        // unbalanced quote with a pipe present → unsafe.
3019        assert_eq!(split_top_level_pipe("a | grep \"x"), PipeSplit::Unsafe);
3020        // unbalanced paren with a pipe present → unsafe.
3021        assert_eq!(split_top_level_pipe("$(a | b | grep x"), PipeSplit::Unsafe);
3022        // FAIL-CLOSED cases (Oracle findings) — a pipe must never be last-staged
3023        // when other top-level structure could mean the captured output isn't
3024        // the last stage's:
3025        // trailing empty stage
3026        assert_eq!(split_top_level_pipe("cargo test |"), PipeSplit::Unsafe);
3027        assert_eq!(split_top_level_pipe("cargo test |&"), PipeSplit::Unsafe);
3028        // pipe coexisting with a top-level separator
3029        assert_eq!(
3030            split_top_level_pipe("true | cargo test --quiet ; printf X"),
3031            PipeSplit::Unsafe
3032        );
3033        assert_eq!(
3034            split_top_level_pipe("true | cargo test && echo done"),
3035            PipeSplit::Unsafe
3036        );
3037        // unmatched close paren with a pipe
3038        assert_eq!(
3039            split_top_level_pipe("echo ) | cargo test"),
3040            PipeSplit::Unsafe
3041        );
3042        // bare `&` background is a separator; `2>&1` / `&>` redirects are not
3043        assert_eq!(split_top_level_pipe("a | b & c"), PipeSplit::Unsafe);
3044        assert_eq!(
3045            split_top_level_pipe("cargo test 2>&1 | grep FAIL"),
3046            PipeSplit::LastStage("grep FAIL".to_string())
3047        );
3048        // No-pipe separator cases: a top-level separator without a pipe still
3049        // forces generic so a head-token compressor can't drop later commands'
3050        // output.
3051        assert_eq!(
3052            split_top_level_pipe("cargo test ; printf SENTINEL"),
3053            PipeSplit::Unsafe
3054        );
3055        assert_eq!(
3056            split_top_level_pipe("cargo test && echo done"),
3057            PipeSplit::Unsafe
3058        );
3059        assert_eq!(
3060            split_top_level_pipe("cargo test\necho done"),
3061            PipeSplit::Unsafe
3062        );
3063        // Redirects are NOT separators — a single command with a redirect must
3064        // still dispatch to its head-token compressor.
3065        assert_eq!(split_top_level_pipe("cargo test 2>&1"), PipeSplit::None);
3066        assert_eq!(
3067            split_top_level_pipe("cargo test &> /dev/null"),
3068            PipeSplit::None
3069        );
3070    }
3071
3072    #[test]
3073    fn strip_top_level_comment_removes_only_real_comments() {
3074        assert_eq!(
3075            strip_top_level_comment("printf keep # | cargo test"),
3076            "printf keep "
3077        );
3078        assert_eq!(
3079            strip_top_level_comment("printf keep # cargo test"),
3080            "printf keep "
3081        );
3082        // `#` not at a word boundary is literal (e.g. a fragment/anchor).
3083        assert_eq!(
3084            strip_top_level_comment("curl http://x/y#frag"),
3085            "curl http://x/y#frag"
3086        );
3087        // `#` inside quotes is literal.
3088        assert_eq!(
3089            strip_top_level_comment("grep \"# not a comment\" f"),
3090            "grep \"# not a comment\" f"
3091        );
3092        assert_eq!(
3093            strip_top_level_comment("echo '# literal'"),
3094            "echo '# literal'"
3095        );
3096        // no comment → unchanged.
3097        assert_eq!(
3098            strip_top_level_comment("git log | grep fix"),
3099            "git log | grep fix"
3100        );
3101    }
3102
3103    #[test]
3104    fn commented_command_does_not_misdispatch_and_preserves_output() {
3105        // The `# cargo test` comment must not let CargoCompressor claim this
3106        // printf command's output and drop it — with OR without a pipe.
3107        for cmd in ["printf keep # | cargo test", "printf keep # cargo test"] {
3108            let compressed = compress_with_registry(cmd, "keep\n", &empty_registry());
3109            assert!(
3110                compressed.text.contains("keep"),
3111                "comment must not drop output for {cmd:?}, got: {}",
3112                compressed.text
3113            );
3114        }
3115    }
3116
3117    #[test]
3118    fn pipe_with_trailing_command_chain_preserves_sentinel() {
3119        // `true | cargo test ; printf SENTINEL` — captured output includes
3120        // SENTINEL; cargo must not claim it and drop the sentinel line.
3121        let compressed = compress_with_registry(
3122            "true | cargo test --quiet ; printf SENTINEL",
3123            "SENTINEL\n",
3124            &empty_registry(),
3125        );
3126        assert!(
3127            compressed.text.contains("SENTINEL"),
3128            "trailing-chain output must survive, got: {}",
3129            compressed.text
3130        );
3131    }
3132
3133    /// MUTATION CONTROL: reverting the no-pipe exit in `split_top_level_pipe`
3134    /// to ignore `saw_top_separator` (returning `PipeSplit::None` unconditionally)
3135    /// makes this test fail — cargo.rs claims the list and drops the sentinel.
3136    #[test]
3137    fn separator_list_forces_generic_and_preserves_sentinel() {
3138        // `cargo test ; printf SENTINEL` — the captured transcript contains both
3139        // cargo noise and the sentinel. A head-token cargo compressor would keep
3140        // only cargo-shaped lines and silently delete the sentinel. The no-pipe
3141        // separator must force generic compression so all output survives.
3142        let cargo_noise =
3143            "running 1 test\ntest ok_test ... ok\n\ntest result: ok. 1 passed; 0 failed\n";
3144        let transcript = format!("{cargo_noise}SENTINEL\n");
3145        let compressed = compress_with_registry(
3146            "cargo test ; printf SENTINEL",
3147            &transcript,
3148            &empty_registry(),
3149        );
3150        assert!(
3151            compressed.text.contains("SENTINEL"),
3152            "separator-list output must survive generic compression, got: {}",
3153            compressed.text
3154        );
3155    }
3156
3157    #[test]
3158    fn cd_prefix_peel_leaves_no_residual_separator_for_cargo() {
3159        // `cd /x && cargo test` — the `cd /x &&` prefix is peeled, leaving a
3160        // clean `cargo test` with NO residual separator. Specialized cargo
3161        // compression must still engage (not force-generic).
3162        let output = format!(
3163            "running 1 test\ntest ok_test ... ok\n{}\ntest result: ok. 1 passed; 0 failed\n",
3164            cargo_test_progress_padding()
3165        );
3166        let compressed = compress_with_registry("cd /x && cargo test", &output, &empty_registry());
3167        // Cargo compressor drops individual "test ... ok" lines in its summary.
3168        assert!(
3169            !compressed.text.contains("test ok_test ... ok"),
3170            "cd-peeled cargo test must still use the cargo compressor, got: {}",
3171            compressed.text
3172        );
3173        assert!(compressed.text.contains("test result: ok"));
3174    }
3175
3176    #[test]
3177    fn clean_single_cargo_test_dispatch_byte_identical() {
3178        // Control: a clean single `cargo test` (no separator, no pipe) must
3179        // continue dispatching to the specialized cargo compressor and produce
3180        // the same output as the original specialized-compression behavior.
3181        let output = format!(
3182            "running 1 test\ntest ok_test ... ok\n{}\ntest result: ok. 1 passed; 0 failed\n",
3183            cargo_test_progress_padding()
3184        );
3185        let compressed = compress_with_registry("cargo test", &output, &empty_registry());
3186        assert!(compressed.text.contains("running 1 test"));
3187        assert!(compressed.text.contains("test result: ok"));
3188        assert!(
3189            !compressed.text.contains("test ok_test ... ok"),
3190            "clean cargo test must keep using the cargo compressor, got: {}",
3191            compressed.text
3192        );
3193    }
3194
3195    #[test]
3196    fn is_shell_boundary_covers_redirects_and_operators() {
3197        for tok in [
3198            "|",
3199            "|&",
3200            ";",
3201            "&",
3202            "&&",
3203            "||",
3204            ">",
3205            ">>",
3206            "<",
3207            "<<",
3208            "<<<",
3209            "&>",
3210            "&>>",
3211            "2>",
3212            "2>>",
3213            "2>&1",
3214            "1>&2",
3215            ">/dev/null",
3216            "2>/dev/null",
3217        ] {
3218            assert!(is_shell_boundary(tok), "{tok} should be a boundary");
3219        }
3220        for tok in ["test", "log", "build", "--release", "-v", "file.txt"] {
3221            assert!(!is_shell_boundary(tok), "{tok} must not be a boundary");
3222        }
3223    }
3224}
3225
3226#[cfg(test)]
3227mod approved_audit11 {
3228    use super::*;
3229
3230    #[test]
3231    fn compound_commands_use_generic_instead_of_runner_rules() {
3232        let output = "   Compiling example v0.1.0\n    Finished `dev` profile target(s)\npackage installation detail\nsecond command detail\n";
3233        let expected = GenericCompressor::compress_stripped_output(output);
3234        let registry = FilterRegistry::default();
3235        for command in [
3236            "cd project && cargo build && printf done",
3237            "cargo build; printf done",
3238            "cargo build || printf failed",
3239            "cargo build\nprintf done",
3240            "(cd project; cargo build && printf done)",
3241            "cargo build & printf done",
3242            "cargo build; { printf a; printf b; }",
3243        ] {
3244            assert!(
3245                matches!(
3246                    resolve_dispatch_target(command),
3247                    DispatchTarget::ForceGeneric
3248                ),
3249                "compound dispatch must remain generic: {command}"
3250            );
3251            let result = compress_with_registry_exit_code(command, output, Some(0), &registry);
3252            assert_eq!(result.text, expected, "{command}");
3253        }
3254        for command in [
3255            "cd 'a&&b' && cargo build",
3256            "cargo build --message 'a;b'",
3257            "cargo build --message \"a&&b\"",
3258            "cargo build --message a\\;b",
3259            "cargo build 2>&1",
3260            "cargo build > output &> errors",
3261            "cargo build --message $(printf 'a;b')",
3262        ] {
3263            assert!(
3264                matches!(resolve_dispatch_target(command), DispatchTarget::Command(_)),
3265                "{command}"
3266            );
3267        }
3268    }
3269}