trusty-agents-common 0.11.2

Stable agent-plugin surface (ToolExecutor, AgentPlugin, ToolResult) shared by trusty-assistants and external agent crates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Per-tool output compression filters.
//!
//! Why: Verbose tool outputs (cargo test, git diff, git log, file reads) waste
//! tokens when re-injected into LLM conversation history. Stripping noise
//! preserves signal while shrinking context.
//! What: `compress_tool_output(name, output)` dispatches to a filter based on
//! the tool name, returning a possibly-shorter string. Each filter is a pure
//! `fn` for unit testability. `classify_tool` names that routing decision and
//! `has_filter_for` exposes it as a predicate, so a caller upstream of the
//! dispatch can tell whether a tool name reaches a filter at all (#6566).
//!
//! Module layout (see #366 split):
//! - `mod.rs` — classification, dispatch, and the native per-tool filters
//! - `structured.rs` — JSON/YAML/TOML/CSV passthrough detection
//! - `source_read.rs` — read-verb-on-a-source-file passthrough detection (#6986)
//! - `strategy.rs` — generic `FilterLevel`/`Language`/`FilterStrategy`
//! - `rtk.rs` — RTK subprocess delegation + async wrapper, plus
//!   `CompressionPath` (issue #1956 stats-logging signal)
//! - `tests.rs` — unit tests
//!
//! Hoisted from `trusty-agents::compress::tool_output` into
//! `trusty-agents-common` in issue #1959 so `trusty-mpm` can reach
//! `compress_tool_output_async` without a full `trusty-agents` path
//! dependency; `trusty-agents` re-exports this module's public surface from
//! `trusty_agents::compress` for source-level compatibility.
//!
//! Test: See `tests` — covers each filter and the dispatch table.

mod rtk;
mod source_read;
mod strategy;
mod structured;

#[cfg(test)]
mod tests;

// Re-export the full public surface so callers can keep using
// `compress::tool_output::{...}` (and `compress::{compress_tool_output, ...}`).
pub use rtk::{
    CompressionPath, ENV_COMPRESS_NO_RTK, RtkResolver, compress_tool_output_async,
    compress_tool_output_async_with_path, compress_tool_output_async_with_path_using,
    compress_via_rtk, compress_via_rtk_with, default_rtk_resolver, no_rtk,
};
pub use source_read::is_source_file_read;
pub use strategy::{
    AggressiveFilter, FilterLevel, FilterStrategy, Language, MinimalFilter, NoFilter, get_filter,
};
pub use structured::is_structured_format;

/// Minimum byte length below which compression is skipped.
///
/// Why: Tiny outputs (status codes, short results) are already cheaper than
/// the cognitive cost of compression artifacts. RTK uses 80 bytes.
const SIZE_GATE_BYTES: usize = 80;

/// Line count above which `git log` output is worth filtering.
const GIT_LOG_LINE_GATE: usize = 30;
/// Line count above which a file read is worth filtering.
const FILE_READ_LINE_GATE: usize = 200;

/// Which native filter [`compress_tool_output`] applies to a given tool name.
///
/// Why: #6566 — callers upstream of the dispatch (the `tm hook` `PreToolUse`
/// Bash rewrite in `trusty-mpm`) need to know whether a tool name reaches a
/// filter at all, so they can skip wrapping a command whose output nothing
/// here would shrink. Naming the routing decision as a value lets
/// [`classify_tool`] answer that question and lets the dispatch match on it
/// exhaustively, so a new filter cannot appear in one without the other.
/// What: One variant per filter branch. `Grep` covers `grep`/`rg`/`find`;
/// `Ls` covers `ls`. Both delegate to the same line-list cap but stay
/// separate so each keeps its own named filter entry point.
/// Test: `classify_tool_*` and `has_filter_for_*` in `tests`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToolFilter {
    /// `cargo test` and other test runners — [`filter_test_runner`].
    TestRunner,
    /// `cargo check` / `cargo clippy` — [`filter_cargo_check`].
    CargoCheck,
    /// Unified diffs — [`filter_git_diff`].
    GitDiff,
    /// `git log` — [`filter_git_log`], above [`GIT_LOG_LINE_GATE`] lines.
    GitLog,
    /// File reads — [`filter_file_read`], above [`FILE_READ_LINE_GATE`] lines.
    FileRead,
    /// `grep`/`rg`/`find` match lists — [`filter_grep_output`].
    Grep,
    /// `ls` directory listings — [`filter_ls_output`].
    Ls,
}

