Skip to content

Verifying: trust the output, not the confidence

← Technical edition start · The friendly primer

Part of the technical edition. An agent's work reads as finished whether it is or not. This page is how to tell: evidence over claims, tests first, what to look for in an agent's diff, checking what it says about libraries, infra and data, and a small eval harness for the prompts and workflows you rely on.

Contents: evidence, not claims · one command for every check · tests first · reviewing an agent's diff · libraries and APIs · infrastructure · data and ML · evals · a small eval harness

Evidence, not claims

Ask for the thing a claim rests on, every time, until it's habit for both of you:

It says Ask for
"All tests pass" The command it ran and the last lines of output
"This function is only called from X" The search it ran, with file:line for every hit
"The bug is in Y" A command that reproduces it, before the fix and after
"This config option does Z" Where it read that: the docs page, or the source in the installed version
"It's faster now" Before and after numbers, from the same benchmark, run the same way
"Nothing else uses this" The search across the whole repo, and whether it checked generated code and configs

Put it in the rules file too: "When you say something works, show the command and its output. When you describe code, cite file:line. Say when you're guessing."

One command for every check

Make the full set of checks one command, so the agent runs all of them instead of the one it remembers: make check, just check, npm run check or a small script. Put it in the rules file as the definition of done.

A typical ladder, fastest first:

  1. Format and lint.
  2. Type check.
  3. Unit tests.
  4. Integration tests, or the slower suite, before a pull request.
  5. The preview for anything that deploys: a plan, a diff, a dry run.
  6. A staged rollout, a canary or a feature flag for anything that reaches users.

The agent can run the first five. The sixth is yours and your pipeline's.

Then run the same command in CI on every pull request, whoever or whatever opened it, so the check doesn't depend on the agent remembering. The first primer's workflow runs every test, shellcheck and a secret scan. Make green part of done in the rules file: "Before you hand a pull request over, wait for its checks, and read the log of any that fail (gh run view --log-failed)."

When a check fails only in CI, suspect the runner before the code: a tool that isn't installed, another version, a security setting. On Ubuntu 24.04 runners, for one, rsyslogd's AppArmor profile lets it read only its own config folders, so a test that starts it with a throwaway config fails there while it passes on a laptop. Fix the environment in the workflow, with a comment saying why, rather than loosening or skipping the test.

Tests first

Agents are good at writing tests, and better at writing code to pass them. Use that, in this order:

  1. Describe the behavior, including the edge cases.
  2. Have it write the failing test, and run it. Check it fails for the reason you expect, not because of a typo or a missing import.
  3. Have it write the code until the test passes, without touching the test.
  4. Run everything, not just the new test.

Watch for the test bending instead of the code. Look at test changes on their own:

git diff main...HEAD -- tests/ '*_test.go' '*.spec.ts'   # only the test changes
git diff main...HEAD | grep -nE '^\+.*(skip|xfail|only\(|@Ignore|t\.Skip)'

Red flags: a new skip or xfail, an assertion that got looser (assertEqual becoming assertIn, a tolerance that grew), an expected value updated to match the new output, a deleted test, a mock that now returns what the test wants. A line in the rules file helps: "Never change a test to make it pass without telling me why the old expectation was wrong."

Reviewing an agent's diff

Read it like a capable colleague's who doesn't know the system's history. The usual suspects:

  • Scope creep. Changes nobody asked for: renamed variables, reformatted files, "while I was here" refactors. Ask for them as a separate commit or not at all.
  • Invented things. A function, flag, config key or API endpoint that doesn't exist. The code may look right and fail only at runtime.
  • Swallowed errors. A new try with a broad except, or || true, that makes the symptom go away.
  • Hard-coded values that should be config, and test values that leaked into real code.
  • New dependencies. Each one is a supply-chain decision. Was it needed?
  • Generated files edited by hand, which the next generation run will undo.
  • Comments that describe what the code doesn't do, often left from an earlier attempt.
  • Security basics: input that reaches a query, a shell or a template; secrets in code or logs; permissions widened to make something work.
  • How you'd roll it back. Migrations, data changes and anything with state.

A reviewer subagent can do a first pass, and it's worth it, but it's a second opinion from the same kind of reader. It doesn't replace yours.

Libraries and APIs

