Sub topic 8
Keeping command and test output small
This chapter assumes you have used a coding agent in a terminal and are comfortable with shell pipes, grep, and a test runner such as pytest. It also assumes you know that everything a tool prints goes into the context window and stays there until the session is compacted or ended.
Why tool output is the biggest hidden cost
When an agent runs a command, the full text the command prints is returned to the model as a tool result. That text is added to the conversation and is re-read on every later turn. A single noisy command can therefore cost far more than its size suggests.
Consider a test suite that prints 4,000 lines of passing tests and one failure. The agent needs perhaps 30 lines of that output. The other 3,970 lines occupy the window for the rest of the session. They also push earlier decisions and instructions further back, which makes them less likely to be used well.
Common sources of oversized output include:
- Test runs with verbose or per-test progress lines.
- Build logs with dependency downloads and compiler warnings.
git log,git diff, andgit statuson large or messy repositories.- Package manager installs.
- Dumps of JSON, logs, or lock files with
cat. - Recursive
greporfindwith no limit.
The goal is not to hide information. The goal is to return the smallest output that still lets the agent make the next decision.
Principles for bounding output
Three habits cover most cases.
- Ask for less at the source. Use quiet flags, stop-on-first-failure flags, and targeted paths. This is the cheapest option because the text is never produced.
- Filter and cap in the pipeline. Use
head,tail,grep, andwcto cut what remains. - Send the full output to a file and read part of it. This keeps the complete record available on disk without putting it in the context.
Searching with a cap
A recursive search over a large repository can return hundreds of matches. Cap the list and then read only the lines you need.
# Find the definition first, then read only the lines around it
grep -rn "def parse_config" src | head -n 20
sed -n '120,180p' src/config.pyThe first command lists at most 20 matches with file names and line numbers. The second prints lines 120 to 180 of one file. Together they put a few dozen lines into the context instead of an entire file.
Useful variations:
grep -rln "pattern" src | head -n 20lists only file names, which is smaller still.grep -rc "pattern" src | grep -v ":0$"counts matches per file and drops files with none.grep -rn "pattern" src --include="*.py" | head -n 20restricts the search to one file type.
A note on head: when head exits early, the command feeding it may receive a broken pipe and stop. This is usually what you want. It does mean the cap hides how many matches existed. If the count matters, run grep -rn "pattern" src | wc -l first.
Keeping test output small
Test runs are the most common source of large output. A failure summary is usually at the end of the output, so the tail is the most useful part.
# Keep only the end of a long test run, where the failure summary appears
pytest -x -q 2>&1 | tail -n 30Each part does a specific job:
-xstops at the first failure, so the agent fixes one problem at a time and the output does not repeat the same root cause many times.-qreduces the per-test progress output.2>&1merges standard error into standard output, so errors are not lost to the terminal and the pipe sees both.tail -n 30keeps the final 30 lines.
Re-running only what failed
After a failure, avoid running the whole suite again. Most runners can re-run a single test or only the previous failures.
pytest tests/test_config.py::test_parse_empty -x -q 2>&1 | tail -n 30
pytest --lf -x -q 2>&1 | tail -n 30The first command runs one test by its identifier. The second, --lf (last failed), re-runs only tests that failed in the previous run. Run the full suite once at the end of a subtask, not after every edit.
Redirecting to a file
When you want the full log without paying for it in the context, write it to a file and inspect it selectively.
pytest -q > /tmp/test-run.log 2>&1
tail -n 30 /tmp/test-run.log
grep -n "FAILED" /tmp/test-run.log | head -n 20The complete output is on disk. The agent reads the 30-line tail first and then searches for failures. If a particular failure needs more detail, it can print a narrow range with sed -n.
Note the exit code. In a pipeline such as pytest ... | tail, the shell reports the exit status of the last command (tail), not pytest. In bash you can check ${PIPESTATUS[0]}, or set set -o pipefail first. When the agent decides whether tests passed, make sure it is looking at the test runner's result and not at tail's.
set -o pipefail
pytest -x -q 2>&1 | tail -n 30
echo "pytest exit status: $?"With pipefail set, the pipeline returns a nonzero status if pytest fails.
Bounding output inside your own tools
If you build tooling for an agent, or wrap commands in scripts, enforce a limit in code. A helper that keeps the start and the end of long text, and marks what was dropped, is a common pattern.
def truncate_output(text, max_lines=60, head=20, tail=20):
lines = text.splitlines()
if len(lines) <= max_lines:
return text
omitted = len(lines) - head - tail
return "\n".join(lines[:head] + [f"... {omitted} lines omitted ..."] + lines[-tail:])The function returns short text unchanged. For long text, it keeps the first 20 and last 20 lines and inserts a marker with the number of omitted lines. The start often holds the command and configuration. The end often holds the summary and the error. The marker tells the reader that something is missing, which matters for the next section.
Edge cases and failure modes
Truncation saves context, and it can also remove the information you needed. These are the cases to watch.
The useful line is in the middle
Head and tail assume the important text is at the edges. A stack trace can appear in the middle of a log, followed by cleanup messages. If a capped result looks inconsistent, such as a failure count with no failure text, search the saved log instead of widening the cap blindly.
grep -n -B2 -A10 "Traceback" /tmp/test-run.log | head -n 60-B2 and -A10 print two lines before and ten lines after each match, and head still caps the total.
Silent truncation
If output is cut without a marker, the agent may treat partial output as complete. Always keep an omitted-lines marker, or check line counts with wc -l, so the agent knows the result is partial.
Filtering away the evidence
A broad grep -v or a pattern like grep ERROR can drop warnings, skipped tests, or the lines that explain an error. Start with a tail, and narrow the filter only after you know what the output looks like.
Quiet flags that hide real problems
Quiet modes reduce noise but can suppress warnings. If a command behaves unexpectedly, run it once without the quiet flag, with a cap, to see what was hidden.
Stopping at the first failure
-x is efficient for fixing problems in sequence. It also means you do not learn how many tests fail. Occasionally run without -x and use tail plus a count, for example pytest -q 2>&1 | tail -n 5, to see the size of the problem.
Large single lines
Minified files, JSON on one line, and long log lines defeat line-based limits. A 60-line cap does not help when one line is 200 KB. Use cut -c1-200 or head -c 4000 to cap by characters.
head -c 4000 build/output.json
cut -c1-200 /tmp/app.log | tail -n 40Comparing the approaches
| Technique | Context saved | Risk | Best used for |
|---|---|---|---|
| Quiet or narrow flags | High, nothing is produced | Hides warnings | Routine test and build runs |
| `tail -n N` | High | Misses mid-log errors | Failure summaries |
| `head -n N` | High | Hides the total count | Search results, listings |
| Redirect to file | Very high | Needs a follow-up read | Long builds, full test runs |
| Targeted re-run (`--lf`, one test) | High | Misses regressions elsewhere | Fixing one failure |
| Character caps | Medium | Cuts mid-token or mid-value | Minified or one-line data |
Habits to adopt
- Decide the size you expect before running a command. If you cannot predict it, cap it.
- Prefer a file path and line range over printing a whole file.
- Run narrow tests while editing and the full suite at checkpoints.
- Keep a marker or a count whenever you cut output.
- Check the exit status of the real command, not the filter.
- If a large result has already entered the context, note the useful part in your progress file and compact. Later chapters cover compaction and external notes.
Exercises
Exercise
A test run prints 3,000 lines. You run pytest -q 2>&1 | tail -n 30 in a script and then check $? to decide whether the tests passed. The tests fail, but the script reports success. Why, and what are two ways to fix it?
Show answer
In a pipeline, $? holds the exit status of the last command, which is tail, and tail succeeds. Fix it by running set -o pipefail before the pipeline, so a failing pytest makes the pipeline fail, or by reading ${PIPESTATUS[0]} in bash right after the pipeline. Another option is to redirect pytest output to a file and check pytest's own exit status before running tail on the file.
Exercise
Your capped output shows "5 failed" but none of the failure messages. What is the likely cause, and what should you do instead of increasing the tail to 500 lines?
Show answer
The failure details are probably earlier in the output than the last lines, for example in a "FAILURES" section followed by a long warnings summary. Redirect the full output to a file, then use grep -n -A15 "FAILURES" file | head -n 60 or grep -n "FAILED" file | head -n 20 to find and read only the relevant section. This keeps the context small and gets the information you need.
Exercise
Write a command that lists at most 15 Python files under src that contain the text TODO, without printing the matching lines.
Show answer
grep -rl "TODO" src --include="*.py" | head -n 15. The -l option prints only file names, --include="*.py" limits the search to Python files, and head -n 15 caps the list.