/// Route a tool name to the filter [`compress_tool_output`] would apply.
///
/// Why: The single source of truth for "which filter, if any, covers this
/// tool name". [`compress_tool_output`] dispatches on its result and
/// [`has_filter_for`] tests it, so the coverage question has exactly one
/// answer (#6566, and the common-entry-point rule).
/// What: [`is_source_file_read`] runs FIRST and short-circuits to `None`
/// (#6986 — see below). After it, substring match against the lowercased
/// name, in the order the dispatch has always used — the `test`/`cargo`
/// family first (with `check`/`clippy` inside it taking the cargo-check
/// filter), then `diff`, `log`, `read`/`cat`. `grep`/`rg`/`find`/`ls` match
/// on the FIRST whitespace token rather than a substring, because `rg` is a
/// substring of unrelated names this sees (`cargo`, `git merge`) that must
/// not misfire (#1957). `None` means no filter covers the name.
///
/// 🔴 The substring branches match the PATH as well as the program, because
/// `tm hook`'s rewrite passes the command's first two tokens as the tool
/// name. `cat crates/x/src/tests.rs` therefore hit the `test` branch and
/// `filter_test_runner` returned an empty string — the whole file, gone
/// (#6986). Ordering the source-read check ahead of them is what keeps a
/// file's own path from choosing the filter that destroys it.
/// Test: `classify_tool_routes_known_tool_families`,
/// `classify_tool_returns_none_for_uncovered_tools`,
/// `classify_tool_passes_through_source_reads`.
pub fn classify_tool(tool_name: &str) -> Option<ToolFilter> {
    // #6986: a read verb on a source file is an agent reading code, not gate
    // output — no filter here can shorten it without damaging it.
    if is_source_file_read(tool_name) {
        return None;
    }
    let n = tool_name.to_ascii_lowercase();
    if n.contains("test") || n.contains("cargo") {
        // Note: "cargo check"/"cargo clippy" go to the cargo_check filter
        // which strips Compiling/Finished lines; "cargo test" goes here.
        if n.contains("check") || n.contains("clippy") {
            return Some(ToolFilter::CargoCheck);
        }
        return Some(ToolFilter::TestRunner);
    }
    if n.contains("diff") {
        return Some(ToolFilter::GitDiff);
    }
    if n.contains("log") {
        return Some(ToolFilter::GitLog);
    }
    if n.contains("read") || n.contains("cat") {
        return Some(ToolFilter::FileRead);
    }
    // #1957: grep/rg/find emit a flat match-or-path list; ls emits a flat
    // directory listing. Matched on the first whitespace token (not
    // `.contains()`, unlike the branches above) — see this function's doc.
    let first_word = n.split_whitespace().next().unwrap_or("");
    if first_word == "grep" || first_word == "rg" || first_word == "find" {
        return Some(ToolFilter::Grep);
    }
    if first_word == "ls" {
        return Some(ToolFilter::Ls);
    }
    if n.contains("check") || n.contains("clippy") {
        return Some(ToolFilter::CargoCheck);
    }
    None
}

