Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,153 @@
//! Important-line classification — the "keep the signal" heuristic shared by the generic pipeline
//! and (later) the structured test reducer.
//!
//! Deterministic, language-agnostic substring/shape checks. A line is important when dropping it
//! would cost the model actionable information: errors, warnings, failing tests, file:line
//! locations, exit/summary lines, stack frames, or auth/device-code prompts. When in doubt, keep.
/// Whether a line carries actionable signal that truncation/filtering must preserve.
pub fn is_important(line: &str) -> bool {
let trimmed = line.trim();
if trimmed.is_empty() {
return false;
}
let lower = trimmed.to_ascii_lowercase();
// Diagnostics + failures (covers rustc `error[E…]`, `error:`, gcc/clang, python, generic).
const MARKERS: &[&str] = &[
"error",
"warning:",
"warning[",
"warn:",
"failed",
"failure",
"fail:",
"panic",
"fatal",
"exception",
"traceback",
"assert",
"cannot find",
"not found",
"unresolved",
"undefined",
"undeclared",
"no such",
"denied",
"timed out",
"timeout",
"exit code",
"exit status",
"test result",
"segmentation fault",
"core dumped",
];
if MARKERS.iter().any(|m| lower.contains(m)) {
return true;
}
// Test-runner summaries and per-test verdicts.
if is_test_signal(&lower) {
return true;
}
// Stack frames: gdb `#0 …`, JS/Java ` at …`, python ` File "…", line N`.
if trimmed.starts_with("at ")
|| (trimmed.starts_with('#') && trimmed[1..].starts_with(|c: char| c.is_ascii_digit()))
|| (lower.starts_with("file \"") && lower.contains("line "))
{
return true;
}
// Auth / device-code prompts the user must act on.
if lower.contains("device code")
|| lower.contains("verification")
|| lower.contains("authenticate")
|| lower.contains("sign in")
{
return true;
}
// A file:line(:col) location reference anywhere in the line.
contains_file_location(trimmed)
}
/// Test-runner signal: verdict tokens and "N passed / M failed"-style summaries.
fn is_test_signal(lower: &str) -> bool {
const TOKENS: &[&str] = &[
"test result",
"tests run",
"0 passed",
"assertion failed",
" passed",
" failed",
"passed;",
"failed;",
"passed,",
"failed,",
];
if TOKENS.iter().any(|t| lower.contains(t)) {
return true;
}
(lower.contains("running") && lower.contains("test"))
|| (lower.contains("passed") && lower.contains("failed"))
}
/// Detects a `path:line` or `path:line:col` reference (a token with a `.`/`/` before a `:number`).
fn contains_file_location(line: &str) -> bool {
for token in line.split(|c: char| c.is_whitespace() || c == '(' || c == ')') {
let bytes = token.as_bytes();
let Some(first_colon) = token.find(':') else {
continue;
};
// Path-ish prefix (has a separator or extension dot) before the colon.
let prefix = &token[..first_colon];
if prefix.is_empty()
|| !(prefix.contains('/') || prefix.contains('.') || prefix.contains('\\'))
{
continue;
}
// Digits immediately after the colon → a line number.
let after = &bytes[first_colon + 1..];
if after.first().is_some_and(u8::is_ascii_digit) {
return true;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_errors_and_warnings() {
assert!(is_important("error[E0308]: mismatched types"));
assert!(is_important("warning: unused variable `x`"));
assert!(is_important("thread 'main' panicked at src/main.rs:5"));
assert!(is_important("FAILED: 3 tests failed"));
}
#[test]
fn keeps_file_locations_and_frames() {
assert!(is_important(" --> src/lib.rs:12:9"));
assert!(is_important(" at Object.<anonymous> (/app/index.js:4:10)"));
assert!(is_important(" File \"app.py\", line 7, in <module>"));
assert!(is_important("#0 main::run (main.rs:4)"));
}
#[test]
fn keeps_test_summaries_and_auth() {
assert!(is_important("test result: FAILED. 1 passed; 2 failed"));
assert!(is_important("running 12 tests"));
assert!(is_important("Enter the device code ABCD-1234 to authenticate"));
}
#[test]
fn drops_plain_noise() {
assert!(!is_important(" Compiling serde v1.0.0"));
assert!(!is_important("Downloading crates ..."));
assert!(!is_important("hello world"));
assert!(!is_important(""));
}
}

View File

@@ -0,0 +1,104 @@
//! Command-specific output reducers — currently the structured test reducer.
//!
//! The test reducer parses a test runner's noisy output into a compact, high-signal summary
//! (framework, pass/fail/skipped counts, failing test names + file:line + message) so the model
//! sees *what failed and where* instead of scrolling a wall of log. It's the most-structured
//! reducer on the compression pipeline; on an unrecognized format it falls back to the generic
//! pipeline so no output is lost. Shared by the `bash` registry and the standalone `test` tool.
use super::stages::strip_ansi;
use super::{CommandInvocation, CommandOutput, CompressionConfig, OutputReducer};
mod go;
mod javascript;
mod python;
mod rust;
mod summary;
use go::parse_go;
use javascript::{parse_jest, parse_node, parse_vitest};
use python::{parse_pytest, parse_unittest};
use rust::{parse_cargo, parse_nextest};
pub use summary::{TestFailure, TestSummary};
/// The structured test reducer.
pub struct TestReducer;
impl OutputReducer for TestReducer {
fn id(&self) -> &str {
"test"
}
fn can_handle(&self, command: &CommandInvocation) -> bool {
is_test_command(command)
}
fn reduce(&self, _command: &CommandInvocation, output: &CommandOutput) -> String {
match parse_test_output(&output.stdout, &output.stderr) {
Some(summary) => summary.render(),
// Unknown format: don't lose the output — fall back to the generic pipeline.
None => super::generic_reduce(output, &CompressionConfig::default()),
}
}
}
/// Whether a command looks like a test invocation (used to route the reducer + the `test` tool).
pub fn is_test_command(command: &CommandInvocation) -> bool {
let exe = command.executable.as_str();
let has = |needle: &str| command.args.iter().any(|a| a == needle);
match exe {
"cargo" => has("test") || has("nextest"),
"go" => has("test"),
"pytest" | "jest" | "vitest" | "tox" | "nox" => true,
// Django's own suite, and a project's `manage.py test`
"runtests.py" => true,
python if python.starts_with("python") => {
has("pytest")
|| has("unittest")
|| command.args.first().is_some_and(|script| script.ends_with("runtests.py"))
|| (command.args.first().is_some_and(|script| script.ends_with("manage.py"))
&& command.args.get(1).is_some_and(|sub| sub == "test"))
|| (has("django") && has("test"))
}
"django-admin" => command.args.first().is_some_and(|sub| sub == "test"),
"npm" | "pnpm" | "yarn" | "bun" => has("test"),
"npx" => command.args.iter().any(|a| a == "jest" || a == "vitest"),
_ => false,
}
}
/// Parse test output, trying each framework in a robust order.
pub fn parse_test_output(stdout: &str, stderr: &str) -> Option<TestSummary> {
let text = strip_ansi(&format!("{stdout}\n{stderr}"));
// Order matters: nextest embeds a libtest `test result:` line, so detect it first.
parse_nextest(&text)
.or_else(|| parse_cargo(&text))
.or_else(|| parse_pytest(&text))
// `unittest` and the runners built on it (Django's `runtests.py`, `manage.py test`)
.or_else(|| parse_unittest(&text))
.or_else(|| parse_vitest(&text))
.or_else(|| parse_jest(&text))
// Ahead of go, whose `ok <package>` lines also match every TAP `ok 1 - name`
.or_else(|| parse_node(&text))
.or_else(|| parse_go(&text))
}
/// `<num> <keyword>` occurring in `line` (e.g. `12 passed`).
fn count_before(line: &str, keyword: &str) -> Option<usize> {
let idx = line.find(keyword)?;
let digits: String =
line[..idx].trim_end().chars().rev().take_while(char::is_ascii_digit).collect();
if digits.is_empty() {
return None;
}
digits.chars().rev().collect::<String>().parse().ok()
}
fn push_unique(failures: &mut Vec<TestFailure>, name: &str) {
if !failures.iter().any(|f| f.name == name) {
failures.push(TestFailure { name: name.to_string(), location: None, message: None });
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,58 @@
//! Go — `go test`, terse and verbose.
use super::{TestFailure, TestSummary};
pub(super) fn parse_go(text: &str) -> Option<TestSummary> {
let mut summary = TestSummary { framework: "go".to_string(), ..Default::default() };
let mut found = false;
let mut current: Option<usize> = None;
// A `t.Errorf` line printed before the verdict it belongs to. Under `-v` go interleaves output
// with the run, so the message arrives *above* its `--- FAIL:` — the opposite of the buffered
// order — and without holding it, the next failure would inherit the previous one's message.
let mut pending: Option<(String, String)> = None;
for line in text.lines() {
let t = line.trim_start();
if let Some(rest) = t.strip_prefix("--- FAIL: ") {
found = true;
let name = rest.split_whitespace().next().unwrap_or(rest);
let (location, message) = match pending.take() {
Some((location, message)) => (Some(location), Some(message)),
None => (None, None),
};
summary.failures.push(TestFailure { name: name.to_string(), location, message });
current = Some(summary.failures.len() - 1);
} else if t.starts_with("--- PASS: ") {
found = true;
summary.passed += 1;
(current, pending) = (None, None);
} else if t.starts_with("--- SKIP: ") {
found = true;
summary.ignored += 1;
(current, pending) = (None, None);
} else if t.starts_with("=== RUN") {
(current, pending) = (None, None);
} else if t.starts_with("ok ") || t.starts_with("ok\t") || t == "PASS" {
found = true;
} else if let Some((loc, msg)) = t.split_once(": ").filter(|(loc, _)| loc.contains(".go:"))
{
// First `file.go:line: message` around a FAIL is its location + message.
match current {
Some(index) if summary.failures[index].location.is_none() => {
summary.failures[index].location = Some(loc.to_string());
summary.failures[index].message = Some(msg.to_string());
}
_ if pending.is_none() => pending = Some((loc.to_string(), msg.to_string())),
_ => {}
}
}
}
summary.failed = summary.failures.len();
if found {
Some(summary)
} else {
None
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,87 @@
use crate::compression::parse_test_output;
#[test]
fn parses_go() {
let out = "--- FAIL: TestBad (0.00s)\n m_test.go:4: got 2 want 3\nFAIL\nFAIL\tm\t0.001s\n";
let s = parse_test_output(out, "").unwrap();
assert_eq!(s.framework, "go");
assert_eq!(s.failed, 1);
assert_eq!(s.failures[0].name, "TestBad");
assert_eq!(s.failures[0].location.as_deref(), Some("m_test.go:4"));
}
/// A real `go test -v ./...`, copied verbatim.
///
/// Verbose is the only mode that says anything about a test that passed — and it prints each
/// message *above* the verdict it belongs to, so the naive reading hands one failure's message
/// to the next one.
#[test]
fn parses_verbose_go_where_the_message_comes_before_its_verdict() {
let out = "\
=== RUN TestGood
--- PASS: TestGood (0.00s)
=== RUN TestBad
m_test.go:4: got 2 want 3
--- FAIL: TestBad (0.00s)
=== RUN TestSkip
m_test.go:5: later
--- SKIP: TestSkip (0.00s)
FAIL
FAIL\tm\t0.001s
FAIL
";
let s = parse_test_output(out, "").expect("go output parses");
assert_eq!((s.passed, s.failed, s.ignored), (1, 1, 1));
assert_eq!(s.failures.len(), 1, "a skip is not a failure");
assert_eq!(s.failures[0].name, "TestBad");
assert_eq!(s.failures[0].location.as_deref(), Some("m_test.go:4"));
assert_eq!(s.failures[0].message.as_deref(), Some("got 2 want 3"));
}
/// A test that reports twice keeps the *first* message, in both orderings.
///
/// `t.Errorf` does not stop the test, so a failure often prints several lines; the one that says
/// what broke is the first, and the last is usually a consequence of it.
#[test]
fn a_go_failure_that_says_several_things_is_summarized_by_its_first() {
let verbose = "\
=== RUN TestBad
m_test.go:3: got 2 want 3
m_test.go:3: and again
--- FAIL: TestBad (0.00s)
FAIL
";
let buffered = "\
--- FAIL: TestBad (0.00s)
m_test.go:3: got 2 want 3
m_test.go:3: and again
FAIL
";
for out in [verbose, buffered] {
let s = parse_test_output(out, "").expect("go output parses");
assert_eq!(s.failures[0].message.as_deref(), Some("got 2 want 3"), "{out}");
}
}
/// go's passes are counted one `--- PASS:` at a time, and the package footer it ends with comes
/// in three spellings that all mean the same thing.
#[test]
fn go_counts_each_pass_and_accepts_every_footer_it_prints() {
let out = "--- PASS: TestOne (0.00s)\n--- PASS: TestTwo (0.00s)\nPASS\nok \tm\t0.5s\n";
let s = parse_test_output(out, "").expect("go output parses");
assert_eq!((s.passed, s.failed), (2, 0));
for footer in ["ok \tm\t0.5s", "ok\tm\t0.5s", "PASS"] {
assert!(parse_test_output(footer, "").is_some(), "{footer} ends a go run");
}
// A failure's location is the first `file.go:line:` under it, and only a go file's.
let mislabeled = "--- FAIL: TestBad (0.00s)\n note: something else\n \
m_test.go:4: got 2 want 3\nFAIL\n";
let s = parse_test_output(mislabeled, "").expect("go output parses");
assert_eq!(s.failures[0].location.as_deref(), Some("m_test.go:4"));
// A `word: text` line that names no go file is prose, and prose is not a location.
let prose = "--- FAIL: TestBad (0.00s)\n reason: the flag was unset\nFAIL\n";
let s = parse_test_output(prose, "").expect("go output parses");
assert!(s.failures[0].location.is_none(), "{:?}", s.failures[0]);
}

View File

@@ -0,0 +1,312 @@
//! JavaScript — jest, vitest, and Node's own runner in its spec and TAP reporters.
use super::{count_before, push_unique, TestFailure, TestSummary};
pub(super) fn parse_jest(text: &str) -> Option<TestSummary> {
let mut summary = TestSummary { framework: "jest".to_string(), ..Default::default() };
let mut found = false;
for line in text.lines() {
let t = line.trim();
if let Some(rest) = t.strip_prefix("Tests:") {
if rest.contains("total") {
found = true;
summary.passed = count_before(rest, "passed").unwrap_or(0);
summary.failed = count_before(rest, "failed").unwrap_or(0);
summary.ignored = count_before(rest, "skipped")
.or_else(|| count_before(rest, "todo"))
.unwrap_or(0);
}
} else if let Some(name) = t.strip_prefix("✕ ").or_else(|| t.strip_prefix("× ")) {
let name = name.rsplit_once(" (").map(|(n, _)| n).unwrap_or(name);
push_unique(&mut summary.failures, name.trim());
} else if let Some(name) = t.strip_prefix("● ").filter(|name| !is_jest_notice(name)) {
// Where a default run actually names its failures: ` ● math › multiplies`, repeated in
// the "summary of all failing tests" block, which `push_unique` folds back together.
// The `✕` list above is verbose mode, so on its own it found nothing at all.
push_unique(&mut summary.failures, name.trim());
}
}
if found {
Some(summary)
} else {
None
}
}
/// Whether a jest `●` header introduces something other than a failing test.
///
/// The bullet is jest's section marker, not a failure marker — console output and deprecation
/// notices wear it too, and a run whose only "failures" were warnings would name them as tests.
fn is_jest_notice(header: &str) -> bool {
["Console", "Deprecation", "Validation", "Warning"]
.iter()
.any(|notice| header.starts_with(notice))
}
/// vitest, which reports the same facts as jest in a different shape.
///
/// Its counts line carries no colon and separates with `|`, and its failure names arrive as
/// `FAIL file > test` — so jest's parser matched none of it, and every vitest run fell through to a
/// raw dump of the runner's own output.
pub(super) fn parse_vitest(text: &str) -> Option<TestSummary> {
let mut summary = TestSummary { framework: "vitest".to_string(), ..Default::default() };
let mut found = false;
for line in text.lines() {
let t = line.trim();
if let Some(rest) =
t.strip_prefix("Tests").filter(|rest| rest.starts_with(char::is_whitespace))
{
found = true;
summary.passed = count_before(rest, "passed").unwrap_or(0);
summary.failed = count_before(rest, "failed").unwrap_or(0);
summary.ignored =
count_before(rest, "skipped").or_else(|| count_before(rest, "todo")).unwrap_or(0);
} else if let Some(name) = t.strip_prefix("FAIL ").filter(|name| name.contains(" > ")) {
// The file-level `FAIL x.test.js` line says nothing a count does not; the one carrying
// `>` names the test, and reads back as a filter.
push_unique(&mut summary.failures, name.trim());
}
}
found.then_some(summary)
}
/// Node's built-in runner (`node --test`), in either of its reporters.
///
/// The spec reporter is what a terminal gets: `✔`/`✖` per test, an `ℹ tests 5` block of counts, and
/// a `✖ failing tests:` section repeating each failure under `test at <file:line:col>` with its
/// assertion below. TAP is what older Nodes print to a pipe: `# pass 3` counts and `not ok 2 - name`
/// with a YAML block carrying `location` and `error`. Either becomes the same summary, which is the
/// point — left unparsed, one failing assertion came back as forty lines of runner chatter.
pub(super) fn parse_node(text: &str) -> Option<TestSummary> {
let mut summary = TestSummary { framework: "node".to_string(), ..Default::default() };
let count = |line: &str, keys: &[&str]| {
keys.iter().find_map(|key| {
line.strip_prefix(key)?.split_whitespace().next()?.parse::<usize>().ok()
})
};
let (mut tests, mut spec, mut tap) = (None, false, false);
for line in text.lines() {
let t = line.trim();
if let Some(n) = count(t, &["ℹ tests ", "# tests "]) {
tests = Some(n);
}
if let Some(n) = count(t, &["ℹ pass ", "# pass "]) {
summary.passed = n;
spec |= t.starts_with('ℹ');
tap |= t.starts_with('#');
}
if let Some(n) = count(t, &["ℹ fail ", "# fail "]) {
summary.failed = n;
}
if let Some(n) = count(t, &["ℹ skipped ", "# skipped "]) {
summary.ignored += n;
}
if let Some(n) = count(t, &["ℹ todo ", "# todo "]) {
summary.ignored += n;
}
}
tests?;
if spec {
node_spec_failures(text, &mut summary);
} else if tap {
node_tap_failures(text, &mut summary);
}
explain_file_failures(text, &mut summary);
Some(summary)
}
/// A test file that died before its tests ran, as Node prints it above the results.
struct FileCrash {
/// The path from the `file://` header, forward slashes
path: String,
line: String,
/// The error's headline, then the source line and caret that point at it
message: String,
}
/// Every file crash in the output: a `file:///…:N` header, the source line and caret, then the
/// error itself, possibly after a blank line. TAP prints the same block as `#` comments.
fn node_file_crashes(text: &str) -> Vec<FileCrash> {
let lines: Vec<String> = text
.lines()
.map(|line| {
let line = line.strip_prefix("# ").or_else(|| line.strip_prefix('#')).unwrap_or(line);
line.replace("\\#", "#")
})
.collect();
let mut crashes = Vec::new();
for (at, header) in lines.iter().enumerate() {
let Some(place) = header.trim().strip_prefix("file://") else { continue };
let Some((path, line)) = place.rsplit_once(':') else { continue };
if line.parse::<u32>().is_err() {
continue;
}
let window = &lines[at + 1..lines.len().min(at + 6)];
let Some(error) = window.iter().position(|line| is_error_headline(line)) else { continue };
let pointer: Vec<&str> = window[..error]
.iter()
.map(|line| line.trim_end())
.filter(|line| !line.trim().is_empty())
.collect();
let mut message = window[error].trim_end().to_string();
for line in pointer {
message.push('\n');
message.push_str(line);
}
crashes.push(FileCrash { path: path.replace('\\', "/"), line: line.to_string(), message });
}
crashes
}
/// `SyntaxError: …`, `ReferenceError: …`, `Error [ERR_MODULE_NOT_FOUND]: …` — an error's first
/// line, flush left the way Node prints an uncaught one.
fn is_error_headline(line: &str) -> bool {
let Some((kind, _)) = line.split_once(": ") else { return false };
let kind = kind.split_once(" [").map_or(kind, |(kind, _)| kind);
!kind.is_empty()
&& kind.ends_with("Error")
&& kind.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
/// Node reports a file that crashed while loading as one failure named for the file, whose only
/// reason is `test failed`. The real reason was printed above the results, so it replaces that,
/// and the location moves to the line that crashed. Without it a missing export read as a failing
/// test, and the model was left to guess.
fn explain_file_failures(text: &str, summary: &mut TestSummary) {
let placeholder = |message: &Option<String>| {
message.as_deref().is_none_or(|message| message.trim().trim_matches('\'') == "test failed")
};
if !summary.failures.iter().any(|failure| placeholder(&failure.message)) {
return;
}
let crashes = node_file_crashes(text);
for failure in summary.failures.iter_mut().filter(|failure| placeholder(&failure.message)) {
let Some(location) = failure.location.as_deref() else { continue };
let file = location.rsplit_once(':').map_or(location, |(file, _)| file).replace('\\', "/");
let Some(crash) = crashes.iter().find(|crash| {
crash.path == file
|| crash.path.ends_with(&format!("/{}", file.trim_start_matches("./")))
}) else {
continue;
};
failure.location = Some(format!(
"{}:{}",
location.rsplit_once(':').map_or(location, |(file, _)| file),
crash.line
));
failure.message = Some(crash.message.clone());
}
}
/// A test's name as the spec reporter prints it, without the `(0.53ms)` it ends in.
fn without_duration(name: &str) -> &str {
match name.rfind(" (") {
Some(at) if name.ends_with("ms)") => &name[..at],
_ => name,
}
}
/// `test/filter.test.js:19:1` → `test/filter.test.js:19`, which is where an editor wants to go.
fn without_column(location: &str) -> String {
let location = location.trim().trim_matches('\'');
match location.rsplit_once(':') {
Some((head, column))
if column.chars().all(|c| c.is_ascii_digit()) && head.contains(':') =>
{
head.to_string()
}
_ => location.to_string(),
}
}
/// Most lines of an assertion kept: the headline and the actual-versus-expected diff under it,
/// which is what tells the model what to change. The stack after them does not.
const NODE_MESSAGE_LINES: usize = 10;
/// An assertion's lines, ending before the stack trace and without the blank lines around them.
fn assertion(lines: Vec<&str>) -> Option<String> {
let kept: Vec<&str> = lines
.into_iter()
.take_while(|line| !line.trim_start().starts_with("at ") && line.trim() != "{")
.take(NODE_MESSAGE_LINES)
.collect();
let message = kept.join("\n");
let message = message.trim_matches('\n').trim_end();
(!message.trim().is_empty()).then(|| message.to_string())
}
/// The failures from the spec reporter's `✖ failing tests:` section, each with where and why.
fn node_spec_failures(text: &str, summary: &mut TestSummary) {
let Some((_, section)) = text.split_once("✖ failing tests:") else { return };
let lines: Vec<&str> = section.lines().collect();
let mut location = None;
let mut at = 0;
while at < lines.len() {
let line = lines[at].trim();
at += 1;
if let Some(place) = line.strip_prefix("test at ") {
location = Some(without_column(place));
} else if let Some(name) = line.strip_prefix("✖ ") {
// The assertion is indented under its test; the next `test at` starts another
let body: Vec<&str> = lines[at..]
.iter()
.take_while(|next| !next.trim_start().starts_with("test at "))
.map(|next| next.strip_prefix(" ").unwrap_or(next))
.collect();
at += body.len();
let name = without_duration(name).to_string();
if !summary.failures.iter().any(|failure| failure.name == name) {
let message = assertion(body);
summary.failures.push(TestFailure { name, location: location.take(), message });
}
}
}
}
/// The failures from TAP's `not ok` lines, with the `location` and `error` of the YAML below each.
fn node_tap_failures(text: &str, summary: &mut TestSummary) {
let lines: Vec<&str> = text.lines().collect();
let mut current: Option<usize> = None;
let mut at = 0;
while at < lines.len() {
let line = lines[at];
at += 1;
let t = line.trim();
// Top level only: a failing subtest is reported again by the test that holds it
if let Some(rest) = line.strip_prefix("not ok ") {
let name = rest.split_once(" - ").map_or(rest, |(_, name)| name).trim();
summary.failures.push(TestFailure {
name: name.replace("\\#", "#"),
location: None,
message: None,
});
current = Some(summary.failures.len() - 1);
} else if line.starts_with("ok ") {
current = None;
} else if let Some(failure) = current.and_then(|at| summary.failures.get_mut(at)) {
if let Some(location) = t.strip_prefix("location: ") {
failure.location = Some(without_column(location));
} else if let Some(error) = t.strip_prefix("error: ") {
// `|-` opens a block: the message is every line indented past the key's own
let inline = error.trim().trim_matches('\'');
if !inline.starts_with('|') {
failure.message = (!inline.is_empty()).then(|| inline.to_string());
continue;
}
let key = line.len() - line.trim_start().len();
let block: Vec<&str> = lines[at..]
.iter()
.take_while(|next| {
next.trim().is_empty() || next.len() - next.trim_start().len() > key
})
.map(|next| next.get(key + 2..).unwrap_or("").trim_end())
.collect();
at += block.len();
failure.message = assertion(block);
}
}
}
}
#[cfg(test)]
pub(super) mod tests;

View File

@@ -0,0 +1,328 @@
use super::*;
use crate::compression::parse_test_output;
/// What Node 25's spec reporter prints for a suite with one failure, captured from a real run.
pub(crate) const NODE_SPEC: &str = r#"✔ dueBy keeps everything up to the cutoff (0.601294ms)
✔ open sorts newest first and drops what is done (3.922396ms)
✔ tagged wants all of them, not any (0.078751ms)
✖ dueBy treats an unpadded cutoff as the same day (#12) (0.625144ms)
ℹ tests 4
ℹ suites 0
ℹ pass 3
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 34.644023
✖ failing tests:
test at test/filter.test.js:31:1
✖ dueBy treats an unpadded cutoff as the same day (#12) (0.625144ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
'Ship the docs',
+ 'Fix the parser',
+ 'Answer Priya'
]
at TestContext.<anonymous> (file:///work/todo/test/filter.test.js:32:10)
at Test.runInAsyncScope (node:async_hooks:226:14)
at Test.run (node:internal/test_runner/test:1201:25)
at Test.processPendingSubtests (node:internal/test_runner/test:831:18)
at Test.postRun (node:internal/test_runner/test:1330:19)
at Test.run (node:internal/test_runner/test:1258:12)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: [ 'Ship the docs', 'Fix the parser', 'Answer Priya' ],
expected: [ 'Ship the docs' ],
operator: 'deepStrictEqual',
diff: 'simple'
}
"#;
/// The same run through `--test-reporter=tap`.
const NODE_TAP: &str = r#"TAP version 13
# Subtest: dueBy keeps everything up to the cutoff
ok 1 - dueBy keeps everything up to the cutoff
---
duration_ms: 0.620974
type: 'test'
...
# Subtest: open sorts newest first and drops what is done
ok 2 - open sorts newest first and drops what is done
---
duration_ms: 3.898016
type: 'test'
...
# Subtest: tagged wants all of them, not any
ok 3 - tagged wants all of them, not any
---
duration_ms: 0.072731
type: 'test'
...
# Subtest: dueBy treats an unpadded cutoff as the same day (\#12)
not ok 4 - dueBy treats an unpadded cutoff as the same day (\#12)
---
duration_ms: 0.548544
type: 'test'
location: '/work/todo/test/filter.test.js:31:1'
failureType: 'testCodeFailure'
error: |-
Expected values to be strictly deep-equal:
+ actual - expected
[
'Ship the docs',
+ 'Fix the parser',
+ 'Answer Priya'
]
code: 'ERR_ASSERTION'
name: 'AssertionError'
expected:
0: 'Ship the docs'
actual:
0: 'Ship the docs'
1: 'Fix the parser'
2: 'Answer Priya'
operator: 'deepStrictEqual'
stack: |-
TestContext.<anonymous> (file:///work/todo/test/filter.test.js:32:10)
Test.runInAsyncScope (node:async_hooks:226:14)
Test.run (node:internal/test_runner/test:1201:25)
Test.processPendingSubtests (node:internal/test_runner/test:831:18)
Test.postRun (node:internal/test_runner/test:1330:19)
Test.run (node:internal/test_runner/test:1258:12)
async Test.processPendingSubtests (node:internal/test_runner/test:831:7)
...
1..4
# tests 4
# suites 0
# pass 3
# fail 1
# cancelled 0
# skipped 0
# todo 0
# duration_ms 32.488839
"#;
/// One failing assertion comes back as its name, where it is, and the diff that says what to
/// change — not the forty lines of runner chatter around it.
#[test]
fn node_spec_output_reduces_to_its_failure() {
let summary = parse_test_output(NODE_SPEC, "").expect("node's spec reporter");
assert_eq!(summary.framework, "node");
assert_eq!((summary.passed, summary.failed, summary.ignored), (3, 1, 0));
assert_eq!(summary.failures.len(), 1);
let failure = &summary.failures[0];
assert_eq!(failure.name, "dueBy treats an unpadded cutoff as the same day (#12)");
assert_eq!(failure.location.as_deref(), Some("test/filter.test.js:31"));
let message = failure.message.as_deref().expect("the assertion");
assert!(message.starts_with("AssertionError"), "{message}");
assert!(message.contains("'Fix the parser'"), "the diff is kept: {message}");
assert!(!message.contains("async_hooks"), "the stack is not: {message}");
assert!(summary.render().lines().count() < 16, "{}", summary.render());
}
/// TAP carries the same facts in YAML: the name unescaped, the location, the error block.
#[test]
fn node_tap_output_reduces_to_its_failure() {
let summary = parse_test_output(NODE_TAP, "").expect("node's TAP reporter");
assert_eq!(summary.framework, "node", "{summary:?}");
assert_eq!((summary.passed, summary.failed), (3, 1));
let failure = &summary.failures[0];
assert_eq!(failure.name, "dueBy treats an unpadded cutoff as the same day (#12)");
assert_eq!(failure.location.as_deref(), Some("/work/todo/test/filter.test.js:31"));
let message = failure.message.as_deref().expect("the error block");
assert!(message.starts_with("Expected values to be strictly deep-equal"), "{message}");
assert!(message.contains("'Answer Priya'"), "{message}");
assert!(!message.contains("code:"), "the block ends with its indent: {message}");
}
/// A file that crashed on import, as Node 25's spec reporter prints it: the crash first, the
/// results after, and the file's own failure carrying nothing but `'test failed'`.
const NODE_SPEC_CRASH: &str = "file:///work/todo/test/filter.test.js:4
import { dueBy, isoDay, open, tagged } from \"../src/filter.js\";
^^^^^^
SyntaxError: The requested module '../src/filter.js' does not provide an export named 'isoDay'
at #asyncInstantiate (node:internal/modules/esm/module_job:326:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:429:5)
Node.js v25.9.0
\u{2716} test/filter.test.js (17.829508ms)
\u{2139} tests 1
\u{2139} suites 0
\u{2139} pass 0
\u{2139} fail 1
\u{2139} cancelled 0
\u{2139} skipped 0
\u{2139} todo 0
\u{2139} duration_ms 23.942601
\u{2716} failing tests:
test at test/filter.test.js:1:1
\u{2716} test/filter.test.js (17.829508ms)
'test failed'
";
/// The same crash under TAP, as comments, beside a top-level throw in a second file that
/// prints a blank line before its error.
const NODE_TAP_CRASH: &str = "TAP version 13
# file:///work/todo/test/filter.test.js:4
# import { dueBy, isoDay, open, tagged } from \"../src/filter.js\";
# ^^^^^^
# SyntaxError: The requested module '../src/filter.js' does not provide an export named 'isoDay'
# at \\#asyncInstantiate (node:internal/modules/esm/module_job:326:21)
# Node.js v25.9.0
# Subtest: test/filter.test.js
not ok 1 - test/filter.test.js
---
duration_ms: 16.531108
type: 'test'
location: '/work/todo/test/filter.test.js:1:1'
failureType: 'testCodeFailure'
exitCode: 1
error: 'test failed'
code: 'ERR_TEST_FAILURE'
...
# file:///work/todo/test/throw.test.js:2
# const x = notDefined + 1;
# ^
#
# ReferenceError: notDefined is not defined
# at file:///work/todo/test/throw.test.js:2:11
# Subtest: test/throw.test.js
not ok 2 - test/throw.test.js
---
location: '/work/todo/test/throw.test.js:1:1'
error: 'test failed'
...
1..2
# tests 2
# pass 0
# fail 2
";
/// A file that never loaded fails for the reason it never loaded, at the line that stopped it.
#[test]
fn a_test_file_that_crashed_says_why() {
let summary = parse_test_output(NODE_SPEC_CRASH, "").expect("node's spec reporter");
let failure = &summary.failures[0];
assert_eq!(failure.location.as_deref(), Some("test/filter.test.js:4"));
let message = failure.message.as_deref().expect("the crash");
assert!(
message.starts_with(
"SyntaxError: The requested module '../src/filter.js' does not provide an export \
named 'isoDay'\nimport { dueBy, isoDay"
),
"{message}"
);
assert!(message.ends_with("^^^^^^"), "the caret points at it: {message}");
assert!(!message.contains("module_job"), "no stack: {message}");
let summary = parse_test_output(NODE_TAP_CRASH, "").expect("node's TAP reporter");
let [import, throw] = &summary.failures[..] else { panic!("{summary:?}") };
assert_eq!(import.location.as_deref(), Some("/work/todo/test/filter.test.js:4"));
assert!(import.message.as_deref().unwrap().starts_with("SyntaxError: "), "{import:?}");
assert_eq!(throw.location.as_deref(), Some("/work/todo/test/throw.test.js:2"));
assert_eq!(
throw.message.as_deref(),
Some("ReferenceError: notDefined is not defined\nconst x = notDefined + 1;\n ^"),
"each crash to its own file, past the blank line"
);
}
/// An assertion that happens to start a line like an error is not a crash, and a placeholder
/// with no crash to explain it stays as Node wrote it.
#[test]
fn only_a_crash_explains_a_file_failure() {
let unexplained = NODE_SPEC_CRASH.split_once("Node.js v25.9.0\n").unwrap().1;
let summary = parse_test_output(unexplained, "").expect("node");
assert_eq!(summary.failures[0].message.as_deref(), Some("'test failed'"));
assert_eq!(summary.failures[0].location.as_deref(), Some("test/filter.test.js:1"));
let no_line = "file:///work/a.js:here\nSyntaxError: nope\n";
assert!(node_file_crashes(no_line).is_empty(), "a crash header ends in its line");
assert!(is_error_headline("Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'x'"));
assert!(is_error_headline("TypeError: x is not a function"));
assert!(!is_error_headline(" at Error: nope"));
assert!(!is_error_headline("AssertionError [ERR_ASSERTION] something"));
assert!(!is_error_headline("Some Error: words"));
}
/// A green run is a count and nothing else, and a run with no Node markers is not Node's.
#[test]
fn node_counts_without_failures_and_nothing_else_is_node() {
let green = "ℹ tests 3\nℹ suites 0\nℹ pass 3\nℹ fail 0\nℹ skipped 1\nℹ todo 1\n";
let summary = parse_node(green).expect("counts alone");
assert_eq!((summary.passed, summary.failed, summary.ignored), (3, 0, 2));
assert!(summary.failures.is_empty() && summary.ok());
assert!(parse_node("ℹ pass 3\n").is_none(), "no test count, not a run summary");
assert!(parse_node("all good\n").is_none());
}
#[test]
fn parses_jest() {
let out = "✕ renders the header (4 ms)\n\
Tests: 1 failed, 2 passed, 1 skipped, 4 total\n";
let s = parse_test_output(out, "").expect("jest output parses");
assert_eq!(s.framework, "jest");
assert_eq!((s.passed, s.failed, s.ignored), (2, 1, 1));
assert_eq!(s.failures[0].name, "renders the header");
}
/// The tail of a real `npx jest` run, copied verbatim.
///
/// Default output names its failures with `●`, not `✕` — the tick list is verbose mode. So the
/// counts parsed and the names, which are the reason to call this tool at all, came back empty.
#[test]
fn parses_the_failure_names_jest_really_prints() {
let out = "\
FAIL ./x.test.js
● bad
● Console
FAIL ./y.test.js
● math › multiplies
Test Suites: 2 failed, 2 total
Tests: 2 failed, 1 skipped, 2 passed, 5 total
";
let s = parse_test_output(out, "").expect("jest output parses");
assert_eq!(s.framework, "jest");
assert_eq!((s.passed, s.failed, s.ignored), (2, 2, 1));
assert_eq!(
s.failures.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),
["bad", "math › multiplies"],
"a console section is not a failing test"
);
}
/// The tail of a real `npx vitest run`, copied verbatim.
#[test]
fn parses_vitest_which_reports_the_same_facts_in_another_shape() {
let out = "\
❯ x.test.js (3 tests | 1 failed | 1 skipped) 3ms
× bad 2ms
FAIL x.test.js > bad
AssertionError: expected 1 to be 2
Test Files 1 failed (1)
Tests 1 failed | 1 passed | 1 skipped (3)
Duration 65ms
";
let s = parse_test_output(out, "").expect("vitest output parses");
assert_eq!(s.framework, "vitest", "named after the runner that produced it");
assert_eq!((s.passed, s.failed, s.ignored), (1, 1, 1));
assert!(
s.failures.iter().any(|f| f.name == "x.test.js > bad"),
"a name that reads back as a filter: {:?}",
s.failures
);
}

View File

@@ -0,0 +1,144 @@
//! Python — pytest, and unittest with the runners built on it.
use super::{count_before, TestFailure, TestSummary};
pub(super) fn parse_pytest(text: &str) -> Option<TestSummary> {
let mut summary = TestSummary { framework: "pytest".to_string(), ..Default::default() };
let mut found = false;
for line in text.lines() {
// pytest centers its closing summary in a banner padded to the terminal width —
// `======== 1 failed, 1 passed in 0.05s ========` — and only `-q` prints the bare line. So
// the banner comes off first, or every default-verbosity run falls through to a raw dump.
let t = line.trim().trim_matches('=').trim();
// Summary line: `1 failed, 1 passed in 0.01s` / `2 passed in 0.1s`.
if (t.contains(" passed") || t.contains(" failed"))
&& t.contains(" in ")
&& t.ends_with('s')
{
found = true;
summary.passed = count_before(t, "passed").unwrap_or(summary.passed);
summary.failed = count_before(t, "failed").unwrap_or(summary.failed);
summary.ignored = count_before(t, "skipped").unwrap_or(summary.ignored);
} else if let Some(rest) = t.strip_prefix("FAILED ") {
let (name, message) = match rest.split_once(" - ") {
Some((n, m)) => (n.trim(), Some(m.trim().to_string())),
None => (rest.trim(), None),
};
summary.failures.push(TestFailure { name: name.to_string(), location: None, message });
}
}
if found {
Some(summary)
} else {
None
}
}
/// Longest a failure's message line may be before it is cut. A Django assertion can print every
/// query it captured on one line, thousands of characters each, and the first few hundred say what
/// went wrong.
const UNITTEST_MESSAGE_CELLS: usize = 300;
/// Lines of a failure's message kept after the exception's own line.
const UNITTEST_MESSAGE_LINES: usize = 4;
/// One `FAIL:`/`ERROR:` block: where it failed and what was asserted.
fn unittest_failure(name: &str, body: &[&str]) -> TestFailure {
let location = body.iter().find_map(|line| {
let rest = line.trim().strip_prefix("File \"")?;
let (path, tail) = rest.split_once("\", line ")?;
let number: String = tail.chars().take_while(char::is_ascii_digit).collect();
Some(format!("{path}:{number}"))
});
let exception = body.iter().position(|line| {
let line = line.trim_start();
!line.is_empty()
&& !line.starts_with("File ")
&& !line.starts_with("Traceback")
&& !line.starts_with("---")
&& !line.starts_with(' ')
&& line.split_once(':').is_some_and(|(kind, _)| {
kind.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '_')
})
});
let message = exception.map(|at| {
body[at..]
.iter()
.map(|line| line.trim_end())
.filter(|line| !line.is_empty() && !line.starts_with("---"))
.take(UNITTEST_MESSAGE_LINES + 1)
.map(|line| match line.chars().count() > UNITTEST_MESSAGE_CELLS {
true => {
let kept: String = line.chars().take(UNITTEST_MESSAGE_CELLS).collect();
format!(
"{kept}… ({} more characters)",
line.chars().count() - UNITTEST_MESSAGE_CELLS
)
}
false => line.to_string(),
})
.collect::<Vec<_>>()
.join("\n")
});
TestFailure { name: name.trim().to_string(), location, message }
}
/// `unittest`: `Ran 45 tests in 0.311s`, then `OK` or `FAILED (failures=2, errors=1, skipped=1)`,
/// with a `FAIL:`/`ERROR:` block per failure above it.
///
/// Each failure keeps the test's own line (unittest strips its frames, so a traceback's first is
/// always the test) and what was asserted, and nothing else: the frames below it are plumbing, and
/// a message line is cut at [`UNITTEST_MESSAGE_CELLS`].
pub(super) fn parse_unittest(text: &str) -> Option<TestSummary> {
let lines: Vec<&str> = text.lines().collect();
let ran = lines.iter().find_map(|line| {
let rest = line.trim().strip_prefix("Ran ")?;
let (count, tail) = rest.split_once(' ')?;
(tail.starts_with("test") && tail.contains(" in ")).then(|| count.parse::<usize>().ok())?
})?;
let verdict =
lines.iter().rev().map(|line| line.trim()).find(|line| {
*line == "OK" || line.starts_with("OK (") || line.starts_with("FAILED (")
})?;
let count = |key: &str| {
verdict
.split(['(', ')', ','])
.filter_map(|part| part.trim().split_once('='))
.filter(|(name, _)| *name == key)
.filter_map(|(_, value)| value.parse::<usize>().ok())
.sum::<usize>()
};
let failed = count("failures") + count("errors") + count("unexpected successes");
let ignored = count("skipped") + count("expected failures");
let mut summary = TestSummary {
framework: "unittest".to_string(),
passed: ran.saturating_sub(failed + ignored),
failed,
ignored,
failures: Vec::new(),
};
let mut index = 0;
while index < lines.len() {
let line = lines[index].trim();
let Some(name) = line.strip_prefix("FAIL: ").or_else(|| line.strip_prefix("ERROR: "))
else {
index += 1;
continue;
};
// The block runs to the next banner; its traceback starts after the dashed rule
let mut end = index + 1;
while end < lines.len()
&& !lines[end].starts_with("======")
&& !lines[end].trim().starts_with("Ran ")
{
end += 1;
}
let body = &lines[index + 1..end];
summary.failures.push(unittest_failure(name, body));
index = end;
}
Some(summary)
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,106 @@
use crate::compression::parse_test_output;
/// Django's `runtests.py` is `unittest` underneath. The literal is a real run's tail from the
/// harness eval, where the whole of it reached the model: 48 KB, most of it one assertion
/// listing every query it captured on a single line.
#[test]
fn a_unittest_run_is_summarized_and_its_long_lines_cut() {
let long = format!(
"2. DELETE FROM \"delete_user\" WHERE (\"delete_user\".\"avatar_id\" IN ({}))",
"1, ".repeat(900)
);
let stderr = format!(
"Creating test database for alias 'default'...\n..s......FF.....\n\
======================================================================\n\
FAIL: test_large_delete (delete.tests.DeletionTests)\n\
----------------------------------------------------------------------\n\
Traceback (most recent call last):\n\
\x20 File \"/repo/tests/delete/tests.py\", line 369, in test_large_delete\n\
\x20 self.assertNumQueries(queries, Avatar.objects.all().delete)\n\
\x20 File \"/repo/django/test/testcases.py\", line 78, in __exit__\n\
\x20 self.test_case.assertEqual(\n\
AssertionError: 22 != 25 : 22 queries executed, 25 expected\n\
Captured queries were:\n\
1. SELECT \"delete_avatar\".\"id\" FROM \"delete_avatar\"\n\
{long}\n\
\n\
======================================================================\n\
ERROR: test_fast_delete (delete.tests.FastDeleteTests)\n\
----------------------------------------------------------------------\n\
Traceback (most recent call last):\n\
\x20 File \"/repo/tests/delete/tests.py\", line 512, in test_fast_delete\n\
\x20 u.delete()\n\
ValueError: boom\n\
\n\
----------------------------------------------------------------------\n\
Ran 45 tests in 0.311s\n\
\n\
FAILED (failures=1, errors=1, skipped=1)\n\
Destroying test database for alias 'default'...\n"
);
let summary = parse_test_output("", &stderr).expect("unittest is recognized");
assert_eq!(summary.framework, "unittest");
assert_eq!((summary.passed, summary.failed, summary.ignored), (42, 2, 1));
assert_eq!(summary.failures[0].name, "test_large_delete (delete.tests.DeletionTests)");
assert_eq!(summary.failures[0].location.as_deref(), Some("/repo/tests/delete/tests.py:369"));
let message = summary.failures[0].message.as_deref().unwrap_or_default();
assert!(message.starts_with("AssertionError: 22 != 25"), "{message}");
assert!(message.contains("more characters"), "the long line is cut: {message}");
assert_eq!(summary.failures[1].message.as_deref(), Some("ValueError: boom"));
assert!(summary.render().len() < 1_500, "{}", summary.render());
let green = "....\n----------------------------------------------------------------------\nRan 4 tests in 0.01s\n\nOK\n";
let summary = parse_test_output("", green).expect("a green run too");
assert!(summary.ok() && summary.passed == 4);
}
#[test]
fn parses_pytest() {
let out = "FAILED test_x.py::test_bad - assert (1 + 1) == 3\n\
1 failed, 1 passed in 0.01s\n";
let s = parse_test_output(out, "").unwrap();
assert_eq!(s.framework, "pytest");
assert_eq!((s.passed, s.failed), (1, 1));
assert_eq!(s.failures[0].name, "test_x.py::test_bad");
assert_eq!(s.failures[0].message.as_deref(), Some("assert (1 + 1) == 3"));
}
/// The tail of a real `python -m pytest` run, copied verbatim.
///
/// The hand-written fixture above is `-q` output, and every line of it is unpadded — so a
/// parser that only understood that shape passed its tests while returning `None` for every
/// default-verbosity run any user or agent would actually produce.
#[test]
fn parses_the_banner_pytest_really_prints() {
let out = "\
=========================== short test summary info ============================
FAILED test_x.py::test_bad - assert (1 + 1) == 3
==================== 1 failed, 1 passed, 1 skipped in 0.01s ====================
";
let s = parse_test_output(out, "").expect("a banner summary is still a summary");
assert_eq!((s.passed, s.failed, s.ignored), (1, 1, 1));
assert_eq!(s.failures[0].name, "test_x.py::test_bad");
let green =
"============================== 1 passed in 0.00s ===============================\n";
let s = parse_test_output(green, "").expect("and so is an all-green one");
assert_eq!((s.passed, s.failed), (1, 0));
}
/// pytest's summary line is identified by shape, and each part of that shape is load-bearing:
/// an all-green run never says "failed", and a line naming a count without a duration is a
/// test's own output rather than the summary.
#[test]
fn the_pytest_summary_line_is_recognized_by_its_whole_shape() {
let green = parse_test_output("2 passed in 0.10s\n", "").expect("an all-green run");
assert_eq!((green.passed, green.failed), (2, 0));
assert!(
parse_test_output("the build passed review\n", "").is_none(),
"a count with no duration is not a summary"
);
assert!(
parse_test_output("1 passed in the first attempt\n", "").is_none(),
"and neither is one that does not end in a duration"
);
}

View File

@@ -0,0 +1,116 @@
//! Rust — libtest and nextest runs, with each failure's panic message.
use super::{count_before, push_unique, TestSummary};
pub(super) fn parse_cargo(text: &str) -> Option<TestSummary> {
let mut summary = TestSummary { framework: "cargo".to_string(), ..Default::default() };
let mut found = false;
for line in text.lines() {
let t = line.trim();
if let Some(rest) = t.strip_prefix("test result:") {
found = true;
summary.passed += count_before(rest, "passed").unwrap_or(0);
summary.failed += count_before(rest, "failed").unwrap_or(0);
summary.ignored += count_before(rest, "ignored").unwrap_or(0);
} else if let Some(name) =
t.strip_prefix("test ").and_then(|s| s.strip_suffix(" ... FAILED"))
{
push_unique(&mut summary.failures, name.trim());
}
}
if found {
enrich_with_panics(text, &mut summary);
Some(summary)
} else {
None
}
}
pub(super) fn parse_nextest(text: &str) -> Option<TestSummary> {
let mut summary = TestSummary { framework: "nextest".to_string(), ..Default::default() };
let mut found = false;
for line in text.lines() {
let t = line.trim();
if let Some(rest) = t.strip_prefix("Summary [").and_then(|s| s.split(']').nth(1)) {
found = true;
summary.passed = count_before(rest, "passed").unwrap_or(0);
summary.failed = count_before(rest, "failed").unwrap_or(0);
summary.ignored = count_before(rest, "skipped").unwrap_or(0);
} else if let Some(rest) = t.strip_prefix("FAIL [") {
// `FAIL [ 0.002s] (2/2) crate tests::name` → keep the crate + test name tail.
if let Some(name) = rest.split(')').nth(1) {
push_unique(&mut summary.failures, name.trim());
}
}
}
if found {
enrich_with_panics(text, &mut summary);
Some(summary)
} else {
None
}
}
/// Attach panic `file:line` + message to matching Rust failures (`thread 'name' panicked at loc:`).
fn enrich_with_panics(text: &str, summary: &mut TestSummary) {
let lines: Vec<&str> = text.lines().collect();
for (i, line) in lines.iter().enumerate() {
let t = line.trim();
let Some(rest) = t.strip_prefix("thread '") else {
continue;
};
let Some((name, after)) = rest.split_once('\'') else {
continue;
};
let Some(loc) = after.split("panicked at ").nth(1).map(|l| l.trim_end_matches(':')) else {
continue;
};
let message = panic_body(&lines, i);
if let Some(failure) = summary.failures.iter_mut().find(|f| names_same_test(&f.name, name))
{
failure.location.get_or_insert_with(|| loc.to_string());
if failure.message.is_none() {
failure.message = message;
}
}
}
}
/// Whether a parsed failure name and a panic's thread name refer to the same test.
///
/// nextest prefixes every failure with the binary that ran it (`crate::bin/name tests::foo`) and
/// the panic line does not carry it, so equality alone matched nothing on a nextest run and every
/// failure came back with a bare name and no assertion text. Comparing the last whitespace-
/// separated segment keeps the binary id out of it without the false positives a substring test
/// would invite (`bar_foo` must not match `foo`).
fn names_same_test(failure_name: &str, thread_name: &str) -> bool {
failure_name == thread_name
|| failure_name.rsplit(char::is_whitespace).next() == Some(thread_name)
}
/// Panic body lines the summary keeps, past which a reader is better served by the artifact file.
const MAX_PANIC_LINES: usize = 6;
/// The panic body under a `thread '…' panicked at …:` line.
///
/// More than one line, because the line that matters for `assert_eq!` is not the first one — the
/// `left:`/`right:` values under it are the whole reason to read the failure. Stops at the runner's
/// own trailers so a backtrace hint never lands in the summary.
fn panic_body(lines: &[&str], panic_line: usize) -> Option<String> {
let mut body: Vec<&str> = Vec::new();
for raw in lines.iter().skip(panic_line + 1).take(MAX_PANIC_LINES) {
let line = raw.trim();
if line.is_empty()
|| line.starts_with("note:")
|| line.starts_with("thread '")
|| line.starts_with("stack backtrace")
{
break;
}
body.push(line);
}
(!body.is_empty()).then(|| body.join("\n"))
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,105 @@
use super::*;
use crate::compression::parse_test_output;
#[test]
fn parses_cargo_libtest() {
let out = "running 3 tests\n\
test tests::skipped ... ignored\n\
test tests::ok_one ... ok\n\
test tests::fails_here ... FAILED\n\n\
thread 'tests::fails_here' (1) panicked at src/lib.rs:6:30:\n\
assertion `left == right` failed\n\n\
test result: FAILED. 1 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s\n";
let s = parse_test_output(out, "").unwrap();
assert_eq!((s.passed, s.failed, s.ignored), (1, 1, 1));
assert_eq!(s.failures.len(), 1);
assert_eq!(s.failures[0].name, "tests::fails_here");
assert_eq!(s.failures[0].location.as_deref(), Some("src/lib.rs:6:30"));
assert!(!s.ok());
}
#[test]
fn parses_nextest() {
let out = " PASS [ 0.002s] (1/2) ct tests::ok_one\n\
FAIL [ 0.002s] (2/2) ct tests::fails_here\n\
Summary [ 0.002s] 2 tests run: 1 passed, 1 failed, 1 skipped\n";
let s = parse_test_output(out, "").unwrap();
assert_eq!(s.framework, "nextest");
assert_eq!((s.passed, s.failed, s.ignored), (1, 1, 1));
assert_eq!(s.failures[0].name, "ct tests::fails_here");
}
/// Copied out of a real `cargo nextest run` artifact, because the defect lives in the gap
/// between the two name spellings nextest emits: the `FAIL [` line carries a binary id that
/// the panic's thread name does not. Matching them by equality found nothing, so every
/// nextest failure came back as a bare name and the assertion text stayed in the log file.
#[test]
fn nextest_failures_carry_their_location_and_assertion_text() {
let out = " FAIL [ 0.004s] (3/4) lazymail::bin/lazymail \
ui::statusbar::tests::pane_loading_uses_the_same_statusbar_spinner\n\
\x20 stderr \u{2500}\u{2500}\u{2500}\n\n\
\x20 thread 'ui::statusbar::tests::pane_loading_uses_the_same_statusbar_spinner' \
(4032629) panicked at src/ui/statusbar.rs:345:9:\n\
\x20 assertion failed: line_text(&build_status_line(&app, 80)).contains(\"\u{2502} \
Fetching message\u{2026}\")\n\
\x20 note: run with `RUST_BACKTRACE=1` environment variable to display a \
backtrace\n\
\x20 Summary [ 0.006s] 4 tests run: 3 passed, 1 failed, 901 skipped\n";
let summary = parse_test_output(out, "").expect("nextest output parses");
assert_eq!(summary.framework, "nextest");
assert_eq!((summary.passed, summary.failed), (3, 1));
let failure = &summary.failures[0];
assert_eq!(failure.location.as_deref(), Some("src/ui/statusbar.rs:345:9"));
let message = failure.message.as_deref().expect("the assertion text is the whole point");
assert!(message.starts_with("assertion failed:"), "{message}");
assert!(!message.contains("RUST_BACKTRACE"), "the trailer is not the failure: {message}");
assert!(summary.render().contains("src/ui/statusbar.rs:345:9"), "{}", summary.render());
}
/// The first line of an `assert_eq!` panic says nothing a reader did not already know; the
/// values under it are the reason to look.
#[test]
fn an_assert_eq_keeps_its_left_and_right_values() {
let out = "test tests::compares ... FAILED\n\
thread 'tests::compares' panicked at src/lib.rs:9:5:\n\
assertion `left == right` failed\n\
\x20 left: 1\n\
right: 2\n\
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\
test result: FAILED. 0 passed; 1 failed; 0 ignored;\n";
let summary = parse_test_output(out, "").expect("cargo output parses");
let message = summary.failures[0].message.as_deref().expect("a panic body");
assert!(message.contains("left: 1") && message.contains("right: 2"), "{message}");
// Every line of the body carries the indent, or the block stops reading as one failure.
let rendered = summary.render();
assert!(rendered.contains("\n left: 1"), "{rendered}");
}
/// The body stops at the runner's own trailers, each of which ends it on its own.
#[test]
fn a_panic_body_stops_at_every_trailer_that_ends_it() {
let lines = ["thread 'x' panicked at a.rs:1:1:", "the message"];
for trailer in ["", "note: run with `RUST_BACKTRACE=1`", "thread 'y' panicked at b.rs:2:2:"] {
let mut with_trailer = lines.to_vec();
with_trailer.push(trailer);
with_trailer.push("not part of the failure");
let body = panic_body(&with_trailer, 0).expect("a body");
assert_eq!(body, "the message", "stopped at {trailer:?}");
}
// `stack backtrace:` ends it too, and is the one trailer with no `note:` in front of it.
let backtrace = ["thread 'x' panicked at a.rs:1:1:", "stack backtrace:", " 0: core"];
assert_eq!(panic_body(&backtrace, 0), None, "a backtrace is not a message");
}
/// A name is matched by its tail, not by containment — `bar_foo` is not `foo`.
#[test]
fn a_panic_never_enriches_a_different_test_that_merely_ends_alike() {
assert!(names_same_test("ct tests::fails", "tests::fails"));
assert!(names_same_test("tests::fails", "tests::fails"));
assert!(!names_same_test("ct tests::bar_fails", "tests::fails"));
assert!(!names_same_test("ct tests::fails_later", "tests::fails"));
}

View File

@@ -0,0 +1,110 @@
//! Summary — a parsed test run, its model-facing rendering, and reading that rendering back.
use super::count_before;
/// A parsed test-run summary.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TestSummary {
/// Detected framework id (`cargo`, `nextest`, `pytest`, `go`, `jest`).
pub framework: String,
pub passed: usize,
pub failed: usize,
pub ignored: usize,
/// Failing tests, with best-effort location and message.
pub failures: Vec<TestFailure>,
}
/// A single failing test.
#[derive(Debug, PartialEq, Eq)]
pub struct TestFailure {
pub name: String,
pub location: Option<String>,
pub message: Option<String>,
}
impl TestSummary {
/// Whether the run passed (no failures).
pub fn ok(&self) -> bool {
self.failed == 0
}
/// A compact, model-facing rendering.
pub fn render(&self) -> String {
let verdict = if self.ok() { "ok" } else { "FAILED" };
let mut out = format!(
"{}: {verdict} — {} passed, {} failed, {} skipped",
self.framework, self.passed, self.failed, self.ignored
);
if !self.failures.is_empty() {
out.push_str("\nFailures:");
for failure in &self.failures {
out.push_str(&format!("\n ✗ {}", failure.name));
if let Some(loc) = &failure.location {
out.push_str(&format!(" ({loc})"));
}
// A panic body can be several lines (`assert_eq!`'s left/right), and each one
// has to carry the indent or the block stops reading as the failure's detail.
if let Some(msg) = &failure.message {
for line in msg.trim().lines() {
out.push_str(&format!("\n {line}"));
}
}
}
}
out
}
/// Reads back what [`Self::render`] wrote, wherever it sits in the `test` tool's reply, for a
/// front-end drawing a test card. Messages come back whole, but only what the reply carried.
/// The skipped count reads as `render` writes it, or as `ignored`, as older replies had it.
pub fn parse_rendered(text: &str) -> Option<Self> {
let mut lines = text.lines().skip_while(|line| !line.contains(" passed, "));
let head = lines.next()?;
let (framework, rest) = head.split_once(": ")?;
if framework.contains(' ') {
return None;
}
let counts = rest.split_once(" — ")?.1;
let mut summary = TestSummary {
framework: framework.to_string(),
passed: count_before(counts, "passed")?,
failed: count_before(counts, "failed")?,
ignored: ["skipped", "ignored"]
.iter()
.find_map(|w| count_before(counts, w))
.unwrap_or(0),
failures: Vec::new(),
};
if lines.next().map(str::trim) != Some("Failures:") {
return Some(summary);
}
for line in lines {
if let Some(entry) = line.strip_prefix(" ✗ ") {
let (name, location) = match entry.rsplit_once(" (") {
Some((name, location)) if location.ends_with(')') => {
(name, Some(location.trim_end_matches(')').to_string()))
}
_ => (entry, None),
};
summary.failures.push(TestFailure {
name: name.to_string(),
location,
message: None,
});
} else if let Some(detail) = line.strip_prefix(" ") {
let Some(failure) = summary.failures.last_mut() else { break };
let message = failure.message.get_or_insert_with(String::new);
if !message.is_empty() {
message.push('\n');
}
message.push_str(detail);
} else {
break;
}
}
Some(summary)
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,51 @@
use super::*;
use crate::compression::parse_test_output;
use crate::compression::reducers::javascript::tests::NODE_SPEC;
/// What `render` writes, `parse_rendered` reads back — from inside the `test` tool's whole
/// reply, with the command above it and notes below.
#[test]
fn a_rendered_summary_reads_back() {
let summary = parse_test_output(NODE_SPEC, "").expect("node");
let reply = format!("$ npm test\n{}\n\nFull output: x.log\n\nExit code: 1", summary.render());
assert_eq!(TestSummary::parse_rendered(&reply), Some(summary));
let green = TestSummary { framework: "cargo".into(), passed: 12, ..Default::default() };
assert_eq!(TestSummary::parse_rendered(&green.render()), Some(green));
assert_eq!(TestSummary::parse_rendered("$ npm test\nall good"), None);
}
/// The skipped count survives the trip: a literal summary as `render` writes it, and a rendered
/// one with failures and skips both read back with it.
///
/// The break this catches: `render` wrote `N skipped` and the parser looked for `ignored`, so every
/// test card drew zero skipped.
#[test]
fn a_rendered_summary_keeps_its_skipped_count() {
let literal = TestSummary::parse_rendered("cargo: ok — 12 passed, 0 failed, 3 skipped");
assert_eq!(literal.map(|summary| summary.ignored), Some(3));
let mut summary = parse_test_output(NODE_SPEC, "").expect("node");
summary.ignored = 4;
assert!(summary.failed > 0, "a summary with failures too");
assert_eq!(TestSummary::parse_rendered(&summary.render()), Some(summary));
let older = TestSummary::parse_rendered("cargo: ok — 1 passed, 0 failed, 2 ignored");
assert_eq!(older.map(|summary| summary.ignored), Some(2), "older output still reads");
}
/// The verdict word every rendering leads with.
#[test]
fn a_run_is_ok_only_with_no_failures() {
let mut summary = TestSummary { passed: 3, ..Default::default() };
assert!(summary.ok());
assert!(summary.render().contains("ok —"));
summary.failed = 1;
assert!(!summary.ok());
assert!(summary.render().contains("FAILED —"));
}
#[test]
fn renders_compact_summary() {
let out = "test tests::a ... FAILED\ntest result: FAILED. 0 passed; 1 failed; 0 ignored;\n";
let rendered = parse_test_output(out, "").unwrap().render();
assert!(rendered.contains("cargo: FAILED — 0 passed, 1 failed"));
assert!(rendered.contains("✗ tests::a"));
}

View File

@@ -0,0 +1,62 @@
use super::*;
#[test]
fn detects_test_commands() {
assert!(is_test_command(&CommandInvocation::parse("cargo test")));
assert!(is_test_command(&CommandInvocation::parse("cargo nextest run")));
assert!(is_test_command(&CommandInvocation::parse("go test ./...")));
assert!(is_test_command(&CommandInvocation::parse("pytest -q")));
assert!(is_test_command(&CommandInvocation::parse("python3 -m pytest")));
assert!(is_test_command(&CommandInvocation::parse("npm test")));
// Both runners `npx` fronts, and neither of them is every `npx` invocation.
assert!(is_test_command(&CommandInvocation::parse("npx jest")));
assert!(is_test_command(&CommandInvocation::parse("npx vitest run")));
assert!(!is_test_command(&CommandInvocation::parse("npx tsc")));
// How models run Django's suite, and a Django project's
assert!(is_test_command(&CommandInvocation::parse(
"cd tests && ../.venv/bin/python runtests.py --settings=test_sqlite x 2>&1 | tail -5"
)));
assert!(is_test_command(&CommandInvocation::parse("./tests/runtests.py admin_views")));
assert!(is_test_command(&CommandInvocation::parse("python3.8 manage.py test app")));
assert!(is_test_command(&CommandInvocation::parse("python -m django test")));
assert!(!is_test_command(&CommandInvocation::parse("python manage.py migrate")));
assert!(!is_test_command(&CommandInvocation::parse("python setup.py build")));
assert!(!is_test_command(&CommandInvocation::parse("cargo build")));
assert!(!is_test_command(&CommandInvocation::parse("ls -la")));
}
/// The reducer is how `bash "cargo test"` gets the same summary the `test` tool renders, so
/// its routing and its output are both load-bearing.
#[test]
fn the_reducer_claims_test_commands_and_renders_their_summary() {
let reducer = TestReducer;
assert_eq!(reducer.id(), "test");
assert!(reducer.can_handle(&CommandInvocation::parse("cargo test")));
assert!(!reducer.can_handle(&CommandInvocation::parse("cargo build")));
let output = CommandOutput {
stdout: "test tests::a ... FAILED\ntest result: FAILED. 0 passed; 1 failed; 0 \
ignored;\n"
.into(),
stderr: String::new(),
exit_code: Some(101),
};
let reduced = reducer.reduce(&CommandInvocation::parse("cargo test"), &output);
assert!(reduced.contains("1 failed"), "the summary survives the reducer: {reduced}");
assert!(reduced.contains("tests::a"), "{reduced}");
}
/// nextest prints each failure twice — once inline, once in the closing list.
#[test]
fn a_failure_named_twice_is_listed_once() {
let out = " FAIL [ 0.002s] (1/1) ct tests::boom\n\
Summary [ 0.002s] 1 test run: 0 passed, 1 failed, 0 skipped\n\
\x20 FAIL [ 0.002s] (1/1) ct tests::boom\n";
let s = parse_test_output(out, "").expect("nextest output parses");
assert_eq!(s.failures.len(), 1, "{:?}", s.failures);
}
#[test]
fn unknown_output_does_not_parse() {
assert!(parse_test_output("just some logs\nno test markers\n", "").is_none());
}

View File

@@ -0,0 +1,232 @@
//! Deterministic text-reduction stages for tool output.
//!
//! Each stage is a pure function over lines/text so the pipeline is testable with golden inputs and
//! never depends on an LLM. Order in the generic pipeline: strip ANSI → collapse carriage returns →
//! drop progress noise → dedupe consecutive → collapse blank runs → important-preserving truncate.
/// Strips ANSI/VT escape sequences (CSI `ESC [ … final`, OSC `ESC ] … BEL|ESC\`, and lone escapes).
/// Terminal color/cursor codes are pure noise to a model, so this is always safe to apply.
pub(super) fn strip_ansi(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
while let Some(c) = chars.next() {
if c != '\u{1b}' {
out.push(c);
continue;
}
match chars.peek() {
// CSI: parameters/intermediates until a final byte in 0x40..=0x7e.
Some('[') => {
chars.next();
while let Some(&next) = chars.peek() {
chars.next();
if ('\u{40}'..='\u{7e}').contains(&next) {
break;
}
}
}
// OSC: string terminated by BEL or ESC\.
Some(']') => {
chars.next();
while let Some(&next) = chars.peek() {
if next == '\u{07}' {
chars.next();
break;
}
if next == '\u{1b}' {
chars.next();
if chars.peek() == Some(&'\\') {
chars.next();
}
break;
}
chars.next();
}
}
// Any other two-character escape (e.g. ESC c).
Some(_) => {
chars.next();
}
None => {}
}
}
out
}
/// Keeps the final rendered segment of a line that used carriage returns to overwrite itself
/// (progress bars, spinners). A line without `\r` is returned unchanged.
pub(super) fn collapse_carriage_returns(line: &str) -> &str {
if !line.contains('\r') {
return line;
}
line.split('\r').rfind(|segment| !segment.is_empty()).unwrap_or("")
}
pub(super) fn collapse_blank_lines(lines: Vec<String>) -> Vec<String> {
let mut out = Vec::with_capacity(lines.len());
let mut prev_blank = false;
for line in lines {
let blank = line.trim().is_empty();
if blank && prev_blank {
continue;
}
prev_blank = blank;
out.push(line);
}
out
}
/// Collapses consecutive identical lines into one, annotating the repeat count (`… (×N)`).
/// Repeated warnings and progress spam collapse to a single line without losing the fact of repeat.
pub(super) fn dedupe_consecutive(lines: Vec<String>) -> Vec<String> {
let mut out: Vec<String> = Vec::with_capacity(lines.len());
let mut run: Option<(String, usize)> = None;
let flush = |out: &mut Vec<String>, line: String, count: usize| {
if count > 1 {
out.push(format!("{line} … (×{count})"));
} else {
out.push(line);
}
};
for line in lines {
match run.take() {
Some((prev, count)) if prev == line => run = Some((prev, count + 1)),
Some((prev, count)) => {
flush(&mut out, prev, count);
run = Some((line, 1));
}
None => run = Some((line, 1)),
}
}
if let Some((prev, count)) = run {
flush(&mut out, prev, count);
}
out
}
/// Drops lines that are pure progress indicators (spinner/braille/block glyphs or percent bars)
/// unless `is_important` keeps them.
pub(super) fn filter_progress(
lines: Vec<String>,
is_important: impl Fn(&str) -> bool,
) -> Vec<String> {
lines.into_iter().filter(|line| is_important(line) || !is_progress_noise(line)).collect()
}
/// Heuristic: a line dominated by spinner/bar glyphs or a bare percentage.
fn is_progress_noise(line: &str) -> bool {
let trimmed = line.trim();
if trimmed.is_empty() {
return false;
}
const GLYPHS: &[char] = &[
'\u{2807}', '\u{2827}', '\u{2837}', '\u{280b}', '\u{280f}', '\u{2819}', '\u{2839}',
'\u{2838}', '\u{283c}', '\u{2834}', '\u{2826}', // braille spinner frames
'\u{2588}', '\u{2589}', '\u{258a}', '\u{258b}', '\u{258c}', '\u{258d}', '\u{258e}',
'\u{258f}', '\u{2591}', '\u{2592}', '\u{2593}', // block bar chars
];
if trimmed.chars().any(|c| GLYPHS.contains(&c)) {
return true;
}
// A line that is essentially just "NN%".
let core: String = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
core.ends_with('%') && core[..core.len() - 1].chars().all(|c| c.is_ascii_digit())
}
/// When `lines` exceeds `max_lines`, keeps the head, every important line, and the tail, inserting
/// `… N lines omitted …` markers for the gaps. Signal (errors, file:line, failures) survives
/// regardless of where it sits in a long log — unlike a blind head/tail cut.
pub(super) fn truncate_preserving(
lines: Vec<String>,
is_important: impl Fn(&str) -> bool,
head: usize,
tail: usize,
max_lines: usize,
) -> Vec<String> {
if lines.len() <= max_lines {
return lines;
}
let total = lines.len();
let head_end = head.min(total);
let tail_start = total.saturating_sub(tail).max(head_end);
let mut keep = vec![false; total];
for k in keep.iter_mut().take(head_end) {
*k = true;
}
for (index, k) in keep.iter_mut().enumerate().take(tail_start).skip(head_end) {
if is_important(&lines[index]) {
*k = true;
}
}
for k in keep.iter_mut().take(total).skip(tail_start) {
*k = true;
}
let mut out = Vec::new();
let mut omitted = 0usize;
for (index, line) in lines.into_iter().enumerate() {
if keep[index] {
if omitted > 0 {
out.push(format!("… {omitted} lines omitted …"));
omitted = 0;
}
out.push(line);
} else {
omitted += 1;
}
}
if omitted > 0 {
out.push(format!("… {omitted} lines omitted …"));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_csi_and_osc() {
assert_eq!(strip_ansi("\u{1b}[31merror\u{1b}[0m here"), "error here");
assert_eq!(strip_ansi("\u{1b}]0;title\u{07}body"), "body");
assert_eq!(strip_ansi("plain"), "plain");
}
#[test]
fn carriage_returns_keep_final_frame() {
assert_eq!(collapse_carriage_returns("10%\r50%\r100%"), "100%");
assert_eq!(collapse_carriage_returns("no cr"), "no cr");
}
#[test]
fn collapses_blank_runs() {
let input = vec!["a".into(), "".into(), "".into(), "".into(), "b".into()];
assert_eq!(collapse_blank_lines(input), vec!["a", "", "b"]);
}
#[test]
fn dedupes_consecutive_with_count() {
let input = vec!["warn".into(), "warn".into(), "warn".into(), "ok".into()];
assert_eq!(dedupe_consecutive(input), vec!["warn … (×3)", "ok"]);
}
#[test]
fn drops_progress_keeps_signal() {
let input = vec!["\u{2588}\u{2588}\u{2588} 40%".into(), "error: boom".into(), "75%".into()];
let out = filter_progress(input, |l| l.contains("error"));
assert_eq!(out, vec!["error: boom"]);
}
#[test]
fn truncate_preserves_head_tail_and_important() {
let mut lines: Vec<String> = (0..100).map(|i| format!("line {i}")).collect();
lines[50] = "error: important".into();
let out = truncate_preserving(lines, |l| l.contains("error"), 5, 5, 20);
let joined = out.join("\n");
assert!(joined.contains("line 0"), "head kept");
assert!(joined.contains("line 99"), "tail kept");
assert!(joined.contains("error: important"), "mid-log signal kept");
assert!(joined.contains("lines omitted"), "omission marker present");
}
}