AI Coding Agents
Build a test output triage filter for coding agents
Coding agent test output filtering keeps the exit status, representative failures, and exact recovery coordinates in the conversation while storing the original output separately. Use it for repeatable test and build commands with recognizable diagnostics, and let the agent fetch narrow line ranges from the original whenever it needs a traceback, an earlier warning, or the sequence of events.
Why raw output costs twice
A coding agent can use one tool result to find a failing test and then carry the rest of that result into requests for the patch, the next test run, and the review. The marginal bill depends on how the host sends history. Claude Code documents that it resends the existing conversation on subsequent requests and pays the cached rate when the prefix can be reused. An unchanged log can therefore contribute input charges on multiple requests. The examples below count only requests that actually include the output. Claude Code prompt caching
The second cost is diagnostic. A failed checkout assertion can sit beside successful checkout tests, a warning from an earlier phase, and another failure that prints the same assertion. Those lines compete for the agent’s attention in different ways. Chroma’s July 2025 Context Rot study distinguished unrelated context from topically related distractors. In its retrieval experiments, adding a distractor lowered performance relative to the no-distractor condition, and adding several lowered it further. The study evaluated models including GPT-4.1, Claude Sonnet 4, and Gemini 2.5 Flash. It motivates testing whether similar but irrelevant log lines confuse your agent. Measure that on your own failures before assuming an accuracy gain. Chroma Context Rot
Start with a job the agent runs repeatedly during a fix. In a checkout suite, a concise first result should direct the agent to the failing currency assertion and tell it whether the same diagnostic appeared in several cases. When those cases differ in setup, a fetched slice can reveal the difference. This division gives the agent enough evidence to choose a next tool call while preserving the original chronology for investigation.
Define what the wrapper returns
Return the child’s exit status, a log handle, and a bounded summary. Treat the exit status and the diagnostic signatures as independent signals. A successful command can emit warning-like or error-like text, and a failed process can end before it prints a recognized diagnostic. The exit status reports how the process ended. The summary helps decide where to read.
| Output feature | Summary treatment | Recovery decision |
|---|---|---|
| Terminal escapes and recognized progress | Strip ANSI sequences from the summary and skip recognized progress lines | Read the original if rendering or timing is part of the investigation |
| Recognized passing tests | Skip individual pass lines | Read nearby lines if order or shared setup could explain the failure |
| Repeated error signatures | Count exact matches and retain the first representative range | Inspect other occurrences when different cases may require separate fixes |
| Repeated stack frames | Keep a few distinct recent frames | Read the raw range before drawing conclusions from omitted frames |
| Unrecognized output | Keep a short numbered tail when no group matches | Switch to passthrough if the tail fails to explain the exit status |
The signature is a grouping key, a candidate root error for triage. Two unrelated tests can emit the same assertion text. Conversely, the same defect can produce different diagnostics when file names or values vary. Keep the full signature as the grouping key and truncate its displayed form for the summary. Add runner-specific normalization only after comparing examples where the same wording means different things. Aggressive normalization can hide those distinctions.
Capture the full log and summarize the failure
This reference implementation uses Python’s standard library. Save the next two blocks in order as triage.py. Run it with an existing private log directory and the intended executable and arguments after --, for example python3 triage.py --log-dir ./agent-logs -- pytest. The wrapper uses an argument list and captures standard output and standard error in one file. Use ordinary runner options or environment settings to select output formats your fixtures cover.
import argparse
import json
import re
import subprocess
import sys
from collections import deque
from pathlib import Path
from tempfile import NamedTemporaryFile
ANSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
NOISE = re.compile(
r"^\s*(?:PROGRESS\b|test .+ \.\.\. ok$|\S+::\S+ PASSED(?:\s|$)"
r"|[.s]+\s+\[\s*\d+%\]$)"
)
FRAME = re.compile(r'^\s+(?:File ".+", line \d+|\d+: .+|at .+)')
ERROR = re.compile(
r"^\s*(?:E\s+(?P<pytest>\w+(?:Error|Exception):.*)"
r"|thread '.+'(?: \(\d+\))? panicked at (?P<cargo>.+)"
r"|(?:.+?:\s*)?(?P<compiler>error TS\d+:\s*.+)"
r"|(?P<build>(?:npm (?:ERR!|error)|error(?:\[\w+\])?:)\s*.+))"
)
def summarize(lines, returncode, full_log_path):
# shortcut: patterns cover common shapes, add fixtures for each runner mode.
groups = {}
omitted_signatures = 0
frames = deque(maxlen=3)
tail = deque(maxlen=4)
for number, raw in enumerate(lines, 1):
line = ANSI.sub("", raw.decode("utf-8", errors="replace")).strip("\r\n")
if not line.strip() or NOISE.match(line):
continue
tail.append([number, line[:200]])
if FRAME.match(line):
frame = line.strip()[:160]
if all(old != frame for _, old in frames):
frames.append((number, frame))
continue
match = ERROR.match(line)
if match:
key = next(value.strip() for value in match.groupdict().values()
if value is not None)
if key in groups:
groups[key]["count"] += 1
elif len(groups) < 5:
start = frames[0][0] if frames else max(1, number - 2)
groups[key] = {
"signature": key[:200],
"count": 1,
"lines": [max(start, number - 39), number + 2],
"frames": [frame for n, frame in frames if n >= number - 39],
}
else:
omitted_signatures += 1
frames.clear()
return {
"returncode": returncode,
"full_log_path": full_log_path,
"groups": list(groups.values()),
"unlisted_matches": omitted_signatures,
"fallback_tail": list(tail) if not groups else [],
}
The parser recognizes selected pytest error lines, Cargo panic or compiler diagnostics, npm error diagnostics, and TypeScript error codes in build output. For a Cargo panic, the text after the panic header becomes the signature, so two tests can point to the same location. Read the following line in the raw log when the panic message lives there. The parser associates recent stack frames by proximity and preserves a representative line range. That range points back to raw lines, including skipped lines in the middle, so the agent can check whether those frames really belong to the selected diagnostic.
A named temporary file keeps simultaneous command runs from reusing the same log path. The code records bytes before summarizing, and its failure exit preserves the child status for shell callers. The JSON line on standard output is still useful when the process exits nonzero. Have your tool host collect both signals so an ordinary test failure doesn’t discard the result that explains it.
def run_command(command, log_dir, passthrough=False):
if not command:
raise ValueError("expected a command")
with NamedTemporaryFile(dir=log_dir, suffix=".log", delete=False) as log:
result = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT,
check=False)
path = Path(log.name)
if passthrough:
return {"returncode": result.returncode, "full_log_path": path.name,
"output": path.read_bytes().decode("utf-8", errors="replace")}
with path.open("rb") as log:
return summarize(log, result.returncode, path.name)
def read_log_slice(log_dir, allowed, path, start, end):
if path not in allowed or Path(path).name != path:
raise ValueError("unknown log")
if type(start) is not int or type(end) is not int or not 1 <= start <= end:
raise ValueError("expected one-based inclusive line bounds")
if end - start >= 100:
raise ValueError("request at most 100 lines")
with (log_dir / path).open("rb") as log:
for number in range(1, end + 1):
raw = log.readline(65537)
if len(raw) > 65536:
raise ValueError("line exceeds retrieval limit")
if not raw:
break
if number >= start:
yield number, raw.decode("utf-8", errors="replace")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--log-dir", type=Path, required=True)
parser.add_argument("--passthrough", action="store_true")
parser.add_argument("command", nargs=argparse.REMAINDER)
args = parser.parse_args()
command = args.command
if command and command[0] == "--":
command = command[1:]
if not command:
parser.error("supply a command after --")
result = run_command(command, args.log_dir, args.passthrough)
print(json.dumps(result, ensure_ascii=False, separators=(",", ":")))
code = result["returncode"]
return 128 - code if code < 0 else code
if __name__ == "__main__":
sys.exit(main())
Keep the log directory private to the tool host and register each returned basename only for the session that ran the command. This design lets the model select a registered log and specify a range. The host supplies the trusted directory and allowlist. Treat logs as potentially sensitive workspace artifacts and apply the same access and retention policy you would use for unfiltered tool output. The reference scans from the beginning for each slice. If frequent reads reach deep into very large logs, index byte offsets when capturing the output.
A common misclassification occurs when several tests fail during setup and the runner later prints assertion failures. Add a fixture that includes both events in order. Require the agent to recover the setup section before it edits the assertion, and decide whether to add a dedicated setup diagnostic pattern. Keep parser rules specific enough that a line reporting that a check passed cannot swallow an error emitted on a different line. When a runner changes its output format, the numbered tail and saved original give you somewhere to start checking the new format.
Give the agent a narrow recovery tool
Register this JSON tool definition as read_log_slice.json. The tool name and argument meanings belong to this reference design. A host can call the Python function with the model’s three arguments plus the host-controlled directory and allowlist. The function yields numbered decoded lines and retains their original whitespace and ANSI escapes. The raw file remains the authority if the bytes need to be inspected directly. Invalid UTF-8 is displayed using replacement characters.
{
"name": "read_log_slice",
"description": "Read exact lines from a log registered for this session.",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "The returned full_log_path."},
"start": {"type": "integer", "minimum": 1},
"end": {"type": "integer", "minimum": 1}
},
"required": ["path", "start", "end"],
"additionalProperties": false
}
}
The range is one-based and inclusive. A range extending beyond the last line returns the lines available. The implementation caps the number of requested lines and rejects oversized lines while scanning. If a command produces long, unbroken records, use a byte-window reader or a runner-specific parser for those logs. Serialize numbered lines in your tool response so the model can quote the location of the evidence it used. Treat text inside retrieved output as diagnostic data, just as you would with a raw command result.
Use the first run of an unfamiliar failure in passthrough mode when the diagnostic may depend on setup, ordering, or several interleaved stack traces. For a flaky test, preserve separate attempts and compare their full relevant sequences before adopting a grouping rule. A passing retry can be evidence about the original failure. Once the failure shape is understood and the same suite runs repeatedly to check patches, use the summary and request slices as needed. If a parser’s summary repeatedly sends the agent back to most of the log, keep that runner on passthrough until the parser improves.
Measure the reduction and price later turns
Save the program below as sample_log.py alongside triage.py. It generates a synthetic pytest-shaped log with repeated passes, progress text, two failures with the same assertion, repeated frames, and ANSI coloring. With a private agent-logs directory already in place, run python3 triage.py --log-dir ./agent-logs -- python3 sample_log.py. Expect exit status 1 and a single failure group with a count of two. Use the returned log handle to open the saved output and compare it with the JSON printed to standard output.
import sys
for index in range(450):
print(f"tests/test_checkout.py::test_cart_{index:03} PASSED [ 82%]")
print("PROGRESS finishing captured checks")
for test in ("test_guest", "test_member"):
print(f"________ {test} ________")
print(' File "tests/test_checkout.py", line 41, in test_checkout')
for _ in range(3):
print(' File "checkout.py", line 18, in total')
print("\x1b[31mE AssertionError: expected USD, got EUR\x1b[0m")
print("2 failed, 450 passed")
sys.exit(1)
On that fixture, the raw UTF-8 text had 23,991 characters across 464 lines. The compact JSON result had 297 characters before the final newline, including the log handle. The representative range was lines 453 through 459. Dividing the character counts by four and rounding gives rough estimates of 5,998 and 74 tokens respectively. ANSI codes, punctuation, and paths can tokenize differently. Use request usage to evaluate an actual rollout. The character counts describe this fixture, including its deliberate repetition.
Assume the log remains visible on 12 later requests. The incremental cost estimate is estimated log tokens multiplied by the sum of the applicable per-million rates across those requests, divided by one million. For Claude Sonnet 5.5 as of November 30, 2026, use $2 per million base input tokens, $0.10 per million cache read tokens, and $2.50 per million five-minute cache write tokens. Exclude other prompt content, generated output, tool definitions, and any follow-up slices. Anthropic pricing · ByteCosts pricing index
| Treatment on 12 later requests | Raw log estimate | Summary estimate | Savings estimate |
|---|---|---|---|
| 12 base-price input sends | $0.143952 | $0.001776 | $0.142176 |
| 12 cache reads of an already written prefix | $0.007198 | $0.000089 | $0.007109 |
| One five-minute cache write, then 11 reads | $0.021593 | $0.000266 | $0.021326 |
Treat these rows as separate scenarios. They describe different outcomes for the prefix that holds the log. A recovered slice adds fresh input when the agent receives it and can add charges on later requests that retain it. Include the cumulative size and frequency of those retrievals when comparing options. A useful trial records how often the agent identifies the right failure from the summary, how often it fetches evidence, and whether it selects the correct next test. Evaluate those results alongside input usage.
Connect the filter to Claude Code and run a trial
As of November 30, 2026, Claude Code’s costs page describes grepping for ERROR and shows a separate PreToolUse example whose Bash matcher runs the hook before every Bash tool call. The script uses a regular expression to select supported forms of npm test, pytest, and go test. It rewrites matching commands through updatedInput to keep the last 100 lines. A project adapting the pattern for cargo test and npm run build should verify the command shape and preserve its authorized arguments and exit behavior. Start by invoking the wrapper explicitly from the agent rather than trying to rewrite arbitrary shell syntax. Claude Code costs · Claude Code hooks
The hooks reference distinguishes PostToolUse, ordinarily after a successful call, from PostToolUseFailure, after tool execution fails. It documents updatedToolOutput on PostToolUse for replacement and additionalContext for adding context alongside the result. Capture the log during command execution if you need the earliest output and a durable recovery path on failure. Test that path with an intentionally failing command and check that the next agent turn still receives its status and log pointer. Claude Code hooks
Run the trial on a routine regression, an unfamiliar compiler failure, and a flaky test. For each run, record which line justified the next action and whether that line was available from the summary or a targeted slice. Keep automatic filtering for cases where the agent can recover evidence quickly and maintain the same diagnostic quality. Use the reversible context compression guide to evaluate retrieval overhead, then carry the exact assertion and log range into a structured compaction checkpoint when changing phases. Use the context rot guide to structure the quality comparison.
Sources
- Context Rot (Chroma, accessed 2026-11-30)
- Manage costs effectively (Anthropic, accessed 2026-11-30)
- Hooks reference (Anthropic, accessed 2026-11-30)
- Prompt caching in Claude Code (Anthropic, accessed 2026-11-30)
- Claude API pricing (Anthropic, accessed 2026-11-30)
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
Build a test output triage filter for coding agents. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/build-test-output-triage-filter/