/// Whether any native filter covers `tool_name`.
///
/// Why: #6566 — `tm hook`'s `PreToolUse` rewrite appended
/// `| tm compress --tool "<name>"` to every eligible Bash command, but only
/// the handful of names [`classify_tool`] recognises reach a filter. Measured
/// over 48h of `~/.trusty-mpm/compression.jsonl`, 3,415 of 3,643 wrapped
/// invocations (93.7%) returned their input byte-for-byte: each one paid a
/// process spawn to change nothing. This predicate lets the rewrite decide
/// before it wraps.
/// What: `true` exactly when [`classify_tool`] returns a variant. It answers
/// the NAME question only — the size gate ([`SIZE_GATE_BYTES`]), the
/// structured-format passthrough, and the per-filter line gates all depend on
/// the output, which a pre-execution caller cannot see, so a `true` here
/// promises a filter branch is reached, not that bytes will drop.
/// Note the RTK path is out of scope: `compress_tool_output_async` prefers
/// the external `rtk` binary when installed, which can shrink names this
/// returns `false` for. A hook gating on this under-wraps in that setup,
/// which is the safe direction — see #6566.
/// Test: `has_filter_for_true_for_covered_tools`,
/// `has_filter_for_false_for_uncovered_tools`,
/// `has_filter_for_agrees_with_classify_tool`.
pub fn has_filter_for(tool_name: &str) -> bool {
    classify_tool(tool_name).is_some()
}

/// Compress a tool's textual output based on its name.
///
/// Why: Centralizes the per-tool filter dispatch so callers don't have to
/// know which filter applies to which tool.
/// What: Applies a size gate and a structured-format passthrough, then routes
/// on [`classify_tool`]. The match is exhaustive over [`ToolFilter`] with no
/// catch-all arm, so adding a filter variant fails to compile until this
/// dispatch handles it — that is what keeps [`has_filter_for`] from drifting
/// away from what the dispatch actually filters (#6566). Unknown tools pass
/// through unchanged. Always infallible.
///
/// A filter that consumed every byte returns the ORIGINAL instead (#6986):
/// emitting nothing loses the caller's output with no way to tell that from
/// a command that genuinely printed nothing. This is a backstop, not the
/// fix — [`classify_tool`] keeps source reads away from the filters in the
/// first place.
/// Test: `compress_tool_output_dispatch_test` plus per-filter tests;
/// `dispatch_never_returns_empty_for_non_empty_input`.
pub fn compress_tool_output(tool_name: &str, output: &str) -> String {
    // Size gate: very small outputs aren't worth touching.
    if output.len() < SIZE_GATE_BYTES {
        return output.to_string();
    }
    // Structured formats (JSON/YAML/TOML/CSV) must pass through unchanged so
    // we don't corrupt machine-parseable payloads.
    if is_structured_format(output) {
        return output.to_string();
    }
    let compressed = match classify_tool(tool_name) {
        None => output.to_string(),
        Some(ToolFilter::TestRunner) => filter_test_runner(output),
        Some(ToolFilter::CargoCheck) => filter_cargo_check(output),
        Some(ToolFilter::GitDiff) => filter_git_diff(output),
        Some(ToolFilter::GitLog) => {
            if output.lines().count() > GIT_LOG_LINE_GATE {
                filter_git_log(output)
            } else {
                output.to_string()
            }
        }
        Some(ToolFilter::FileRead) => {
            if output.lines().count() > FILE_READ_LINE_GATE {
                filter_file_read(output)
            } else {
                output.to_string()
            }
        }
        Some(ToolFilter::Grep) => filter_grep_output(output),
        Some(ToolFilter::Ls) => filter_ls_output(output),
    };
    // #6986: a filter that emptied a non-empty input destroyed the caller's
    // output rather than shortening it. Hand back the original.
    if compressed.trim().is_empty() && !output.trim().is_empty() {
        return output.to_string();
    }
    compressed
}

