Dev.to AI 🤖 Ai 👁 0 📖 19 min read

Your agent says it's done. Make your tests decide

In this article I'm going to show you how to check your coding agent's "done, all tests pass" with your own tests. We'll build it in five steps: a file of criteria, a report per test, a 38-line script, a Claude Code Stop

Your agent says it's done. Make your tests decide

In this article I'm going to show you how to check your coding agent's "done, all tests pass" with your own tests. We'll build it in five steps: a file of criteria, a report per test, a 38-line script, a Claude Code Stop hook and a required CI check.

I build Gitmoap, a code forge I run on my own, and it has a feature for exactly this. I'll get to it at the end. Everything before that works in any repository on any host. The Node script and the hook are tested: their output in this post is pasted, not typed.

The short version, if you are in a hurry

  • Write each criterion as a test name before the agent starts, and make your test runner leave a JUnit report, red or green.
  • A 38-line Node script joins the two and gives every criterion a verdict with a reason. A Stop hook hands those reasons back to the agent, and a required check holds the merge.
  • Both stop short in specific places, and I list them. The last part shows the same Definition of Done on Gitmoap, where the join is built in.

Let's get started!

What we're building: a join

To decide whether one acceptance criterion is met, we need three facts at the same time: the criterion, the result of the one test that proves it, and the commit that test ran on. Here they are, with names I made up:

Done is a join: a tracker's criterion bound to a test, a CI run's per-test result, and git's commit on main, joined on commit and test name.
Three facts that usually live in three products. The names are made up for the example.

Most setups never do that join. The tracker has a checkbox and has never run a test. CI has run every test, but it reports a total ("412 passed, 1 failed"), and a total can't tick a box because it can't say which test. In between sits the agent, which has read both and writes a sentence.

So let's do the join ourselves, as cheaply as possible, and then see where cheap runs out.

Step 1: write "done" as test names, before the agent starts

Put the Definition of Done for the work on this branch in a file. I call it DONE.json. Each criterion is a sentence a person can read and, where a machine can check it, the exact name of the test that proves it:

{
  "work_item": "Tell a prerelease from a release",
  "criteria": [
    { "text": "isPrerelease tells a prerelease from a release",
      "test": "isPrerelease > tells a prerelease from a release" },
    { "text": "Versions still order by semver precedence",
      "test": "VER-ORDER — semver precedence > orders the Semantic Versioning example list" },
    { "text": "The parser's error keeps the given text",
      "test": "VER-PARSE — version syntax > keeps the given text on the error" },
    { "text": "The README shows how to use it", "required": false }
  ]
}

Here's one of those criteria, taken apart:

The first criterion of DONE.json: a text for people, and a test name for the script.
No test key? Then a person ticks it.

Three things matter here:

  1. Name the test before the agent starts. If the agent names the test, the agent defines done. When you name it, a test called anything else doesn't count.
  2. Use the name your runner writes into its report, not the name you'd say out loud. Four common runners are in the table below.
  3. Leave the criteria a machine can't check as plain sentences. "The README shows how to use it" is a good criterion, and it's a person's call. A Definition of Done that demands a test for every line is one nobody writes.
Runner The name in its report
Vitest describe > it
pytest the function as name, the module path as classname
cargo-nextest the test path as name, the binary as classname
go test TestRetry/no_double_charge

Step 2: leave a report for every test, red or green

The join needs a result per test, and every mainstream runner can write one as JUnit XML:

# Vitest: in vitest.config.ts, reporters: ["default", "junit"], outputFile: { junit: "reports/junit.xml" }
npx vitest run

# pytest
pytest --junitxml=reports/junit.xml

# Go, through gotestsum
gotestsum --junitfile reports/junit.xml -- ./...

# Rust: .config/nextest.toml has [profile.ci.junit] path = "junit.xml"
cargo nextest run --profile ci        # writes target/nextest/ci/junit.xml

There's one rule in this step, and I got it wrong in my own product for 114 days: the report has to exist when the tests fail.

