GitHub Actions for Agent PRs: Slicing Tests Without Trusting the Map
In this article
Slicing tests for agent-generated pull requests (PRs) in GitHub Actions means running only the subset of tests that cover the code changed in the PR, rather than the full suite. The challenge is that you cannot trust the agent's own description of what changed—you must derive the test slice from the actual diff and a reliable mapping between source files and test files. This article explains how to build that mapping and use it in GitHub Actions, without relying on the agent's self-reported intent.
Why Slicing Matters for Agent PRs
When a human opens a PR, they typically run the full test suite or manually select relevant tests. But agent-generated PRs can arrive frequently, often with large or scattered changes. Running the entire test suite on every commit is slow and expensive, especially in monorepos with thousands of tests. Slicing reduces feedback time and CI costs, but it introduces a risk: if the slice misses tests that should have run, regressions slip through. The danger is especially acute with agents because they may not understand the full impact of their changes.
The core principle is to base the slice on the actual diff (the files changed in the PR) and a deterministic mapping from source files to test files. You never ask the agent which tests to run; you compute it yourself.
Building a Reliable Source-to-Test Map
The map is the foundation. You need a way to answer: given a changed source file, which test files are likely to exercise it? There are several approaches, each with trade-offs.
- Convention-based: If your project follows a strict naming convention (e.g.,
src/foo.tsmaps totest/foo.test.ts), you can derive the mapping with simple string manipulation. This works well for small, well-organized projects but breaks when files are moved or renamed. - Static analysis: Tools like
jestwith--listTestsormochawith--recursivecan list test files, but they don't tell you which source files they cover. For a true mapping, you need to parse the code and find dependencies. Tools likemadge(for JS/TS) orpytest --cov(for Python) can produce a dependency graph. - Coverage-based: Run the full test suite once (or on a schedule) with coverage instrumentation. The coverage report shows which source files each test file touched. This is the most accurate but requires an initial full run and can become stale as code evolves.
- Hybrid: Start with a convention-based map, then augment it with a coverage-based map that you refresh periodically. This gives you a fallback for files that don't follow the convention.
The key is to store this mapping as a file in your repository (e.g., test-map.json) that your GitHub Actions workflow can read. You can generate it with a script that runs in CI on a schedule or on pushes to the main branch.
Implementing the Slice in GitHub Actions
Once you have the map, the workflow is straightforward. Here's a high-level outline using a shell script and jq to process JSON.
- Get the diff: Use
actions/checkoutwithfetch-depth: 0to get the full history, then rungit diff --name-only origin/main...HEADto list changed files. - Look up each changed file in the map: For each changed file, read the map and collect the associated test files. If a file is not in the map, you have a decision: either run the full suite (safe) or skip it (risky). The safe default is to run the full suite when the map is incomplete.
- Deduplicate and run: Combine the list of test files, remove duplicates, and pass them to your test runner. For example, with Jest:
npx jest $(cat test-files.txt). - Handle untracked files: If a changed file is new and not in the map, you should treat it as requiring the full suite, because you have no information about its dependencies.
Here's a minimal example of the core logic in a bash step:
CHANGED_FILES=$(git diff --name-only origin/main...HEAD | grep -E '^src/' || true)
TEST_FILES=$(echo "$CHANGED_FILES" | while read f; do
jq -r --arg f "$f" '.[$f][]?' test-map.json
if [ -z "$(jq -r --arg f "$f" '.[$f][]?' test-map.json)" ]; then
echo "FULL_SUITE"
fi
done | sort -u)
if echo "$TEST_FILES" | grep -q "FULL_SUITE"; then
npm test
else
npx jest $TEST_FILES
fiThis script falls back to the full suite if any changed file is missing from the map.
Choosing the Right Granularity
The map can map a source file to a single test file, a directory, or a test suite. Finer granularity (file-to-file) gives the smallest slice but requires a more accurate map. Coarser granularity (file-to-directory) is safer but runs more tests. A good compromise is to map each source file to a directory of tests, or to a list of test files that are known to cover it.
Consider your project's structure. If you have a monorepo with multiple packages, you might want to map to the package level first, then to specific tests within the package. This reduces the chance of missing cross-package dependencies.
Common Pitfalls and How to Avoid Them
- Stale map: The map can become outdated as tests are added or removed. Mitigate by regenerating the map on every merge to main, and by including a freshness check in CI (e.g., fail if the map is older than a week).
- Non-deterministic test selection: Some test runners (like Jest) may order tests differently when given a list of files, which can cause flaky failures. Use
--runInBandor a deterministic seed. - Ignoring test-only changes: If the PR changes a test file itself, you must run that test file (and possibly the full suite if the test file is not in the map). Always include changed test files in the slice.
- Configuration files: Changes to config files (e.g.,
package.json,tsconfig.json) can affect all tests. If any such file is changed, run the full suite.
Costs and Trade-offs
The primary benefit is speed: a slice can run in minutes instead of hours. This speeds up agent iteration and reduces CI minutes (and cost). The trade-off is the risk of missing a test that would have caught a regression. The risk is highest when the map is incomplete or when changes have cross-cutting effects (e.g., a change to a shared utility).
To mitigate, consider a two-stage approach: run the slice as a fast pre-check, then run the full suite on merge or on a nightly schedule. This gives quick feedback while still providing a safety net.
Alternatives to a Static Map
If maintaining a map is too heavy, there are other strategies:
- Run all tests in affected directories: Use the diff to identify top-level directories (e.g.,
src/components) and run all tests under those directories. This is simpler but runs more tests than a precise map. - Use a test impact analysis service: Some CI platforms offer built-in test impact analysis that automatically determines which tests to run based on the diff. These services maintain the mapping for you, but they may be a paid add-on.
- Run the full suite always: For small projects, this is often the simplest and most reliable. Slicing only pays off when the full suite takes more than a few minutes.
Each alternative trades off precision for simplicity. The right choice depends on your project size, test suite duration, and tolerance for missed regressions.
Safety and Accuracy Considerations
When implementing slicing, always default to the full suite when in doubt. Specifically:
- If a changed file is not in the map, run the full suite.
- If the map file is missing or unreadable, run the full suite.
- If the diff includes files outside your source/test conventions (e.g., CI config, docs), decide whether they affect tests. If unsure, run the full suite.
Also, ensure that the slice runs in a clean environment. In GitHub Actions, each job starts from a fresh checkout, so you must regenerate any build artifacts before running the tests. A common mistake is to run the slice on a dirty working tree, which can cause false results.
Frequently Asked Questions
How do I generate the test map for a Python project?
For Python, you can use pytest --cov with the --cov-report json option. The resulting JSON contains per-file coverage data. You can post-process it to create a mapping from source files to test files by looking at which test files covered each source file. This requires an initial full run with coverage, but you can automate it on a schedule.
What if my project uses a language without good static analysis tools?
If you cannot easily build a dependency graph, fall back to a convention-based map or run tests at the directory level. For example, if your project has a tests/ directory mirroring src/, you can map each changed source file to the corresponding test file by path. If that fails, run the full suite.
Can I use GitHub Actions' built-in path filters to slice tests?
Path filters (like on: pull_request: paths:) can trigger workflows only when certain files change, but they don't tell you which tests to run. You can use them to skip the workflow entirely if no source files changed, but you still need a map to select the tests.
How do I handle generated files or files that are both source and test?
If a file is generated (e.g., from a build step), it should not be in the map. If a file is both source and test (e.g., a test helper), include it in the map as a test file that covers itself. When such a file changes, run the tests that depend on it.
Is it safe to run only the sliced tests on every PR?
It is safe only if you have a reliable map and a fallback to the full suite. Even then, there is a small risk of missing a test due to an incomplete map. Many teams run the slice on every commit and the full suite on merge or nightly to catch any gaps.
What is the best way to keep the map up to date?
Regenerate the map on every merge to main. You can have a GitHub Actions workflow that runs the full test suite with coverage and commits the updated map. This ensures the map reflects the latest code structure.