/// Drop a test runner's passing-test lines and keep everything else.
///
/// Why: Hundreds of `test foo ... ok` lines drown out the few failures the
/// model needs to see. Until #7544 this was an ALLOWLIST — a line survived
/// only by containing `FAILED`/`error`/`warning` or starting `---- ` /
/// `failures:` — so the panic location, the `left:`/`right:` assertion values
/// and every multiline context line were discarded as noise, and only the LAST
/// `test result:` line was kept. A failing suite followed by a passing one
/// therefore compressed to output ending `test result: ok`, which reads as a
/// green run.
/// What: A blocklist. Every line is emitted in its original position except a
/// passing or ignored per-test line ([`is_passing_test_line`]) and cargo's
/// indented build-progress chatter ([`is_cargo_progress_line`]); runs of blank
/// lines collapse to one and leading/trailing blanks are dropped. Every
/// `test result:` summary survives in order, next to the diagnostics that
/// explain it, and a shape this function does not recognise is kept rather
/// than discarded.
/// Test: `test_runner_keeps_every_suite_summary_in_order`,
/// `test_runner_keeps_panic_location_and_assertion_values`,
/// `test_runner_keeps_the_failing_test_name_list`,
/// `test_runner_keeps_unrecognised_blocks`,
/// `test_runner_drops_cargo_progress_lines`,
/// `test_runner_still_reduces_passing_only_output`,
/// `test_runner_strips_passing_tests`, `test_runner_keeps_summary_line`,
/// `test_runner_no_failures_returns_summary_only`.
pub fn filter_test_runner(output: &str) -> String {
    let mut kept: Vec<&str> = Vec::new();
    // #7544: a blank line is held back rather than emitted, so a run collapses
    // to one and a trailing run is dropped without a second pass.
    let mut pending_blank: Option<&str> = None;
    for line in output.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            if !kept.is_empty() {
                pending_blank = Some(line);
            }
            continue;
        }
        // #7544: the only two droppable shapes. Everything else — panics,
        // assertion values, every `test result:` summary, output from a
        // harness this has never seen — is kept where it stands.
        if is_passing_test_line(trimmed) || is_cargo_progress_line(line, trimmed) {
            continue;
        }
        if let Some(blank) = pending_blank.take() {
            kept.push(blank);
        }
        kept.push(line);
    }
    kept.join("\n")
}

fn is_passing_test_line(s: &str) -> bool {
    // Match `test <something> ... ok` (cargo's per-test line)
    if !s.starts_with("test ") {
        return false;
    }
    s.ends_with(" ... ok") || s.ends_with(" ... ignored")
}

/// Whether `raw` is one of cargo's build-progress lines.
///
/// Why: #7544 made the filter keep every unrecognised line, so the only lines
/// it may still drop are ones whose shape is known to carry no test signal.
/// Cargo's progress chatter is that shape; `Running`, which names the suite
/// each `test result:` line belongs to, deliberately is not.
/// What: true when `raw` is indented — cargo right-aligns these verbs into a
/// 12-column gutter — and `trimmed` starts with one of them. A line at column
/// 0 is a test's own stdout and is kept whatever it says. `Blocking` is absent
/// on purpose: a build waiting on a lock is worth seeing.
/// Test: `test_runner_drops_cargo_progress_lines`,
/// `test_runner_keeps_column_zero_lines_that_look_like_progress`.
fn is_cargo_progress_line(raw: &str, trimmed: &str) -> bool {
    if !raw.starts_with(' ') {
        return false;
    }
    const VERBS: [&str; 7] = [
        "Compiling ",
        "Finished ",
        "Updating ",
        "Downloading ",
        "Downloaded ",
        "Fresh ",
        "Locking ",
    ];
    VERBS.iter().any(|verb| trimmed.starts_with(verb))
}

