Skill v1.0.0
currentAutomated scan100/100name: pr-shepherd description: Drive a just-created or just-updated PR to ready-for-review, and merge it when it is safe to. Use IMMEDIATELY after creating a PR (gh pr create) or after pushing new commits to an open PR in any {{GITHUB_ORG}} repo. Watches CI to green, resolves merge conflicts, addresses every finding from the automated reviewer ({{REVIEW_BOT_LOGIN}}) by fixing it or replying why not, un-drafts the PR early (because the reviewer skips drafts), and merges by default once everything is green. Only genuinely risky PRs (schema migrations, deploy and config rollouts, ingress, auth and security, very large diffs) stop at ready-for-review for a human. Also use when asked to "babysit", "shepherd", or "get the PR green / ready / merged". metadata: version: "1.0.0"
PR shepherd
Configure before first use. Every{{PLACEHOLDER}}below is a decision foryour team. Fill them in, delete the sections that do not apply (there is aper-section note where a whole step is optional), then rungrep -nE '\{\{[A-Z][A-Z_]*\**\}\}' SKILL.mdand confirm nothing is left. Theinstaller runs the same check. A skill with live placeholders sends the agentchasing comment markers and commands that do not exist.
0. Configuration
| Placeholder | What it is | Example | |
|---|---|---|---|
{{GITHUB_ORG}} | GitHub org or user that owns the repos | acme-inc | |
{{REPOS}} | Repos this skill covers, for the description line | api, web, infra | |
{{DEFAULT_BRANCH}} | Branch PRs merge into | main | |
{{MERGE_METHOD}} | --squash, --merge or --rebase | --squash | |
{{AUTO_MERGE}} | yes to merge by default, no to always stop at ready-for-review | yes | |
{{REVIEW_BOT_LOGIN}} | Login of the automated reviewer, exactly as GitHub reports it | claude[bot] | |
{{REVIEW_MARKER}} | Hidden HTML marker in the review comment body, if it has one | <!-- ai:review --> | |
{{REVIEW_UNAVAILABLE_MARKER}} | Marker the reviewer posts when it gave up, if it has one | <!-- ai:review-unavailable --> | |
{{CI_DIAGNOSIS_MARKER}} | Marker for an automated failed-workflow diagnosis, if you have one | <!-- ai:actions --> | |
{{REVIEW_MENTION}} | Mention keyword that makes the reviewer answer a reply | @claude | |
{{REVIEW_WAIT_MINUTES}} | How long to wait for a review before proceeding without one | 20 | |
{{REVIEWED_COMMIT_FOOTER}} | The line in the review that names the commit it read | Reviewed commit <sha> | |
{{CI_ALERT_CHANNEL}} | Where default-branch CI failures are announced | #ci-alerts | |
{{MIGRATION_DIRS}} | Paths that hold DB migrations | db/migrations/, alembic/ | |
{{MIGRATION_MERGE_CMD}} | How your migration tool resolves two heads, if it can | alembic merge -m "..." <head> <head> | |
{{DEPLOY_REPOS}} | Repos where a merge is itself a production rollout | infra-values, gitops | |
{{SIZE_LIMIT_LINES}} / {{SIZE_LIMIT_FILES}} | Diff size above which a human looks | 1500 / 50 | |
{{LOCAL_GATE_RULE}} | Any machine-local constraint on running lint or tests | (delete if none) | |
{{TRACKER_*}} | Issue tracker wiring, covered in step 6. Delete the whole block if you have none. |
If you have no automated reviewer, delete step 5 and the fourth exit condition. If you have no issue tracker link step, delete "Before merging: record the PR on the issue". Everything else is tracker-agnostic and reviewer-agnostic.
Given a PR (argument: number or URL, otherwise the PR for the current branch via gh pr view --json number,url,isDraft), do not stop until ALL of these hold for the latest pushed commit:
- No conflicts.
mergeableisMERGEABLE - CI green. Every check concluded SUCCESS, SKIPPED or NEUTRAL
- Un-drafted.
gh pr readyexecuted (skip if it was never a draft) - Every review finding addressed. Code updated and pushed, or a reply
explaining why not
Then merge (if {{AUTO_MERGE}} is yes and the PR misses step 6's risk list), watch the default branch's own CI on the merge commit (step 7), and report (step 8). Hard limits: never push to {{DEFAULT_BRANCH}} directly, never force-push, never close the PR, and never merge a PR on the risk list. Those stop at ready-for-review for a human to merge.
Un-draft comes before the review, not after. Most automated reviewers decline draft pull requests, and the draft-to-ready transition is one of the events that starts a review. A shepherd that saves gh pr ready for last waits for a review that by construction never runs. This skill used to do exactly that.
Run gh from the PR's worktree, or pass -R {{GITHUB_ORG}}/<repo> explicitly. A checkout whose origin points somewhere other than GitHub will otherwise send every command to the wrong place.
1. Snapshot
gh pr view <n> --json number,url,isDraft,mergeable,mergeStateStatus,headRefName,statusCheckRollup
Order matters: check conflicts before interpreting checks. A PR with zero check suites at all almost always means mergeable: CONFLICTING. GitHub cannot build the merge ref, so Actions never starts. Fix the conflict (step 2), do not conclude "CI is broken", and do not re-create the branch.
2. Conflicts
If mergeable is CONFLICTING (poll a few times if UNKNOWN, since GitHub computes it lazily):
- In the PR's worktree, run
git fetch origin && git merge origin/{{DEFAULT_BRANCH}},
resolve the conflicts, commit the merge, and push. Merge, never rebase. Force-push is banned and rebase requires it.
- Migrations. If both sides added a migration under
{{MIGRATION_DIRS}}you
now have two heads. Resolve with a no-op merge revision ({{MIGRATION_MERGE_CMD}}) rather than renumbering either side, and expect any schema-golden or snapshot tests to need regenerating.
- A push resets the checks, so go back to step 1 after any push.
3. CI to green
Watch until every check concludes:
gh pr checks <n> --watch --interval 30
Run it with a large timeout (10 minutes) and re-run while checks are still pending. It exits non-zero when something failed.
On failure:
- Get the failing job's log with
gh run view <run-id> --log-failed. Find the run
id in the check's detail URL or via gh run list --branch <headRefName>.
- If you have an automated failure diagnosis, read it first. It is a separate
comment per failed run, not a finding you have to answer, so it is a free first read:
``sh gh api repos/{{GITHUB_ORG}}/<repo>/issues/<n>/comments \ --jq '.[] | select(.body | contains("{{CI_DIAGNOSIS_MARKER}}")) | {id, created_at, body}' ``
- PR checks build the merge of the branch with `{{DEFAULT_BRANCH}}`. Before
blaming the PR, check whether plain origin/{{DEFAULT_BRANCH}} reproduces the failure, because a parallel PR may have landed a semantic conflict. If the default branch is red, fix forward only if the fix belongs in this PR. Otherwise report that it is broken and stop the loop there. Do not grind a PR against a red default branch.
- {{LOCAL_GATE_RULE}} *(for example: "only one lint or typecheck process may run
on this machine at a time, so wait for the lock before starting, run sequentially, and never run it in the background". Delete this bullet if you have no such rule.)*
- Fix, commit, push, then go back to step 1.
4. Un-draft
Do this as soon as the branch is pushed and free of conflicts, not at the end. It is what starts the review (step 5), and it lets the review run against the same head commit CI is already testing instead of serially after it:
gh pr ready <n>
Skip it if the PR was never a draft. If CI then goes red and you push a fix, the push re-reviews on its own, so nothing is lost by having gone ready early.
5. Automated review
(Delete this whole step if you have no automated reviewer. Do not replace it with a guess. An agent that invents a review is worse than one that has none.)
{{REVIEW_BOT_LOGIN}} posts the review as an issue comment carrying the hidden marker {{REVIEW_MARKER}}. The review is advisory: it posts no check run, never submits CHANGES_REQUESTED, and never blocks CI. That is what makes bounding the wait safe.
Three terminal states, and "still running" is not one of them
A failed review turn is often retried, and some reviewers keep the intent owed and re-drive it minutes later. So there are three states to poll for, not two:
| What you see | What it means | |
|---|---|---|
{{REVIEW_MARKER}} comment | Reviewed. Answer the findings. | |
{{REVIEW_UNAVAILABLE_MARKER}} comment | The reviewer gave up and said so. Record it, nothing to answer. | |
| Neither, yet | Still in flight, possibly waiting on a retry. |
Bound the wait, and know what your reviewer's slow path costs. In one measured case the review turn failed when the backing service rolled mid-request, a sweep re-drove it 15 minutes later, and the verdict landed 16 minutes after the failure, onto a PR this skill had already merged on a "~10 minutes at the outside" rule. A clean PR was merged unreviewed and the review arrived on a closed PR. Hence: wait up to ~{{REVIEW_WAIT_MINUTES}} minutes from the last push, checking for both markers each poll. If you proceed without either, say exactly that in the report ("no review and no unavailable notice after N minutes, may still be in flight"), never "the review came back clean".
When it runs
- PR opened (not a draft), draft to ready, and every push to the
branch.
- Drafts are declined. Step 4 is the trigger for a draft-opened PR.
- Head-SHA dedup. A commit already reviewed is not reviewed twice. Marking an
already-public PR ready without pushing produces no second review, and that is correct, because the existing review covers that commit.
Which repos have it
If the reviewer is bound per-repo (a GitHub App installation) rather than by a workflow file in the repo, it is a per-repo fact that changes as repos are connected. Probe, do not keep a list. An unreviewed PR and an unbound repo look identical from a single PR:
for pr in $(gh pr list -R {{GITHUB_ORG}}/<repo> --state all --limit 5 --json number --jq '.[].number'); dohits=$(gh api repos/{{GITHUB_ORG}}/<repo>/issues/$pr/comments \--jq '[.[] | select(.user.login=="{{REVIEW_BOT_LOGIN}}") | select(.body | contains("{{REVIEW_MARKER}}"))] | length')echo "<repo>#$pr reviewed=$hits"done
The version of this skill that carried a hardcoded list of reviewed repos had it wrong within two weeks, and a shepherd that trusted the list skipped waiting for a review that was on its way.
When a repo genuinely has no reviewer, say so in the report ("no automated review posted for this PR") rather than reporting a clean review. Never invent a review that did not happen.
Collecting it
Two surfaces. The summary comment always exists, inline findings are anchored to their lines, and the second query simply returns nothing where there are none:
# summary comment (one per PR, upserted in place)gh api repos/{{GITHUB_ORG}}/<repo>/issues/<n>/comments \--jq '.[] | select(.user.login=="{{REVIEW_BOT_LOGIN}}") | select(.body | contains("{{REVIEW_MARKER}}")) | {id, updated_at, body}'# inline findings pinned to linesgh api repos/{{GITHUB_ORG}}/<repo>/pulls/<n>/comments \--jq '.[] | select(.user.login=="{{REVIEW_BOT_LOGIN}}") | {id, path, line, body}'
The summary comment is edited in place, not reposted. There is exactly one per PR and a re-review PATCHes it, so polling for a new comment after a push waits forever. Re-fetch the same id and read the footer:
{{REVIEWED_COMMIT_FOOTER}}
That SHA is the gate. It must match the latest pushed commit (git rev-parse --short=12 HEAD) before the findings can be called addressed. If the footer still names an older commit after {{REVIEW_WAIT_MINUTES}} minutes, note it in the report and proceed.
Poll for both markers, so a reviewer that gave up is not mistaken for one still working:
gh api repos/{{GITHUB_ORG}}/<repo>/issues/<n>/comments \--jq '.[] | select(.user.login=="{{REVIEW_BOT_LOGIN}}")| select(.body | test("{{REVIEW_MARKER}}|{{REVIEW_UNAVAILABLE_MARKER}}"))| {id, updated_at, unavailable: (.body | contains("{{REVIEW_UNAVAILABLE_MARKER}}"))}'
Inline comments are not upserted. If your reviewer dedups them by a fingerprint of (path, title), a finding already pinned is not restated on the next push, so an inline comment created two commits ago is live rather than stale, and still needs an answer.
Do not mistake the same bot's other comment types for a review, such as preview-environment cards, the failed-workflow diagnosis from step 3, or the bot answering someone's question. Match on the marker, not just the login.
Reading the verdict
Read the findings, not the adjective in the header. The verdict line is usually derived from the findings rather than written independently. Expect severities (high, medium, low) and a cap on how many findings one turn reports. When the reviewer's output fails to parse, the comment body may be a raw JSON blob instead of markdown. Every finding is still there under the same keys, so read them out of the JSON rather than treating the comment as unreadable.
Handling findings
For each finding, decide on the merits. The review is often right and sometimes not:
- Valid. Fix it, commit, push (checks restart, so back to step 1). The push
re-reviews automatically, so there is nothing to ask for.
- Not valid, or intentional. Reply with the concrete reason, pointing at the
code or the frozen contract that makes it intentional, in the finding's own thread where it has one:
# inline finding, threaded replygh api repos/{{GITHUB_ORG}}/<repo>/pulls/<n>/comments/<comment-id>/replies -X POST -F body=@/tmp/reply.md# summary finding, normal PR commentgh pr comment <n> --body-file /tmp/reply.md
Use --body-file or -F body=@file rather than inline body text. Long bodies on the command line get mangled by quoting, and any hook that inspects command text sees the whole review reply.
Mentioning {{REVIEW_MENTION}} in a reply gets the bot to answer you. That is a conversation lane, not a review lane, so it does not produce a fresh review. Only a push does.
No finding may be left dangling. Every one ends as either a pushed fix or a posted reply. Keep a checklist of finding to FIXED or REPLIED.
6. Merge (default, and only the risky stuff waits for a human)
Once the review is addressed, merge the PR yourself by default (when {{AUTO_MERGE}} is yes). Leave it ready-for-review ONLY if it hits the risk list below, and name the exact criterion in the report. "It feels big-ish" is not a criterion. Either it matches a bullet or it merges.
Risk list, where a human merges:
- Deploy and config repos,
{{DEPLOY_REPOS}}. A merge there is a production
or staging rollout, not a code change.
- DB schema migrations. Any changed file under
{{MIGRATION_DIRS}},
including merge-revision-only PRs.
- Ingress and edge proxy config. Controller config, annotations, proxy or
buffer settings, anywhere.
- Deploy and rollout surfaces. Charts,
deploy/manifests, and workflows
that deploy, release or publish. Plain CI workflow tweaks (lint, test and build jobs that run on the PR itself) are NOT risky, and Dockerfiles are NOT risky when CI builds the image.
- Auth and security surfaces. Authn and authz, RBAC, session and CSRF
handling, secrets or credential storage and rotation, token formats.
- Public or machine-to-machine contracts. Removing or renaming endpoints or
fields that a deployed client depends on. Additive changes and routine golden or fixture updates do not count.
- Explicitly flagged for a human. The PR body or the issue says HUMAN-MERGE
or needs sign-off for this specific change (legal copy, pricing, retention numbers).
- Human signal pending. A CHANGES_REQUESTED review, pending requested
reviewers, or unresolved non-bot comments. Also a review finding you replied-away rather than fixed, when it was high severity or the verdict was "changes requested". Let a human confirm the reply. A finding you actually fixed does not hold the PR, and neither does a low or medium one you argued down on its merits.
- Very large.
additions + deletions > {{SIZE_LIMIT_LINES}}or
changedFiles > {{SIZE_LIMIT_FILES}} (gh pr view <n> --json additions,deletions,changedFiles,files), not counting lockfiles, generated code, or golden and fixture churn. Big refactors and renames get a human eye even when green.
And as always, steps 1 to 5 must hold for the latest commit (checks green after the final push, and the review footer naming that same commit) before merging anything.
Before merging: record the PR on the issue
(Delete this block if you have no issue tracker, or replace the commands with your tracker's. The lesson generalises even where the tooling does not.)
Required gate, not a nicety. Automatic issue closing on merge needs the link to exist in both directions, and in practice exactly one of them gets done. A sweep of our tracker once found 263 issues parked in "in review" whose delivering PRs had merged, some of them months earlier, all for want of direction 1.
1. The issue must reference the PR, as a full URL:
{{TRACKER_LINK_CMD}} # e.g. tracker comment <issue-id> "PR: https://github.com/{{GITHUB_ORG}}/<repo>/pull/<n>"
A short <repo>#<n> reference resolves only if your tooling already knows that repo, which makes issue closure depend on each person's local setup. Use the URL.
2. The PR must cite the issue in the title, the branch name, or a dedicated {{TRACKER_CITE_RULE}} line in the body. Body prose should not count, deliberately: PR bodies routinely list follow-up issues they filed, and counting prose closes unfinished work. Verify rather than assume:
gh pr view <n> --json title,headRefName,body \--jq '[.title, .headRefName, (.body|split("\n")[]|select(test("^\\s*{{TRACKER_CITE_RULE}}")))] | join(" ")' \| grep -q "<issue-id>" || echo "NOT DELIVERY-CITED"
If it is not cited, the cheapest fix on an open PR is adding that line to the body, since the branch name is fixed and retitling churns the log:
gh pr view <n> --json body --jq .body > /tmp/body.mdprintf '\n{{TRACKER_CITE_RULE}} <issue-id>\n' >> /tmp/body.mdgh pr edit <n> --body-file /tmp/body.md
Merge:
gh pr merge <n> {{MERGE_METHOD}} --delete-branch
If the merge is refused by branch protection (required approvals), report it as blocked and do not work around it. Remember that merging to {{DEFAULT_BRANCH}} may kick a deploy pipeline, so a merged PR can be live shortly after. That is fine for ordinary features and fixes. If for this particular PR the thought makes you hesitate, check whether the hesitation maps to a risk-list bullet. If it does, leave it for a human. If it does not, merge.
7. Post-merge: the default branch is yours until it is green
Merging is not the end of the loop. The merge commit runs CI on {{DEFAULT_BRANCH}} (and any deploy pipeline), and that run can fail even though the PR was green. Two green PRs can conflict semantically, the canonical case being two migration-bearing PRs merged back to back, which left the default branch with two migration heads and failed preflight plus three test suites at once. A deploy-only job never exercised on the PR can break, or a required suite can flake. A shepherd that walks away at merge time leaves that red for whoever looks next.
After each merge:
- Watch the merge commit's runs until they conclude:
``sh gh run list -R {{GITHUB_ORG}}/<repo> --branch {{DEFAULT_BRANCH}} --limit 5 \ --json databaseId,conclusion,status,workflowName,displayTitle ``
{{CI_ALERT_CHANNEL}} is the human-visible surface for these failures, and gh run list is the same signal at its source. Read the channel too where you can, because a teammate may already be discussing the failure there.
- Batch rule. When merging several PRs into one repo back to back, wait for
the previous merge's default-branch run before the next merge whenever the PRs share a risk surface. Always wait when more than one carries a DB migration (each chains from the head its branch was cut at, so merging two in one window is precisely the two-head fork), and generally for generated-code, golden or deploy-surface pairs. Disjoint UI and backend pairs can merge without the wait.
- On a red default-branch run, before anything else:
- Check whether it is already claimed. A red default branch summons every
watcher at once. Search open PRs and recently pushed branches on GitHub first, because GitHub is the one store every machine sees in real time, whereas an issue tracker that syncs at session boundaries cannot referee that race. Two of our machines once shipped duplicate fixes for the same red build with every tracker-side duplicate check green. Then check the tracker and {{CI_ALERT_CHANNEL}}. Joining someone's PR beats filing a twin.
- No existing issue, so file one (high priority, naming the failing check,
the run id and the merge commit) and claim it.
- Announce that you are working on it, in
{{CI_ALERT_CHANNEL}}and on
the issue, so the claim is visible both ways.
- Fix forward through this same skill. Push the fix branch and open the
draft PR citing the issue before implementing, because the draft PR is the claim every machine can see, then implement, shepherd to green and merge. Further merges into that repo pause until its default branch is green again. Shepherding more PRs onto a red default branch just buries the signal.
If the failure is not yours to fix, such as a parallel merge's breakage someone else already claimed, say so in the report and hand the watch over instead of looping.
8. Report
End with the PR URL, the final check status, whether it merged or was left ready-for-review (with the qualifying or disqualifying criterion), conflict resolutions made if any, and a table of every review finding and how it was handled (fixed in <sha>, or replied with a reason), naming the commit the review footer covers. If no review posted, say that plainly instead of implying one came back clean. If blocked, whether by a red default branch, a check that needs human re-run permissions, branch protection refusing the merge, or a finding you cannot judge, say exactly what is blocking and stop the loop there rather than looping forever. Three consecutive fix-push cycles that fail the same check means stop and report.