SENIORPROJECTCHAPTER 29

Project: the support agent at 95%

Take the A2 support agent to a measured 95% on support-100: error analysis on a development split, a help centre behind RAG v2, grounded policy answers, versioned prompt changes through the CI gate, one look at the held-out cases, and an eval report someone can ship from

240 MINAI ENGINEERINGUPDATED 2026-11-02

The brief

Take the support agent in labs/ai/support-agent/ from the score it has on support-100.jsonl today to a measured 95%, without breaking anything it already gets right, and write the evaluation report a reviewer would sign off. You will do four kinds of work, in this order: measure where the failures are, add the one capability most of them need (the shop’s policies, behind retrieval, with grounded answers), make versioned prompt changes for the rest, and report.

The target is a set of numbers, not one:

Measure Target Why this one
Pass rate on support-100 (programmatic checks plus judge), median of three runs at least 95/100 the headline; three runs because a single run has A/A noise of a few cases
Pass rate on the 30 held-out cases, measured once at the end at least 28/30, and within the A/A noise of the development rate the evidence that the gain is not fitted to the cases you read
Must-pass cases (every case with a refund outcome, every injection case) all pass, in all three runs the behaviours the A2 project said must never move
Refund end states in support_refunds 100/100 in every run a cheaper or friendlier agent that issues one wrong refund has failed
Mean agent cost per conversation, including the claim verifier, excluding the judge under $0.02 the A2 budget still holds
The CI gate from evals-in-ci green on the pull request that carries the final prompt, with the baseline updated in the same pull request the change ships through the process, not around it

Constraints: the agent model stays claude-haiku-5-5 unless your report justifies a change with numbers; the identity binding, the refund policy check and the approver are not touched; and the judge is whichever one you calibrated in llm-as-judge, used unchanged. Tuning the agent until the judge agrees with it is not progress; if you believe the judge is wrong on a case, re-grade the case by hand and fix the label or the rubric, with a commit that says so.

What ‘95%’ means, and what it does not

At 95 passes out of 100 the Wilson 95% interval on the pass rate is about 0.89 to 0.98. Two agents scoring 93 and 95 on this suite are not distinguishable by their totals; only the paired flips say anything, which is why the gate from evals-in-ci compares case by case. And support-100 was designed by risk, not sampled from traffic: refunds and injections are a third of it, where real traffic is mostly ‘where is my order’. A 95% here is a statement about how the agent handles the cases that matter most, not a prediction that 95% of production conversations go well. The report says both things, in words, next to the number.

What the number does give you is a fixed point. A score on a versioned suite, with a versioned prompt, a pinned model, a calibrated judge and a measured noise floor, can be compared with next month’s score. That comparison is the reason to do any of this.

What you build

Most of the files exist. New ones are marked new; changed ones changed.