/// Collapse runs of context lines in a unified diff.
///
/// Why: Diff context (lines starting with a space) is rarely needed by the
/// model; the +/- lines carry the real signal.
/// What: Replaces every run of context lines with a single
/// `@@ ... @@ [+N added, -N removed]` summary header reflecting counts of
/// the surrounding hunk. Preserves `---`, `+++`, `@@`, `+`, `-` lines.
/// Test: `filter_git_diff_strips_context_lines`,
/// `filter_git_diff_preserves_adds_and_removes`,
/// `filter_git_diff_passthrough_no_context`.
pub fn filter_git_diff(output: &str) -> String {
    // First pass: count adds/removes per hunk so we can annotate replacement headers.
    let lines: Vec<&str> = output.lines().collect();
    let mut hunk_stats: Vec<(usize, usize)> = Vec::new(); // (added, removed) per hunk
    let mut cur_add = 0usize;
    let mut cur_rem = 0usize;
    let mut in_hunk = false;
    for line in &lines {
        if line.starts_with("@@") {
            if in_hunk {
                hunk_stats.push((cur_add, cur_rem));
            }
            cur_add = 0;
            cur_rem = 0;
            in_hunk = true;
            continue;
        }
        if !in_hunk {
            continue;
        }
        if line.starts_with("+++") || line.starts_with("---") {
            continue;
        }
        if line.starts_with('+') {
            cur_add += 1;
        } else if line.starts_with('-') {
            cur_rem += 1;
        }
    }
    if in_hunk {
        hunk_stats.push((cur_add, cur_rem));
    }

    // Second pass: emit, collapsing context runs.
    let mut out: Vec<String> = Vec::new();
    let hunk_idx: usize = 0;
    let mut in_context_run = false;
    let mut had_any_context = false;
    for line in &lines {
        if line.starts_with("@@") || line.starts_with("---") || line.starts_with("+++") {
            in_context_run = false;
            out.push((*line).to_string());
            continue;
        }
        if line.starts_with('+') || line.starts_with('-') {
            in_context_run = false;
            out.push((*line).to_string());
            continue;
        }
        // Treat any other line (including " ..." context, blank) as context.
        had_any_context = true;
        if !in_context_run {
            in_context_run = true;
            // Emit a collapsed-context marker referencing the current hunk's totals.
            let (a, r) = hunk_stats
                .get(hunk_idx.saturating_sub(0))
                .copied()
                .unwrap_or((0, 0));
            // Hunk index advances when we encounter an `@@` header; for context
            // lines belonging to the current hunk we reuse the current totals.
            let _ = hunk_idx; // explicit no-op to avoid unused warnings if logic shifts.
            out.push(format!("@@ ... @@ [+{a} added, -{r} removed]"));
        }
        // Drop the context line itself.
        let _ = line;
    }

    if !had_any_context {
        // Passthrough: nothing to compress.
        return output.to_string();
    }
    out.join("\n")
}

/// Strip author/date/body lines from `git log` output, keeping commit headers.
///
/// Why: Long logs are mostly metadata; the SHA + subject is enough for
/// most LLM reasoning.
/// What: Keeps lines matching `commit <7+ hex chars>` (and the very next
/// non-blank non-metadata line as the subject). Drops Author:, Date:,
/// Merge:, and indented body lines.
/// Test: `filter_git_log_strips_author_date`, `filter_git_log_passthrough_short`.
pub fn filter_git_log(output: &str) -> String {
    let mut out: Vec<String> = Vec::new();
    let mut expect_subject = false;
    for line in output.lines() {
        if is_commit_header(line) {
            out.push(line.to_string());
            expect_subject = true;
            continue;
        }
        if expect_subject {
            // Subject is the first indented non-metadata line after author/date.
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            if trimmed.starts_with("Author:")
                || trimmed.starts_with("Date:")
                || trimmed.starts_with("Merge:")
                || trimmed.starts_with("commit ")
            {
                continue;
            }
            // First real content line — treat as subject.
            out.push(line.to_string());
            expect_subject = false;
        }
    }
    out.join("\n")
}

fn is_commit_header(line: &str) -> bool {
    // `commit <hash>` where hash is 7+ hex chars.
    let stripped = match line.strip_prefix("commit ") {
        Some(s) => s.trim(),
        None => return false,
    };
    let hex_len = stripped
        .chars()
        .take_while(|c| c.is_ascii_hexdigit())
        .count();
    hex_len >= 7
}

/// Strip blank and comment-only lines from large file reads.
///
/// Why: When the model loads a 500-line file, blanks and bare comments are
/// often non-essential.
/// What: Drops lines that are blank, or trim-start with `//` or `#`. If the
/// result is < 20 lines (over-filtered, perhaps an all-comment file), returns
/// the original to avoid hiding too much.
/// Test: `filter_file_read_strips_blank_comment_lines`,
/// `filter_file_read_no_over_filter`.
pub fn filter_file_read(output: &str) -> String {
    let kept: Vec<&str> = output
        .lines()
        .filter(|line| {
            let t = line.trim_start();
            if t.is_empty() {
                return false;
            }
            if t.starts_with("//") {
                return false;
            }
            if t.starts_with('#') {
                return false;
            }
            true
        })
        .collect();
    if kept.len() < 20 {
        return output.to_string();
    }
    kept.join("\n")
}

