Most coding agents spend a large share of their turns in one loop: change code, run the tests, read the result, change code again. The quality of that loop depends on what "read the result" means. An exit code of 1 tells the model something failed and nothing about what. The full log tells it everything, at a cost in tokens and attention, and the one assertion that matters is somewhere in the middle.
Test runners already know the answer in structured form. Most can write a report that lists every test, its status, and for each failure a message and a stack trace. This post shows how to get those reports out of a sandbox and turn them into a tool result built for a model: the counts, the first few failures, and a clear signal when the run did not finish at all.
Ask the runner for a report
Three common runners, each writing a report next to its normal output:
| Runner | Flag | Format |
|---|---|---|
| pytest | --junitxml=report.xml | JUnit XML, built in |
| Vitest | --reporter=junit --outputFile=report.xml | JUnit XML, built in |
| go test | -json | One JSON event per line on stdout, built in |
Jest can write the same JUnit XML through the separately installed jest-junit reporter. JUnit XML is the closest thing the ecosystem has to a shared format: a testsuite holds testcase elements, and a failing case has a failure or error child with a message attribute and the trace as text. Skipped cases have a skipped child.
Go's format is a stream instead. Each line is an event with an Action such as run, output, pass, fail or skip, plus the Package and Test it belongs to. A test's output arrives as a series of output events before its fail.
Turn the report into a summary
The parser below reads either format and returns the same shape: totals, the first five failures, and how many more were left out. Each failure's message and details are cut to a fixed size. It uses the fast-xml-parser package for XML.
import { XMLParser } from 'fast-xml-parser'; export interface Failure { test: string; // "suite > name" or "package TestName" message: string; details: string; // stack trace or output, already cut to size } export interface TestSummary { total: number; failed: number; skipped: number; failures: Failure[]; // the first few, not all of them omittedFailures: number; } const MAX_FAILURES = 5; const MAX_DETAIL = 1500; function cut(text: string, max = MAX_DETAIL): string { const t = text.trim(); return t.length <= max ? t : `${t.slice(0, max)}\n[... ${t.length - max} more characters]`; } function summarize(failures: Failure[], total: number, skipped: number): TestSummary { return { total, failed: failures.length, skipped, failures: failures.slice(0, MAX_FAILURES), omittedFailures: Math.max(0, failures.length - MAX_FAILURES), }; } const asArray = <T>(x: T | T[] | undefined): T[] => (x === undefined ? [] : Array.isArray(x) ? x : [x]); // JUnit XML, as written by pytest --junitxml and vitest --reporter=junit, among others. export function fromJUnit(xml: string): TestSummary { const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '', textNodeName: 'text' }); const doc = parser.parse(xml); const suites = asArray(doc.testsuites?.testsuite ?? doc.testsuite); const failures: Failure[] = []; let total = 0; let skipped = 0; for (const suite of suites) { for (const tc of asArray<any>(suite.testcase)) { total++; if (tc.skipped !== undefined) skipped++; const problem = asArray<any>(tc.failure)[0] ?? asArray<any>(tc.error)[0]; if (problem === undefined) continue; const body = typeof problem === 'string' ? problem : (problem.text ?? ''); failures.push({ test: [tc.classname, tc.name].filter(Boolean).join(' > '), message: cut(String(problem.message ?? body.split('\n')[0] ?? ''), 300), details: cut(String(body)), }); } } return summarize(failures, total, skipped); } // go test -json: one JSON event per line. export function fromGoTestJson(stream: string): TestSummary { const output = new Map<string, string>(); const failures: Failure[] = []; let total = 0; let skipped = 0; for (const line of stream.split('\n')) { if (!line.startsWith('{')) continue; const ev = JSON.parse(line) as { Action: string; Package?: string; Test?: string; Output?: string }; if (!ev.Test) continue; // package-level events const key = `${ev.Package} ${ev.Test}`; if (ev.Action === 'output') output.set(key, (output.get(key) ?? '') + (ev.Output ?? '')); if (ev.Action === 'pass' || ev.Action === 'fail' || ev.Action === 'skip') total++; if (ev.Action === 'skip') skipped++; if (ev.Action === 'fail') { const out = output.get(key) ?? ''; const firstError = out.split('\n').find((l) => /\.go:\d+:/.test(l)) ?? ''; failures.push({ test: key, message: cut(firstError, 300), details: cut(out) }); } } return summarize(failures, total, skipped); } A few choices here are deliberate:
- The first few failures, not all of them. When 200 tests fail, they usually fail for one or two reasons. Five full failures plus "195 more" gives the model enough to find the cause and a clear signal that the change broke something broad.
- Per-failure caps. A single failure's trace can be enormous, for example a snapshot diff. Cutting each one keeps one bad test from crowding out the others. Our post on feeding command output back to an LLM covers truncation in more depth.
- Skips are counted. An agent that "fixes" a test by skipping it shows up as a rising skip count.
Run it in the sandbox, and handle the run that never finished
The tool that runs the tests should distinguish three outcomes, because the right next step is different for each:
- Passed. Exit code 0 and no failures in the report.
- Failed. The report exists and lists failures. The model should read them and fix the code.
- Did not finish. No report was written, or the command timed out or ran out of memory. Collection errors, syntax errors in a test file and crashes all land here. The report has nothing to say, so the tool returns the tail of stderr instead.
Here is that tool for pytest with the Sandscale TypeScript SDK. run returns exitCode, stdout, stderr, timedOut and oomKilled, and readFile reads the report back:
import { Sandscale } from '@sandscale/sdk'; import { fromJUnit, type TestSummary } from './test-report'; const sandscale = new Sandscale({ apiKey: process.env.SANDSCALE_API_KEY }); export interface TestToolResult { outcome: 'passed' | 'failed' | 'did-not-finish'; exitCode: number; timedOut: boolean; oomKilled: boolean; summary: TestSummary | null; // null when no report was written stderrTail: string; // only when there is no report to explain the failure } export async function runTests(box: { id: string; region: string }): Promise<TestToolResult> { await sandscale.sandboxes.run(box.id, ['rm', '-f', '/workspace/report.xml'], { region: box.region }); const run = await sandscale.sandboxes.run( box.id, ['python', '-m', 'pytest', '-q', '--junitxml=/workspace/report.xml'], { region: box.region, workdir: '/workspace/repo', timeoutSeconds: 600 }, ); let summary: TestSummary | null = null; try { const xml = new TextDecoder().decode( await sandscale.sandboxes.readFile(box.id, '/workspace/report.xml', { region: box.region }), ); summary = fromJUnit(xml); } catch { summary = null; // no report: the run crashed, timed out, or never reached the tests } const finished = summary !== null && !run.timedOut && !run.oomKilled; return { outcome: !finished ? 'did-not-finish' : run.exitCode === 0 && summary!.failed === 0 ? 'passed' : 'failed', exitCode: run.exitCode, timedOut: run.timedOut, oomKilled: run.oomKilled, summary, stderrTail: summary ? '' : run.stderr.slice(-3000), }; } The stale report is deleted before each run. Without that, a run that crashes before pytest writes anything would read the previous run's report and tell the model its tests failed for old reasons, or passed.
Combine the exit code with the report rather than trusting either alone. A runner can exit non-zero with no failing tests listed, for example pytest exits with a distinct code when it collected no tests at all, and the summary's total of zero is the clue the model needs.
Help the model narrow down
Once the model knows which test failed, it rarely needs the whole suite again. Say so in the tool description, and give it a way to rerun a subset:
- pytest:
--lfreruns only the tests that failed last time, and-kselects by name. - Vitest: pass a file path, or
-twith a test name pattern. - go test:
-run '^TestName$'selects by regular expression.
Narrow reruns are cheaper and give shorter, clearer reports. Run the full suite again before the agent declares the task done.
A report from the sandbox is evidence for the loop, not for the merge
Everything in this post runs inside the sandbox, under the agent's control. That is the right place for the edit-test loop, and the wrong place to decide whether a change is safe to merge. An agent can edit a test until it passes, mark it skipped, or change the configuration that decides which tests run. None of that is malicious; it is what optimizing for "tests pass" looks like.
So keep two things separate:
- In the loop: the sandbox report, so the agent iterates on focused results.
- At the gate: the full suite on a clean checkout of the agent's patch, run by your CI, as in running an agent PR's tests in a sandbox from GitHub Actions. Flag changes to test files and test configuration for a reviewer, the way checking an agent's patch flags CI files.
Where Sandscale fits
A Sandscale sandbox gives each run its own Firecracker microVM, so test suites the agent wrote or changed run against their own kernel and filesystem, with the network mode defaulting to none. The builtin:base template has Python 3, Node.js, Git and a C compiler; your project's own test dependencies go in with the project. The result fields this post relies on, exitCode, timedOut and oomKilled, come straight from run, and the command and the files read back are recorded in the audit log.
Originally published on the Sandscale blog.
