SuperAPI AI Directory

pr-sweep

General & other

View repository

Updated 10-15 17:29

About this skill

PR Sweep — batch-review + dedup-close + gated auto-merge

Repo profile — read .claude/repo-profile.md first. This skill is repo-agnostic; arc is the reference implementation. Use the profile's values wherever this doc shows an arc default: repo_slug (the gh -R target), gate_mode (arc = scripts: no CI on PRs, so gh pr checks is empty and pre-merge is the only gate; ci/both repos ALSO require gh pr checks green), verification_entry / pre_merge_entry. Arc's own provenance for the lessons below is not inlined here (fuller case narratives, where they exist, are under .claude/case-law/).

A batch driver over pr-review. pr-review handles ONE PR (read → verify against code → run verification gate → detect conflicts → verdict). pr-sweep runs that engine across all open PRs, then does the two things a single-PR engine can't: resolve cross-PR duplicate/conflict clusters (keep one, comment + close the rest) and gated auto-merge the clean ones.

This is the thing a cron schedules: one run = sync + review-all + dedup-close + (optionally) merge. It is the PR-world twin of issue-sweep; together they let an independent machine keep both issues and PRs moving with no human in the loop — escalating only the genuinely human-only decisions.

Output language follows profile comment_language。 All team-facing outputs — verdict comment, dedup/close explanations, the "needs human confirmation block" escalated to a person, and thedescription bodyof PRs opened by this sweep itself (verification-fix, etc.) — are written in the body language; code identifiers, paths, commands,path:line、gh output stays as-is.PR and commit titlesfollow comment_language title-language section, must not be mixed. Do not pile up: start with a one-sentence conclusion, then the minimum but sufficient evidence (docs / code path:line / real test output,UI-related must attach screenshots— ui-verify's screenshots/screen recordings are this kind of evidence); collapse long logs into <details>。

Goal (why it exists): make the "scheduled machine" push PRs from open to terminal state — review, dedup, merge — with as little need for human review as possible. There is no CI on PRs anymore; the gate is the pre-merge verification script; on failure look at the root cause, and if the gate/script is broken, fix the script. Humans step in only at irreversible, high-risk decision points.

Usage

/agentloop:pr-sweep              # 全量 review + 评论 + 去重关闭(不自动 merge)
/agentloop:pr-sweep --merge      # 以上 + 对通过「合并闸」的低风险 PR 自动 merge
/agentloop:pr-sweep --dry-run    # 只报告 WOULD-DO,不发 comment / 不关 / 不合
/agentloop:pr-sweep <pr#…>       # 限定到指定 PR

--dry-run semantics are consistent with all loop skills — see the plugin README's Dry-run contract。

Repo is <repo_slug>. If there is a local gh CLI use it directly; otherwise use mcp__github__*, loaded via ToolSearch.

Step 0 — first sync local <default_branch>(cannot be skipped)

Everything downstream —git grep security checks,check-types、gh pr diff comparison, every rebase — must run onthe latest <default_branch>(throughout, "main" means <default_branch>; some repos use master), not on the stale tree the container happened to clone. A previous sweep round may have already merged PRs, moved <default_branch>。

asplain commandsrun them one by one and read the results —you are the control flow, do not wrap them in shell loops/conditionals/$(…)(the sandbox's Bash guard will reject it, and this step will hard-fail before the sweep even starts — this has been hit in production).

git fetch origin <default_branch>   # 偶发失败就再跑一次(你自己就是重试循环)
git reset --hard origin/<default_branch>
git log --oneline -1                # 确认在真正的 tip

Do not use git checkout <default_branch>: in a git worktree (e.g. fleet checkout) that branch is taken by the main worktree, so checkout is bound to fail; the above fetch + reset works whether on a branch or detached. If the working tree has leftovers from a previous round → git reset --hard + git clean -fd. Start a sweep from a clean, up-to-date tree.

Step 1 — enumerate all open PRs + metadata

gh pr list --state open --limit 100 \
  --json number,title,author,headRefName,baseRefName,mergeable,files,labels,body,createdAt

Gate shape is determined by profile gate_mode : arc = scripts(deleted, ci.yml/pr-title.yml,gh pr checks is always empty,pre-merge script is the only gate);ci/both repos also need gh pr checks to be green — the gate signal comes from the pre-merge verification fanned out in Step 3, no longer reading red/green from status checks.

Step 1.5 — round awareness: only process PRs with "new input/new actionable" (the lifeblood of a scheduled routine)

First: identify PRs with agent:hold (human reservation) and apply "terminal-state freeze" to them. During Step 1 enumeration --json already has labels, each PR's labels are already in hand.agent:hold What is frozen is irreversible terminal-state actions, not freezing handling— a human applying this label usually means "I decide this PR's fate, don't merge without my feedback", not "ignore it":

  • Absolutely forbidden during hold: merge, close (including duplicate close), remove label — until a human removes it agent:hold。
  • During hold, do as usual(round-aware rules same as non-hold PR):Someone has a new human comment (after the last agent comment) or a new commit → still review + respond— read human feedback, reply to comments, follow humanexplicitly given change requestswork on the PR branch (push after fixing + rerun pre-merge, verdict annotated held: 等人摘 label 后才可合)。no new input → skip(same as an ordinary already-reviewed PR, do not repeatedly spam conclusions).

Counterexample (hold≠don't touch): sweep once completely skipped a human's explicit change request because of hold, misreading "hold=don't merge" as "hold=don't touch". A human's new comment on a hold PRis precisely the highest-priority input(the human came specifically to speak), and must be responded to.

agent:hold is the generic "human reserved" for issues/PRs (GitHub label repo-level shared); it is orthogonal to the processing mutex, on the PR sidedoes notintroduce agent:processing(concurrent dedup relies on deterministic branch + claim check + disposition label).

Before agent:hold , first identify and entirely exclude PRs with epic-managed . It belongs to an epic-conductor exclusively drivenepic (see epic-conductor): that conductor will dispatch its own clean-context reviewer, route findings, run the merge-gate, merge itself and unlock the next wave. sweep does not touch it at all—no review, no comment, no duplicate close, no merge (even if the verdict would be MERGE, even if the risk tier is 🟢). Different from agent:hold(frozen final state but still responds to human comments):epic-managed does not even review/comment, because that is the conductor's job, and sweep interfering would collide with its in-flight worker/reviewer. epic PRs usually also carry agent:hold as double insurance, but epic-managed is the stronger, cleaner exclusion key (one rule covers all epics).filter all PRs of an epic:gh pr list --label "epic:<父issue#>"。

Without this step, every hour the same batch of "already reviewed, nobody replied, and cannot auto-merge" PRs would be re-spawned with agents + repeatedly spammed with comments—burning tokens, spamming, and possibly racing. Rule:by default trust the previous round's conclusion, and only act when "there is new input" or "the external blocker has been cleared". This is the PR-side dual of issue-review "round-aware".

First use gh metadata for cheap triage (without spawning an agent). agent comment = hasmachine marker(sweep-trace / Generated by [Claude Code] footer / author is Bot); the rest = human (see the needsReview code block below).Do not judge by the > 🤖 header——<agent_identity_script> generates the same header for humans and agents, so a hand-pasted comment would be misjudged as an agent verdict and skipped (live arc#1722 was skipped for 19h). presence > 📡 heartbeat is the only exception recognized by the first line. For eachunfinishedPR, apply a controlled disposition label, and the next round will triage by it:

disposition label meaning next round action
(none / merged / closed) previous round already finalized no longer in the open list, naturally skipped
pr-sweep:needs-fix BLOCK, butthe fix path is already clear(review or a human gave the exact path) agent has → then fix: implement that route on the PR branch → turn it green → after passing the Step 5 merge gate, then decide whether to merge(risk tier recalculated; routes originating from human-requested changes must go back to the human for approval). This is "there is clear work for the agent to do,"not waiting for a person(see Step 5 "the PR is the unit of work").at most 3 consecutive rounds(see "fix round limit" below); if it is still not green after the 3rd round → switch to pr-sweep:awaiting-direction, and do not automatically start a 4th round
pr-sweep:awaiting-glance 🟢light green merge at a glance: AI has fully verified everything (verification green + claim check), the UI side already has screenshots attached for the current HEAD, and the human only needs to do a visual/common-sense confirmation wait for the humanexplicit approval wording → pass the Step 5 common prerequisites and merge directly. This is the tier with the lightest human burden; in the comment give "what to look at + which image + a one-sentence confirmation is enough."the AI side may only apply this label when there is nothing left undone——incomplete evidence (screenshot missing/stale) = still needs-fix, not glance
pr-sweep:awaiting-direction 🔵blue wait for direction decision: AI is confused or faces an A/B choice and needs the human to givehigh-level direction(product intent, architectural direction, scope trimming)——not low-level details(details should be chewed on by the AI itself or routed to needs-fix) wait for a new human comment. The comment must elevate the question to the level a human should handle: options + their respective consequences + AI recommendation + what evidence can settle it; never make the human read code on the AI's behalf
pr-sweep:awaiting-judgment 🟡yellow risk uncertain: AI perceives potential risk (semantic boundary, rollback surface, blast radius) but is not confident enough to decide on its own, and asks the human to judge "whether this risk is real and acceptable" wait for a new human comment. In the verdict,state specifically what is uncertain(not "it's a feature so escalate"); if the human judges "no risk/acceptable" = approval wording → can merge
pr-sweep:awaiting-caution 🔴dark red institutional caution: security surface / breaking change / irreversible operation / changing verification gate semantics——i.e. the 🔴 tier of Step 5, no matter how confident the AI is, human approval is mandatory wait for the humanexplicit approval wording;comment must include the pr-review "needs human confirmation block"(for security, list security properties item by item + verification commands). Red is reserved only for this tier——only it deserves the "urgent/dangerous" visual signal
pr-sweep:awaiting-human(old, deprecated) existing escalations without a tier assignment migration: read the escalation reason in the last verdict and reassign the tier——pure waiting for confirmation→glance; direction question→direction; risk concern→judgment; security/breaking→caution; if the reason is no longer in the current 🔴 table (e.g. merely because "it's a feature") or there is actually clear work→re-review as needsReview/convert to needs-fix. After switching labels, delete the old label,and do not newly apply this label

common semantics of the four awaiting-* tiers: truly waiting for human input, with 0 action by the agent this round (until a new commit or a new human comment); the only difference iswhat the human has to put in——glance is a 10-second confirmation, direction is a direction decision, judgment is a risk assessment, caution is an institutional review.When labeling, go from light to heavy by human burden and when in doubt choose the lower one; this whole family only contains "waiting for someone", not "has a clear task" (that is needs-fix)。What a new human comment unlocks is "handling", not "merging"(next item).

★ Change request ≠ merge approval (iron rule). awaiting-* / On a 🔴-tier PR, new human comments must beread as two categories:

  • Explicit approval wording("LGTM" / "可以合" / "approve" / "merge it") → unlocks merge (still must pass the Step 5 general prerequisites).
  • Change request(everything else: change styling, add functionality, swap implementation—even if the fix is completely clear) → only unlocks "doing the work": the agent implements on the PR branch → push → attach evidence (for UI surfaces, before/after screenshots against the new HEAD must be attached) + rerun pre-merge → set pr-sweep:awaiting-glance(evidence is ready, human takes a look to confirm), @ the person in the comment asking them to confirm——never merge on your own just because "the request has been satisfied". A human raising a change request = the human is reviewing this PR = the human wants to see how it looks after the change before signing off (the agent merged directly without waiting for confirmation after the human raised a change request). | pr-sweep:blocked-deps | Only becausean unrelated dependent packageis red on <default_branch> and it is blocked (PR code already verified) | do not re-review; only run Step 5's cheap gate to recheck, and merge once it is green (do not post a new comment). Once the dependent is fixed it lands automatically |

Bounded repair (issue #1204, human decision: "during automatic repair, at most no more than 3 rounds each time, that is, if three rounds still do not work, then report the current state and ask the human to give input and direction"):

pr-sweep:needs-fix is not unbounded retry——needs-fix In this state, each time full-review starts an agent repair counts as one round; if 3 consecutive rounds still cannot run green (or run green but cannot pass the merge gate), you must stop and escalate to a human, and must not retry a 4th time burning tokens.

  • Counter carrier: the round count is embedded in the verdict comment, in the same paragraph as the sweep-trace marker, without opening new storage:<!-- pr-sweep-attempt: N -->(N = which repair attempt this round is). Before starting the agent, first read this marker in the last 🤖 AI Agent PR Review comment; if the marker is absent = this is repair round 1 (N=1)。
  • Increment timing: each time because of needs-fix you start an agent repair and push a new commit, the new verdict comment's N = the previous N + 1. Read-only verdict rechecks (cheap gate, no new code changes) are not counted as rounds.
  • Reset timing: after round 3 escalates to pr-sweep:awaiting-direction , a comment where the human gives new direction (not a simple "continue"-style follow-up) is treated as the starting point of a new round of repair,N counts again from 1—the old 3 times were exhausting the old direction and should not be carried over to the new direction.
  • Escalation action if round 3 still is not green: switch to pr-sweep:awaiting-direction(the tier among existing non-deprecated tiers that best fits "the agent is stuck and needs a human to give direction"; do not create a new label), and the verdict comment must include a summary of each round of attempts, format:
    ## 修复上限已达(3/3 轮),需要人类给方向
    - 第 1 轮(<sha>):尝试了 X,失败原因 Y
    - 第 2 轮(<sha>):尝试了 X',失败原因 Y'
    - 第 3 轮(<sha>):尝试了 X'',失败原因 Y''
    **agent 判断仍缺**:Z(需要人类决定/提供)
    
  • Not applicable: red and BLOCKED due to an external dependency (pr-sweep:blocked-deps) is not counted as a round (that is waiting for the dependent to be fixed, not the agent repeatedly failing on its own).

Determine "a full review is needed" (start an agent) — if any of the following holds:

  1. Never reviewed (no agent comment — judged by the predicate below, not by some literal prefix); or
  2. head commit time > time of the last agent comment(code changed → old conclusion is invalidated, re-judge); or
  3. after the last agent commentthere is a human comment(new feedback → enter the resolve phase); or
  4. time of the last Draft → Ready event > time of the last agent comment(#1831 blind spot two: transitioning to ready neither moves head nor produces a comment, so pure timestamp/sha comparison can never see it — the author marking ready is the "please review" signal).
# 每个 PR:head commit vs 最后 agent 评论 vs 最后 human 评论 vs 最后 ready_for_review 事件
# ⚠️ 人类意见散在三个面:①会话 comment ②代码行 inline review comment(pulls/comments)
# ③review 总评(pulls/reviews)。只查 --json comments 会漏 ②③,人类 inline 修改要求会看不见。
# 必须三面并集:
head=$(gh pr view <n> --json commits --jq '.commits|last|.committedDate')
all=$( gh api repos/{owner}/{repo}/issues/<n>/comments --paginate --jq '.[]|{t:.created_at, body, bot:(.user.type=="Bot"), login:.user.login}'
       gh api repos/{owner}/{repo}/pulls/<n>/comments  --paginate --jq '.[]|{t:.created_at, body, bot:(.user.type=="Bot"), login:.user.login}'
       gh api repos/{owner}/{repo}/pulls/<n>/reviews   --paginate --jq '.[]|select(.body!="")|{t:.submitted_at, body, bot:(.user.type=="Bot"), login:.user.login}' )
# 「是 agent 评论」= 带**机器标记**,human = 它的否定。判据不是 `🤖` 头:
# <agent_identity_script> 给**人和 agent 生成同样的** `> 🤖 AI Agent @host·runner:…·skills@…` 头,
# 人手贴的评论逐字节相同 —— 按头判会把人类指令当成 agent 裁决跳过(实盘 arc#1722 跳了 19h)。
# 机器标记(可靠、人不会手写):① sweep-trace HTML 注释(本 skill 每条 verdict 强制附,见文末);
# ② `Generated by [Claude Code]` footer;③ 作者是 Bot(云端 runner 走 GitHub App → claude[bot])。
# 例外:presence board 的 `> 📡` 心跳脚本发的、不带 trace,靠首行 `📡` 认(否则每轮重刷 board)。
# 标记可能 HTML 转义(`&lt;!-- … --&gt;`,#1278),先 decode。老的无标记评论按人类处理(新规范)。
#
# ★ Codex / bot-review connector 是第三类时间戳(既不是 hu 也不是「可忽略的 bot 噪声」):
# 若把 chatgpt-codex-connector 全算进 isAgent,Codex 在 verdict 之后的 P1 永远不触发 needsReview,
# epic/普通 PR 都会「全绿却挂着未处理 bot finding」。单独取 codex 时间;codex > ai → needsReview。
# 它们仍不是人类:不触发「修改要求 → awaiting-glance」那条铁律,只触发「读 finding → needs-fix」。
JQ='
  def dec: gsub("&lt;";"<") | gsub("&gt;";">");
  def firstline: .body | split("\n")
     | map(select((test("^[ \t\r]*$")|not) and (test("^[ \t]*<!--")|not))) | first // "";
  def isCodex: (.login // "") | test("chatgpt-codex-connector|codex-connector";"i");
  def isAgent: ((.body|dec) | test("<!--[ \t]*sweep-trace:"))
            or (.body | test("Generated by \\[Claude Code\\]"))
            or ((.bot // false) and (isCodex|not))
            or (firstline | test($pre));'
PRE='^[ \t]*(#{1,6}[ \t]*)?(>[ \t]*)?📡'
ai=$(jq -rs --arg pre "$PRE" "$JQ"'[.[]|select(isAgent)]    |max_by(.t)|.t // empty' <<<"$all")
hu=$(jq -rs --arg pre "$PRE" "$JQ"'[.[]|select(isAgent|not)|select(isCodex|not)]|max_by(.t)|.t // empty' <<<"$all")
codex=$(jq -rs --arg pre "$PRE" "$JQ"'[.[]|select(isCodex)]|max_by(.t)|.t // empty' <<<"$all")
# Draft→ready 也要触发重审(#1831 盲区二):PR 从 Draft 转 ready_for_review 后应重新 full-review。
rfr=$(gh api repos/{owner}/{repo}/issues/<n>/timeline --paginate \
      --jq '[.[]|select(.event=="ready_for_review")|.created_at]|max // empty')
# needsReview = ai 为空 / head > ai / hu > ai / codex > ai / rfr > ai
if [[ -z "$ai" || "$head" > "$ai" || ( -n "$hu" && "$hu" > "$ai" ) || ( -n "$codex" && "$codex" > "$ai" ) || ( -n "$rfr" && "$rfr" > "$ai" ) ]]; then echo needsReview; fi

(a COMMENTED row with an empty body in reviews is the shell of an inline comment, already covered by ②, so filter it out; when "responding to human feedback", inline comments must use pulls/<n>/comments of path+line to locate the specific code. The TS reference implementation of the human-vs-machine criterion (with regression tests):issue-sweep/test/sweep-golden/lib.ts of isAiAgentComment / scripts/team-report.ts of isHumanComment— to change the criterion, change those two places + the tests first, then sync here.)

gh equivalent call when unavailable = pull_request_read of get_comments/get_review_comments/get_reviews three methods (same lookup table as pr-review Step 0 ) —the output of these three methods must all appear in this round's record; you cannot just call one or two and consider the three-way check done. Andnote that this section's script folds only .body/.t into hu/ai for the freshness determination; it does not read .state— "is there a CHANGES_REQUESTED" is not judged here, it is judged by the independent Review gate at Step 5 below in this file; here it only answers "should a review be started again", not "can it be merged".

★ sha takes priority over timestamp (#1812 retrospective): if the sweep-trace of the last AI verdict carries the sha field (pr-review Step 0.6), directly compare sha == headRefOid— precise, cross-runner machine-deduplicable; the timestamp comparison above is only a fallback for the old format (without sha).But equal sha only short-circuits criterion 2 (new commit), not criteria 3/4— new human comments and Draft-to-ready do not move head, so sha is still equal (#1831). And when needsReview holds, the fanned-out pr-review agent does, per its Step 0.6,incremental re-review + in-place upsert of the canonical verdict— it does not redo from scratch or append new comments (#1812: three runners each doing one round of full review, 6 stacked comments, and not a single one being a valid verdict on the current HEAD, is exactly the absence of these two).

★ criterion 2 (new commit) does not hold for mechanically regenerated PRs. automatic release tools (release-please and the like) rewrite their own branch on every upstream merge,head is always newer than ai, so criterion 2 holds every round and every round is needsReview — while the conclusion is constant (such PRs are conventionally merged manually).Real-world: one automatic release PR accumulated 29 comments, 22 conclusions word-for-word identical, spanning 26 skills versions— not a bug in some version, but the criterion picking the wrong dimension. Therefore:

When a PR satisfies "mechanically regenerated" (branch name has an automatic release prefix / has a autorelease -style label / the diff touches only version numbers · CHANGELOG · lockfile) and already carries pr-sweep:awaiting-* or agent:hold , criterion 2 does not apply—— Only criterion 3 (new human comment), criterion 4 (Draft→ready), ordiff shape changed(touched file set exceeds the mechanical parts) is needsReview re-triggered. All other rounds take 0 actions; not even a sha refresh needs a new comment (see pr-review Step 0.6 "treated as fresh").

Otherwise (already reviewed, no new commit, no new human comment):

  • pr-sweep:awaiting-*(any of the four tiers) → this round takes 0 actions, skip directly.
  • pr-sweep:blocked-deps → skip review, only do the cheap gate recheck of Step 5; merge if the gate is satisfied (the root fix is still to fix that broken dependent package).

Idempotent wrap-up (for every PR that completes full-review): according to the conclusionrefresh disposition label (terminal=merge/close, remove label; held=apply the corresponding label), verdict comment per pr-review Step 6 's canonical upsert update in placerather than posting anew (marker <!-- pr-review-verdict --> locate + PATCH, so the same one can be refreshed across runners;--edit-last only covers the case where "the previous one was posted by yourself").Never repost the same conclusion when there is "no new input". Create these labels if missing, using only this controlled vocabulary (pr-sweep:needs-fix / pr-sweep:awaiting-glance / pr-sweep:awaiting-direction / pr-sweep:awaiting-judgment / pr-sweep:awaiting-caution / pr-sweep:blocked-deps), don't create variants again,and no longer newly apply the deprecated pr-sweep:awaiting-human。

★ "canonical upsert" covers every PR comment this skill posts, not just the verdict. Explanations posted by the sweep itself, such as disposition / recheck / "new information", likewise go through marker locate + PATCH in-place update——at most one agent comment carrier per PR. The real-world bug is right here: verdict has an upsert rule, disposition does not, so each round appends one, and a single PR accumulates up to 29 comments of which only 11 carry the upsert marker.A new comment is only allowed when "this PR does not yet have any agent comment".

★ Cross-runner collision self-check before posting a comment (cheap, replaces a mutex). The PR side does not introduce agent:processing(see Step 0), so N runners may simultaneously judge needsReview in the same round.Refetch comments once before posting; if a sweep-trace already exists with the same gate and the same val , andsha also equals the current HEAD → it means another runner just posted the same conclusion, this round switches to 0 actions(no new post, no duplicate upsert). This can't stop nanosecond-level simultaneous writes, but it can stop the vast majority of real-world patterns where "three runners each post one within a few minutes".

Only PRs that Step 1.5 judges as needsReview enter Step 2 clustering + Step 3 review. The rest only go through "cheap gate recheck + merge if mergeable". This compresses the number of agents started per round from "all open PRs" to "PRs that actually changed", keeping routine stable long-term and avoiding spam.

Step 2 — Clustering (the basis for dedup + conflict)

Two primary keys, compute clusters first, then review——so each review agent can carry the context of "who its peers are".

  1. Same-issue cluster(the main battleground for dedup closure). From headRefName extract the issue number (claude/<verb>-<N>-<slug> → <N>), and extract from the body Fixes #N / Part of #N。multiple open PRs with the same <N> = suspected duplicate cluster.
    gh pr list --state open --json number,headRefName,body --jq '
      .[] | {n:.number, br:.headRefName,
          issue:(.headRefName|capture("-(?<i>[0-9]+)-")?.i
     	    // (.body|capture("(?:Fixes|Part of) #(?<i>[0-9]+)")?.i))}' \
    | python3 -c "import json,sys,collections; \
        d=[json.loads(l) for l in sys.stdin]; \
        m=collections.defaultdict(list); [m[x['issue']].append(x['n']) for x in d if x['issue']]; \
        [print('issue #%s -> PRs %s'%(k,v)) for k,v in m.items() if len(v)>1]"
    
  2. Same-file cluster(line-level conflict / shared config risk). Compute the file -> [PRs] inverted index; those >1 are overlaps.Exclude noise:release-please automatically creates a PR that touches every package.json + CHANGELOG.md, such global overlap does not count as a conflict; identify the release cluster separately.

Feed each PR's peer list to its review agent (Step 3).

Step 3 — fan out pr-review (clean context, one per PR)

Hand each open PR to the pr-review engine,with clean context and independent judgment, along with its peer cluster information. Return astructured verdict(5 categories + verification result + conflict conclusion + evidence + comment draft for problematic items). pr-review runs pre-merge verification every time and incorporates the result into the verdict (there is no longer any CI on the PR).

For PRs with UI changes: pr-review's Step 3.5 conditionally triggers UI Face Pathswhen the diff matches profile ui-verify(that repo's companion, see repo-profile's Companion Skills; if there is none, stub it or skip that step) (screenshots + screen recording posted back to the PR) —provided that this routine's environment has a running daemon. A pure static sweep environment with no daemon will apply the ui-verify:pending label + note it, and a routine with a daemon will make up for it using the pending scan step below (#1205) — it no longer counts as done just by leaving a one-line note; the label makes the make-up run a deterministic closed loop instead of relying on a human to dig through verdict text to find omissions.

Step 2.5 — ui-verify:pending make-up scan (only when this routine has a daemon)

When this routine's environment has a running daemon , before the normal Step 3 review fan-out, first scan this deterministic label queue and make up the ui-verify that daemon-less environments owe:

gh api "repos/{owner}/{repo}/issues?state=open&labels=ui-verify:pending&filter=all" \
  --jq '.[] | select(.pull_request != null) | .number'

For each matching PR: if HEAD has a new push after the label was applied (go through the Step 1.5 fresh determination again), still make up the run against the new HEAD; run /ui-verify --pr <n>, after screenshots/recording are posted back to the PR, gh pr edit <n> --remove-label ui-verify:pending。this routine has no daemon → skip this step (silently, not a fail), this is the other half of "the two environments complement each other": the pure static environment is responsible for discovery + marking, and the daemon environment is responsible for making up runs + removing the label.

ui-verify:pending ≠ BLOCKED(issue #3010, the terms must not be conflated):pending label means "the daemon/browser itself is unavailable, so this round did not run at all", and produces no evidence comment;BLOCKED is one possible result value of the sticky evidence comment, meaning "it ran and the screenshot exists, but it could not be published as a publicly readable URL". Neither one allows merging, but the semantics differ — a pending PR must never be described as "UI verified" or "screenshots are just pending, so it can be merged", before a successful make-up run it is simply missing evidence.

  • Model: per-PR review is abounded task(read 1 diff + related issue + verification + run pre-merge once + possibly 1 test) → Sonnet。cross-PR synthesis (deciding cluster winners, judging whether contradictions are real, merge-gate decisions) should use a strong model (Opus) in the main control, do not delegate it. The cost difference is ~5×.
  • Concurrency/orchestration — split into two paths by runtime environment (this determines whether the routine can run unattended):
    • Unattended (cron routine) → serial inline review, never call Workflow. Workflow The tool requiresinteractive opt-in confirmation, and it is usually not in the routine's allowed_tools → it pops up a confirmation dialog, no one is there to click it in the routine → hangs forever(observed: the pr-sweep routine got stuck all night on "please allow Workflow"). So in a routine,Only tools within allowed_tools that don't trigger confirmation(Bash/Read/Write/Edit/Glob/Grep/Skill), per-PR review is done by this session one by one, inline(read diff + verify + decide verdict).Step 1.5 round awarenessEach round's PRs have already been compressed to "just the few that actually changed"; serial is entirely sufficient and saves more.
    • Interactive (human present / explicit opt-in) → Workflow fan-out may be usedto accelerate:parallel(PRS.map(pr => () => agent(prReviewPrompt(pr), {model:'sonnet', schema: VERDICT_SCHEMA}))), main Opus synthesizes, resumable.
    • Iron rule: in any unattended run, never call a tool that triggers confirmation / waits for the user / requires opt-in (Workflow, AskUserQuestion, EnterPlanMode, and anything not in allowed_tools ) — it will deadlock the entire routine. If unsure whether a tool will trigger confirmation → assume it will, and switch to inline / gh / Skill. If a human decision is needed → the question (options + recommendation) is posted as a comment on needs-human-confirm to the corresponding PR/issue, then continue with the next item. The repo hook (.claude/hooks/deny-interactive-unattended.py) hard-denies these three tools as a backstop in unattended sessions — if denied, follow this item, don't retry.
  • review read-only: analyze only, produce only verdict + comment draft,no comment posted, no merge, no close. All outward writes are done uniformly in Steps 4–5 (rate-limit controllable, decisions centralized).

Step 4 — dedup-close: duplicate pairs on the same issue, keep one, close the rest

This is the core increment of sweep over a single-PR engine, and also the current highest-frequency cleanup action. When a same-issue cluster has ≥2 open PRs:

  1. Choose the keeper: use pr-review's keep-which criteria — more complete diff > more correct (against authoritative source) > has tests > newer base > first-come. Synthesize with Opus to decide, with evidence. 1.5. second opinion (closing the wrong PR is irreversible — the author will receive a close notification, worth spending an extra round to verify; #1055 direction five / #1208): before deciding the keeper, fan out againan independent, brand-new context agent (Agent tool,general-purpose), give it a summary of the same cluster's PRs (diff outline + criteria table, without the main session's conclusions), require it to independently choose a keeper by the same criteria, and return a structured result {keep: <PR号>, reason: "<一句话>"}(natural-language comparison is unreliable, see #1208 evaluation — only compare keep PR numbers, do not compare reason wording).
    • The two keep agree → continue with steps 2-4 per these criteria.
    • Disagree → do not dedup-close this cluster this round, tag each PR in the cluster with pr-sweep:awaiting-direction, and comment listing both agents' choices + reasons, waiting for a human to decide which is the keeper.
    • Triggered only for dedup-close keeper selection— other high-risk decisions (security flagging, verification gate semantics) follow the existing conservative path, without adding second-opinion, so as not to slow down daily sweep speed (evaluation conclusion in #1208: security is already conservative enough as comment-only, and the verification gate scenario does not exist in issue-sweep/pr-sweep).
  2. Contradictions must be checked against the authoritative source: two PRs in the cluster assert conflicting(e.g. the same license, one BUSL-1.1 one BSL-1.1)→ first check the repo authoritative source (LICENSE / existing canonical docs) to determine which is correct,only the correct one can be the keeper; if both are wrong and neither fits, comment to point it out.
  3. Close the redundant side (twin): for each non-keeper:
    gh pr comment <twin> --body-file <note.md>   # 说明:与 #<keeper> 重复(同 issue #N),保留 #<keeper> 因 <判据+证据>;本 PR 关闭
    gh pr close <twin> --comment "superseded by #<keeper>"   # 或先 comment 再 close
    
    The top of the comment carries the full identity line (the whole line is generated by <agent_identity_script> --header "PR Review" --skill pr-sweep , cannot be replaced by a date, placeholder, or manual assembly, and do not hand-write Claude Code(<model>)either——engine/model are automatically brought in by the script according to ARC_AGENT_ENGINE/ARC_AGENT_MODEL ; append the read/run scope at the end of the line). The body states responsibility in one sentence + points to the keeper.
  4. Leave one on the keeper: note "duplicate #twin has been closed, this PR is the retained one" for human traceability.

Closing is reversible(can be reopened), and here there is clear evidence + two-way backlinks → this is "do automatically". Butdo not close by mistake: only close when it is established as "same issue, same change scope, truly redundant/superseded"; if unsure, keep both COMMENTand lay out the conflict for humans.If any PR in the cluster has agent:hold(human retain) → do not participate in deduplication closing(hold freezes terminal-state actions, close is terminal: it is neither closed as a twin, nor used as a keeper to close others——its own fate has not yet been decided by a human; the conflict facts are still written into the verdict comment for human reference).

Step 5 — merge gate (--merge when): auto-merge by risk tier, escalate high risk to humans

Gating = profile gate_mode(arc = scripts: no CI on the PR,pre-merge the script is the gate;ci/both stacked with gh pr checks green), and do not merge blindly either. For each MERGE/COMMENT-mergeable verdict, pass this gate:

Common prerequisites (required for all tiers):

  • ★ Verification gate (strong constraint, the real merge gate, cannot be skipped): run before merge <merge_gate_entry> Confirm that the sha in the PR comment matches the current PR HEAD and result=PASS or result=NA:
    <merge_gate_entry> <pr#>
    
    exit 0 → can merge; exit 1 → print the reason and stop: no comment / SHA stale (not re-verified after push) / result=FAIL. If missing, first run <pre_merge_entry> --comment <pr#>to post the report; fix simple errors yourself and rerun; for complex errors, post the failure diagnosis + full logs as a comment to escalate to humans. This is the merge gate that replaces CI——pr-review only judges and does not merge, so the gate lands here. <merge_gate_entry> also requires that every gate listed in profile additional_merge_gates passes(arc: e2e-gate)——when the diff hitsa backend surface that can be startedit also requires e2e-gate sticky comment (SHA==HEAD and PASS/NA); it runs scope.ts to independently determine backend hits, and pure docs/UI/frontend/test PRs automatically record e2e-gate=N/A, without blocking. New reasons for exit 1: backend surface hit but no e2e-gate comment / e2e-gate result=FAIL / e2e-gate SHA stale.additional_merge_gates For repos with empty
  • ★ Review gate (same level as the verification gate, independent of mergeable_state 's interpretation): before mergeindependently re-fetch pulls/<n>/reviews(or MCP pull_request_read(method="get_reviews")), by reviewer take each person'slatest review's state。only recognize human reviewers(user.type != "Bot"; Exclude chatgpt-codex-connector[bot] and other bot-review connectors—they follow the "Codex / bot-review short-wait" clause below + codex-review-backlog,notthis human CHANGES_REQUESTED hard gate). Anyhuman reviewer's latest state is CHANGES_REQUESTED and has not been superseded by the same person's later APPROVED → hard stop, do not auto-merge—even if Step 3 verification is all green, regardless of what GitHub's mergeable_state shows (that field is opaque; you cannot use it to infer whether there is CHANGES_REQUESTED, nor conversely assume that if it reports no anomaly there is none; only trust the result of this independent fetch). When hit, handle via the standard escalation path (paste that review's state+bodyin the comment, usually tag pr-sweep:awaiting-direction:what the reviewer raises is a directional question of whether to change scope per their request, not a mechanical fix that can be self-decided).This gate is independent of whether Step 0/pr-review has already checked all three sides—both places must have it; if either place misses it the other can still block, they do not depend on each other. And
  • ★ Codex / bot-review short-wait (progress-first, do not hang for a long time): This org's Codex after open/ready/push usuallywithin a few minutesgives inline findings, or leaves only a 👍 to indicate no opinion. Rule:
    • 👍 / no inline finding → does not block merge (not counted as the human review gate).
    • Has a P1 inline finding and the agent has not yet fixed or REJECT-replied → treat as actionable work: add/keep pr-sweep:needs-fix, fix on the PR branch or reject-reply in the thread, then rerun pre-merge;Do nothang for hours because of "waiting for Codex to review once more".
    • After the fix is pushedat most short-wait ≤10min to see re-review/👍; if timed out with no new P1 → merge per the remaining gates.
    • Late Codex arriving only after merge → do not roll back this round's merge decision; hand it to codex-review-backlog。
    • with the same contract as epic-conductor §6 (epic PRs are executed by the conductor; this skill applies the same short-wait semantics to non- epic-managed PRs). And
  • PR does not carry agent:hold(reserved for humans; during hold, review/response proceed as usual butmerging is always frozen—this is a hard gate before merge; with a hold, never merge, even if the risk tier is 🟢, even if the verdict is MERGE. Write the verdict as MERGE (held) and have someone remove the label); and
  • ★ UI evidence gate (symmetric with the backend data-plane gate, welded shut by <merge_gate_entry> , issue #3010):diff hits profile UI Face Paths → before merge there must be for the current PR HEAD、published (publicly, readable without credentials) of <ui_shot_script> / ui-verify screenshot evidence—automatically enforced by <merge_gate_entry> (it runs .claude/skills/ui-verify/scripts/scope.ts to judge a hit, not relying on self-discipline; the check target is a <!-- ui-verify-report sticky comment's sha=/result=, not parsing the PR body text). All three cases are rejected:no evidence for the current SHA, evidence attached to a stale SHA, evidence judged BLOCKED(screenshots only exist at a local path, upload fails, unreachable after publish due to anonymity— screenshots in pending-upload never count as "verification complete").Any push—including the agent's own fix commit—invalidates existing evidence,retake/resend and then merge;daemon/browser itself unavailable(truly pending, distinct from BLOCKED)→ label ui-verify:pending label, do not merge, leave it for a routine with a daemon or a human to re-run (renderer/widget-level changes go through <ui_shot_script> no daemon needed, "no daemon"≠"cannot screenshot", must not skip renderer screenshots on the grounds of "no daemon"). Static pre-merge cannot see "what the popup looks like"; this gate fills exactly that eye; for the deterministic fallback when upload fails (browser native attachment upload, requires posting both the PR + linked issue) see ui-verify SKILL's Step 3;and
  • ★ Backend data-plane gate (symmetric to the UI evidence gate, welded shut by <merge_gate_entry> ):diff hits profile Backend Face Paths → before merge there must be for the current PR HEAD the e2e-gate sticky comment (PASS/NA, SHA==HEAD). Automatically enforced by <merge_gate_entry> (it runs scope.ts to determine a hit, not relying on self-discipline)—any push invalidates the existing e2e-gate comment, re-run then merge. When the comment is missing, first run /e2e-gate --pr <n>(start the service for the diff-hit blocklet and run Tier A+C smoke, post back to the PR); a pure static environment where the daemon cannot start → do not merge, leave it for a routine with a daemon to re-run. This gate fills exactly the eye for "static all green, 500 on first run"; and → after the agent responds to changesmust not merge on its own, must post evidence + wait for a human'sexplicit approval wording;and
  • pr-review verdict ∈ {MERGE, or COMMENT and the concern is non-blocking};and
  • declared verified (Step 3's item-by-item verification passed);and
  • mergeable == MERGEABLE(not CONFLICTING; if conflicting, rebase first or leave it to a human);and
  • no unresolved same-issue/same-file conflicts (Step 4 has converged).

(there is no longer a CI status check on the PR; the above pre-merge PASS is the only gate. When the failure root cause is (b) flaky/(d) noise, handle it per pr-review Step 3's judgment—do not block, may self-fix; (a) defects in this PR are never merged.)

Risk tier (decides auto vs escalation)—policy: pass by default, tighten when problems arise:

active development phase, no external users—"it's a feature" is itself not a risk, "waiting for a human" is the cost(the vast majority of feat PRs escalated to humans get merged directly by a human with zero feedback). Pushing an all-green, fully-verified PR to a human for rubber-stamp is offloading responsibility onto the human, not caution. To judge risk, look atthe change content(security surface? breaking? direction undecided?), not the commit type prefix, not the diff size.

Tier PR type --merge behavior
🟢 Low risk docs-drift, test-only, comment/type/lint fixes, polyfill already in the repo, release-please PR (keeper) auto squash-merge
🟡 Medium risk core-code bug fix (with tests), behavior change,Non-breaking feature(including backward-compatible protocol additions: new action / new optional field / new enum value + supporting consumer side), cross-platform parity completion, large diff but semantically additive DefaultAuto-merge(precondition: all universal prerequisites pass —pre-merge green + declaration verification + UI evidence gate + new behavior has real tests); any reservation in the verdict (partial fix / missing tests / parity gap / no-caller suspicion) → downgrade to comment and wait for a human
🔴 High risk security surface(auth/authz/payment/exec-gate/keys/sandbox boundary),breaking change(criteria see below),changing the architecture direction / design A/B undecided / a human has explicitly expressed disagreement, changing verification gate semantics (security gate) Never auto-merge; escalate to a human — security/breaking/gate semantics → pr-sweep:awaiting-caution, direction undecided/human already disagreed → pr-sweep:awaiting-direction;verdict must include the pr-review "needs human confirmation block"(what you need them to decide + how to verify + recommendation; for security list each security property path:line + verification command)

Hard prerequisite before escalation (issue #1860, same as pr-review Step 5.5 / issue-review Step 5.5): before judging 🔴 first ask "can I state a safe default action?" — if yes → do not judge 🔴, immediately execute that default action per the ratchet and leave a trace; if no, then it is a real judgment call and only then does it warrant escalating to a human.

Breaking change criteria (any one hit counts; rename/refactor within the same PR inside the monorepo does not count — types/tests green is the evidence):

  • Incompatible protocol/wire change: already-deployed clients (Swift/Kotlin native, already-shipped blocklet) will disconnect or misinterpret the message because of it;
  • Schema change with no migration path (existing D1/SQLite data will be lost or misread — refer to the migration discipline of d1-table-naming);
  • Deleting or semantically flipping public API/CLI behavior still consumed outside the repo;
  • Destructive data operations (dropping tables, clearing data, irreversible migration). Pure addition (new provider, new action, new optional field, new page, new renderer)is not breaking。

★ The risk tier is recomputed before every merge attempt, and applies to all paths. It is not settled once during the first review round — needs-fix after the follow-up fix runs green,blocked-deps after the cheap re-check, after pushing in response to a human change request,before merging, all must re-run this table. 🔴 tier (security/breaking/direction undecided)never auto-merges on any path: even if a human gave an explicit fix route, even if fully green after the fix — "green → merge" only holds for 🟢/🟡, and the endpoint for 🔴 is always "green → post evidence → wait for approval". Also note, independent of tier and in effect on its own: for a PR where a human has issued a change request, regardless of tier, after responding you must wait for explicit approval language (human feedback re-approval gate).

★ Scale evolution (ratchet, the only legitimate way to tighten): A pattern that was auto-merged and then reverted / caused a real incident → add that pattern to the 🔴 table with a case link(one instance equals one entry, precise to the pattern, not sending the whole feature category back to 🔴). The reverse direction: a certain type of PR repeatedly gets zero-feedback rubber-stamped → that is a signal to move it out of 🔴. Better to start permissive and tighten based on evidence; "when unsure, escalate" doesn't require changing the table, but the verdict must clearly state the specific thing you're unsure about (not "it's a feature so escalate").

gh pr merge <n> --squash --delete-branch    # 低风险闸通过

Fix it yourself when it's a trivial effort; don't write an "action suggestion" and toss it to someone else (pr-sweep's core discipline)

When a PR is only a 'mechanical operation' away from merging, the agent does it and merges it itself, and never outputs a checklist saying "please follow these steps." This is the PR-side dual of issue-sweep's "do it if you can"——Writing "action suggestion: delete a space, rebase, re-trigger, then it can merge" and then tossing it to a person = bug. These are all things the agent can do itself:

Mechanical blocker Agent does it itself
Formatting/whitespace/lint noise (reported by profile formatter ) On PR branchrun <formatter>/ remove whitespace → commit → git push(pushing to the other party's branch requires permission; only escalate if there is no permission)
base is behind / BLOCKED-behind gh pr update-branch <n> --rebase, then rerun pre-merge
verification expired (not revalidated after push) rerun <pre_merge_entry> --comment <n> → <merge_gate_entry> <n> passes the gate
review already explicitly pointed outa small deterministic change (add a line, change an id, remove redundancy) apply it directly on the PR branch

After these mechanical fixes are done, the PR usually passes the gate → merge directly. Only when there still remains after mechanical fixesreal judgment/logic/design/securityissue should you escalate to a person. Criterion:"Can I now push it with gh/git/editor to mergeable?" If yes → do it; if not (logic must change, design must be decided, human authorization is needed) → only then pr-sweep:awaiting-*(according to the four tiers, choose the lower not the higher) + comment.(verdict has determined it can be mechanically advanced but it was still tossed to a person)

autonomy ladder, same origin as issue-review, tiered by reversibility of consequences:

  • Do automatically: post/edit comment, adjust label,close redundant PRs after deduplication、rebase / update-branch、self-fix formatting/whitespace/lint + push to PR branch, apply the small deterministic diff already called out by review, rerun pre-merge verification, 🟢/🟡 tier merge.
  • Escalate to a person (pr-sweep:awaiting-*, choose the tier according to the person's burden: pure confirmation→glance / direction→direction / risk assessment→judgment / security·breaking·gating→caution): 🔴 tier merge, real logic/design/security defects, closing anon-duplicateactive PR, changing safety gates such as verification gates/scripts, undecided A-vs-B direction. When escalatingset the source issue's author + assignees as reviewers of that PR(inheritance rules see issue-sweep Step 4; if already an assignee, just add reviewer, and if assignment fails, skip it without blocking) — escalation must land in the right person's review queue, not be posted as an unclaimed comment.——only escalate what is still stuck after mechanical fixes. The escalation comment must include the pr-review "needs human confirmation block"(What you're asking them to decide + what the agent has already verified so it need not redo it + how to verify: if it can be restored to a command, give the command + path:line + expected result; for security, list item by item; for decision questions, give options + criteria + recommendation; never fabricate commands + the unlock actions for each branch once decided).Do not stop at "please confirm manually".
  • Iron rules:Never force-merge past an unresolved conflict;🔴 tier is never auto-merged; closing a PR must come with evidence + a backlink.Never write "what you could do yourself with a little effort" as an action suggestion handed to a human.

A PR is the unit of work: pr-sweep is responsible for pushing the PR to a terminal state (including fixing rejected PRs), without bouncing back to the issue

Once a PR exists, the work lives on the PR——branch, diff, verification, review threads are all here. After being rejected by pr-sweep (BLOCK),the responsibility for continued fixing lies with pr-sweep, not bounced back to issue-review. Bouncing back is a harmful indirection layer: it loses context (branch/verification/threads), leaves ownership anchored at neither end, and runs into the AI→AI freeze (next item). issue-sweep/issue-review creates PR,pr-sweep carries it to a terminal state(fixed and merged / or escalated as a real decision).The three kinds of BLOCK:

BLOCK type Handling label
Mechanical (whitespace/format/rebase/re-trigger) agent fixes on the spot + merges (previous section) —
Substantive defect with an already-clear path: review orhumanhas given the exact fix route (e.g. some reviewer confirms "change inheritance from BaseMessageProvider + add conformance fixture") agent implements this confirmed route on the PR branch → runs green → re-passes the Step 5 merge gate(risk tier recalculated + UI evidence gate + human feedback re-approval gate): 🟢/🟡 and no human-unapproved change request → merge; 🔴 or the fix route comes from a human change request → post evidence (for UI-facing, attach a screenshot of the new HEAD) and wait for human approval."Implementation" does not wait on people, "merging" follows the gate pr-sweep:needs-fix(agent-owned, continued in the next round,not awaiting-*)
A true decision that needs a person: a design A/B no one has decided, security, irreversible, "I disagree with this approach" Escalate, with a pr-review "needs human confirmation block" (what you're asking them to decide + what has been verified + how to verify/criteria + recommendation + unlock actions for each branch) pr-sweep:awaiting-direction(direction) / pr-sweep:awaiting-caution(security·irreversible)

pr-sweep:needs-fix ≠ pr-sweep:awaiting-*: the former means "there is clear work for the agent to do", the latter means "waiting for a humaninput"——and the four tiers spell out which kind of input is being waited for (confirmation/direction/risk assessment/cautious approval).

Triggers look at state, not "who made the last comment" (unlocking the AI→AI freeze)

Root cause: using "was the last comment made by a human?" as the master switch for "should I act?" → when AI hands work to AI, it looks like "already handled, waiting on a person", so it freezes to death.This is exactly why 'comment back to the issue so the next round of issue-review picks it up' gets stuck: that is an AI comment, and issue-review thinks no one has intervened.

Solution: handoff relies on explicit state (label/checkbox), not on commenter identity. One handoff = setting one state(needs-fix / in-progress / needs-human); the receiving partytriggered by state, without asking "who just spoke". "The human replied" is just awaiting-*the unlock signal for the (truly waiting for human input) family,not the master switch for all work. Inference:don't bounce work back to the issue to swap in another agent for the relay— on the same PR, pr-sweep sets itself needs-fix → next round it continues fixing itself, all on the PR, zero cross-skill jumps, zero freezes. This is the correct interpretation of "all handled by PR-handling agents, there is essentially no difference":the closure is in pr-sweep, the PR is the unit of work, the issue is only provenance.

Step 6 — verification gate self-healing (if the gate is broken, fix the gate, don't drag every PR into it)

arc gate_mode=scripts: no CI on the PR,pre-merge the script is the only gate (ci/both repo overlay gh pr checks) (.claude/verify/). During review, if the gate is found to be caused bya fixable script/infrastructure repeatedly producing false positives (not some PR's fault, but some check-* being too strict / some test being flaky / some dependency not compiled):

  • do notmake every PR manually bypass it / stay red forever.
  • Diagnose the root cause(check-*.ts 's decision logic / some flaky test / missing native dependency build), open an independent verification-fix PR(going through this sweep's low-risk gate), treat "should the gate be this strict/this fragile" as an independently fixable engineering problem.
  • Example: some test is flaky due to WASM recompilation → fix the test or adjust the timeout;format noise → is already warn-only (check-format.ts)。
  • changing the gate's decision semantics (which check counts as blocking) = safety gate → belongs to the 🔴/needs-human-confirmation category,open a PR + escalate, don't merge it yourself. The escalation comment includes a "needs human confirmation block": the gate change that needs human confirmation + how to verify it (before/after pre-merge output comparison) + recommendation.

Rate limiting / orchestration / idempotency (mandatory for batches)

  1. GitHub "content creation" hard constraints: ≤500/h, ≤80/min. At most 1 verdict comment per PR; dedup close, 1 per twin + 1 close;gh on 403 secondary limit → back off and retry (≤3), still failing mark as RATE-LIMITED don't error out the whole batch (can be filled in via resume).
  2. Concurrency: ~10–14 × ~2–3min per agent ≈ ~250–300 POST/h, safely under the rate limit. Don't blindly crank it up to trigger an 80/min burst.
  3. Idempotency: re-running a sweep should not re-comment/re-close. Before posting a comment, check whether the PR already has this round's agent comment (same predicate; if same conclusion then --edit-last don't post a new one); skip already-closed ones; remove already-merged ones from candidates.
  4. Resumable:Interactive onlyUse Workflow orchestration for resumability (resumeFromRunId)。unattended routine does not use Workflow(see Step 3 iron rule) — rely on idempotency (item 3) to achieve "resumability": if it crashes/hits the rate limit, the next cron round naturally continues based on the disposition label + existing verdict comment, without duplicating or hanging.

Source governance: stop producing duplicate PRs (point back to issue-sweep)

Dedup close isa symptomatic fix。the root fixis at the PR producer side — multiple machines running issue-sweep each open a PR for the same issue (branch claude/<verb>-<N>-<slug>, same issue number, different slug → no collision → double open). Root fix (already written into issue-sweep "Step 4 — Discipline" anti-duplication clause):

  • deterministic branch names:claude/issue-<N>(or claude/issue-<N>-p<phase>),do not usethe model-invented verb/slug → two machines compute the same branch name, and the second push/gh pr create naturally collides.
  • Pre-creation claim check: before opening a PR, gh pr list --search check whether an open PR already points to #N; if so, SKIP.

Each sweep round can conveniently verify in passing: if newly appearing duplicate clusters still come from nondeterministic branch names → it means some machine's issue-sweep has not yet been updated to deterministic naming; note this in the summary.

Practical lessons learned (accumulated from this repo's first run; mandatory reading for autonomous machines)

See this repo's case-law appendix (arc:.claude/case-law/pr-sweep/first-run-lessons.md; new repos build their own) — the 7 pitfalls hit during the first run of pr-sweep : review data easily goes stale; verification failures must be peeled back layer by layer (format → flaky tests); the fix for a gating failure may already be sitting in another PR; after a large pull, a stale dist causes check-types false red; no required CI check (the merge gate is pre-merge PASS, not gh pr checks); after rebase, the base can still move; the gate only runs affected, not the full suite.

Key Principles

  1. Each PR is judged independently in a clean context, with centralized decision-making by the controller. Sonnet fans out reviews; Opus synthesizes cluster winners + the merge gate.
  2. The verification gate is a signal, not a judge (there is no longer CI on the PR). Diagnose root causes of failures, and block only for (a) defects in this PR; noise/flaky does not block merging; if the gate itself is broken/too strict, fix the script (Step 6).
  3. Deduplication: keep one, close the rest, with criteria + backlinks. Contradictory pairs must be checked against authoritative sources; if uncertain, keep both and wait for a human.
  4. Merges are assigned risk tiers, and the tier is recalculated before every merge attempt — no exemptions on any path. 🟢🟡 automatic (includingnon-breaking features— "it is a feature" is not a reason for escalation; judge risk by the content of the change: only security/breaking/undetermined direction are 🔴), 🔴 escalate (never auto-merge on any path, including after a needs-fix run turns green); patterns that have caused incidents are appended one by one to 🔴 according to the "ratchet of evolving standards", not by rolling back the whole category; UI-facing PRs must have screenshot evidence against the current HEAD (invalidated as soon as pushed);a human's change request ≠ merge approval— after responding, attach evidence and set awaiting-glance to await an explicit approval phrase; never force-merge past conflicts; closing is reversible but only close confirmed redundancy. Escalation comments to humans (🔴/security/awaiting-direction|caution) must include the pr-review "needs human confirmation block": what you need them to decide + what the agent has verified (to avoid redoing work) + how to verify (if it can be reduced to commands, give runnable steps + path:line + expected result; for security, list each security property; for judgment questions, give options + criteria + recommendation, and never fabricate commands) + the unlock action for each branch.Do not stop at "please confirm manually"。
  5. Artifacts land in the PR + git history, not in the conversation. One sweep round = several PRs reaching terminal states + traceable verdict/close/merge records.
  6. Cure the root cause at the source. Deduplication is a symptomatic fix; deterministic branches + claim check (issue-sweep) are what eradicate duplicates.
  7. Round awareness: do not redo work without new input (mandatory for scheduled routines). PRs already reviewed with no new commits and no new human comments are skipped by default; only start agents for PRs that have truly changed, and cheaply recheck and merge only PRs whose external blockers have been cleared.pr-sweep:awaiting-*(four tiers) / pr-sweep:blocked-deps and other disposition labels carry cross-round state.Never repost the same conclusion comment(see Step 1.5). "new input" is judged by "will the conclusion change", not "did the bytes change": mechanical regeneration of the PR's sha churn does not count as new input (the mechanical regeneration clause of Step 1.5); for a PR that has been escalated and is waiting on someone, if the conclusion stays the same after incremental re-review, silently refresh the sha and do not restate (pr-review Step 0.6)。Escalating once is enough—escalating again before the person replies is just noise.
  8. agent:hold = terminal-state freeze, not processing freeze. A person labels the PR with agent:hold means "don't merge/don't close without my feedback", not "ignore it": during hold, merge/close/removing the label is absolutely forbidden (hard-blocked by the merge gate in Step 5, even for the 🟢 tier; deduplication in Step 4 does not treat it as a twin/keeper), butnew human comments/new commits trigger review + response as usual—especially change requests a human leaves on a held PR, which are the highest-priority input and must be accepted (reply to the comment, fix on the PR branch as explicitly requested, re-verify after push, mark the verdict held). Only a human adds and only a human removes; the agent never auto-removes. Same name and same meaning as on the issue side (issue-review ★concurrency lock); on the PR sidedoes notintroduce agent:processing(concurrency deduplication relies on deterministic branching + claim check + disposition label).

★ sweep-trace instrumentation (L2 observability layer)

At the end of every AI comment this skill postsmustappend one line of sweep-trace HTML comment (invisible to humans, grep-able, reused by L1 eval as the golden baseline data source):

<!-- sweep-trace: {"ver":1,"pr":N,"gate":"<gate>","val":"<val>","sha":"<head-oid>","run":"<ISO8601>"} -->

Fields:

  • ver: schema version, currently 1
  • pr: corresponding PR number (numeric)
  • gate: decision gate name, from the controlled vocabulary:needsReview / disposition。 ★ mislabeling the gate makes deduplication silently fail—the next round looks up gate:"verdict"(pr-review end of the document), if a verdict comment is labeled needsReview(seen in production), that verdict cannot be found, and the next round treats it as "no verdict" and runs the full first-round process, posting another one.There is only one criterion: does this comment carry the conclusion of "how this PR should be handled"—yes → gate:"verdict"(posted by pr-review); it is merely sweep's own triage/labeling record → gate:"disposition". If unsure, label it as verdict (better to over-deduplicate than to miss deduplication).
  • sha: the PR HEAD this decision targets (40-character commit oid)—the machine key for cross-runner freshness determination (Step 1.5 sha priority rule; old traces without this field are considered stale)
  • val: decision value, from the corresponding controlled vocabulary:
    • needsReview gate:true / false
    • disposition gate:pr-sweep:needs-fix / pr-sweep:awaiting-glance / pr-sweep:awaiting-direction / pr-sweep:awaiting-judgment / pr-sweep:awaiting-caution / pr-sweep:blocked-deps / merged / closed(pr-sweep:awaiting-human exists only in historical traces, deprecated)
  • run: UTC time,new Date().toISOString() format

The trace is appended only at the end of verdict comments this skill actually posts; in dry-run mode no comment is posted, so no trace is appended.