/// Strip `Compiling` and `Finished` chatter from `cargo check`/`cargo clippy`.
///
/// Why: These lines are progress noise; warnings/errors are the signal.
/// What: Drops lines beginning with `   Compiling ` or `    Finished `.
/// Keeps everything else verbatim.
/// Test: `filter_cargo_check_strips_compiling`, `filter_cargo_check_keeps_warnings`.
pub fn filter_cargo_check(output: &str) -> String {
    output
        .lines()
        .filter(|line| !line.starts_with("   Compiling ") && !line.starts_with("    Finished "))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Line count above which [`cap_line_list`] head/tail-caps its input.
const LINE_LIST_CAP: usize = 60;
/// Leading lines kept when [`cap_line_list`] triggers.
const LINE_LIST_HEAD: usize = 25;
/// Trailing lines kept when [`cap_line_list`] triggers.
const LINE_LIST_TAIL: usize = 10;

/// Head/tail-cap a flat, one-entry-per-line output, announcing the drop.
///
/// Why: `grep`/`rg`/`find`/`ls` output has no natural summary line the way
/// `cargo test`'s `test result:` or a diff's hunk header does, so there is
/// nothing to fall back to — the cap must state what it removed rather than
/// dropping it silently (compression that silently drops content is this
/// project's recurring defect; see #1957's PR discussion).
/// What: Passes output through unchanged at or under `LINE_LIST_CAP` lines.
/// Above that, keeps the first `LINE_LIST_HEAD` lines, inserts a
/// `... N lines omitted ...` marker giving the exact count of dropped
/// lines, then the last `LINE_LIST_TAIL` lines.
/// Test: `filter_grep_output_caps_long_match_list`,
/// `filter_ls_output_caps_long_listing`.
fn cap_line_list(output: &str) -> String {
    let lines: Vec<&str> = output.lines().collect();
    if lines.len() <= LINE_LIST_CAP {
        return output.to_string();
    }
    let omitted = lines.len() - LINE_LIST_HEAD - LINE_LIST_TAIL;
    let mut out: Vec<String> = Vec::with_capacity(LINE_LIST_HEAD + LINE_LIST_TAIL + 1);
    out.extend(lines[..LINE_LIST_HEAD].iter().map(|s| (*s).to_string()));
    out.push(format!("... {omitted} lines omitted ..."));
    out.extend(
        lines[lines.len() - LINE_LIST_TAIL..]
            .iter()
            .map(|s| (*s).to_string()),
    );
    out.join("\n")
}

/// Cap long `grep`/`rg`/`find` match-or-path lists.
///
/// Why: These tools emit one match/path per line with no built-in summary —
/// the #1953 spike found grep output passed through `compress_tool_output`
/// with 0% reduction because no filter branch existed for it (#1957).
/// What: Delegates to [`cap_line_list`] — passthrough at/under
/// `LINE_LIST_CAP` lines, head/tail-capped with an explicit omission count
/// above it.
/// Test: `filter_grep_output_caps_long_match_list`,
/// `filter_grep_output_passthrough_short`.
pub fn filter_grep_output(output: &str) -> String {
    cap_line_list(output)
}

/// Cap long `ls` directory listings.
///
/// Why: Same coverage gap as [`filter_grep_output`] for `ls -la` output —
/// the #1953 spike measured 0% reduction because no filter branch existed
/// for it (#1957).
/// What: Delegates to [`cap_line_list`].
/// Test: `filter_ls_output_caps_long_listing`, `filter_ls_output_passthrough_short`.
pub fn filter_ls_output(output: &str) -> String {
    cap_line_list(output)
}