Agents know a lot of libraries, from a snapshot, mixed across versions.

  • Check that a package exists, and is the one you mean, before installing it. Names that are almost right are a known way to slip malware in, and agents sometimes suggest packages that don't exist. Look it up on the registry, check the maintainer and the download history, and pin the version.
  • Point it at the version you actually have. "Read the installed source of requests under .venv/" beats what it remembers. pip show, npm ls and the lock file tell you which version that is.
  • Prefer the docs for that version when it's about behavior, and paste or fetch the relevant page rather than asking from memory.
  • Make it say when it isn't sure. "If you're not certain this flag exists in version X, say so" gets you far fewer confident inventions.

Infrastructure

  • Read the preview yourself. The agent's summary of a terraform plan is a convenience. Every destroy, replace and -/+ line deserves your eyes.
  • Validate before you plan: terraform validate, helm lint, kubectl apply --dry-run=server, ansible-playbook --syntax-check, and a schema check for your manifests.
  • Policy as code in CI (rules like "no public buckets" or "every resource has an owner tag") catches what reviews miss, whoever wrote the change.
  • Dev first, then staging, then production, with the same change, and production applied by a person or the pipeline after review.
  • For scripts, the first real run is yours, after the dry run, on one host or a small batch first.

Data and ML

Numbers are the easiest thing for an agent to get confidently wrong, so tie every number to a file:

  • Metrics come from a run's log or metrics file, quoted with the path, never from the agent's memory of an earlier run.
  • Compare like with like: same data split, same seed, same preprocessing, same evaluation code. Ask it to list what differs between two runs before it compares them.
  • Look for leakage whenever a result looks too good: the same rows, users or time periods in train and test, features computed with future information, a target that sneaked into a feature.
  • Keep a baseline (the current model, a simple heuristic, the majority class) and report against it.
  • Sanity-check the data first: shapes, row counts before and after each step, missing values, label balance, a few raw rows by eye.
  • Fix seeds and log configs, so a result can be reproduced by someone else, or by you next month.

Evals

An eval is a set of example inputs with checks on the outputs, run the same way every time. It's how you know whether a change to a prompt, a rules file, a model or an agent workflow made things better, worse or just different. Without one, every change is a vibe.

What makes a useful one:

  • Small and real. Ten to thirty cases from things you actually ask, including the ones that went wrong. Add a case every time something fails in real use.
  • Checks a machine can run where possible: contains, doesn't contain, matches a pattern, parses as JSON with the right keys, under a length.
  • Several runs per case. Outputs vary. A case that passes four times out of six is flaky, which is worth knowing before you rely on it.
  • Run before and after every change, and keep the results so you can compare.
  • Careful with AI-graded checks. Using a model to grade answers against a rubric can work for things a pattern can't check, but read a sample of its grades yourself before you trust it, and grade with a different prompt from the one being tested.

For ML engineers this is familiar: it's a test set for behavior. For everyone else, think of it as unit tests for a prompt.

A small eval harness

run_evals.py runs each case through any command-line tool, applies the checks and reports a pass rate. It needs only Python 3, has a dry run, never uses a shell, and exits 1 when the pass rate is below the bar you set, so it can gate CI.

#!/usr/bin/env python3
"""Run a small eval set against any command-line AI tool and report a pass rate.

Each line of the cases file is one JSON case:
  {"id": "short-name", "input": "the prompt", "checks": [{"contains": "..."}, ...]}

Checks (all must pass):
  {"contains": "text"}        output includes text (case-insensitive)
  {"not_contains": "text"}    output doesn't include text (case-insensitive)
  {"regex": "pattern"}        Python regex found anywhere (multiline)
  {"max_chars": 600}          output is at most this long
  {"json_keys": ["a", "b"]}   output is a JSON object with these keys
The command must also exit 0.

Exit status: 0 if the pass rate reaches --min-pass, 1 if it doesn't, 2 for a bad
cases file or a command that can't start.

--cmd is split like a shell would split it, but no shell runs it. An argument that
is exactly {input} is replaced by the case's input; with no {input}, the input goes
to the command's stdin.

  run_evals.py cases.jsonl --cmd "my-ai-tool --prompt {input}" --dry-run
  run_evals.py cases.jsonl --cmd "my-ai-tool --prompt {input}" --repeat 3 --out run.jsonl
"""
import argparse
import json
import re
import shlex
import subprocess
import sys
import time