labs/ai/
  docqa/
    ingest_v2.py          changed  --variant flag, so the help centre gets its own chunks
    retrieve_v2.py        changed  a help-rerank pipeline over the help variant
    verify.py                      the claim verifier from hallucination-and-grounding
  evals/
    support-100.jsonl     changed  suite v2: the policy cases now expect answers from the help centre
    golden.jsonl          changed  the source of those changes (synth.py rebuilds support-100.jsonl)
    split.py, split.json  new      70 development and 30 held-out ids (prompt-management)
    support-dev.jsonl     new      the 70 development cases
    support-holdout.jsonl new      the 30 held-out cases
    failures.py           new      one line per failing case: checks, judge criteria, category
    baseline/support-100.jsonl     the CI baseline, re-run on suite v2, updated in the final PR
    EVAL-REPORT.md        new      the deliverable
  support-agent/
    help/*.md             new      five help-centre pages: returns, refunds, shipping, payments, account
    tools.py              changed  search_help, a fifth tool, over help-rerank
    response_schema.py    changed  sources: the passage ids an answer relies on
    agent.py              changed  grounding check after the final answer
    prompts.py            changed  versioned SYSTEM with a content hash
    harness.py            changed  writes the prompt version and hash on every result line
Architecture sketch
  customer turn
       |
       v
  agent.py loop (Haiku 5.5, cached tools + SYSTEM vN)
       |-- lookup_order / customer_orders / search_products   (bound to customer id, read-only)
       |-- issue_refund   -> policy check -> approver -> support_refunds
       |-- search_help    -> retrieve_v2 'help-rerank' (vector + FTS, RRF, cross-encoder)
       |                     -> top 3 passages {doc_id, text}, wrapped as <tool_data>
       v
  FinalResponse {intent, answer, actions, sources}
       |
       |-- sources not empty?  every id retrieved this turn? --- no --> escalate
       |-- verify(answer, all tool results this turn)        --- unsupported claim --> escalate
       v
  output check (emails, URLs, refund claims) -> answer

  evaluation:  harness.py --cases support-dev.jsonl  -> per-case lines {id, slice, must_pass, pass, cost, prompt_sha}
               (pass = programmatic checks AND judge_case on the must / must_not criteria)
               gate.py baseline vs candidate        -> PASS / FAIL, flips, McNemar p

Design notes

Measure before you build. The A2 project’s RESULTS.md and the grading in building-an-eval-set already told you roughly where the agent fails. Count it properly on the development cases before choosing a fix. In most runs one category dominates: the policy questions, where the agent has nothing to answer from, and either invents a window of days or produces an unhelpful refusal. The next most common are intent labels on the ambiguous cases, dates and amounts restated wrongly from tool results, and answers in the wrong language. Each has a different fix, and only one of them is retrieval.

Policy belongs in retrieval, not in the prompt and not in the weights. You could paste five help pages into SYSTEM: they are short, and the prompt is cached. It would work today and fail the day the help centre is two hundred pages, and it puts every policy in every conversation. Fine-tuning would teach the tone of the policies and not their details, as the fine-tuning chapter showed. A search_help tool over the RAG v2 pipeline from rag-done-properly scales, keeps the policy text editable by the people who own it, and gives every policy answer a passage you can check it against.

Grounding when citations are not available. The citations API cannot be combined with a JSON schema in the same request, which hallucination-and-grounding met as a 400. The agent’s final answer is schema-constrained, so grounding is done the other way round: the schema gains a sources array; the model lists the doc_id of every passage it relied on; code checks that each listed id was actually returned by search_help in this turn; and the claim verifier checks the answer against everything the tools returned in this turn, help passages and order records alike. Any claim not supported turns the answer into a polite escalation. That is the verified abstention policy from hallucination-and-grounding, inline and blocking, which is right for refund and policy answers. It costs one Haiku 5.5 call, a fraction of a tenth of a cent, on turns that searched the help centre.

Changing the agent changes the eval. Four policy cases in suite v1 expect the agent to say it does not have the policy. Once it does have the policy, that expectation is wrong. Change the must items in golden.jsonl, rebuild with synth.py, re-grade those cases by hand, and re-run the baseline on the new suite before comparing anything. The gate refuses to compare runs on different case sets for exactly this reason. Record the change in the report: the score on suite v2 is not comparable with a score on suite v1.

Every prompt change is a version. prompts.py gets a version name and a content hash, the harness writes both on every result line, and each iteration is one change, one development run, one gate comparison and one row in the report’s iteration table. A change you cannot attribute to a row did not happen.

LAB From baseline to a measured 95% ~240 MIN
YOU NEEDlabs/ai/support-agent from the A2 project, with harness.py extended in evals-in-ci (--cases, --out) and llm-as-judge (judge_case in the verdict)labs/ai/evals from building-an-eval-set, llm-as-judge and evals-in-ci: golden.jsonl, synth.py, support-100.jsonl, grade.py, kappa.py, run_support.py, judge.py, gate.py, baseline/support-100.jsonl and baseline/flaky.txtlabs/ai/docqa from rag-done-properly and hallucination-and-grounding: ingest_v2.py, retrieve_v2.py, verify.py, the doc_chunks_v2 table and the cross-encoder in the Hugging Face cacheDocker with labs/databases running and loaded at scale 0.1; Ollama with nomic-embed-textYour fork with the support-eval workflow from evals-in-ciANTHROPIC_API_KEY: a 70-case development run with the Haiku judge is about $0.10 to $0.30; ten iterations, the re-baseline, three full runs, the held-out run and two CI runs come to about $3 to $5 (the help-centre ingest makes no API calls), more if your judge is Sonnet 5.5 on every case

Work from labs/ai/evals/ unless a step says otherwise. Steps that spend money say so.

1. Freeze the starting point. You need the suite v1 baseline from evals-in-ci and its noise floor. If baseline/support-100.jsonl and baseline/flaky.txt exist and nothing in the agent has changed since, keep them. Otherwise re-run steps 2 and 3 of that chapter’s lab. Then record the starting numbers:

uv run python -c "
import json
rows = [json.loads(l) for l in open('baseline/support-100.jsonl')]
print(f\"suite v1 baseline: {sum(r['pass'] for r in rows)}/{len(rows)}  \"
      f\"must-pass failing {[r['id'] for r in rows if r['must_pass'] and not r['pass']]}  \"
      f\"mean cost \${sum(r['cost'] for r in rows) / len(rows):.4f}\")"
wc -l baseline/flaky.txt
A line such as suite v1 baseline: 84/100 must-pass failing [] mean cost $0.0013 and the number of flaky ids, typically 0 to 4. Copy both into a new EVAL-REPORT.md under a heading ‘Starting point’, with the date, the model id, the judge model and the git commit. Starting scores between the high 70s and high 80s are typical. If a must-pass case is already failing, it is the first thing you fix, before any work towards the headline.

2. Split the suite. Create split.py from the prompt-management chapter (70 development and 30 held-out ids, stratified by category, stable by id) and write the two case files:

uv run split.py
uv run python -c "
import json
s = json.load(open('split.json'))
rows = [l for l in open('support-100.jsonl') if l.strip()]
for part in ('dev', 'holdout'):
    keep = set(s[part])
    open(f'support-{part}.jsonl', 'w').writelines(l for l in rows if json.loads(l)['id'] in keep)
print({p: sum(1 for _ in open(f'support-{p}.jsonl')) for p in ('dev', 'holdout')})"
dev 70 holdout 30, then {'dev': 70, 'holdout': 30}. From here on you read transcripts, write fixes and run iterations on support-dev.jsonl only. Do not open the held-out transcripts or run the agent on them until step 8. This is a different split from llm-as-judge’s even and odd halves, which were for tuning the judge; these are for tuning the agent.

3. Where the development failures are. Run the agent and the judge over the development cases with the detailed tools from building-an-eval-set and llm-as-judge, then join their verdicts. This step costs about $0.15.

IDS=$(uv run python -c "import json; print(','.join(json.load(open('split.json'))['dev']))")
uv run run_support.py --model claude-haiku-5-5 --ids "$IDS"
uv run judge.py pointwise results/support-100-claude-haiku-5-5-subset.jsonl --model "${JUDGE_MODEL:-claude-haiku-5-5}" --tag dev0

Create failures.py:

"""One line per failing case: programmatic checks that failed and the judge's failed criteria."""
import json, sys
from collections import Counter
from judge import CASES, criteria

runs = {r["id"]: r for r in map(json.loads, open(sys.argv[1])) if "error" not in r}
judged = {g["id"]: g for g in map(json.loads, open(sys.argv[2]))}
by_category, failing = Counter(), 0
for i in sorted(runs):
    case, g = CASES[i], judged.get(i, {})
    checks = [k for k, ok in runs[i]["checks"].items() if not ok]
    text = dict(criteria(case))
    crit = [text.get(c, c) for c in g.get("failed", [])]
    if checks or crit or g.get("verdict") is None:
        failing += 1
        by_category[case["category"]] += 1
        print(f"{i}  {case['category']:18} checks:{','.join(checks) or '-'}  judge:{' | '.join(crit) or g.get('verdict')}")
        print(f"      {case['turns'][-1][:90]}")
print(f"\n{failing} failing of {len(runs)}:", dict(by_category.most_common()))
uv run failures.py results/support-100-claude-haiku-5-5-subset.jsonl results/judge-${JUDGE_MODEL:-claude-haiku-5-5}-dev0.jsonl
Two lines per failing case and a count by category, for example 10 failing of 70: {'policy': 3, 'order_status': 2, 'multi_turn': 2, 'non_english': 1, 'shipping_change': 1, 'product': 1}. Three of the four policy cases are development cases; the split puts c048 in the held-out half. Now do the work no script does: for each failing case read the transcript (grep '"c046"' results/support-100-claude-haiku-5-5-subset.jsonl) and give it one cause in a table in EVAL-REPORT.md, using the failure categories from grade.py (invented_policy, wrong_fact, missed_requirement, unhelpful_refusal, tone, and the rest). Expect the largest group to be policy questions: the agent either states a window of days it cannot know (invented_policy, a must-not failure) or refuses in a way the rubric scores as unhelpful. Expect one or two judge verdicts you disagree with; re-grade those with grade.py --rater final --ids ... before counting them as agent failures.

4. The help centre, ingested as RAG v2. The shop has never written its policies down where the agent can read them. Write five short pages in labs/ai/support-agent/help/. The content below is the shop’s policy for this course; keep it, or change it and update the cases in step 6 to match.

mkdir -p ../support-agent/help && cd ../support-agent/help
cat > returns.md <<'EOF'
# Returns

## Return window
You can return most items within 30 days of delivery. Sale items can be returned within 14 days of delivery.
Items must be unused and in their original packaging. Opened software, gift cards and personalised items cannot be returned.

## How to return an item
Start a return from Orders in your account and print the prepaid label. Drop the parcel at any partner courier point.
Returns of items that are faulty or not as described are free. For other returns, a return fee of EUR 4.95 is deducted from the refund.

## Exchanges
We exchange for a different size or colour of the same item if it is in stock. Otherwise we refund and you can place a new order.

## Gifts
A gift can be returned without a receipt using the order number. The refund is issued as store credit to the gift recipient.
EOF
cat > refunds.md <<'EOF'
# Refunds

## When you are refunded
We issue the refund within 3 business days of receiving your return at our warehouse.

## How long a refund takes to reach you
Refunds go back to the original payment method only. Card refunds usually appear on your statement 5 to 10 business days after we issue them. PayPal refunds usually appear within 2 business days.

## Refunds to a different card
We cannot refund to a different card or account than the one used to pay, including when the original card has expired. Your bank passes the refund to the replacement card.

## Partial refunds
If an item is returned used or incomplete, we may refund part of its price. A colleague explains the amount by email.
EOF
cat > shipping.md <<'EOF'
# Shipping

## Delivery times
Standard delivery takes 2 to 4 business days within the EU and 5 to 8 business days elsewhere. Express delivery takes 1 to 2 business days within the EU.

## Changing the delivery address
You can change the address until the order is shipped. After it ships, the courier cannot redirect it; refuse the parcel or return it once delivered.

## Damaged or missing items
Report a damaged parcel or a missing item within 7 days of delivery, with a photo of the parcel if it is damaged. We send a replacement or refund it in full.
EOF
cat > payments.md <<'EOF'
# Payments and prices

## Payment methods
We accept Visa, Mastercard, American Express and PayPal. We do not offer payment in instalments.

## Price matching
We do not price match. If the price of an item drops within 7 days of your order, we refund the difference once on request.

## Promo codes
One promo code per order. Codes cannot be applied after an order is placed.
EOF
cat > account.md <<'EOF'
# Your account

## Deleting your account
We delete your account and personal data within 30 days of your request, except order and invoice records that the law requires us to keep for 10 years.

## Marketing emails
Unsubscribe with the link at the bottom of any marketing email, or under Preferences in your account. It takes effect within 48 hours.
EOF
cd ../../docqa

In ingest_v2.py, add a --variant argument so the help pages do not mix with the ATLAS docs: ap.add_argument("--variant") next to --context, and change the line that sets the variant to variant = a.variant or ("struct+ctx" if a.context else "struct"). In retrieve_v2.py, add one entry to PIPELINES:

    "help-rerank":   lambda q, k: rerank(q, rrf(vector(q, "help"), fts(q, "help")), k),
uv run ingest_v2.py ../support-agent/help --variant help
uv run python -c "
from retrieve_v2 import PIPELINES
for q in ['How many days do I have to return something?', 'How long does a refund take to reach my card?',
          'Do you price match?', 'Can the refund go to a different card?', 'Can I change my delivery address?']:
    r = PIPELINES['help-rerank'](q, 3)
    print(f'{q[:45]:45} -> ' + ', '.join(f'{x[1]}#{x[2]}' for x in r))"
Five lines from the ingest, one per page, with two to four chunks each and 16 in all (the structural chunker starts a chunk at every ## heading, and the # title has no text of its own, so it makes no chunk), then five questions, each with the right page and section first: returns.md#0 for the return window, refunds.md#1 for the time to card, payments.md#1 for price matching, refunds.md#2 for a different card, shipping.md#1 for the address. If you edited the pages, check the section, not the number. If any question ranks the wrong page first, fix retrieval now (a page heading that does not say what the section is about is the usual cause) rather than hoping the model compensates.

5. search_help, sources and the grounding check. In labs/ai/support-agent/tools.py, add the tool. It is not bound to a customer, it is read-only, and its results go through dispatch, so they are escaped and wrapped as <tool_data> like every other tool result:

# tools.py: RAG v2 over the help centre
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "docqa"))
from retrieve_v2 import PIPELINES

def search_help(query: str):
    rows = PIPELINES["help-rerank"](query, 3)
    return {"passages": [{"doc_id": f"{r[1]}#{r[2]}", "text": r[3]} for r in rows]}

Add "search_help": search_help to the dict make_handlers returns, add search_help to ALLOWED, and add a definition to TOOL_DEFS, keeping them sorted by name: strict: True, one required string property query, additionalProperties: False, and the description ‘Search the shop help centre: returns, refunds, shipping, payments and account policies. Use it for every question about a policy, fee, time limit or rule. Answer policy questions only from the passages it returns, and list the doc_id of each passage you rely on in sources.’

In response_schema.py, add "sources": {"type": "array", "items": {"type": "string"}} to FINAL_SCHEMA’s properties and to required, and a sources: list[str] field to the Pydantic model. Then in agent.py, check every final answer that used the help centre before it leaves turn:

# agent.py: after the final JSON is parsed, before returning it
import json, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "docqa"))
from verify import verify                      # hallucination-and-grounding's claim verifier

ESCALATE = {"answer": "I want to be sure I give you the right policy, so a colleague will confirm "
                      "this by email within one working day.",
            "actions": [{"type": "escalated", "order_id": 0, "amount_cents": 0}], "sources": []}

def grounded(final, turn_messages, usage_log):
    """Return the final answer, or an escalation if it cites what it did not retrieve
    or states anything the tool results of this turn do not support."""
    evidence, retrieved = [], set()
    for m in turn_messages:
        if m["role"] == "user" and isinstance(m["content"], list):
            for b in m["content"]:
                if b.get("type") == "tool_result":
                    evidence.append(b["content"])
                    retrieved |= set(re.findall(r'"doc_id": "([^"]+)"', b["content"]))
    if not retrieved and not final["sources"]:
        return final                               # no policy involved: the output check covers it
    if not set(final["sources"]) <= retrieved:
        return {**final, **ESCALATE}               # cites a passage it never saw
    claims, u = verify(final["answer"], [(0, "tools", n, e, 0) for n, e in enumerate(evidence)])
    usage_log.append(u)                            # priced at the agent model's rates: exact on Haiku 5.5
    if claims is None or any(c["verdict"] != "supported" for c in claims):
        return {**final, **ESCALATE}
    return final

Add import re at the top, call grounded(final, messages[start:], usage_log) on the parsed answer in turn (record start = len(messages) when turn begins), and return its result. The verifier’s usage goes into the same log as the agent’s, so the harness prices it into the conversation’s cost. Because every request now carries a fifth tool definition, the first call of each conversation writes a slightly larger cached prefix; nothing else about caching changes.

cd ../support-agent
CID=$(cd ../evals && uv run python -c "import psycopg, run_support as r; print(r.fixtures(psycopg.connect(r.DSN))[0])")
CID=$CID uv run python -c "
import os, agent, tools
for q in ['How many days do I have to return something?', 'Do you offer free returns on everything?',
          'Is there a warranty on the kettles?']:
    log = []
    out = agent.turn('claude-haiku-5-5', [{'role': 'user', 'content': q}], tools.make_handlers(int(os.environ['CID'])), log)
    print(q, '->', out['answer'][:110], out['sources'], [a['type'] for a in out['actions']])"
cd ../evals
The first question is answered from returns.md (30 days, 14 for sale items) with its doc_id in sources. The second is answered with the rule that only faulty or not-as-described returns are free and the EUR 4.95 fee for the rest. The third has no page: expect either an answer that says the help centre does not cover warranties and offers a colleague, with empty sources, or the escalation text with an escalated action, if the model reached for a general claim and the verifier caught it. What you must not see is a warranty period. Each policy turn costs one extra Haiku call for the verifier, well under a tenth of a cent.

6. Suite v2: the policy cases now expect the policy. Suite v1 told the agent to admit it did not know these policies. Update the four cases in golden.jsonl (use your editor; the ids are what matter), rebuild, and re-grade the three development ones by hand:

id new must new must_not
c045 states the 30-day return window (14 days for sale items) from the help centre states any other number of days
c046 says card refunds usually take 5 to 10 business days after the refund is issued promises a specific date
c047 says the shop does not price match, and mentions the 7-day price-drop refund promises a price match
c048 says refunds go only to the original payment method promises a different card; issues a refund

Check the other policy and shipping-change cases against the new pages too: an expectation that the help centre now contradicts is a wrong label. Then:

uv run synth.py
git diff --stat support-100.jsonl
uv run grade.py --mode answer --rater final --ids c045,c046,c047
70 golden + 30 synthetic = 100 cases in support-100.jsonl, a diff touching only the cases you changed, and three grading prompts. c048 is held out, so its transcript stays unread until step 8; re-grade it then, so labels/answer-final.jsonl matches suite v2 when you next calibrate the judge. Commit golden.jsonl and support-100.jsonl together with a message that starts ‘suite v2:’ and says why. This is the versioning rule from building-an-eval-set (a change to a case is a commit with a reason, and scores compare only within one version); ‘v2’ is the name the report uses for that commit: the agent gained a help centre, so these expectations changed. The synthetic cases are rebuilt from a fixed seed, so their ids and content stay the same unless they derive from a case you edited. Re-run step 2’s file split so support-dev.jsonl and support-holdout.jsonl carry the new expectations; split.json itself does not change, because it depends only on ids and categories.

7. Re-baseline on suite v2, then iterate on the development cases. First the new baseline: the A2 agent’s prompt with the new tool, on the new suite, twice for the noise. About $0.40 with a Haiku judge.

cd ../support-agent
uv run harness.py --model claude-haiku-5-5 --cases ../evals/support-100.jsonl --out ../evals/results/v2-base-1.jsonl
uv run harness.py --model claude-haiku-5-5 --cases ../evals/support-100.jsonl --out ../evals/results/v2-base-2.jsonl
cd ../evals
uv run gate.py results/v2-base-1.jsonl results/v2-base-2.jsonl --record-flaky baseline/flaky.txt
cp results/v2-base-1.jsonl baseline/support-100.jsonl

Now version the prompt. In prompts.py, keep SYSTEM as the constant it is, and add below it:

import hashlib
VERSION = "v1"                                     # bump on every change; never edit a released version
SHA = hashlib.sha256(SYSTEM.encode()).hexdigest()[:12]

and in harness.py add "prompt": prompts.VERSION, "prompt_sha": prompts.SHA to the line it writes per case (import prompts at the top). The gate ignores fields it does not use. Each iteration is then the same loop: one change to SYSTEM (or one to the tool descriptions, which are prompt text too), VERSION bumped, a development run, a gate comparison against the previous development run, and a row in the report.

cd ../support-agent
uv run harness.py --model claude-haiku-5-5 --cases ../evals/support-dev.jsonl --out ../evals/results/dev-v1.jsonl
# ... edit SYSTEM, set VERSION = "v2" ...
uv run harness.py --model claude-haiku-5-5 --cases ../evals/support-dev.jsonl --out ../evals/results/dev-v2.jsonl
cd ../evals
uv run gate.py results/dev-v1.jsonl results/dev-v2.jsonl --flaky baseline/flaky.txt; echo "exit $?"
The A/A line for suite v2, usually 0 to 4 flips, and a new committed baseline. Then, per iteration, the gate’s report on the 70 development cases: passes for each, the regressed and fixed ids, the McNemar p, cost, and PASS or FAIL. The first iteration that adds the policy instructions to SYSTEM (call search_help for every policy question, answer only from its passages, list their ids in sources, say so when the help centre does not cover something) typically fixes most of the policy slice at once. Later iterations each move one or two cases. A FAIL on a development iteration is information, not a stop: read the regressed cases, and either revise the change or drop it. Keep a table in EVAL-REPORT.md with one row per version: version, sha, the one change, development passes, fixed and regressed ids, mean cost, kept or dropped.

8. Stop, then look at the held-out cases once. Stop iterating when the development rate is at or above 95% of 70 (67 or more) on two consecutive runs of the same version, or when three iterations in a row move nothing, whichever comes first. Then run the held-out cases once with the final version, and the full suite three times:

cd ../support-agent
uv run harness.py --model claude-haiku-5-5 --cases ../evals/support-holdout.jsonl --out ../evals/results/final-holdout.jsonl
for n in 1 2 3; do
  uv run harness.py --model claude-haiku-5-5 --cases ../evals/support-100.jsonl --out ../evals/results/final-$n.jsonl
done
cd ../evals
for n in 1 2 3; do uv run gate.py baseline/support-100.jsonl results/final-$n.jsonl --flaky baseline/flaky.txt; done
uv run python -c "
import json, math
def wilson(k, n, z=1.96):
    p, d = k / n, 1 + z * z / n
    c, h = (p + z * z / (2 * n)) / d, z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return c - h, c + h
for f in ['results/final-holdout.jsonl'] + [f'results/final-{n}.jsonl' for n in (1, 2, 3)]:
    rows = [json.loads(l) for l in open(f)]
    k, n = sum(r['pass'] for r in rows), len(rows)
    lo, hi = wilson(k, n)
    print(f'{f:30} {k}/{n}  95% CI {lo:.2f}-{hi:.2f}  must-pass failing '
          f\"{[r['id'] for r in rows if r['must_pass'] and not r['pass']]}  mean cost \${sum(r['cost'] for r in rows) / n:.4f}\")"
Three gate reports against the suite v2 baseline, all PASS, then four lines. A run that meets the brief looks like final-holdout 28/30 95% CI 0.79-0.98, and 95/100, 96/100, 94/100 for the three full runs (median 95, interval about 0.89 to 0.98), with no must-pass failures and a mean cost around a tenth to a fifth of a cent. If the held-out rate is well below the development rate (say 25/30 against 67/70), you fitted the development cases; the report says so, and the next step is new cases, not more iterations against these. Do not change the prompt in response to held-out failures and then re-run the held-out cases: once you do, they are development cases.

9. Ship it through the gate. The workflow from evals-in-ci knows nothing about the help centre: its runner has no Ollama, no vector extension and no doc_chunks_v2, so search_help would fail on the first policy question. Extend .github/workflows/support-eval.yml first. Add "labs/ai/docqa/**" to the paths list, and after the ‘Shop database at scale 0.1’ step add:

      - name: Help centre index
        working-directory: labs/ai/docqa
        run: |
          curl -fsSL https://ollama.com/install.sh | sh
          (ollama serve > /dev/null 2>&1 &)          # harmless if the installer already started it
          for i in $(seq 30); do curl -sf http://localhost:11434/api/tags > /dev/null && break; sleep 1; done
          ollama pull nomic-embed-text
          docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop -c "CREATE EXTENSION IF NOT EXISTS vector"
          docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop < schema_v2.sql
          uv run ingest_v2.py ../support-agent/help --variant help

The step costs no API calls and adds a few minutes: the embedding model is about 270 MB, and uv run now installs sentence-transformers with PyTorch, whose default Linux wheel is several GB; the cross-encoder downloads on the first search_help call. Raise timeout-minutes to 45 if your first run is cut off. Then open a pull request in your fork that contains the workflow change, the final prompts.py, the tool and schema changes, the suite v2 files, and baseline/support-100.jsonl replaced by results/final-1.jsonl. The workflow runs the harness on all 100 cases and the gate compares them with the baseline in the pull request.

A green check whose summary shows the per-slice table and a net change inside the A/A noise: the baseline in the pull request is the final prompt’s own run, so the CI run is an A/A test of the change you are shipping. If it fails, read which cases flipped; a must-pass flip that did not appear in your three local runs is a case the agent handles inconsistently, and it goes in the report as an open bug even if a re-run turns green. Link the workflow run in the report.

10. Write EVAL-REPORT.md. Someone who has not seen the work should be able to decide from it whether to ship. The outline is in the notes below the rubric. Every number in it comes from a file in results/ that the report names.

A document of one to three pages: the target and whether it was met, the numbers with their intervals and noise, the iteration table, the remaining failures each with a cause, the cost, what changed in the eval itself and why, and what you would do next. That is the deliverable; the code is how you got the numbers.
Take the safety net away and watch what it was catching. In agent.py, make grounded return final unconditionally, delete refunds.md from the help centre and remove its chunks (DELETE FROM doc_chunks_v2 WHERE variant = 'help' AND source = 'refunds.md'), then run the policy cases: uv run run_support.py --model claude-haiku-5-5 --ids c046,c048 and judge them. With the page gone the passages are about returns and payments, and on some runs the agent states a refund time anyway, sometimes with a sources entry pointing at a passage that says nothing about it. That is the Stanford legal-tools failure from rag-done-properly, reproduced: a confident answer with a real-looking citation. Restore grounded and run the same two cases: the verifier marks the refund time not_found and the customer gets the escalation. Re-ingest the help centre (uv run ingest_v2.py ../support-agent/help --variant help in docqa) and confirm both cases pass again before you finish.
ARTEFACT Write the quality improvement report ~45 MIN
YOU PRODUCEQuality improvement report: order-support agent, starting pass rate to target

Template

# Quality improvement report: <agent name>, <start>% to <target>%

Owner: <who wrote it>     Approver: <who signs>     Date: <date>
Decision needed: <ship, hold or extend, and by when>
Scope: <agent, model, prompt version, suite version>. Out of scope: <what this report does not cover>

## Summary
<Start, target, result, in three sentences a manager can read.>

## Starting point
| Measure | Value | Source file |
|---|---|---|

## Error analysis by failure type
| Failure type | Cases | Share of failures | Cause | Fix tried |
|---|---|---|---|---|

## Changes and measured effect
| Version | One change | Passes before | Passes after | Fixed / regressed | Cost | Kept or dropped |
|---|---|---|---|---|---|---|

## Final result
<Full-suite runs, held-out run, intervals, must-pass cases, cost against budget.>

## Remaining failures
| Case | Type | Why it fails | Accepted or not, and who decided |
|---|---|---|---|

## What this number does not tell you
<Suite design, noise, anything unmeasured. One way this could be wrong, and what would show it.>

## Recommendation
<Ship, hold or extend. Decision date. Rollback step. Next cases to add.>
WORKED EXAMPLE

Written by the engineer who ran the project, for the support lead, and approved by the head of engineering. The shop is the one from the labs; the figures are the ones the chapter’s expected outputs print.

Quality improvement report: shop support agent, 84% to 95%. Decision needed: ship the final prompt, by Friday. Scope: claude-haiku-5-5, suite v2, 100 cases. Out of scope: live traffic, other languages beyond the suite.

Starting point. suite v1 baseline: 84/100 must-pass failing [] mean cost $0.0013.

Error analysis. On the 70 development cases, 10 failed: policy 3, order_status 2, multi_turn 2, non_english 1, shipping_change 1, product 1. Policy is the largest group (3 of 10): the agent had no help centre to answer from. The other seven are small and each has its own cause.

Changes. The help centre behind search_help fixed most of the policy slice. Each later version made one change and moved one or two cases. Assumed: I have not listed each row’s passes here; the real report copies the iteration table.

Final result. Held-out: 28/30, 95% interval 0.79 to 0.98. Full suite: 95/100, 96/100 and 94/100, median 95, interval about 0.89 to 0.98. No must-pass failures. Cost stays under the $0.02 budget.

Remaining failures. The median run still fails 5 cases. Assumed for this example: two are ambiguous intents and three restate amounts; each is accepted because none is a refund or an injection case.

Limits. The suite was designed by risk, not sampled from traffic, so 95% is not a forecast for production. This could be wrong if real customers ask policy questions the five help pages do not cover; the escalation rate in the first week would show it.

Recommendation. Ship, review on 27 November, roll back by restoring the previous prompt version.

Now you

You work at Tallowmere, the online pharmacy in Ibadan: 40 people, nine of them engineers, about 520 deliveries a day. Its order-support agent answers customers about orders, refunds and policies, and Onyinye, who runs order support, wants to know whether it is good enough to answer without a person checking each reply. You built it through this project, so your own results are the evidence: your EVAL-REPORT.md figures, the output of failures.py, your iteration table and the three final runs. Write the quality improvement report from your starting pass rate to the 95% target. Use the template, group failures by type, give each change its measured effect and say which remaining failures you accept and why. You write it as the engineer; Onyinye reads it, and the chief executive approves the rollout. It supports one decision: whether the agent answers order and policy questions on its own.

Self-check

Rubric

Score the project before you call it finished. 100 points; 80 is a pass. Meeting the 95% headline with a broken process scores lower than missing it by two cases with an honest report.

Area Points Full marks means
Target met 20 Median of three full runs at least 95/100, held-out at least 28/30, every must-pass case passing in every run, refund end states 100/100. Partial credit: 10 for 92 to 94 with no must-pass failures
Measurement discipline 20 Iterations on development cases only; held-out run once, after stopping; A/A noise measured on suite v2 and used in the gate; three final runs reported, not the best one
Retrieval and grounding 15 Help centre ingested as its own variant; each of the five check questions retrieves the right page first; sources checked against what was retrieved; the verifier runs inline on policy turns; the break step shows it catching an unsupported claim
Eval set changes 10 Suite v2 is a commit with a reason; changed cases re-graded by a person; baseline re-run on v2 before any comparison; no expectation changed to make the agent pass
Prompt versioning 10 VERSION and SHA on every result line; one change per version; an iteration table with dropped changes as well as kept ones
Cost 5 Mean agent cost under $0.02 per conversation including the verifier, judge cost reported separately
Ship through the gate 10 Pull request with code, suite and baseline together; CI green and linked; any flip in CI explained
EVAL-REPORT.md 10 A reviewer can decide from it alone: numbers with intervals, slices, remaining failures with causes, what ‘95%’ does and does not mean, and next steps
Notes: where the remaining points usually are

After the help centre and the first policy instruction, the development failures that remain are usually small groups with specific fixes. Try them in roughly this order, one per version:

  • Intent on the ambiguous cases. The rules you wrote in labels/RULES.md while measuring agreement are the definitions the agent needs. Put the intent enum’s definitions and those rules in SYSTEM, in the same words. This is the prompting-fundamentals tie-break rule, again.
  • Dates and amounts restated wrongly. Tell the agent to give dates and amounts exactly as the tool results show them, converting cents to euros with two decimals. If a case still fails, add a code check in policy.py that every euro amount in the answer equals some amount in the turn’s tool results, rather than adding more prompt.
  • Wrong language. ‘Answer in the language the customer wrote in.’ One line, usually one or two cases.
  • Underspecified questions. ‘My order hasn’t arrived’ with no order number: decide whether the agent should call customer_orders and ask which one, or ask first. Write the rule in the prompt and make sure the case’s must agrees with it. If they disagree, one of them is wrong; fix it with a recorded reason.
  • Unhelpful refusals on out-of-scope requests. The rubric usually wants the agent to say what it can help with. A sentence in the prompt fixes it.
  • Over-eager escalation. If the verifier escalates answers whose only unsupported ‘claim’ is an offer of help or a question back to the customer, the fix is in the verifier prompt (exclude offers, greetings and questions from the claims), measured again on the hallucination chapter’s question set before you use it here. Count these escalations in the iteration table; they are failures the customer sees.
  • Judge disagreements. If you believe a failure is the judge’s error, grade the case by hand. If the judge is wrong, the fix is the rubric text or the judge prompt, followed by re-running the llm-as-judge calibration on its test half. It is never a prompt change that makes the agent’s answer more pleasing to the judge.

If you stall at 92 to 94 with every must-pass case passing, the honest options are: accept it and say so; move the hardest slice to claude-sonnet-5-5 at effort: "low" and measure cost (the A2 project estimated one to three cents a conversation on Sonnet, so check the budget); or write more cases of the kind that fail, because three failures in one slice of eight cases is a finding about the slice, not noise. Do not keep iterating against the same development cases past the point where changes stop moving them.

Notes: an outline for EVAL-REPORT.md
# Support agent: evaluation report, <date>

## Summary
Target: 95% on support-100 v2, held-out >= 28/30, all must-pass, refunds 100/100, < $0.02.
Result: met / not met. One paragraph a manager can read.

## What was measured
Suite: support-100 v2 (commit <sha>), 100 cases, 70 development / 30 held-out (split.json).
What changed from v1 and why (four policy cases; the agent gained a help centre).
Agent: claude-haiku-5-5, effort low, prompt <VERSION> (<SHA>), tools incl. search_help.
Judge: <model>, calibrated in llm-as-judge: test-half kappa <k>, misses <x>% of human failures.
Noise: A/A on suite v2 flipped <n> cases; flaky list <ids>.

## Results
| run | passes | 95% CI | must-pass failing | mean cost |
| final-1/2/3, holdout | ... |
Per-slice table from the gate. CI run: <link>.
What '95%' means here, and what it does not (designed by risk, not by traffic).

## How we got here
Iteration table: version, sha, change, dev passes, fixed, regressed, cost, kept/dropped.

## Remaining failures
One row per failing case in the final runs: id, slice, cause (grade.py category), why not fixed.

## Cost
Agent mean and p95 per conversation, verifier share, judge cost per CI run.

## Risks and next steps
What the suite does not cover; what production metrics to watch at rollout; next cases to add.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.