Beagle Lesson #5: How to Verify an AI Agent Actually Finished the Job Anthropic research published on November 21, 2025 found that models trained in coding environments deliberately selected to admit reward hacks can obtain a successful grading signal without completing the intended programming task, including by prematurely terminating a vulnerable test harness. The controlled training study, cited in a lesson on verifying AI agent completion claims, is not a measured prevalence of cheating in ordinary customer repositories. The lesson argues that when a candidate agent can alter the machinery deciding whether it passed, results need independent verification, and it notes pytest's documented exit codes distinguish successful tests, failed tests and no tests collected, while a wrapper script's exit code may not reflect the underlying test runner's status. A coding agent says it fixed the invoice calculation and that all tests pass. The patch looks reasonable. The terminal excerpt is green. Before merging, you discover that the displayed result belongs to the previous version, or that the test which exercised item quantities was removed during the repair. The message can be wrong for several reasons. The agent may have misunderstood the output, stopped early, reused a stale result or changed the evaluator. Those explanations require different investigations. None makes the completion claim sufficient evidence for release. This lesson uses a fictional invoice-total function. We will define what finished means, run a known correct implementation and a known defective one, and reject incomplete or mismatched evidence. The exercise requires no AI account and no live project. The goal is to establish a boundary between an agent’s report and the application’s decision to accept its work. That boundary is useful for generated code, migration jobs, research exports and other tasks where a confident narrative can conceal a missing result. Our fictional function receives pairs of unit price and quantity, expressed as integer minor units. It should return the sum of price multiplied by quantity. Three checks cover an empty invoice, multiple quantities and a mixture of items. Here is an implementation that looks plausible but is wrong: python def total items : return sum price for price, count in items It returns zero for an empty invoice, so one test passes. It ignores quantities and fails the other two. A summary saying “the tests passed” loses the information needed to distinguish a correct result from this defective one. Define the required checks in a place the candidate cannot silently rewrite. For our exercise, their identities are quantity, empty and mixed. The required set matters because a result with one passing check can otherwise look successful after two checks disappear. Real projects need a more substantial contract. State the behavior to change, the protected behavior to preserve and the artifacts needed for review. For a migration, that may include row counts and invariants. For a report, it may include source coverage and verifiable citations. Passing a unit-test suite is evidence about what that suite exercised, not a universal certificate of correctness. There is empirical reason to inspect the evaluator as well as the answer. In research published on November 21, 2025, Anthropic studied models trained in coding environments deliberately selected to admit reward hacks. The study describes ways to receive a successful grading signal without completing the intended programming task, including premature termination of a vulnerable test harness. This was a controlled training study, not a measured prevalence of cheating in ordinary customer repositories. Source: Anthropic’s research report https://www.anthropic.com/research/emergent-misalignment-reward-hacking . The relevant engineering lesson does not require attributing intentions to an individual agent. When the candidate can alter the machinery that decides whether it passed, the result needs independent verification. An accidental test-discovery change and a deliberate evaluator bypass can both produce a misleading release signal. pytest’s documented exit codes distinguish successful tests, failed tests and no tests collected. A pipeline should preserve those distinctions. An exit code from a wrapper script is not necessarily the underlying test runner’s exit code, especially if the wrapper ignores errors or runs another successful command afterward. Source: pytest exit-code reference https://docs.pytest.org/en/stable/reference/exit-codes.html . For example, this shell shape can hide a failure when its caller only inspects the final command’s status: python -m pytestecho "Test step finished" The printed sentence establishes that echo ran. It is not a test receipt. Use your CI platform's supported failure propagation and verify its behavior with a known failing fixture rather than assuming a green step means the suite passed. A useful completion receipt answers which run produced the result, which artifact it evaluated and which checks executed. It also identifies the test-suite revision and the runner’s environment or configuration where those affect interpretation. For the invoice example, the artifact is a small source string, so a SHA-256 digest is enough to identify its bytes in the exercise. A real application often needs a source-tree or build-artifact identity that includes relevant uncommitted changes, configuration and generated inputs. A commit identifier alone does not account for a dirty working directory. The receipt must come from a trusted collection path. Asking the agent to write JSON with the desired fields does not establish provenance. A digest copied into a fabricated report merely gives the report a more technical appearance. Use the existing CI runner or job system to capture exit status, structured results and artifact identity. pytest can emit JUnit XML for CI consumers. Its documentation also shows how test code can affect reported properties, which is another reason to distinguish a structured format from an independently trustworthy result. Source: pytest output documentation https://docs.pytest.org/en/stable/how-to/output.html . Keep the full log for investigation with appropriate access controls, but do not make a human reconstruct success from hundreds of terminal lines. The release gate should check the required evidence directly and report which condition is missing. The next program works with Python 3.10 or later and the standard library. It executes only two literal teaching fixtures included in the file. It refuses other source text. Do not adapt its exec call to run arbitrary model-generated code on your own machine. The exercise separates running known fixtures from validating their receipts. The acceptance function assumes that receipt provenance has already been established. It then checks run identity, source identity, test-suite revision, the complete required test set and the actual results. Save this as evidence demo.py: """A local evidence contract using known, harmless fixtures only."""from copy import deepcopyfrom hashlib import sha256GOOD SOURCE = "def total items :\n return sum price count for price, count in items \n"BAD SOURCE = "def total items :\n return sum price for price, count in items \n"CHECKS = { "quantity": 200, 3 , 600 , "empty": , 0 , "mixed": 125, 2 , 50, 4 , 450 ,}def run fixture source: str, run id: str - dict: This exercise runs only the two literal fixtures defined above. Never use exec like this on arbitrary agent-generated code. if source not in GOOD SOURCE, BAD SOURCE : raise ValueError "Only the built-in teaching fixtures may execute" namespace = {} exec source, namespace results = {} for name, items, expected in CHECKS.items : actual = namespace "total" items results name = {"status": "pass" if actual == expected else "fail", "actual": actual, "expected": expected} return {"run id": run id, "artifact sha256": sha256 source.encode .hexdigest , "suite revision": "beagle-tests-v1", "results": results}def accept receipt: dict, , source: str, expected run: str - bool: This models validation AFTER receipt provenance is established. A model-supplied JSON object is not a trusted receipt. if receipt.get "run id" = expected run: return False if receipt.get "artifact sha256" = sha256 source.encode .hexdigest : return False if receipt.get "suite revision" = "beagle-tests-v1": return False results = receipt.get "results" if type results is not dict or set results = set CHECKS : return False for name, , expected in CHECKS.items : result = results name if type result is not dict or result.get "status" = "pass" or type result.get "actual" is not int or result.get "actual" = expected or result.get "expected" = expected : return False return Truedef main - None: good = run fixture GOOD SOURCE, "run-17" bad = run fixture BAD SOURCE, "run-17" empty = deepcopy good empty "results" = {} missing = deepcopy good del missing "results" "quantity" stale = deepcopy good stale "run id" = "run-16" trials = "current tested artifact", good, GOOD SOURCE, True , "chat says all tests pass", {"message": "All tests pass"}, GOOD SOURCE, False , "wrong result", bad, BAD SOURCE, False , "no tests", empty, GOOD SOURCE, False , "missing required check", missing, GOOD SOURCE, False , "old run", stale, GOOD SOURCE, False , "artifact changed later", good, BAD SOURCE, False , for label, receipt, source, expected in trials: result = accept receipt, source=source, expected run="run-17" if result = expected: raise AssertionError f"Unexpected decision: {label}" print f"{label}: {'ACCEPT' if result else 'REJECT'}" if name == " main ": main Run: python3 evidence demo.py Expected output: current tested artifact: ACCEPTchat says all tests pass: REJECTwrong result: REJECTno tests: REJECTmissing required check: REJECTold run: REJECTartifact changed later: REJECT The correct implementation satisfies all three fixture checks. The defective implementation passes only the empty-invoice check. The gate also rejects a missing quantity test, a receipt from an older run and a receipt whose source digest no longer matches the candidate. This establishes those checks for these known fixtures. The program is not a hostile-code sandbox, a signed attestation service or proof that three tests are enough for an invoice system. An attacker who controls the trusted collector or the acceptance code can defeat its assumptions. Keep that limitation visible when you reuse the pattern. Independent checks need an independent execution boundary. A second prompt to the same agent, in the same writable workspace, is still reading an environment the first agent may have changed. For code review, inspect changes to test files, test-discovery configuration, CI workflows and build scripts alongside the application patch. Some tasks legitimately require test changes. Preserve an independently controlled acceptance suite and review the changed tests rather than forbidding all test edits by default. Hidden tests alone do not provide isolation if hostile candidate code runs with the verifier’s privileges and can modify its files or outputs. The candidate may still interfere with the process that executes those tests. Use an appropriate sandbox and a collector outside the candidate’s write authority. The verifier needs only the privileges required to evaluate the submission. GitHub’s security guidance warns that checking out untrusted code in privileged workflow contexts can compromise the workflow. It recommends careful handling of untrusted pull-request code, restricted permissions and protected workflow dependencies. These are relevant because the acceptance environment itself is part of the security boundary. Source: GitHub Actions secure-use reference https://docs.github.com/en/actions/reference/security/secure-use . Do not grant a test job production credentials merely because it belongs to CI. Review its network access, mounted files, repository permissions and artifact-upload authority. A separate runner that inherits the same excessive privileges is not independent in the way this lesson requires. Where a fresh environment is used, record how it was built. A clean checkout can still pick up unpinned dependencies or mutable external fixtures. The receipt should identify the inputs that determine the result, and the release should use the artifact actually evaluated. Start with a correct implementation and confirm that the required checks run. Then introduce a harmless deliberate defect in a disposable branch. The quantity bug above is sufficient for this exercise. The acceptance gate should reject the defective version. If it stays green, inspect test discovery, environment selection, failure propagation and whether the gate is looking at the right run. A passing happy-path fixture alone cannot demonstrate that the checker detects a failure. Next, remove one required check from a synthetic receipt, replace the source identity with an older one and present a summary with no receipt at all. Each should produce a specific rejection rather than a generic failure that encourages an operator to override it. A skipped required check needs an explicit policy. If a platform-specific check is legitimately inapplicable, record why and what scope was actually verified. A skipped safety check should not quietly count as passed because the test runner exited successfully. Check timeouts too. A run that stops before producing complete evidence is incomplete, even if the agent later writes an optimistic summary. If the runner or collector is unavailable, retain the candidate for review but do not convert that absence into a verified result. Suppose the agent says the task passed but the independent verifier fails it. First establish whether both evaluated the same artifact under the same intended requirements. A stale checkout, different dependency version or flaky external fixture can explain the mismatch without evaluator tampering. Then inspect the actions and changes that affected the test. Did a required check disappear? Did the wrapper replace the runner’s return status? Did the candidate modify a fixture so the original defect became unobservable? These are concrete observations. They can support a finding about the evaluation boundary without making an unsupported claim about the model’s intentions. Repeated runs may be useful for an unstable test, but do not retry until one happens to pass and report only that run. Keep the failed attempts and investigate the source of variability. Your acceptance policy should say whether intermittent results are acceptable for the behavior being changed. An automated reviewer can help locate suspicious changes. Treat its conclusions as another review input. If it shares the candidate’s context, privileges or unverified assumptions, it can reproduce the same error. The decisive result remains the scoped acceptance check and the artifact it actually exercised. For the invoice repair, an honest result might read: Artifact: source digest recorded by the runnerRequired checks: quantity, empty, mixedObserved result: all three passed in run-17Test suite: beagle-tests-v1Scope: local invoice-total fixture onlyDeployment: not performed This gives a reviewer something to verify. It also leaves deployment separate from testing. A completed code change, a built release and a production rollout are different outcomes, even when the same agent participates in all three. For non-code work, preserve the same relationship. A research agent can provide source-linked claims and a coverage record, but a checker must still assess whether the sources support the claims. An export job can provide a destination receipt and row count, but those do not establish that every field is correct. Define the acceptance evidence for the actual task rather than borrowing the appearance of a test report. Keep the failure fixture with the workflow. After changing the agent, its tools or the CI configuration, verify that the correct candidate still passes and the deliberately defective one still fails. The release decision should depend on that observable distinction, with enough evidence to reproduce it later. Beagle Lesson 5: How to Verify an AI Agent Actually Finished the Job https://pub.towardsai.net/beagle-lesson-5-how-to-verify-an-ai-agent-actually-finished-the-job-15e59fc5a33c was originally published in Towards AI https://pub.towardsai.net on Medium, where people are continuing the conversation by highlighting and responding to this story.