CHECKS = {"contains": str, "not_contains": str, "regex": str, "max_chars": int,
          "json_keys": list}
TYPE_NAMES = {str: "string", int: "whole number", list: "list"}


def die(message):
    print(message, file=sys.stderr)
    sys.exit(2)


def load_cases(path):
    cases, seen = [], set()
    with open(path, encoding="utf-8") as f:
        for n, line in enumerate(f, 1):
            if not line.strip() or line.lstrip().startswith("#"):
                continue
            try:
                case = json.loads(line)
            except json.JSONDecodeError as err:
                die(f"{path}:{n}: not valid JSON ({err})")
            if not isinstance(case, dict):
                die(f"{path}:{n}: each line must be a JSON object")
            if not isinstance(case.get("id"), str) or not isinstance(case.get("input"), str):
                die(f"{path}:{n}: needs a string id and a string input")
            if case["id"] in seen:
                die(f"{path}:{n}: duplicate id {case['id']!r}")
            seen.add(case["id"])
            checks = case.get("checks", [])
            if not isinstance(checks, list):
                die(f"{path}:{n}: checks must be a list")
            for check in checks:
                if not isinstance(check, dict) or len(check) != 1 or next(iter(check)) not in CHECKS:
                    die(f"{path}:{n}: unknown check {check!r}; use one of {', '.join(CHECKS)}")
                (kind, want), = check.items()
                if not isinstance(want, CHECKS[kind]) or isinstance(want, bool):
                    die(f"{path}:{n}: {kind} needs a {TYPE_NAMES[CHECKS[kind]]}, not {want!r}")
                if "regex" in check:
                    try:
                        re.compile(check["regex"])
                    except re.error as err:
                        die(f"{path}:{n}: bad regex {check['regex']!r} ({err})")
            cases.append(case)
    if not cases:
        die(f"{path}: no cases found")
    return cases


def build(cmd, text):
    argv = shlex.split(cmd)
    if "{input}" in argv:
        return [text if a == "{input}" else a for a in argv], None
    return argv, text


def failures(output, code, checks):
    failed = [] if code == 0 else [f"exit code {code}"]
    low = output.lower()
    for check in checks:
        (kind, want), = check.items()
        if kind == "contains" and want.lower() not in low:
            failed.append(f"missing {want!r}")
        elif kind == "not_contains" and want.lower() in low:
            failed.append(f"contains {want!r}")
        elif kind == "regex" and not re.search(want, output, re.MULTILINE):
            failed.append(f"no match for /{want}/")
        elif kind == "max_chars" and len(output) > want:
            failed.append(f"{len(output)} chars, over {want}")
        elif kind == "json_keys":
            try:
                data = json.loads(output)
            except json.JSONDecodeError:
                failed.append("not JSON")
                continue
            if not isinstance(data, dict):
                failed.append("JSON but not an object")
                continue
            missing = [k for k in want if k not in data]
            if missing:
                failed.append(f"JSON missing {', '.join(missing)}")
    return failed


