Sub topic 13
CI as an Independent Check on Agent Changes
This chapter assumes you can write and run unit tests with pytest or a similar framework. It also assumes you know Git branches, commits, and pull requests, and that you have followed the earlier chapters on the red-green-refactor cycle and on instructing an agent to work test-first. You don't need prior experience with continuous integration (CI). The examples use GitHub Actions, but the ideas carry over to GitLab CI, CircleCI, Jenkins, and similar tools.
Why the agent's own test run is not enough
In the previous chapters the agent ran python -m pytest -q after every change and read the output. That feedback loop is the core of test-driven development (TDD) with an agent. It has weaknesses, though, because the agent controls everything around the run:
- The environment is the agent's. The working directory may contain untracked files, stale build output, a cached virtual environment, or a package installed by hand that is missing from
requirements.txt. Tests can pass locally and fail for everyone else. - The code under test may not be what you review. The agent can run tests, then make one more edit and forget to rerun them. What it commits may differ from what it tested.
- The report is text. An agent may summarize "all tests pass" without having run the suite in that state, or after running only one test file.
- The agent can change the rules. It can edit tests, add
skipmarkers, or change the test command. Earlier chapters covered instruction files and review as defenses, but both depend on the agent complying or on a human noticing.
Continuous integration is a server that checks out the committed code in a fresh environment and runs a fixed set of commands. The agent doesn't control those commands, and its claims don't enter into the result. CI therefore gives you an independent check: the same suite, run somewhere the agent can't influence the environment.
What CI adds and what it does not
| Question | Agent's local run | CI run |
|---|---|---|
| Does the committed code pass the suite? | Only if the agent ran it after its last edit | Always, on the exact commit |
| Are all dependencies declared? | Not necessarily, because the local environment may hide gaps | Yes, because the environment starts clean |
| Did the agent change the test command? | Cannot tell | Visible, if workflow changes need review |
| Is the test itself meaningful? | No | No |
| Is the implementation correct beyond the tests? | No | No |
The last two rows matter. CI runs the tests the repository contains. If the agent wrote a weak test, or hardcoded return "hello-world" to satisfy the one example, CI reports green. CI checks that your process was followed and that results reproduce. It doesn't judge whether the specification was good. Human review stays necessary.
A minimal workflow
The following workflow runs the pytest suite on every pull request and on pushes to main. Save it as .github/workflows/tests.yml.
name: tests
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
pytest:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install pytest
if [ -f requirements.txt ]; then python -m pip install -r requirements.txt; fi
- name: Run tests
run: python -m pytest -q -rsThree details are worth noting:
permissions: contents: readgives the job a read-only token. A job that only runs tests needs nothing more, and a smaller grant limits the damage if a test or dependency misbehaves.- The install step uses only what the repository declares. If the agent installed a library by hand and forgot to list it, this step or the tests fail. That is a failure you want to see before merge.
-rsprints the reason for every skipped test in the summary. Skips are one way an agent can make a failing suite look healthy, so make them visible in the log.
For the slugify example, the repository would contain slugify_util.py, test_slugify.py, and optionally a requirements.txt. The workflow needs no changes as the suite grows.
Making the check binding
A workflow that nobody has to respect is only advice. Two settings turn it into a gate:
- Work through pull requests. Have the agent push to a feature branch and open a pull request instead of pushing to
main. The workflow'spull_requesttrigger then runs on the proposed change. - Require the status check. In your repository's branch protection (or rulesets) settings, mark the
pytestjob as a required status check formain. Merging is blocked until it passes.
Also give the agent credentials that cannot bypass these rules. If the agent runs with an administrator token, it can merge a red pull request or change the protection settings. Use a token scoped to pushing branches and opening pull requests.
Letting CI catch test tampering
Earlier chapters covered instructions that tell the agent not to edit, skip, or delete tests. CI can enforce part of that rule mechanically. This job fails if a pull request deletes any test file. Add it under jobs: in the same workflow file.
guard-tests:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Fail if test files were deleted
env:
BASE_REF: ${{ github.base_ref }}
run: |
deleted=$(git diff --name-only --diff-filter=D "origin/${BASE_REF}...HEAD" -- '*test_*.py')
if [ -n "$deleted" ]; then
echo "Test files were deleted in this pull request:"
echo "$deleted"
exit 1
fiThe step does the following:
fetch-depth: 0downloads the full history, so Git can compare the pull request branch with the base branch.- The branch name goes through an
envvariable and is then quoted in the shell. Don't paste${{ github.base_ref }}directly into the script. Expression values are substituted into the text before the shell sees it, so an unusual branch name could inject commands. --diff-filter=Dlists only deleted files. The pathspec'*test_*.py'matches any path containingtest_and ending in.py.
This guard catches whole-file deletions only. It doesn't see a test removed from inside a file or an assertion weakened from == to !=. Those changes still need a person reading the diff. You can strengthen the suite itself with pytest settings that turn quiet failures into loud ones:
# pytest.ini
[pytest]
xfail_strict = true
addopts = --strict-markersWith xfail_strict = true, a test marked xfail that unexpectedly passes counts as a failure. This stops an agent from parking a failing test as "expected to fail" and leaving it. --strict-markers rejects misspelled or undeclared markers instead of ignoring them.
A test count or coverage threshold is another option, but treat it with care. A threshold gives an agent a number to game, for instance by adding assertion-free tests that execute code. Use thresholds as a flag for reviewers, not as proof of quality.
Closing the loop: CI output as agent feedback
CI also feeds back into the agent loop. After the agent pushes, a failed run can be handed back to it just as local pytest output was. With the GitHub CLI installed, the agent can run:
gh pr checks
gh run view --log-failedThe first command lists the checks on the current pull request and their status. The second prints the logs of the failed steps. Add a line to your agent instructions: "After pushing, wait for the CI result. If it fails, read the failed log, reproduce the failure locally, and fix it without modifying tests."
Reproducing locally matters. If CI fails and local passes, the cause is usually an environment difference, such as an undeclared dependency, a different Python version, or a test that depends on the clock, the working directory, or execution order. Fixing the real cause teaches the agent something. Rerunning until green does not. This is also why you should not configure CI to retry failing tests automatically. Automatic retries hide flaky tests, and an agent has no reason to look into a failure that disappears on a second run.
Common errors
- CI is green but nothing ran. A misspelled path or an overly narrow
on:filter can skip the job. A skipped required check may count as passing on some platforms. Confirm the job appears and executes tests in the log, and check that the log shows a nonzero test count. - Passing because of
|| true,continue-on-error: true, or-x --co. Any of these can make a failing or empty run succeed. Review workflow diffs for them. - Tests that need secrets or network access. Don't give the agent's branch production credentials just to make tests pass. Use fakes or test accounts, and keep real secrets out of workflows that run on agent-authored pull requests.
- Version drift. If your local Python is 3.11 and CI uses 3.12, a feature or behavior difference can cause failures that look unrelated to the change. Pin the version in both places.
- Treating green as approved. CI answers "do these tests pass on this commit?" You still need to ask whether the tests specify the right behavior and whether the diff is the smallest change that achieves it.
Putting it into your routine
- The agent completes one red-green-refactor cycle locally and commits it.
- It pushes the branch and opens or updates a pull request.
- CI runs the suite in a clean environment and runs the guards.
- If CI fails, the agent reads the log and fixes the cause, with tests off-limits.
- When CI is green, a human reviews the diff, paying attention to tests, workflow files, and anything that looks like special-casing of test inputs.
- The reviewer merges.
CI doesn't replace the habits from earlier chapters. Small cycles keep the diff readable, protected tests keep the specification stable, and review catches what automation can't judge. CI makes sure the claim "all tests pass" is checked by something other than the agent.
Exercise
An agent opens a pull request for the slugify change and reports that all tests pass. CI is also green. In the diff, you notice that slugify now contains if text == "a -- b": return "a-b" and CI's workflow file has run: python -m pytest -q || true. Which problems does CI's green status hide, and what would you change?
Show answer
The || true makes the test step succeed even when pytest fails, so the green status says nothing about the tests. Remove it, and require review for changes under .github/. The special case for the input "a -- b" is hardcoding to the test's expected value. CI can't detect it even with a correct workflow, because the tests pass. Only review, or additional varied tests, can catch it. Ask the agent to remove the special case and add a test with a different input, such as "x y", that fails first.
Exercise
Your pipeline sometimes shows a test failing in CI but passing locally. The agent proposes adding an automatic retry of failed tests in the workflow. Give two reasons this is a poor fix and one better action.
Show answer
Retries hide flaky or environment-dependent tests, so a real defect can pass on a second attempt and reach main. They also teach the agent that failures are noise, which removes its reason to investigate. A better action is to reproduce the failure locally under CI conditions, for example with the same Python version and a fresh virtual environment, and fix the cause, such as an undeclared dependency or an order-dependent test. Only after that should you decide whether a test needs to be quarantined, and a person should make that decision.