Sub topic 13
Delivering results as branches and pull requests
This chapter assumes you can write the wrapper script from earlier in the tutorial. It also assumes you know Git branches, the gh command-line client for GitHub, and branch protection rules. The same ideas apply to GitLab and other hosts, but the commands differ.
Why unattended changes should arrive as a branch
A headless agent that edits files and pushes to your main branch has no reviewer. If the prompt was ambiguous, the model misjudged the task, or injected text steered it, the damage lands in the code everyone builds on. A branch plus a pull request puts a human decision between the agent's output and your default branch.
Delivery as a branch gives you four properties:
- Isolation. The agent's work cannot affect anyone until someone merges it.
- Review. A person reads a diff and approves or rejects it.
- Reversibility. Closing the PR and deleting the branch undoes everything.
- A record. The PR shows what the agent changed, when, and from which run.
The delivery flow
The agent edits files in a working copy. It does not commit or push. The wrapper script does that, so the commands that touch the remote stay in code you wrote and can audit.
A wrapper that delivers a pull request
This script extends the earlier nightly wrapper. It assumes git and gh are installed and that GH_TOKEN is set in the job's environment. The next section covers what that token may do. AGENT_CMD is still a placeholder for your agent's non-interactive command that reads the prompt from stdin.
#!/usr/bin/env bash
# nightly-agent-pr.sh
set -euo pipefail
: "${AGENT_CMD:?set AGENT_CMD to your agent's non-interactive command}"
: "${GH_TOKEN:?set GH_TOKEN to a token scoped to this repository}"
BASE="main"
BRANCH="agent/nightly-$(date -u +%Y-%m-%d)"
MAX_FILES=20
cd /srv/repos/my-project
# Use a dedicated clone. Refuse to start on a dirty tree.
if [ -n "$(git status --porcelain)" ]; then
echo "working tree is dirty, refusing to run" >&2
exit 1
fi
git fetch origin "$BASE"
# Idempotency: one branch per UTC day. If it exists, an earlier run delivered.
if git ls-remote --exit-code --heads origin "$BRANCH" > /dev/null; then
echo "branch $BRANCH already exists on origin, nothing to do"
exit 0
fi
git checkout -B "$BRANCH" "origin/$BASE"
# AGENT_CMD is intentionally unquoted so a command with arguments splits into words.
timeout 20m $AGENT_CMD < prompts/nightly.md
if [ -z "$(git status --porcelain)" ]; then
echo "agent made no changes"
exit 0
fi
git add -A
changed=$(git diff --cached --name-only | wc -l)
if [ "$changed" -gt "$MAX_FILES" ]; then
echo "agent changed $changed files (limit $MAX_FILES), not delivering" >&2
exit 1
fi
git -c user.name="nightly-agent" \
-c user.email="[email protected]" \
commit -m "chore: nightly agent changes ($changed files)"
git push origin "$BRANCH"
gh pr create \
--base "$BASE" \
--head "$BRANCH" \
--draft \
--title "Nightly agent changes $(date -u +%Y-%m-%d)" \
--body "Automated run. Review the diff before merging. Host: $(hostname)."Because of set -e, a timeout (exit status 124), a failed push, or a failed gh call ends the script with a non-zero status. The scheduler and your alerting see the failure, as described in the chapters on exit codes and alerting.
What each guard protects against
| Guard | Failure it prevents |
|---|---|
| Clean-tree check | A crashed earlier run leaving half-edited files that end up in today's commit |
| `ls-remote` check | A rerun or retry creating a duplicate branch and a second PR for the same day |
| No-change exit | Empty commits and empty PRs on days when nothing needed doing |
| `MAX_FILES` limit | A confused agent rewriting half the repository and burying a reviewer |
| `--draft` | Someone merging by reflex before reading |
Limit what the token can do
A script that opens PRs is only as safe as the credential behind it. If the token can push to main, a prompt-injected or buggy agent can bypass your review step by pushing there directly. Apply two layers.
- Scope the token. Use a fine-grained token limited to this single repository, with only "Contents: read and write" and "Pull requests: read and write". It should have no administration, workflow, or secrets permissions.
- Protect the default branch. Require a pull request and at least one approving review before merging to
main. Do not let the bot's account bypass this rule. Check that no administrator-bypass setting covers the token's owner.
Test the protection once on purpose. From the job's account, try git push origin HEAD:main and confirm that it is rejected. Run the test where the agent's own tool permissions cannot reach git push at all. The earlier chapter on pre-approved tools covers that: the agent edits files, and only the wrapper pushes.
Delivery from a CI scheduler
On GitHub Actions the built-in GITHUB_TOKEN can do this work if you grant it the right permissions. The read-only contents: read block from the earlier workflow is not enough for delivery. Change it like this:
permissions:
contents: write # push the agent's branch
pull-requests: write # open the pull requestTwo details commonly surprise people:
- The repository setting "Allow GitHub Actions to create and approve pull requests" must be enabled, or
gh pr createfails with a permissions error. - Pull requests created with
GITHUB_TOKENdo not trigger other workflows, so your test suite will not run on them automatically. If you need CI on the agent's PRs, use a dedicated app or token instead, and keep it scoped as described above.
Naming branches and handling reruns
A deterministic branch name is what makes the idempotency check work. agent/nightly-2026-11-28 identifies the run's purpose and day. A random or timestamped name would let every retry create a new branch.
Choose the name's granularity to match the job:
- Daily job, one PR per day: date in the name, as above.
- Job that tracks a moving target (for example, dependency updates): a fixed name such as
agent/deps. A rerun then updates the same branch with a force-push, and you check for an existing PR before creating one. Force-pushing is acceptable here only because no human commits to that branch. Document that rule. - Job tied to an input (an issue number, a failing test ID): include that identifier, so two inputs never collide.
Note what the daily scheme does when a PR from yesterday is still open and unreviewed. The run opens another PR from a new branch, and open PRs pile up. If that is a problem, add a check at the top such as gh pr list --state open --head "agent/nightly-*". Alternatively, skip the run when more than a set number of agent PRs are waiting. A queue of unreviewed agent PRs usually means the job's output is not worth its cost, so treat the pile-up as a signal and not just a nuisance.
Making the pull request reviewable
A reviewer gets the PR with no context about what the agent was asked to do. Help them:
- Put the prompt's name or version in the PR body, so they know which instructions produced the diff.
- Include a link or path to the run log.
- Keep each PR to one kind of change. A prompt that says "fix lint errors in
src/" yields smaller, easier diffs than "improve the codebase". - Have CI run tests on the PR where possible, so the reviewer sees a result and does not rerun it by hand.
Review the diff as you would review code from a stranger. The agent's PR description may claim tests pass, but only the CI result counts.
Exercise
Your nightly job fails at the git push step because the network dropped. The scheduler retries the script ten minutes later. Using the script in this chapter, what happens on the retry, and why? Then describe a different failure, the agent timing out halfway through editing files, and say which guard handles it on the next night's run.
Show answer
On the retry, the local branch from the failed attempt may still exist, but the remote branch does not, so the ls-remote check finds nothing and the script continues. Before that, though, the clean-tree check runs first, and the working tree still holds the earlier commit's state. The commit was already made, so the tree is clean. The script then runs git checkout -B from origin/main, discarding the earlier local commit, and the agent runs again from scratch. The retry therefore produces a fresh branch and one PR. Nothing is duplicated, because no PR was created before the push failed. For the timeout case, timeout exits with status 124 and set -e stops the script before any commit. The edited files remain uncommitted in the working copy. On the next night, the clean-tree check sees the dirty tree and exits with status 1 and a message, so the failure is visible and a human can clean the clone. The script never commits half-finished work.