Cookbook: Fix an Issue behind a regression test
Reproduce an Issue as a test suite, gate the fix in CI, fold the cases into your baseline, and watch production for it.
Root-cause an Issue ends
with a diagnosis: when get_menu times out for Cedar Grill, the
lunch-order agent drops the restaurant
without telling the user. This cookbook takes that Issue the rest of the way
around the improvement loop: a test
suite that fails the way production did, a fix that makes it pass, a CI gate
on the pull request, and a judge on production traffic.
The Issue lifecycle is in early access, and so are test environments. Both work only for organizations where they're turned on. Contact support to turn them on.
Add the Issue gate to your CI with your coding agent
Paste it into your agent from your repo's root.
Prerequisites:
- The Judgment MCP server connected to your coding agent. See Connect your coding agent.
- Tests set up in the repo: a
.judgment/folder, a baseline suite, and a CI job that runsjudgeval test run. Follow Set up tests in your repo first. That page also covers the personal API key a run needs. - judgeval 1.10.2 or later.
Test runs and judges use Judgment Units.
Hand the Issue to your coding agent
Open the Issue and choose Fix with, then your coding agent, or Copy as prompt to paste it yourself. With the lifecycle on, the prompt does more than ask for a fix. On top of the Issue's description, impact and cited traces, it tells the agent to:
- Build the cases from the inputs the cited traces actually received, plus
one or two cases for nearby behavior that works today. Every case is tagged
issue:<issue ID>. - Build the environment: the seed data and tool results that put the
agent back where production was, as a file in
.judgment/environments/published withjudgeval test env push <name>. - Pick the judges: a code judge wherever the recorded tool calls answer the question, an agent judge only where the reply has to be read.
- Prove it: publish the suite, run it on the current code with
judgeval test run --suite "<suite name>"and see the Issue's cases fail, fix, and run the same version again until every case passes. Expected values never change to make a case pass. - Link the pull request with a
Judgment-Issue:line in its description.
The rest of this page shows what the coding agent builds for the Cedar Grill Issue, and what your CI does with it.
The environment
The environment starts from seed data, the office and the restaurants the
agent can order from, and adds the one condition that matters: every
get_menu call for Cedar Grill returns the timeout production saw. Calls for
other restaurants match no rule, so the real tool runs against the seed.
{
"description": "Cedar Grill's menu times out. Every other tool is real.",
"seed": {
"office": { "address": "500 Market St", "dietary_notes": ["6 vegetarian"] },
"restaurants": ["Olive & Thyme", "Falafel House", "Cedar Grill"]
},
"tools": {
"get_menu": [
{
"match": { "restaurant": "Cedar Grill" },
"return": { "error": "504 Gateway Timeout" }
}
]
}
}The coding agent publishes the file:
judgeval test env push menu-timeoutmenu-timeout@1 createdTwo things in the repo make the file take effect, and the agent checks both.
run in .judgment/run.py loads environment["seed"] before it calls the
agent, and get_menu is marked @mockable. Without the mark, the rule mocks
nothing and the case passes for the wrong reason. See
Apply the environment in run.py,
and Design a test environment
for how to keep one complete baseline and change one thing per environment.
The cases and the judge
The check reuses the judge from Root-cause an Issue, which reads the trace and returns No tool failure, Failed and told user or Failed silently. Whether the user was told is in the reply, so this is an agent judge.
| Case | Environment | Expected |
|---|---|---|
| "order me mediterranean food to feed 30 hungry engineers" (from an evidence trace) | menu-timeout@1 | Failed and told user |
| "mediterranean catering for 20 by noon" (from an evidence trace) | menu-timeout@1 | Failed and told user |
| "order me mediterranean food to feed 30 hungry engineers", every menu loads | baseline@1 | No tool failure |
The third case guards what works today: a fix that warns about restaurants
that loaded fine would break it. Each case is tagged issue:<issue ID> and
names its environment in metadata.environment. The coding agent adds them
with add_test_cases and publishes the suite with publish_test_suite.
Then it runs the suite on the current code:
judgeval test run --suite "Cedar Grill menu timeout"The two menu-timeout@1 cases come back Failed silently, and the command
exits with 1. That's the reproduction. The fix (retry get_menu
with backoff, then tell the user which restaurant couldn't be checked) turns
both into Failed and told user, and the third case still passes.
Link the pull request
The coding agent puts this line in the pull request description:
Judgment-Issue: https://app.judgmentlabs.ai/org/<org ID>/project/<project ID>/issues/<issue ID>The bare issue ID works too. Link a pull request on the Issue copies the
line for you. Nothing in the repository lists the Issue's suite: CI finds it
by the issue:<issue ID> tag on its cases.
Gate the pull request in CI
Judgment doesn't start runs. Your CI job does four things:
- Runs your baseline suites with
judgeval test run. This is the job from Set up tests in your repo. - Reads the
Judgment-Issue:line from the pull request description and links the pull request to the Issue, so the Issue page shows it with its test runs. - Runs every suite whose cases carry
issue:<issue ID>and haven't been folded yet, withjudgeval test run --suite. - After the merge, on
main, folds the Issue's cases into the baseline, so every later pull request runs them.
The baseline is the list in .judgment/judgment.json. The first suite in it
is the one Issue suites fold into:
{
"project": "lunch-order-agent",
"suites": ["Baseline"]
}judgeval test run has no option for steps 2 to 4 yet, so one script does
them and calls the command for the runs.
The script
import json
import os
import re
import subprocess
import sys
import urllib.request
from pathlib import Path
from judgeval import Judgeval
ISSUE_LINE = re.compile(r"^Judgment-Issue:\s*(?:\S*/)?([0-9a-f-]{36})\s*$", re.M | re.I)
FIELDS = ("name", "input", "expected", "tags")
REPO = os.environ["GITHUB_REPOSITORY"]
EVENT_NAME = os.environ["GITHUB_EVENT_NAME"]
config = json.loads(Path(".judgment/judgment.json").read_text())
client = Judgeval(project_name=config["project"])
event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
def pull_request() -> dict:
"""The pull request under test or, on main, the one whose merge made this commit."""
if "pull_request" in event:
return event["pull_request"]
if EVENT_NAME != "push":
return {} # a manual run links and folds nothing
sha = os.environ["GITHUB_SHA"]
found = subprocess.check_output(["gh", "api", f"repos/{REPO}/commits/{sha}/pulls"])
return next((p for p in json.loads(found) if p["merge_commit_sha"] == sha), {})
def link_pull_request(issue_id: str, pull: dict) -> None:
"""Record the pull request on the Issue. A failed link doesn't fail the gate."""
merged = bool(pull.get("merged_at"))
body = {
"repo": REPO,
"number": pull["number"],
"url": pull["html_url"],
"title": pull["title"],
"state": "merged" if merged else pull["state"],
**({"merged_sha": pull["merge_commit_sha"]} if merged else {}),
}
api = os.environ.get("JUDGMENT_API_URL", "https://api.judgmentlabs.ai")
request = urllib.request.Request(
f"{api}/v1/projects/{os.environ['JUDGMENT_PROJECT_ID']}/issues/{issue_id}/pull-requests",
data=json.dumps(body).encode(),
method="PUT",
headers={
"Authorization": f"Bearer {os.environ['JUDGMENT_API_KEY']}",
"X-Organization-Id": os.environ["JUDGMENT_ORG_ID"],
"Content-Type": "application/json",
},
)
try:
urllib.request.urlopen(request)
except Exception as error:
print(f"Could not link the pull request to Issue {issue_id}: {error}")
def all_cases(suite_id: str, **version) -> dict:
listing = client.test_suites.list_cases(suite_id, **version)
assert listing["next_offset"] is None, f"{suite_id} has more cases than one page"
return listing
def issue_suites(names: dict, baseline: list, issue_id: str) -> list:
"""Suites whose cases carry the Issue's tag and haven't been folded."""
found = []
for suite_id in names:
if suite_id in baseline:
continue
tags = {tag for case in all_cases(suite_id)["cases"] for tag in case["tags"]}
if f"issue:{issue_id}" in tags and not any(t.startswith("merged-into:") for t in tags):
found.append(suite_id)
return found
def fold(baseline_id: str, suite_id: str, merged_by: str) -> None:
"""Copy an Issue suite's cases into the baseline, then mark them folded."""
suites = client.test_suites
cases = all_cases(suite_id)["cases"]
published = all_cases(baseline_id)
in_draft = all_cases(baseline_id, version="draft")["cases"]
copied = {c["metadata"].get("source_case_id") for c in in_draft}
missing = [
{**{f: c[f] for f in FIELDS}, "metadata": {**c["metadata"], "source_case_id": c["case_id"]}}
for c in cases
if c["case_id"] not in copied
]
if missing:
suites.add_cases(baseline_id, missing)
if {c["case_id"] for c in cases} <= {c["metadata"].get("source_case_id") for c in published["cases"]}:
version = published["version"]
else:
version = suites.publish(baseline_id)["version"]
suites.create_draft(suite_id)
marks = [f"merged-into:{baseline_id}@v{version}", f"merged-by:{merged_by}"]
for c in cases:
case = {f: c[f] for f in (*FIELDS, "metadata")}
suites.update_case(suite_id, c["case_id"], {**case, "tags": c["tags"] + marks})
suites.publish(suite_id)
pull = pull_request()
match = ISSUE_LINE.search(pull.get("body") or "")
if pull and match:
link_pull_request(match[1].lower(), pull)
if EVENT_NAME == "pull_request" and pull["state"] == "closed":
sys.exit(0) # merged or abandoned: the link is updated, and main runs the suites
# A manual run names the Issue itself, to record the run before the fix.
issue_id = (os.environ.get("ISSUE") or (match[1] if match else "")).lower()
if not issue_id:
sys.exit(0)
listing = client.test_suites.list()
assert listing["next_offset"] is None, "more test suites than one page"
names = {suite["test_suite_id"]: suite["name"] for suite in listing["test_suites"]}
# judgment.json names its suites by ID or by name.
baseline = [next(i for i, n in names.items() if wanted in (i, n)) for wanted in config["suites"]]
suites = issue_suites(names, baseline, issue_id)
if not suites:
sys.exit(0)
selected = [argument for suite_id in suites for argument in ("--suite", suite_id)]
failed = subprocess.run(["judgeval", "test", "run", "--retry-failures", *selected]).returncode
baseline_passed = os.environ.get("BASELINE_OUTCOME", "success") == "success"
if not failed and baseline_passed and pull.get("merged_at") and EVENT_NAME == "push":
for suite_id in suites:
fold(baseline[0], suite_id, f"{REPO}#{pull['number']}")
sys.exit(failed)What each part does:
issue_suitesfinds the Issue's suites by tag, so a new Issue never needs a change tojudgment.json. A suite whose cases carrymerged-into:has already joined the baseline and doesn't run twice.listandlist_casesreturn one page, so the script stops rather than skip a suite it didn't see.judgeval test run --suiteplays the Issue's suites the same way the baseline step plays the baseline: it callsrunin.judgment/run.py, retries the failures once, prints each result, and exits1when a case fails. In GitHub Actions the command records the repository, the pull request and the job on each run, and the Issue page uses them to show a run under its pull request.- The run before the fix is a run of the Issue's suite with no pull
request. Start the workflow by hand on
mainwith the Issue ID before you merge, and the Issue page shows that run next to the pull request's. link_pull_requestrecords the pull request on the Issue. An open or merged pull request moves an Issue in Needs review to Fix in progress, and a merge records that the fix shipped. Closing the Issue's last open pull request without merging it returns the Issue to Needs review. To unlink a pull request whose description no longer names the Issue, sendDELETEto the same route withrepoandnumberas query parameters. A refused link is printed and the job carries on: the suites decide whether the pull request can merge.foldruns only on the push tomainthat the merge produced, and only after the baseline and the Issue's suites passed. Each copy records itssource_case_id, so a job that fails part way can be run again without copying a case twice. Publishing the baseline also publishes anything else in its draft.
The workflow
This is the workflow from Set up tests in your repo with the script as a second step. That page lists the secrets the job needs and what to change for your repo.
name: Judgment tests
on:
pull_request:
# edited: adding or removing the Judgment-Issue line reruns the job
# closed: an abandoned pull request returns the Issue to review
types: [opened, synchronize, reopened, edited, closed]
push:
branches: [main]
workflow_dispatch:
inputs:
issue:
description: Issue ID whose suites to run, such as before the fix merges
required: false
permissions:
contents: read
# On main, to find the pull request whose merge made the commit.
pull-requests: read
concurrency:
group: judgment-tests-${{ github.event.pull_request.number || github.ref }}
# never cancel a run on main: it may be folding a suite
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
judgment-tests:
# Pull requests from forks receive no secrets.
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
timeout-minutes: 65
env:
JUDGMENT_API_KEY: ${{ secrets.JUDGMENT_API_KEY }}
JUDGMENT_ORG_ID: ${{ vars.JUDGMENT_ORG_ID }}
JUDGMENT_PROJECT_ID: ${{ vars.JUDGMENT_PROJECT_ID }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
- name: Run the baseline suites
id: baseline
if: github.event.action != 'closed'
run: uv run judgeval test run --retry-failures
# Runs even when the baseline failed, so the pull request is still
# linked and the Issue's suites still run.
- name: Run the suites of the Issue this pull request names
if: ${{ !cancelled() }}
env:
GH_TOKEN: ${{ github.token }}
BASELINE_OUTCOME: ${{ steps.baseline.outcome }}
ISSUE: ${{ inputs.issue }}
run: uv run python .github/scripts/judgment_issue.pyJUDGMENT_PROJECT_ID is one more repository variable: the project's ID, from
the project's URL in Judgment. Mark the judgment-tests job as a required
status check, so the pull request can't merge until the baseline and the
Issue's suites pass.
Instructions for the coding agent
Work from the agent's root folder. Never print, log or commit an API key.
- Check that
.judgment/judgment.jsonexists and that a workflow already runsjudgeval test run. If either is missing, follow Set up tests in your repo first. - Add the script as
.github/scripts/judgment_issue.py. - Change the existing workflow to match the workflow: the
triggers, the permissions, the
idandifon the baseline step, and the second step. Keep the working directory and provider keys it already has. - Ask the user to add the
JUDGMENT_PROJECT_IDrepository variable. Don't read or set secrets yourself. - Show the user the diff. Tell them to mark the job as a required status check, and that each run spends Judgment Units.
Watch production
On the Issue page, the side panel shows the pull request with its test runs, the regression suite's runs before and after the fix, and, after the merge, where its cases were folded ("Folded into Baseline v4 by PR #212").
Cedar Grill is a trace Issue, so watch it with Review, then Monitor with Judge, and pick the judge and its Failed silently label; see Triage and fix. On a conversation Issue, choose Start watching instead: pick the judge and the label it watches for, and the dialog turns the judge on for production traffic if it isn't already. The Issue moves to Verifying fix and compares the label's rate since the watch started with the 14 days before.
To hear about it when the label comes back, add a judge action that posts to Slack.
What you did by hand
- Chose the Issue and handed it to your coding agent.
- Reviewed the cases, the environment and the fix in the pull request.
- Added one script to the CI job once. Every later Issue reuses it.
- Merged the pull request and started the production watch.