In Gitmoap's first version, the report was an output of the test step, and a step's outputs only existed when the step succeeded. So a failing test threw away its own report. My checker saw "no tests", which is not the same as "a test failed".

A red test is the most important thing a report will ever say, and mine couldn't say it.

Here's that design, and what one failing test did to it:

Two chains: the design, where a report goes from the test step to the work item; and one failing test, where the outputs are skipped, the second step never runs and the criterion goes stale.
From the commit that fixed it, 7 November 2026.

The longer version of that story is in my Medium post.

Every runner above writes its report on failure. So make sure nothing between the runner and your checker deletes it, or skips the step that reads it.

Step 3: the join, in 38 lines

Now the fun part. The script has no dependencies and needs Node 18 or later. It reads DONE.json and a JUnit report, and gives every criterion a verdict with a reason:

// check-done.mjs: join a Definition of Done to a JUnit report.
// usage: node scripts/check-done.mjs [DONE.json] [reports/junit.xml]
import { existsSync, readFileSync } from "node:fs";

const [donePath = "DONE.json", reportPath = "reports/junit.xml"] = process.argv.slice(2);
const { criteria } = JSON.parse(readFileSync(donePath, "utf8"));

// 1. Per-test results: "suite::name" and "name" -> passed | failed | skipped.
const decode = (s) =>
  s.replace(/&(lt|gt|quot|apos|amp);/g, (_, e) => ({ lt: "<", gt: ">", quot: '"', apos: "'", amp: "&" })[e]);
