返回 CodeWhale
shell_output.rs
根目录 / crates / engine / src / tools / shell_output.rs
1 //! Output truncation and summarization helpers for shell tools.
2
3 /// Maximum output size before truncation (30KB like Claude Code).
4 const MAX_OUTPUT_SIZE: usize = 30_000;
5 /// Head bytes preserved for large shell/test output. Qwen-style: head is
6 /// `threshold / 5` so the bulk of the budget stays on the tail (compiler
7 /// summaries, test failures) without a second command.
8 const TRUNCATED_HEAD_BYTES: usize = MAX_OUTPUT_SIZE / 5;
9 const TRUNCATED_TAIL_BYTES: usize = MAX_OUTPUT_SIZE - TRUNCATED_HEAD_BYTES;
10 /// Limits for summary strings in tool metadata.
11 const SUMMARY_MAX_LINES: usize = 3;
12 const SUMMARY_MAX_CHARS: usize = 240;
13 /// Maximum number of preserved high-signal lines extracted from the tail
14 /// when output is truncated (#242).
15 const MAX_PRESERVED_SUMMARY_LINES: usize = 80;
16 /// Byte ceiling for the whole preserved-summary block, and the character
17 /// ceiling applied to each line before it is admitted.
18 ///
19 /// The line count alone does not bound the block: a single rustc `error:` or
20 /// `note:` line carrying a long inferred type, a minified bundler frame, or a
21 /// `--verbose` link command is routinely hundreds of kilobytes, and eighty of
22 /// them are unbounded in every way that matters to a context budget. These two
23 /// limits are what make the block small next to [`MAX_OUTPUT_SIZE`].
24 const MAX_PRESERVED_SUMMARY_BYTES: usize = 4 * 1024;
25 const MAX_PRESERVED_SUMMARY_LINE_CHARS: usize = 400;
26
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 enum OutputPhase {
29 Compiling,
30 BuildFinished,
31 Running,
32 Unknown,
33 }
34
35 fn cargo_status_word(line: &str) -> Option<&str> {
36 let rest = line.strip_prefix(' ')?;
37 let indent = line.len() - line.trim_start().len();
38 if indent < 2 {
39 return None;
40 }
41 let trimmed = rest.trim_start();
42 let word_end = trimmed.find(' ')?;
43 let word = &trimmed[..word_end];
44 let tail = trimmed[word_end..].trim_start();
45 if tail.is_empty() {
46 return None;
47 }
48 Some(word)
49 }
50
51 fn output_phase(text: &str) -> OutputPhase {
52 for line in text.lines().rev().take(200) {
53 let trimmed = line.trim_start();
54 if trimmed.starts_with("test result:")
55 || trimmed.starts_with("Doc-tests ")
56 || (trimmed.starts_with("running ")
57 && (trimmed.ends_with(" tests") || trimmed.ends_with(" test")))
58 {
59 return OutputPhase::Running;
60 }
61 match cargo_status_word(line) {
62 Some("Running") if trimmed.contains("target/") || trimmed.contains("(target") => {
63 return OutputPhase::Running;
64 }
65 Some("Finished") => return OutputPhase::BuildFinished,
66 Some("Compiling" | "Checking" | "Downloading" | "Downloaded" | "Updating") => {
67 return OutputPhase::Compiling;
68 }
69 _ => {}
70 }
71 }
72 OutputPhase::Unknown
73 }
74
75 pub fn output_phase_hint(text: &str) -> &'static str {
76 match output_phase(text) {
77 OutputPhase::Compiling => "output phase: still compiling, no test or program output yet",
78 OutputPhase::BuildFinished => "output phase: build finished, program or tests starting",
79 OutputPhase::Running => "output phase: past compile, tests or program running",
80 OutputPhase::Unknown => "output phase: not recognized from the output",
81 }
82 }
83
84 pub fn kill_outcome_note(text: &str) -> &'static str {
85 match output_phase(text) {
86 OutputPhase::Compiling => {
87 "Killed during the compile phase: artifacts already written to disk are not removed, only the unfinished compile step is lost."
88 }
89 OutputPhase::BuildFinished | OutputPhase::Running => {
90 "Killed after the compile phase: compiled artifacts are not removed, but the run time already spent on this command is discarded."
91 }
92 OutputPhase::Unknown => {
93 "Build phase not recognized from the output: artifacts already written to disk are not removed, but progress inside the command is lost."
94 }
95 }
96 }
97
98 #[derive(Debug, Clone, Copy, Default)]
99 pub struct TruncationMeta {
100 pub original_len: usize,
101 pub omitted: usize,
102 pub truncated: bool,
103 }
104
105 pub fn truncate_with_meta(output: &str) -> (String, TruncationMeta) {
106 let original_len = output.len();
107 if original_len <= MAX_OUTPUT_SIZE {
108 return (
109 output.to_string(),
110 TruncationMeta {
111 original_len,
112 omitted: 0,
113 truncated: false,
114 },
115 );
116 }
117
118 let head_end = char_boundary_at_or_before(output, TRUNCATED_HEAD_BYTES);
119 let tail_start =
120 char_boundary_at_or_after(output, original_len.saturating_sub(TRUNCATED_TAIL_BYTES));
121 let head = &output[..head_end];
122 let omitted_middle = &output[head_end..tail_start];
123 let tail = &output[tail_start..];
124 let omitted = omitted_middle.len();
125 let note = format!(
126 "...\n\n[Output truncated: showing first {head_bytes} bytes and last {tail_bytes} bytes. {omitted} bytes omitted.]",
127 head_bytes = head.len(),
128 tail_bytes = tail.len(),
129 );
130
131 // Preserve high-signal summary lines from the omitted middle (cargo test
132 // results, rustc errors, panics, completion markers). The raw tail is
133 // already included below; these snippets keep earlier failures visible
134 // without re-running `cargo test | tail` repeatedly (#242/#1450).
135 let mut combined = format!("{head}{note}");
136 let preserved = collect_summary_lines(omitted_middle);
137 if !preserved.is_empty() {
138 combined.push_str("\n\n[Preserved summary lines from omitted middle]\n");
139 combined.push_str(&preserved.join("\n"));
140 }
141 combined.push_str("\n\n[Output tail]\n");
142 combined.push_str(tail);
143
144 (
145 combined,
146 TruncationMeta {
147 original_len,
148 omitted,
149 truncated: true,
150 },
151 )
152 }
153
154 /// Extract high-signal summary lines from a chunk of output that would
155 /// otherwise be discarded by truncation. Recognises Cargo/rustc output,
156 /// generic test framework summaries, panic markers, exit-status lines,
157 /// and `Finished`/`running ...` markers. Returns at most
158 /// `MAX_PRESERVED_SUMMARY_LINES` lines, oldest-first within each match
159 /// class so the most actionable signal is at the end.
160 ///
161 /// Each line is clipped to `MAX_PRESERVED_SUMMARY_LINE_CHARS` and the block
162 /// stops at `MAX_PRESERVED_SUMMARY_BYTES`. Both bounds are load-bearing: the
163 /// line count alone let one very wide `error:` line put the entire omitted
164 /// middle back into a result the caller had just bounded to
165 /// `MAX_OUTPUT_SIZE`.
166 pub fn collect_summary_lines(text: &str) -> Vec<String> {
167 let mut preserved: Vec<String> = Vec::new();
168 let mut remaining = MAX_PRESERVED_SUMMARY_BYTES;
169 for line in text.lines() {
170 if preserved.len() >= MAX_PRESERVED_SUMMARY_LINES {
171 break;
172 }
173 if !is_summary_line(line) {
174 continue;
175 }
176 let clipped = truncate_chars(line, MAX_PRESERVED_SUMMARY_LINE_CHARS);
177 // `+ 1` for the newline `truncate_with_meta` joins these lines with.
178 let cost = clipped.len().saturating_add(1);
179 if cost > remaining {
180 break;
181 }
182 remaining -= cost;
183 preserved.push(clipped);
184 }
185 preserved
186 }
187
188 /// Heuristics for "this line is worth preserving even when most of the
189 /// output is dropped." Tuned for Cargo/rustc and generic test runner
190 /// vocabulary. Intentionally conservative: false positives only cost a
191 /// handful of bytes; false negatives force the agent to re-run gates.
192 fn is_summary_line(line: &str) -> bool {
193 let trimmed = line.trim_start();
194 if trimmed.is_empty() {
195 return false;
196 }
197 // Cargo / rustc canonical markers. Note `trim_start` already stripped
198 // any leading whitespace, so match the bare word — the indentation
199 // Cargo prints (e.g. " Finished") would never reach this point.
200 if trimmed.starts_with("test result:")
201 || trimmed.starts_with("failures:")
202 || trimmed.starts_with("FAILED")
203 || trimmed.starts_with("error[")
204 || trimmed.starts_with("error:")
205 || trimmed.starts_with("warning:")
206 || trimmed.starts_with("panicked at")
207 || trimmed.starts_with("note:")
208 || trimmed.starts_with("help:")
209 || trimmed.starts_with("Finished")
210 || trimmed.starts_with("Compiling")
211 || trimmed.starts_with("Building")
212 || trimmed.starts_with("Running")
213 || trimmed.starts_with("running ")
214 || trimmed.starts_with("Doc-tests")
215 || trimmed.starts_with("---- ")
216 {
217 return true;
218 }
219 // Generic test runner vocabulary.
220 if trimmed.contains("PASS") || trimmed.contains("FAIL") || trimmed.contains("ASSERT") {
221 return true;
222 }
223 // Process-level signal lines.
224 if trimmed.starts_with("Killed")
225 || trimmed.starts_with("Aborted")
226 || trimmed.starts_with("Segmentation fault")
227 || trimmed.starts_with("Error:")
228 || trimmed.starts_with("exit status")
229 || trimmed.starts_with("exit code")
230 {
231 return true;
232 }
233 // `test some::name ... ok|FAILED|ignored` is the per-test result line in
234 // libtest. Cheap to match and useful for pinpointing the failing case.
235 if trimmed.starts_with("test ") && (trimmed.ends_with("FAILED") || trimmed.ends_with("ignored"))
236 {
237 return true;
238 }
239 false
240 }
241
242 pub(crate) fn char_boundary_at_or_before(text: &str, max_bytes: usize) -> usize {
243 if max_bytes >= text.len() {
244 return text.len();
245 }
246
247 let mut last_end = 0usize;
248 for (idx, ch) in text.char_indices() {
249 let end = idx.saturating_add(ch.len_utf8());
250 if end > max_bytes {
251 break;
252 }
253 last_end = end;
254 }
255
256 last_end.min(text.len())
257 }
258
259 fn char_boundary_at_or_after(text: &str, min_bytes: usize) -> usize {
260 if min_bytes >= text.len() {
261 return text.len();
262 }
263 if text.is_char_boundary(min_bytes) {
264 return min_bytes;
265 }
266 text.char_indices()
267 .map(|(idx, _)| idx)
268 .find(|&idx| idx > min_bytes)
269 .unwrap_or(text.len())
270 }
271
272 fn strip_truncation_note(text: &str) -> &str {
273 text.split_once("\n\n[Output truncated")
274 .map_or(text, |(prefix, _)| prefix)
275 }
276
277 fn truncate_chars(text: &str, max_chars: usize) -> String {
278 if text.chars().count() <= max_chars {
279 return text.to_string();
280 }
281
282 let mut end = text.len();
283 for (count, (idx, _)) in text.char_indices().enumerate() {
284 if count == max_chars {
285 end = idx;
286 break;
287 }
288 }
289
290 format!("{}...", &text[..end])
291 }
292
293 pub fn summarize_output(text: &str) -> String {
294 let stripped = strip_truncation_note(text);
295 let summary = stripped
296 .lines()
297 .take(SUMMARY_MAX_LINES)
298 .collect::<Vec<_>>()
299 .join("\n")
300 .trim()
301 .to_string();
302
303 if summary.is_empty() {
304 String::new()
305 } else {
306 truncate_chars(&summary, SUMMARY_MAX_CHARS)
307 }
308 }
309
310 #[cfg(test)]
311 mod tests {
312 use super::*;
313
314 #[test]
315 fn truncation_preserves_cargo_test_summary_lines_from_tail() {
316 let mut head = String::with_capacity(MAX_OUTPUT_SIZE + 4_000);
317 head.push_str("running 5 tests\n");
318 for i in 0..3_000 {
319 head.push_str(&format!("test test::case_{i} ... ok\n"));
320 }
321 // Pad to force tail truncation
322 while head.len() < MAX_OUTPUT_SIZE {
323 head.push_str("...padding line below threshold...\n");
324 }
325 head.push_str("\ntest result: ok. 1687 passed; 0 failed; 2 ignored\n");
326 head.push_str(" Finished `dev` profile target(s) in 4.87s\n");
327
328 let (truncated, meta) = truncate_with_meta(&head);
329 assert!(meta.truncated, "expected truncation");
330 assert!(
331 truncated.contains("test result: ok. 1687 passed"),
332 "summary line must be preserved\nGot: {}",
333 &truncated[truncated.len().saturating_sub(400)..]
334 );
335 assert!(
336 truncated.contains("Finished"),
337 "Finished marker must be preserved"
338 );
339 }
340
341 #[test]
342 fn truncation_preserves_failure_lines_from_tail() {
343 let mut head = String::with_capacity(MAX_OUTPUT_SIZE + 1_000);
344 for _ in 0..MAX_OUTPUT_SIZE {
345 head.push('a');
346 }
347 head.push_str("\nfailures:\n test::flaky_thing FAILED\n");
348 head.push_str("test result: FAILED. 0 passed; 1 failed\n");
349
350 let (truncated, _meta) = truncate_with_meta(&head);
351 assert!(truncated.contains("failures:"), "must preserve failures:");
352 assert!(truncated.contains("FAILED"), "must preserve FAILED");
353 }
354
355 #[test]
356 fn truncation_includes_raw_tail_for_shell_output() {
357 let mut output = String::new();
358 output.push_str("head-marker\n");
359 output.push_str(&"middle noise\n".repeat(3_000));
360 output.push_str("tail-marker: final compiler error\n");
361
362 let (truncated, meta) = truncate_with_meta(&output);
363
364 assert!(meta.truncated, "expected truncation");
365 assert!(truncated.contains("head-marker"));
366 assert!(
367 truncated.contains("[Output tail]"),
368 "tail section should be explicit: {truncated}"
369 );
370 assert!(
371 truncated.contains("tail-marker: final compiler error"),
372 "raw tail must remain visible"
373 );
374 }
375
376 #[test]
377 fn preserved_summary_lines_are_bounded_in_bytes_not_only_in_count() {
378 // One rustc `error:` line can be megabytes wide (a long inferred type,
379 // a minified bundler frame, a `--verbose` link line). Landing in the
380 // omitted middle, it was re-inlined verbatim by the preserved-summary
381 // block, so the "30KB" truncation returned a 400KB tool result.
382 let mut output = String::from("head-marker\n");
383 output.push_str(&"noise line\n".repeat(1_000));
384 output.push_str(&format!("error: {}\n", "T".repeat(400_000)));
385 output.push_str(&"noise line\n".repeat(4_000));
386 output.push_str("tail-marker\n");
387
388 let (truncated, meta) = truncate_with_meta(&output);
389 assert!(meta.truncated, "expected truncation");
390 assert!(
391 truncated.contains("error: TTT"),
392 "the high-signal line must still be preserved"
393 );
394 assert!(
395 truncated.len() <= MAX_OUTPUT_SIZE + 2 * MAX_PRESERVED_SUMMARY_BYTES,
396 "preserved summary blew the output budget: {} bytes",
397 truncated.len()
398 );
399 }
400
401 #[test]
402 fn collect_summary_lines_skips_noise() {
403 let body = "\nblah blah\nrandom line\nokay\n\n";
404 assert!(collect_summary_lines(body).is_empty());
405 }
406
407 #[test]
408 fn collect_summary_lines_picks_rustc_errors() {
409 let body = "\
410 some preamble
411 error[E0277]: the trait `Foo` is not implemented for `Bar`
412 --> src/lib.rs:42:9
413 warning: unused variable
414 note: see help
415 ";
416 let preserved = collect_summary_lines(body);
417 assert!(preserved.iter().any(|line| line.contains("error[E0277]")));
418 assert!(preserved.iter().any(|line| line.contains("warning:")));
419 }
420 }
421
421 lines RUST