Skip to content

The agent that grows with you

fix(terminal): warn when exit_code 0 masks a piped build/test failure

Teknium8ad055414bca
diff --git a/tests/tools/test_terminal_hints.py b/tests/tools/test_terminal_hints.py
index c3d08db2bc6..fe2857f40fe 100644
--- a/tests/tools/test_terminal_hints.py
+++ b/tests/tools/test_terminal_hints.py
@@ -5,7 +5,7 @@ from unittest.mock import patch as mock_patch
import pytest
-from tools.terminal_hints import annotate_failure
+from tools.terminal_hints import annotate_failure, annotate_masked_success
class TestAnnotateFailureBasics:
@@ -120,3 +120,129 @@ class TestTerminalIntegration:
# table still covers it.
from tools import terminal_tool
assert terminal_tool._interpret_exit_code("grep foo bar.txt", 1) is not None
+
+
+class TestMaskedSuccess:
+ """annotate_masked_success: exit-0 pipelines that hide real failures."""
+
+ def _fail_out(self):
+ return (
+ "error[E0308]: mismatched types\n"
+ "error: could not compile `llama_manager` due to 11 previous errors\n"
+ )
+
+ def test_cargo_pipe_tail_flagged(self):
+ hint = annotate_masked_success(
+ "cargo build --release 2>&1 | tail -20", self._fail_out()
+ )
+ assert hint and "last pipeline command" in hint
+
+ def test_pipe_head_flagged(self):
+ hint = annotate_masked_success("cargo check | head -50", self._fail_out())
+ assert hint is not None
+
+ def test_or_echo_fallback_flagged(self):
+ hint = annotate_masked_success(
+ 'cargo build || echo "BUILD FAILED"',
+ "error: could not compile `x`\nBUILD FAILED\n",
+ )
+ assert hint and "||" in hint
+
+ def test_or_true_flagged(self):
+ hint = annotate_masked_success(
+ "pytest tests/ || true",
+ "FAILED tests/test_x.py::test_y - AssertionError\n= 3 failed in 1.2s\n",
+ )
+ assert hint is not None
+
+ def test_bare_command_not_flagged(self):
+ # No pipe, no ||: exit 0 with error-looking output is not our call.
+ assert annotate_masked_success("cargo build", self._fail_out()) is None
+
+ def test_clean_output_pipe_not_flagged(self):
+ assert (
+ annotate_masked_success(
+ "cargo build 2>&1 | tail -20",
+ " Compiling llama_manager v0.1.0\n Finished release\n",
+ )
+ is None
+ )
+
+ def test_grep_pipeline_excluded(self):
+ # Search output legitimately CONTAINS failure text; grep|head exit 0
+ # is a real success (matches found).
+ assert (
+ annotate_masked_success(
+ "grep -rn 'error\\[E' build.log | head -20",
+ "build.log:12:error[E0308]: mismatched types\n",
+ )
+ is None
+ )
+
+ def test_rg_pipeline_excluded(self):
+ assert (
+ annotate_masked_success(
+ "rg 'could not compile' logs/ | tail -5",
+ "logs/b.txt:error: could not compile `x`\n",
+ )
+ is None
+ )
+
+ def test_pipe_into_grep_not_flagged(self):
+ # grep as CONSUMER filters and its exit status is meaningful
+ # (0 = matched) — not a passthrough truncation consumer.
+ assert (
+ annotate_masked_success(
+ "cargo build 2>&1 | grep -c error",
+ "error[E0308]: mismatched types\n",
+ )
+ is None
+ )
+
+ def test_or_operator_alone_not_confused_with_pipe(self):
+ # `a || b` must not match the single-pipe regex.
+ assert (
+ annotate_masked_success(
+ "test -f x || stat y",
+ "error[E0308]\n", # would need a masking shape too
+ )
+ is None
+ )
+
+ def test_generic_error_word_not_enough(self):
+ # Weak signal ("error" substring) must not fire the note.
+ assert (
+ annotate_masked_success(
+ "make install 2>&1 | tail -30",
+ "checking error handling support... yes\nInstall complete.\n",
+ )
+ is None
+ )
+
+ def test_pytest_summary_via_tee(self):
+ hint = annotate_masked_success(
+ "pytest tests/ | tee /tmp/out.log",
+ "FAILED tests/a.py::test_b\n=========== 2 failed, 10 passed ===========\n",
+ )
+ assert hint is not None
+
+ def test_empty_inputs(self):
+ assert annotate_masked_success("", "") is None
+ assert annotate_masked_success("cargo build | tail", "") is None
+ assert annotate_masked_success("", "error[E0308]") is None
+
+ def test_echo_printf_heads_excluded(self):
+ assert (
+ annotate_masked_success(
+ "printf 'a.rs:1:error[E0308]: x\\n' | cat | tail -3",
+ "a.rs:1:error[E0308]: x\n",
+ )
+ is None
+ )
+ assert (
+ annotate_masked_success(
+ 'echo "error: could not compile x" | tee log.txt',
+ "error: could not compile x\n",
+ )
+ is None
+ )
diff --git a/tools/terminal_hints.py b/tools/terminal_hints.py
index 8410b3e645c..7c0176d1512 100644
--- a/tools/terminal_hints.py
+++ b/tools/terminal_hints.py
@@ -145,6 +145,111 @@ _EXIT_CODE_HINTS: dict[int, str] = {
}
+# ---------------------------------------------------------------------------
+# Masked-success detection (exit 0 that probably isn't a success)
+# ---------------------------------------------------------------------------
+#
+# `cargo build 2>&1 | tail -20` exits with tail's 0 even when the build
+# failed: bash (without pipefail) reports the LAST pipeline command's status.
+# Likewise `cargo build || echo "BUILD FAILED"` exits with echo's 0. The
+# model treats exit_code 0 as a strong success signal, so it can conclude a
+# build passed while the visible output says it failed. OpenCode's answer is
+# prompt-side only ("do NOT pipe through head/tail"); this adds a cheap
+# result-side backstop for when the model pipes anyway.
+#
+# Deliberately conservative — BOTH must hold:
+# 1. the command's shape can mask an upstream status (a top-level pipe into
+# a passthrough/truncation consumer, or a `|| <cheap fallback>`), and
+# 2. the output contains a strong, tool-specific failure shape (rustc /
+# pytest / gcc / npm / tracebacks), not a generic "error" substring.
+# Search/read-only pipelines (`grep ... | head`) are excluded: their output
+# legitimately CONTAINS error text without anything having failed.
+#
+# The note is advisory metadata only — exit_code itself is never modified.
+
+# Consumers whose exit status says nothing about the upstream command.
+_PASSTHROUGH_CONSUMERS = r"(?:tail|head|cat|tee|less|more|wc|sort|uniq)"
+
+# Top-level `... | tail -20` (not `||`); consumer must be the LAST segment.
+_MASKING_PIPE_RE = re.compile(
+ r"(?<!\|)\|(?!\|)\s*" + _PASSTHROUGH_CONSUMERS + r"\b[^|]*$"
+)
+
+# `cmd || echo ...` / `cmd || true` — fallback swallows the failure status.
+_MASKING_OR_RE = re.compile(r"\|\|\s*(?:echo\b|printf\b|true\b|:\s|:$)")
+
+# Read/search/content-producing heads whose piped output legitimately
+# contains failure text (search results, log reads, echoed strings) —
+# nothing upstream can meaningfully "fail" in the masked sense.
+_READONLY_HEADS = frozenset({
+ "grep", "rg", "ag", "find", "ls", "cat", "head", "tail", "jq", "awk",
+ "sed", "strings", "zcat", "journalctl", "dmesg", "echo", "printf",
+})
+
+# Strong failure shapes. Keyed to specific tools so that error-mentioning
+# *content* (diffs, logs being read, commit messages) rarely matches.
+_FAILURE_SHAPES = re.compile(
+ r"(?:"
+ r"error\[E\d+\]" # rustc
+ r"|error: could not compile" # cargo
+ r"|error: aborting due to" # rustc summary
+ r"|Traceback \(most recent call last\)" # python
+ r"|(?m:^(?:=+ )?\d+ failed)" # pytest summary
+ r"|(?m:^FAILED (?:\S+::|\S+\.py))" # pytest per-test lines
+ r"|compilation terminated\." # gcc/clang
+ r"|npm ERR!" # npm
+ r"|BUILD FAILED|Build FAILED" # gradle/msbuild/echoed fallbacks
+ r"|FAILED: " # ninja
+ r"|(?m:^make(?:\[\d+\])?: \*\*\*)" # make
+ r")"
+)
+
+
+def _first_token(command: str) -> str:
+ for tok in (command or "").strip().split():
+ # Skip env-var assignments and common wrappers.
+ if "=" in tok and not tok.startswith(("=", "./", "/")):
+ continue
+ return tok.rsplit("/", 1)[-1]
+ return ""
+
+
+def annotate_masked_success(command: str, output: str) -> Optional[str]:
+ """Return a warning note when an exit-0 result likely masks a failure.
+
+ Fires only for exit_code == 0 results (caller gates on that) whose
+ command shape can swallow an upstream failure status AND whose output
+ carries a strong tool-specific failure shape. Returns None otherwise.
+ Never modifies the exit code — advisory only.
+ """
+ cmd = command or ""
+ window = (output or "")[:_SCAN_CHARS]
+ if not cmd or not window:
+ return None
+ if _first_token(cmd) in _READONLY_HEADS:
+ return None
+ if not _FAILURE_SHAPES.search(window):
+ return None
+ if _MASKING_PIPE_RE.search(cmd):
+ return (
+ "exit_code 0 here is the status of the last pipeline command "
+ "(tail/head/cat/...), NOT of the command before the pipe — and "
+ "the output contains failure indicators. Treat this run as "
+ "FAILED until proven otherwise: re-run the command WITHOUT the "
+ "pipe (output is auto-truncated and the full text is saved to a "
+ "file, so piping through tail/head is never needed) to get the "
+ "real exit code."
+ )
+ if _MASKING_OR_RE.search(cmd):
+ return (
+ "exit_code 0 here is the status of the `||` fallback (echo/true), "
+ "NOT of the command before it — and the output contains failure "
+ "indicators. Treat this run as FAILED until proven otherwise: "
+ "re-run the command bare to get its real exit code."
+ )
+ return None
+
+
def annotate_failure(command: str, exit_code: int, output: str) -> Optional[str]:
"""Return one short recovery hint for a failed command, or None.
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 5249d1fdc99..492cdab0925 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -1078,6 +1078,7 @@ import sys
TERMINAL_TOOL_DESCRIPTION = """Execute shell commands on a Linux environment. Filesystem, current working directory, and exported environment variables persist between calls.
Do NOT use cat/head/tail (use read_file), grep/rg/find/ls (use search_files), sed/awk (use patch), or echo/heredoc file creation (use write_file). Reserve terminal for: builds, installs, git, processes, scripts, network, package managers, and anything that needs a shell.
+NEVER pipe a build/test command through tail/head/cat to shorten output (e.g. `cargo build | tail -20`): output is auto-truncated with the full text saved to a file, and the pipe makes exit_code report the LAST pipeline command's status (tail's 0), masking real failures. Run the command bare; the same applies to `cmd || echo failed`, which also masks the exit code.
Environment state persists: activate a virtualenv or export variables once per session, not before every command.
Foreground (default): returns INSTANTLY when the command finishes, even with a high timeout — set timeout generously for long builds.
@@ -3423,6 +3424,19 @@ def terminal_tool(
failure_hint = annotate_failure(command, returncode, output)
except Exception:
failure_hint = None
+ elif returncode == 0:
+ # Masked-success backstop: `cargo build | tail -20` returns
+ # tail's exit 0 even when the build failed (bash reports the
+ # last pipeline command's status; same for `cmd || echo ...`).
+ # When the command shape can mask an upstream failure AND the
+ # output carries strong failure indicators, warn the model so
+ # exit_code 0 isn't read as a success signal. Advisory only —
+ # the exit code itself is never modified.
+ try:
+ from tools.terminal_hints import annotate_masked_success
+ failure_hint = annotate_masked_success(command, output)
+ except Exception:
+ failure_hint = None
result_dict = {
"output": output,