def main():
    p = argparse.ArgumentParser(description=__doc__,
                                formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("cases", help="JSONL file of cases")
    p.add_argument("--cmd", required=True, help="command to run for each case")
    p.add_argument("--repeat", type=int, default=1, help="runs per case (default 1)")
    p.add_argument("--timeout", type=float, default=300, help="seconds per run (default 300)")
    p.add_argument("--min-pass", type=float, default=1.0,
                   help="exit 1 if the overall pass rate is below this (default 1.0)")
    p.add_argument("--only", action="append", default=[], help="run only this id (repeatable)")
    p.add_argument("--out", help="write every run's output to this JSONL file")
    p.add_argument("--dry-run", action="store_true",
                   help="check the cases and show the commands; run nothing")
    a = p.parse_args()
    if a.repeat < 1:
        p.error("--repeat must be 1 or more")

    cases = load_cases(a.cases)
    if a.only:
        unknown = set(a.only) - {c["id"] for c in cases}
        if unknown:
            p.error(f"no case with id {', '.join(sorted(unknown))}")
        cases = [c for c in cases if c["id"] in a.only]

    if a.dry_run:
        print(f"Dry run: {len(cases)} case(s), {len(cases) * a.repeat} run(s); nothing will run.")
        for c in cases:
            argv, stdin = build(a.cmd, c["input"])
            how = "input on stdin" if stdin is not None else "input as an argument"
            print(f"  {c['id']}: {shlex.join(argv)[:100]}  ({how}, {len(c.get('checks', []))} checks)")
        return 0

    out = open(a.out, "w", encoding="utf-8") if a.out else None
    passed_runs = total_runs = 0
    for c in cases:
        argv, stdin = build(a.cmd, c["input"])
        passes, reasons = 0, []
        for i in range(a.repeat):
            start = time.monotonic()
            try:
                r = subprocess.run(argv, input=stdin, capture_output=True, text=True,
                                   timeout=a.timeout)
                output, code = r.stdout.strip(), r.returncode
            except subprocess.TimeoutExpired:
                output, code = "", "timeout"
            except OSError as err:
                die(f"could not run {argv[0]!r}: {err}")
            failed = failures(output, code, c.get("checks", [])) if code != "timeout" else ["timed out"]
            passes += not failed
            reasons += [f for f in failed if f not in reasons]
            if out:
                out.write(json.dumps({"id": c["id"], "run": i + 1, "passed": not failed,
                                      "failed": failed, "seconds": round(time.monotonic() - start, 2),
                                      "output": output}) + "\n")
        passed_runs += passes
        total_runs += a.repeat
        mark = "PASS" if passes == a.repeat else ("FLAKY" if passes else "FAIL")
        detail = f"  ({'; '.join(reasons)})" if reasons else ""
        print(f"{mark:5}  {passes}/{a.repeat}  {c['id']}{detail}")
    if out:
        out.close()
    rate = passed_runs / total_runs
    print(f"Pass rate: {passed_runs}/{total_runs} runs ({rate:.0%})")
    return 0 if rate >= a.min_pass else 1


if __name__ == "__main__":
    sys.exit(main())

A cases file, cases.jsonl, one JSON object per line:

{"id": "rotate-key", "input": "A teammate pasted an API key into a public channel. What do we do, in order?", "checks": [{"contains": "revoke"}, {"contains": "rotate"}, {"not_contains": "delete the message and move on"}, {"max_chars": 1500}]}
{"id": "review-json", "input": "Review this diff and answer only with a JSON object with keys severity and summary: query = \"SELECT * FROM users WHERE id=\" + user_id", "checks": [{"json_keys": ["severity", "summary"]}, {"regex": "(?i)inject"}]}
{"id": "no-made-up-flag", "input": "Which kubectl flag shows what apply would change, without changing anything?", "checks": [{"regex": "kubectl diff|--dry-run=server"}, {"not_contains": "--preview"}]}

Check the cases and the command without running anything, then run each case three times and keep the outputs:

python3 run_evals.py cases.jsonl --dry-run \
  --cmd 'claude -p {input} --bare --tools "" --permission-mode dontAsk --max-budget-usd 0.20'

python3 run_evals.py cases.jsonl --repeat 3 --out results-before.jsonl \
  --cmd 'claude -p {input} --bare --tools "" --permission-mode dontAsk --max-budget-usd 0.20'

The output looks like this (the numbers here are made up):

PASS   3/3  rotate-key
FLAKY  2/3  review-json  (no match for /(?i)inject/)
PASS   3/3  no-made-up-flag
Pass rate: 8/9 runs (89%)
  • --bare keeps the run from picking up whatever rules files and hooks are in the folder you run it from, so results don't change with your working directory. It needs ANTHROPIC_API_KEY. To test a rules file on purpose, drop --bare and run it from that repo.
  • --tools "" gives the model no tools, which suits questions. To eval an agent workflow, give it the tools it would really have, in a throwaway copy of the repo.
  • Every run is a paid model call. Cases times repeats is the bill; the budget flag caps each run.
  • Any other tool works the same way: put its command in --cmd, with {input} where the prompt goes, or leave it out to send the prompt on stdin.

We tested the harness against a stand-in script instead of a real model: passing, flaky, failing, crashing and timed-out cases, prompts on stdin and as an argument, and broken cases files. We didn't run the claude lines above, because they make paid calls.

To sum up a results file case by case, and compare it with the next one:

summary='group_by(.id) | map({id: .[0].id, passed: (map(select(.passed)) | length), runs: length})'
jq -s "$summary" results-before.jsonl
jq -s "$summary" results-after.jsonl

← Back: Workflows · Next: Worked examples → · Technical edition start