const attrs = (s) => Object.fromEntries([...s.matchAll(/([\w:-]+)\s*=\s*"([^"]*)"/g)].map(([, k, v]) => [k, decode(v)]));
// Conjunctive: failed anywhere beats passed; passed beats skipped (a skip proves nothing).
const worse = (a, b) => (a === "failed" || b === "failed" ? "failed" : a === "passed" || b === "passed" ? "passed" : "skipped");

const results = new Map();
const report = existsSync(reportPath) ? readFileSync(reportPath, "utf8") : "";
const testcase = /<testcase\b((?:[^>"']|"[^"]*"|'[^']*')*?)(\/>|>([\s\S]*?)<\/testcase>)/g;
for (const [, rawAttrs, , body = ""] of report.matchAll(testcase)) {
  const { name, classname = "" } = attrs(rawAttrs);
  const status = /<(failure|error)\b/.test(body) ? "failed" : /<skipped\b/.test(body) ? "skipped" : "passed";
  for (const key of [name, `${classname}::${name}`]) results.set(key, worse(results.get(key), status));
}

// 2. Each criterion against them, with a reason a person (or an agent) can act on.
const verdicts = criteria.map((c) => {
  const required = c.required ?? true;
  if (!c.test) return { ...c, required, met: c.checked === true, reason: c.checked ? "ticked" : "not ticked" };
  if (results.size === 0) return { ...c, required, met: false, reason: "no report: no step wrote one" };
  const status = results.get(c.suite ? `${c.suite}::${c.test}` : c.test);
  if (status === undefined) return { ...c, required, met: false, reason: "not in any report" };
  if (status === "skipped") return { ...c, required, met: false, reason: "skipped, which proves nothing" };
  return { ...c, required, met: status === "passed", reason: status };
});

for (const v of verdicts) console.log(`${v.met ? "✓" : "✗"} ${v.text} (${v.reason})${v.required ? "" : " [optional]"}`);
const unmet = verdicts.filter((v) => v.required && !v.met);
console.log(`${verdicts.filter((v) => v.required).length - unmet.length} of ${verdicts.filter((v) => v.required).length} required criteria met`);
process.exit(unmet.length === 0 ? 0 : 1);

Let's run it. In this report the agent wrote a test called isPrerelease > works instead of the one the criterion names, and an assertion failed in another test:

A terminal: check-done.mjs on a red report. One test is not in any report, one failed, and 1 of 3 required criteria are met.
Real output of the post's script, on a report where one test has the wrong name and one failed.

So we get three different answers for the three required criteria: a pass, a failure, and a test that isn't in the report at all.

Four decisions are baked into the script, and I'd keep each one if you rewrite it:

  • A name that fails anywhere is failing. If a test name passes in one suite and fails in another, it's failing. Anything else lets a criterion go green while the thing it names is broken.
  • A skipped test proves nothing. It's neither a pass nor a fail.
  • "Not in any report" is not "failed". It's a different problem with a different fix: rename the test, or point the criterion at the right one.
  • No report is never a pass. If no step wrote anything, every criterion with a test is unmet.

To be fair, parsing XML with a regex is nothing to be proud of. It copes with the JUnit a test runner writes, including > inside quoted names and self-closing <testcase/>. Use an XML parser if you'll ever feed it anything else.

Step 4: hold the agent with a Stop hook

Claude Code runs a Stop hook when it finishes responding. If the hook prints {"decision": "block", "reason": "…"}, Claude Code doesn't stop: it gets the reason and keeps working (Claude Code's hooks reference, read 20 November 2026).

Register the hook in .claude/settings.json:

{
  "hooks": {
    "Stop": [
      { "hooks": [{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/definition-of-done.sh" }] }
    ]
  }
}

And here's the hook itself:

#!/usr/bin/env bash
# A Claude Code Stop hook: the agent may finish only when DONE.json is met.
cd "${CLAUDE_PROJECT_DIR:-.}" || exit 0
cat >/dev/null                      # the hook's input; this check does not need it
[ -f DONE.json ] || exit 0          # no Definition of Done on this branch: nothing to hold

rm -f reports/junit.xml             # never judge this turn by the last turn's report
npm test >/dev/null 2>&1            # writes reports/junit.xml, whether the tests pass or fail

if verdict="$(node scripts/check-done.mjs DONE.json reports/junit.xml)"; then
  exit 0                            # every required criterion is met: let it stop
fi
jq -n --arg v "$verdict" '{
  decision: "block",
  reason: ("DONE.json is not met yet:\n" + $v + "\nKeep working until every required criterion is met. Do not edit DONE.json.")
}'

The rm -f matters more than it looks. Without it, a compile error that stops the test runner before it writes anything leaves the last turn's green report in place. Then the hook happily judges new code by old evidence.

Now "done, all tests pass" gets an answer from your machine, and not a nod from you. Here's that answer, and what the script says once the test with the right name exists:

A terminal: the Stop hook blocks with one criterion not in any report and 2 of 3 required met; after the test is written the script reports 3 of 3 and the hook lets the agent stop.
The post's own hook and script on its two example reports. Cut short.

What about endless loops? The hook's input has a stop_hook_active flag, which says the turn is already continuing because of a stop hook, and the documentation recommends checking it. I don't. I lean on Claude Code's own limit: after a stop hook has continued the turn eight times in a row, it ends the turn anyway.

That count resets whenever the agent calls a tool. So an agent that keeps working stays held, and an agent that's stuck is let go after eight tries.

Where the hook stops

  • It's on your machine. It runs inside the agent's own session, and it isn't on anyone's merge. Your teammate's agent, without the hook, is not held.
  • It judges the working tree, not a commit. What it checked may never be pushed, or may be pushed together with something it never saw.
  • It lives where the agent writes. .claude/settings.json, the hook script and DONE.json all sit in the repository the agent edits. "Do not edit DONE.json" is a request. Deny edits to those paths in your Claude Code permission settings if you mean it.
  • It runs your test suite every time the agent stops. That's fine for a library and painful for a monorepo. Run only the named tests if your runner can filter.
  • It forgets. When the test goes red next month, nothing tells the work it proved.

Step 5: hold the merge with a required check

Run the same script in CI, after the tests and also when they fail, and make the job a required status check:

# .github/workflows/definition-of-done.yml
name: definition-of-done
on: pull_request
jobs:
  done:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npm test                                   # writes reports/junit.xml, red or green
      - run: node scripts/check-done.mjs DONE.json reports/junit.xml
        if: ${{ !cancelled() }}                         # read the report when the tests failed too

Then make definition-of-done / done required on your protected branch. And protect the criteria themselves with a code owner:

# .github/CODEOWNERS
/DONE.json  @your-handle

Turn on "Require review from Code Owners" as well. Now the agent can propose a change to the Definition of Done, but it can't merge one past you.

Where the required check stops

  • Skipped counts as passing. GitHub's documentation says required status checks "must have a successful, skipped, or neutral status" (docs.github.com, "About protected branches", read 20 November 2026). A job whose if: condition was false reports skipped. For a Definition of Done, no evidence should never be a pass.
  • The criteria travel inside the change they judge. DONE.json is part of the pull request. The code owner rule helps, but the Definition of Done should live with the work item, and not in the diff.
  • It knows a file, not an issue. Closes #12 closes the issue on merge, whether or not DONE.json was the Definition of Done for #12.
  • It judges the head, never the product. The check proves the criteria at the pull request's head. Nothing records that they held on main after the merge, and nothing notices when they stop holding.

Here are the three levels again, with where each one stops:

Three ways to hold done and where each one stops: test names in the task, a Stop hook, a required check.

What a script can't do cheaply

There are four things where the join needs the tracker, the CI results and the history in one place. I couldn't find a cheap way to build them on top of separate products, and they're the reason I built them into a forge.

  1. "Safe to merge" versus "done". A run at a merge request's head proves the change is safe to merge. Only a run on the branch you ship proves the work is done. Those are two facts with two lifetimes: the first lasts until the next push, the second until the next run on main.
  2. Whose absence counts. A test missing from a run is "stale", not "failed", and only when the same step that last proved the criterion ran again and reported completely. Otherwise your lint pipeline, which reports no tests, quietly unproves every criterion you have.
  3. Order by ancestry, not by clock. A slow run on an old commit that finishes after a fast run on a newer one must not overwrite the newer verdict. That takes git merge-base, for every stored verdict.
  4. Coming back. When the test that proved a closed item goes red on main, the item should reopen, and say which commit was last green and which was first red.

For instance, here's how Gitmoap decides point 2 (simplified, the comments are mine):

fn is_stale<T>(row: &BindingRow<T>, evidence: &RunEvidence, rule: StaleRule<'_>) -> bool {
    let StaleRule::ByPipeline(run_pipeline) = rule else { return false };
    if row.last_evidence_pipeline_id.as_ref() != Some(run_pipeline) {
        return false; // another pipeline never proved it, so it cannot unprove it
    }
    match &row.last_evidence_node_id {
        // the step that last proved it ran again, and was read in full
        Some(node) => evidence.nodes.get(node).is_some_and(|n| n.end.ran() && n.complete),
        None => evidence.every_ran_step_complete(),
    }
}

And there's a fifth one, which is a policy and not a feature: decide who may write evidence. If anyone who can start a CI run can also choose its steps and its commit, they can make it vouch for anything.

The same Definition of Done on Gitmoap

Here's how the five steps look where the join is built in. The example is the public showcase repository gitmoap-showcase/commitkit, a small TypeScript library that parses Conventional Commits and works out the next version.

The criteria live on the work item. Each one can be bound to a test, a coverage floor, a measurement or a pipeline step. From the CLI:

gitmoap issue-criteria create --repo-id gitmoap-showcase/commitkit --issue-id 4 --data - <<'EOF'
{
  "text": "isPrerelease tells a prerelease from a release",
  "binding": { "kind": "test", "test_id": "isPrerelease > tells a prerelease from a release" }
}
EOF

Nobody can tick a bound criterion. If you try anyway, this is the answer:

A terminal: ticking a bound criterion by hand is refused with CRITERION_IS_BOUND (409).
Rebuilt from the API's and the command line's own wording. I didn't run it on the live site.

commitkit goes one step further. With the Gitmoap Terraform provider, it declares a work-item type whose Definition of Done every change inherits. Here it is (trimmed: the full file also carries descriptions, categories and an optional docs facet):

resource "gitmoap_repository_issue_blueprint" "library_change" {
  blueprint_id = "library-change"
  name         = "Library change"
  base_type    = "story"
  facets = [
    { key = "rule",  label = "Rule",  required = true,  binding = { mode = "manual" },
      hint = "The rule this change implements is declared in specs/, and names the tests that enforce it" },
    { key = "tests", label = "Tests", required = true,
      binding = { mode = "bound", criterion = { kind = "node", node_id = "test" } } },
    { key = "lint",  label = "Lint",  required = true,
      binding = { mode = "bound", criterion = { kind = "node", node_id = "lint" } } },
    { key = "coverage", label = "Coverage", required = true,
      binding = { mode = "bound", criterion = { kind = "coverage", path_glob = "src/**/*.ts", min_pct = 95 } } },
  ]
}

The test step leaves its report, and nothing has to wire it. commitkit's pipelines are HCL files in .gitmoap/pipelines/ci/. Here's its test step:

step "test" {
  name       = "Unit tests"
  uses       = "node:test"
  connection = "npm-read"
  inputs     = { source = step.clone.source }
  with = {
    test_command    = "npm test -- --maxWorkers=1"
    report_format   = "junit"
    report_path     = "reports/junit.xml"
    coverage_report = "coverage/lcov.info"
  }
}

Every step has a reports folder (GITMOAP_REPORTS_DIR), and the launcher reads it after the step ends, however it ended. The built-in test steps for Rust, Go, Node, Playwright, Python, PHP, Ruby, Java, Kotlin and .NET put their runner's report there.

For test results, Rust needs test_runner: nextest and Node needs report_format: junit. The others need nothing with their default commands. A shell step writes into the folder with one flag: pytest --junitxml="$GITMOAP_REPORTS_DIR/pytest.xml".

The gate is a setting. commitkit declares it with the Gitmoap Terraform provider (an excerpt):

resource "gitmoap_repository_mr_settings" "commitkit" {
  repo_id                      = gitmoap_repository.commitkit.repository_id
  override_group_settings      = true
  require_pipeline_success     = true
  require_issue_criteria_green = true
}

The merge check is the join, with a reason per criterion. This is the answer for commitkit's !2 on 20 November 2026, cut down to its issue_criteria check and two of its seven criteria, with the ids removed:

$ gitmoap mr merge-check --repo-id gitmoap-showcase/commitkit --mr-id 2 --output json
{
  "check": "issue_criteria",
  "status": "passed",
  "criteria_state": "passed",
  "message": "7/7 required acceptance criteria are satisfied at the head",
  "criteria": [
    { "text": "Every source file keeps at least 95% line coverage",
      "satisfied": true, "reason": "passing", "node_id": "test", "value": 100.0 },
    { "text": "git's revert message is read as the commit it undoes",
      "satisfied": true, "reason": "passing", "node_id": "test" }
  ]
}

And the work item behind !2? Still unverified on 20 November, because that merge request hasn't merged. The proof at its head says it's safe to merge. Only the run on main after the merge can say it's done:

The same work asked twice: commitkit!2's head satisfies all seven required criteria, each proved by a pipeline step; the work item it closes, commitkit#1, stays unverified on main.
Read through Gitmoap's MCP server and command line, November 2026.

When a criterion isn't met, the check gives its reason. Here are eight of the nine reasons, with the words the merge check uses for each (the ninth, not_passing, is for a service check):

reason What the merge check says
failing failing
pending waiting for a pipeline
no_run no pipeline tested this head
no_report no step sent a report
not_reported not in any report
rerun_needed bound since the last run; run the pipelines again
skipped its step did not run
unchecked not ticked

And the merge is refused with a message that names the criterion and its reason:

Merge blocked: 1 of 7 required acceptance criteria are not satisfied at the head: <criterion text> (<reason in words>)

Here's an illustration of that refusal, with the merge check's own names and message format:

Illustration of a merge check: not a draft, approvals satisfied, every pipeline passed, and the merge still refused because one required acceptance criterion has no test result at the head commit.
An illustration, in the merge check's real names and wording.

The agent reads all of it over MCP. Connect Claude Code with a token you mint in Gitmoap: Settings, Access tokens, the mcp_agent_write bundle, bound to one repository if that's all it needs (https://docs.gitmoap.com/guides/access-tokens).

claude mcp add --transport http gitmoap https://api.gitmoap.com/mcp \
  --header "Authorization: Bearer gmp_…"

The server's own instructions, which every client receives, already tell the agent what to do: "Read them before starting work and again after, to check whether the work actually finished." Two tools do the reading:

  • gitmoap_issue_get returns the criteria and whether each passes on the branches that ship.
  • gitmoap_mr_get returns the merge request's blocking list, with each unmet criterion's reason and the run and step that decided it.

Here's Claude Code calling both on commitkit:

A terminal: Claude Code reading commitkit#1's acceptance criteria and commitkit!2's merge check through Gitmoap's MCP server.
Real calls from Claude Code to Gitmoap's MCP server, 21 November 2026. The JSON is cut short.

If you want it spelled out for your own repository, a few lines like these in CLAUDE.md do it:

## Definition of Done
- Before you start a work item, read it with gitmoap_issue_get and list its criteria back to me.
- You are done when the merge request's issue_criteria check says passed, not before.
- If a criterion says "not in any report", the test it names does not exist yet: write that test, with that name.

What it costs

  • With the standard agent connection, the agent can edit the criteria. mcp_agent_write includes issue:update, which every criterion write needs. The agent can't tick a bound criterion, but it can reword, unbind, make optional or delete one, and deleting the last unmet required criterion opens the gate.
  • The way around it is a token without issue:update. The agent still reads everything, and it can't edit work items either.
  • A criterion is only as good as its test. Naming the test in advance stops "I wrote a different test". It doesn't stop a weak test with the right name. So read the test.
  • Only pipelines saved in Gitmoap prove criteria. A GitHub Actions run can't. That's on purpose: the commit, the branch and the steps of the run have to be facts the platform holds, and not claims somebody sent.
  • Clone and push go through the Gitmoap git helper (Homebrew on Apple Silicon, apt, apk or the install script: https://docs.gitmoap.com/getting-started/install). There's no HTTPS or SSH yet, and no importer. A local agent is fine. A cloud sandbox needs the helper installed.
  • It's a free Beta run by one person, with no uptime commitment.

What I'd copy if I were you

If you only take one thing from this article, take this one:

Write "done" as test names before the agent starts, and let a script give the answer.

And then, in order of value:

  1. Start with DONE.json and the 38-line script. They work with any agent, and with any test runner that writes JUnit.
  2. Make the report survive a failure. Delete the old one before each run, and read the new one when the tests fail too.
  3. Add the Stop hook if you use Claude Code. It turns "done" into a question your machine answers.
  4. Add the required check as soon as more than one person, or more than one agent, pushes to the repository.
  5. Give every "no" a reason. "Not in any report" tells the agent which test is still missing.

An invite to you

Everything in Steps 1 to 5 is yours to copy. And if you want the join without maintaining it, there's Gitmoap: a code forge where a work item's Definition of Done is bound to tests, coverage and pipeline steps, decided by the pipeline, and read by your agent over MCP.

It's free and I run it alone. Your code is stored in AWS Ireland and isn't used to train generative AI models.

And you can try it today! Push one repository there next to wherever your code lives now, bind one criterion to one test, turn on the gate, and hand your agent the work item's address.

If your Stop hook does something smarter than mine, I'd love to see it. Questions, ideas, criticism: all welcome in the comments.

Cheers!
Kevin

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.