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.
// Re-export the full public surface so callers can keep using
// `compress::tool_output::{...}` (and `compress::{compress_tool_output, ...}`).
pub use ;
pub use is_source_file_read;
pub use ;
pub use 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.
/// 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`.