Copilot pr followup
Internal routed strategy behind `dev-loop` for GitHub-first Copilot-owned PR follow-up: inspect the canonical PR state, request or re-request Copilot when appropriate, wait deterministically for new review activity, run narrow Pi fix/reply/resolve passes, verify gate evidence, and stop for explicit human approval before merge.From its SKILL.md
npx -y skills add mfittko/dev-loops --skill copilot-pr-followupAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 18 stars18 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
84.6 KB, as published. Nobody here has run it
Copilot PR Follow-up
Canonical owner for the internal copilot_pr_followup route behind the public dev-loop façade.
It is also the canonical internal owner of the shared post-PR mechanics used by this repo: PR discovery and interpretation, async watch behavior, fix / reply-resolve / re-request flow, gate sequencing, final approval, and merge-ready preconditions.
Route ownership
Use this skill whenever the public router lands on any PR-follow-up path that shares the same post-PR mechanics:
copilot_pr_followupexternal_pr_followupreviewer_fixerwait_watch
Route-specific companion docs:
- routed
issue_intakework is implemented through this skill plus Copilot Loop Operations and Issue Intake Procedure - routed
final_approvalwork is implemented through this skill's Human approval checkpoint section; Final Approval is now a thin redirect to that canonical section - the deterministic state-machine/operator guide lives in Copilot Loop Operations
Operational cookbook
All commands use the resolved skill scripts directory (see Skill asset path resolution below).
1. Detect current loop state
node <resolved-skill-scripts>/loop/detect-copilot-loop-state.mjs --repo <owner/name> --pr <number>
Emits JSON including { ok: true, state, allowedTransitions, nextAction, snapshot }. Follow nextAction.
2. One-step detect → request → emit watch params (preferred handoff contract)
node <resolved-skill-scripts>/loop/copilot-pr-handoff.mjs --repo <owner/name> --pr <number>
Use this helper output as source of truth for the normal routing seam. Interpret:
requestWatchContract.routingStatefor request-vs-watch posturerequestWatchContract.requestStatusand top-levelaction/nextActionwatchArgsonly whenaction: "watch"andrequestWatchContract.watchEntryConfirmed=truerequestWatchContract.stopStatefor explicit blocked/stop handling
3. Preferred async wait-boundary helper
node <resolved-skill-scripts>/loop/run-watch-cycle.mjs --repo <owner/name> --pr <number>
Persistent async watch/fix loop, not handoff-only behavior: watch → detect → if threads found, fix + reply + resolve → re-request → watch again → … → pre_approval_gate → merge. A single returned watch cycle is never completion by itself.
PERSISTENCE MODEL: Subagents do bounded implementation tasks and exit on external wait. The main session drives the loop and re-dispatches when continuation is feasible. If cycleDisposition is pending and terminal is false, the subagent exits on the wait boundary; the main session re-dispatches another watch boundary.
Under the Claude Code harness, run this loop inline in a single agent: the helper-owned wait tools (
dev-loops loop watch-cycle,gh run watch,dev-loops gate probe-copilot) block inline and return — whencycleDispositionispendingandterminalisfalse, run the next watch cycle yourself. Do not exit on the wait boundary to have a parent re-dispatch the loop; keep driving it in this agent until a terminal state or the watch budget expires. (Delegating a bounded fix to thefixeragent, per Step 6, is still fine — that is task delegation, not re-dispatching the watch loop.)
Max watch timeout: 30 minutes (from policy-constants.mjs COPILOT_REVIEW_WAIT_TIMEOUT_MS); expired budget + still waiting_for_copilot_review = hard stop. If the user explicitly asks for async handoff-only behavior, say that out loud and stop after the handoff boundary.
4. Low-level helpers
node <resolved-skill-scripts>/github/request-copilot-review.mjs --help
node <resolved-skill-scripts>/github/probe-copilot-review.mjs --help
node <resolved-skill-scripts>/github/list-review-threads.mjs --help
node <resolved-skill-scripts>/github/wait-pr-checks.mjs --help
node <resolved-skill-scripts>/loop/detect-copilot-loop-state.mjs --help
For detailed machine guarantees, judgment calls, pre-follow-up planning rules, PR description rules, and timeout defaults, use Copilot Loop Operations.
Required startup reads
Read the canonical entrypoint briefing first: Entrypoint Strategies. Then read only the contract docs needed for the current step:
- Agent Instructions (repo constitution)
- Public Dev Loop Contract (always)
- Retrospective Checkpoint Contract (when async state/resume applies)
- Active GitHub issue/PR
- Task-relevant source, tests, config, and CI
Route-dependent: see Copilot Loop Operations and Issue Intake Procedure when relevant. Verify all material claims against source, tests, configuration, and CI.
Skill asset path resolution
When this skill refers to helper paths such as scripts/... or docs/..., resolve them from the actual skill installation layout you are running, not from the active target repository checkout.
Use this rule:
- if the skill is installed as a normalized standalone copy, the required bundled contract docs live under the shared
../docs/directory next to the installed skill directories. <!-- rule: ASSET-PATH-INSTALLED-NO-ASSUME -->ASSET-PATH-INSTALLED-NO-ASSUME: Agents MUST NOT assume helper scripts are bundled unless that installed layout actually contains them. - if you are working in the
dev-loopssource repository, this skill file lives underskills/copilot-pr-followup/, so source-repo helper scripts live two levels up at../../scripts/, while required bundled contract docs live one level up at../docs/ - when in doubt, resolve helper paths relative to this skill file first, then verify the target file exists before running it
Required bundled runtime contract docs for installed copies of this skill:
- Public Dev Loop Contract
- Retrospective Checkpoint Contract
- Issue Intake Procedure
- Copilot Loop Operations
Read those bundled ../docs/ files from the installed skill layout instead of assuming the source repository checkout is present. If any required bundled contract doc is missing from the installed skill layout, treat that as a packaging/installer bug.
Stale-installed-CLI: prefer worktree-source verdict/ledger tooling (#1661)
A stale installed dev-loops CLI (e.g. rc.1) lacks the gate-evidence CI exclusion that newer source (rc.4+) has, so posting a pre_approval_gate verdict through the stale script blocks on WAITING_FOR_CI. To keep the canonical gate path green regardless of install state, resolve where the verdict/ledger tooling should run from FIRST via the deterministic helper (issue #1661):
node <resolved-skill-scripts>/loop/resolve-verdict-ledger-source.mjs --jq .preferredSource
- When
preferredSourceisworktree, run the verdict/ledger tooling (upsert-checkpoint-verdict.mjs,write-gate-findings-log.mjs,detect-checkpoint-evidence.mjs, and their gate helpers) from the worktree/sourcescripts/layout instead of the installed layout. - When
preferredSourceisinstalled, run them from the resolved skill-scripts layout (installed) as usual. - The helper compares the installed dev-loops CLI version against the current source/worktree version (bounded candidate detection); it never changes the gate-evidence CI-exclusion logic itself (
#1661non-goal) and fails soft to the canonical installed layout when a version cannot be read.
This is the canonical fix surface for #1661: prefer worktree-source scripts for verdict/ledger tooling when the installed CLI is stale, with no change to the gate path's own behavior.
Source files under review vs. helper-script paths
The rule above governs HELPER SCRIPT paths invoked as tooling (scripts/... you RUN). It does not govern SKILL/DOC SOURCE FILES you REVIEW as content. A gate reviewer citing a skill/doc file (e.g. skills/<name>/SKILL.md, skills/docs/..., docs/...) in a finding is reviewing the PR's content, not invoking tooling — and installed copies of those source files lag the PR under review. Reading an installed copy (.pi/skills/<name>/SKILL.md, ~/.pi/agent/...) produces false high-severity findings against text the PR already fixed (#1603).
When reviewing a PR that modifies skill/doc source, read those source files from the worktree checkout under review (relative paths from the worktree cwd named on the briefing prefix's worktree: line), never from the installed layouts above. Cross-check any line you plan to cite in a finding against git show HEAD:<path> (the worktree source at the reviewed head) before reporting — a citation absent from that source is a stale-installed-copy false positive. Helper SCRIPT paths invoked as tooling (not reviewed as content) still resolve from the installed skill layout per the rule above. The canonical GATE-EXEC-SOURCE-READ-WORKTREE rule and its briefing-prefix wiring live in Gate Review Sub-Loop Contract.
Authority and safety rules
Source code, tests, CI, and config are authoritative. Generated wiki is navigation aid only. See Confirmation Rules, Stop Conditions, and Merge Preconditions for authorization boundaries.
Structural quality
Apply Structural Quality standards from the deep review angle during implementation and follow-up fixes.
Step 5: PR discovery and interpretation
Treat the PR as the main working artifact once it exists.
Before invoking resolve-dev-loop-startup.mjs --pr <number> to continue an externally-created PR (one create-pr did not just self-assign), claim ownership: node scripts/github/edit-pr.mjs --repo <owner/name> --pr <number> --add-assignee @me (skip if already assigned to the viewer). The resolver's single-contributor ownership gate fails closed on a foreign or unclaimed assignee, or a linked issue assigned to another human — see Public Dev Loop Contract.
Inspect: PR body/title (must satisfy PR description contract), closing reference (operator-controlled; subagents must NOT modify), author, review summaries, unresolved comments, latest commits, CI results.
At the issue-assignment seam, use detect-initial-copilot-pr-state.mjs and keep waiting when waiting_for_initial_copilot_implementation.
COPILOT-FOLLOWUP-REQUEST-HELPER-ONLY: Copilot review requests MUST go through request-copilot-review.mjs (see Operational cookbook); the agent MUST NOT request Copilot by posting literal /copilot or /copilot re-review PR comments, and MUST NOT rely solely on gh pr view --json reviewRequests to confirm a request. After draft→ready or fix push, explicitly decide whether another pass is desired; if yes, ensure green/credibly green posture first.
COPILOT-FOLLOWUP-REQUEST-BRANCHING: The agent MUST branch on the request-copilot-review.mjs machine-readable result exactly as follows, and MUST NOT treat an attempted request as equivalent to a confirmed request:
requested: if another Copilot pass is actually desired, immediately re-baseline withdetect-copilot-loop-state.mjsand follow itsnextAction(enter persistent wait only throughdev-loops loop watch-cycleorgh run watch)already-requested: apply the same detector-first rebasing and wait branching asrequestedsuppressed_same_head_clean: report clean-converged state and stop unless--force-rerequest-reviewbypass is intentionally authorizedsuppressed_post_convergence_docs_only: at the round cap, the post-convergence head bump was a provable pure doc/prose delta since the last Copilot-reviewed head, so no fresh blocking round was forced (the prior converged Copilot review still stands). Do NOT enter a Copilot wait seam; treat the PR as converged and proceed topre_approval_gate. Any code/test/config/CI or unclassifiable delta re-opens the round as normalunavailable: report the limitation and stopblocked_by_copilot_comment: no request was placed. Delete the violatingviolationCommentIds(or confirm they only quote the rule inside a code span/fenced block, which does not arm the guard) and re-run; do NOT treat this as a placed request and do NOT enter a wait seam- non-zero / unexpected failure: stop and report error
Branch on status, never on ok/exit-code truthiness alone: ok: true means the helper ran without error, not that a review was placed. Under --silent, the exit code is 0 only for requested; every other status (including blocked_by_copilot_comment) exits non-zero.
Re-attachment guard (check for existing loop state first)
Before entering issue-intake normalization or asking "what should we do" for a PR that already has an outer-loop checkpoint, check whether the checkpoint implies an auto-resume:
- Read the existing outer-loop checkpoint from
tmp/copilot-loop/<owner>/<repo>/pr-<n>/outer-loop-state.json. Do not runouter-loop.mjsfor this guard — it always rewrites the checkpoint (includingtimestampand potentially incrementingwaitCycles). Read the on-disk artifact without mutating it. - If
outerActioniscontinue_wait:- The loop was waiting; resume it from the checkpoint.
<!-- pi-only -->Under Pi the subagent exits and the main session re-dispatches a fresh
dev-loopasync subagent that resumes from the checkpoint.<!-- /pi-only --> Under the Claude Code harness, continue the wait inline (run the next watch cycle yourself).
- The loop was waiting; resume it from the checkpoint.
<!-- pi-only -->Under Pi the subagent exits and the main session re-dispatches a fresh
- If
outerActionisreenter_copilot_loop:- The copilot inner loop needs action. Run
copilot-pr-handoff.mjsto determine the exact next step and proceed.
- The copilot inner loop needs action. Run
- If
outerActionisreenter_reviewer_loop:- The reviewer inner loop needs action. Enter the reviewer-loop path.
- If
outerActionisstop:- Report the
reasonfield and ask for direction.
- Report the
- If no checkpoint exists or
outerActionisdone:- Continue with normal step sequencing.
Do not skip this guard when resuming work on the same PR<!-- pi-only --> (under Pi, between async subagent runs)<!-- /pi-only -->. The outer-loop checkpoint is the canonical re-attachment artifact.
Step 6: Async watch behavior
Start every wait seam with a detector refresh: detect-copilot-loop-state.mjs --repo <owner/name> --pr <number>.
COPILOT-FOLLOWUP-WAIT-TOOLS: The agent MUST wait only through allowed deterministic tools: detect-copilot-loop-state.mjs (one-shot), dev-loops loop watch-cycle (persistent), copilot-pr-handoff.mjs --watch-status (refresh after timeout/idle), dev-loops loop watch-ci --repo <owner/name> --pr <number> (provider-agnostic CI: CircleCI / Actions / external commit-status), scripts/github/wait-pr-checks.mjs --repo <owner/name> --pr <number> (same provider-agnostic CI wait, with a direct 0/1/2 process-exit-code contract for shell/scripted callers instead of a JSON status field), gh run watch <run-id> --repo <owner/name> (Actions-only fallback when the run id is known); otherwise exit and resume later from a fresh detector call.
COPILOT-FOLLOWUP-REREQUEST-AFTER-PUSH:
After ANY push that advances the head of a PR Copilot has already reviewed — a gate fix, a
Copilot-thread fix, a rebase, a docs touch-up — the agent MUST run
request-copilot-review.mjs for the new head and branch on its machine-readable result
(COPILOT-FOLLOWUP-REQUEST-BRANCHING) BEFORE entering any watch. Copilot does not re-review
a new head on its own, so a watch entered without that explicit request waits on a review
that was never requested until the budget expires. The green-posture precondition
(COPILOT-FOLLOWUP-REREQUEST-GREEN-GATE) and the round cap
(COPILOT-FOLLOWUP-ROUND-CAP) still decide WHETHER the request is made; when either blocks
it, or the result is a suppression, stop and report instead of entering a watch.
Practical rules: do not poll manually. waiting_for_copilot_review → run-watch-cycle.mjs or report-and-resume. waiting_for_ci with pending/none CI → dev-loops loop watch-ci --repo <owner/name> --pr <number> (provider-agnostic; covers CircleCI / Actions / external commit-status) or report-and-resume; gh run watch <run-id> is an Actions-only fallback. dev-loops loop watch-cycle also auto-routes a waiting_for_ci boundary to this CI watcher. Bounded CI exception: zero current-head suites + previous-head green + local npm run verify passed → rerun detector with --local-validation-head-sha for crediblyGreen promotion. ciStatus=failure → stop/fix, never wait.
Preferred approach:
- route decisions through
copilot-pr-handoff.mjsoutput; enter watcher only onaction: "watch"withwatchEntryConfirmed=true; preferdev-loops loop watch-cyclefor deterministic handoff → watch changed→ re-enter Step 7 fix/reply-resolve/validate immediately; do not stop after one watch cycletimeout/idle→ re-runcopilot-pr-handoff.mjs --watch-status <status>once to refresh state; if stillwaiting_for_copilot_reviewafter 30-minute watch budget exhausted, hard stop withwatch timeout — PR #<number> needs manual attention- zero-timeout
idleprobes are for explicit one-shot status/reattach checks only; they are not the normal async wait mechanism - after a successful fix / reply-resolve / re-request cycle, returning to
waiting_for_copilot_reviewis a persistence boundary: resume the watcher instead of reporting completion
- if a child async run exits and the refreshed state remains non-terminal (for example
waiting_for_copilot_review) before merge and without a hard stop, treat that as early exit and the main session re-dispatches the same-PR follow-up path when feasible (the subagent exits on external wait)
- dispatch fix findings to the
fixeragent; do not run inline fix passes in-watcher - do not report completion while unresolved Copilot feedback remains
- once a watch/probe settles, do not parse its raw output: re-read via
detect-copilot-loop-state.mjs --repo <owner/name> --pr <number>, and read the unresolved working set viacapture-review-threads.mjs --repo <owner/name> --pr <number> --unresolved --bodies(joined bodies; the canonical re-entry read) orlist-review-threads.mjs --repo <owner/name> --pr <number> --unresolved-only(thread/comment ids for reply-resolve) — inline interpreters are barred byOPS-NO-INLINE-INTERPRETERin Copilot loop operations
Canonical async dispatch wording
Every async dev-loop dispatch task body must include this clause verbatim so fresh-context subagents inherit the gate requirement:
Before reporting merge-ready or stopping at the human approval checkpoint, you must complete the pre_approval_gate procedure and verify that a visible clean checkpoint verdict comment exists on the PR for the current head SHA. Do not stop or report completion without this evidence.
Key rules:
- helper-owned sleep inside
dev-loops loop watch-cycle,dev-loops gate probe-copilot, ordev-loops loop watch-initialis allowed - agent-authored shell polling is forbidden: do not use
nohup, detached shell jobs,tmux,screen, or ad hocfor i in $(seq ...),while true,until ...; do sleep ...; done, orsleep-retry bash loops - do not wrap repeated
gh pr view,gh pr checks,gh api, ordetect-copilot-loop-state.mjscalls inside shell polling loops - do not bypass session-based async notifications with detached shell automation
- if the designated async follow-up skill is not appropriate or available, stop and report rather than improvising a shell watcher
- the async-start contract is enforced in code:
outer-loop.mjsfails closed without a visible async run id whenworkflow.asyncStartMode: required(relaxed automatically under the Claude Code harness — see #830)
Async delegation guard rules (#524)
See Guard rules in the public dev-loop skill. Those rules are authoritative and apply to all async subagent dispatch in the PR-followup pipeline. The dev-loop skill is the single source of truth; this section exists only to ensure the rules are visible when this skill is loaded standalone.
Step 7: Pi review/fix follow-up loop
This step covers four responsibilities: the draft gate right before gh pr ready, the narrower post-review follow-up loop once unresolved feedback exists, the pre-approval gate before calling the PR merge-ready, and the final approval / merge boundary.
Follow-up loop when unresolved feedback exists
When unresolved feedback exists, use a narrow follow-up loop:
A gate-authored medium review thread still inside its gate's round window
(GATE-EXEC-THREAD-DISPOSITION in Gate Review Sub-Loop Contract)
is unresolved feedback exactly like an external Copilot comment, and closes through this
same fix → reply-with-resolving-commit → resolve path, not a separate one. A gate-authored
question thread is answered (never deferred) through the same loop, and an unanswered
question is likewise unresolved feedback.
- inspect unresolved comments/threads and failing checks
- the canonical loop re-entry read for the working set (all currently-unresolved thread bodies, e.g. after a fix push, a resolve pass, or a crash) is
scripts/github/capture-review-threads.mjs --repo <owner/name> --pr <number> --unresolved --bodies— it emits only unresolved threads as{ threadId, path, line, isOutdated, bodies }with the comment bodies already joined, so no capture-then-parse step (and no inline interpreter) is ever needed to read them - enumerate unresolved threads (with the thread/comment ids the reply-resolve helpers below need) via
scripts/github/list-review-threads.mjs --repo <owner/name> --pr <number> --unresolved-onlyrather than a hand-writtengh api graphqlquery
- the canonical loop re-entry read for the working set (all currently-unresolved thread bodies, e.g. after a fix push, a resolve pass, or a crash) is
- before the first local file write in each fixer pass on a Copilot-assigned PR, run
node <resolved-skill-scripts>/loop/pre-write-remote-freshness-guard.mjs --branch <headRefName>as a required fail-closed guard- source
<headRefName>from authoritative PR state (headRefName), not from a local branch guess - if the guard exits non-zero (
remote_ahead), stop writing locally, reconcile to the refreshed remote head, then restart the fixer pass
- source
- classify findings:
- high: blocks gate; always fixed
- medium: blocks gate when
blockCleanOnFindingSeveritiesincludes it; a LOCATABLE finding is also fixed through round 3 of the gate's chain even when not blocking (then deferred), while a NON-LOCATABLE one is deferred immediately (GATE-EXEC-BLOCKING-ONLY-FIXin Gate Review Sub-Loop Contract) - low / non-blocking / disagree (defer is the fixer's disposition for these, not a severity)
- question: never deferred; answer it (promoting to a defect severity if the answer reveals one, or escalating to the author when unanswerable) — an unanswered question blocks gate-close exactly like an open defect (unresolved feedback, same as a high finding), so it is never a thread to sweep past unanswered
- nit: cosmetic, non-defect; deferred immediately, no fixer action on the severity axis (judge-acted nits excepted)
- apply only the accepted narrow fixes
- run the smallest validation that honestly proves the fix
- if files changed, run
node <resolved-skill-scripts>/loop/pre-commit-branch-guard.mjs --expected-branch <headRefName>immediately before everygit add && git commitsequence as a required fail-closed guard- source
<headRefName>from authoritative PR state (headRefName), not from a local branch guess - if the guard exits non-zero (
branch_mismatch), stop and realign to the expected branch before staging or committing - this guard reads the CURRENT branch, which is itself cwd-relative;
WORKTREE-DEFAULT-USEin worktree-guidance.md additionally mandates addressing the tree explicitly (git -C <absolute-worktree-path> …) for theadd/commit/pushthemselves
- source
- if files changed, push the resolving commit before any thread reply claims the fix is present
-
<!-- rule: COPILOT-FOLLOWUP-REPLY-RESOLVE-HELPER --> `COPILOT-FOLLOWUP-REPLY-RESOLVE-HELPER`: When a comment or thread is actually addressed, the agent MUST reply on GitHub with a short resolution note that references the resolving commit SHA or commit URL when applicable, using the deterministic helpers below rather than ad hoc thread mutations:
- each thread's resolving reply states the specific change (file or behavior) that fixed THAT thread, with the resolving commit; a shared body across threads is permitted only when one shared root cause genuinely fixed them all, and the reply must name that shared cause
- for one thread, must use the deterministic helper
reply-resolve-review-thread.mjsfrom the resolved skill scripts directory - for multiple matching unresolved threads, use
reply-resolve-review-threads.mjs --message-map <path>(a JSON file mapping threadId to its distinct resolution body) instead of ad hoc inlinegh api/gh api graphqlmutations;--messagealone is only for the shared-root-cause case above - when using the single-thread helper, pair
--comment-idand--thread-idfrom the same fresh PR thread snapshot rather than mixing ids across review rounds - use a body file under
tmp/rather than inline shell text for the single-thread reply body (via--messageor stdin); the batch helper takes its per-thread bodies from--message-map <path>— a JSON file, never stdin — so there is no separate stdin body file to prefer there - when the intent is GitHub linkability, keep commit SHAs and issue/PR refs as plain text (for example 3ee82fc and owner/repo#70) and do not wrap them in backticks
- keep backticks for actual code/path/CLI literals only
- if either helper was newly added or recently changed, smoke-check it against one real thread before assuming the rest of the loop can rely on it
-
<!-- rule: COPILOT-FOLLOWUP-VERIFY-BEFORE-RESOLVE --> `COPILOT-FOLLOWUP-VERIFY-BEFORE-RESOLVE`: before resolving an addressed review thread, run a post-fix verification checkpoint
- confirm the GitHub reply actually exists on the intended thread/comment, not only in local notes or helper stdout
- confirm the pushed current-head diff genuinely addresses the reviewer concern on the flagged lines or pattern; if the concern is only partially addressed, leave the thread open and explain what remains
- refresh the API-backed thread snapshot via
dev-loops gate capture-threadsand use that refreshed data — including the unresolved thread count — for follow-up decisions rather than prose assumptions - if any verification check fails, do not resolve the thread; leave it open, add a short explanation when needed, and re-enter the fix/reply loop
-
<!-- rule: COPILOT-FOLLOWUP-RESOLVE-AFTER-REPLY --> `COPILOT-FOLLOWUP-RESOLVE-AFTER-REPLY`: resolve the addressed review thread only after the reply is attached successfully, the verification checkpoint passes, and the concern is genuinely addressed
- do not stop at a local fix if GitHub-side reply/resolve is authorized
- after completing reply/resolve for a pass, verify zero unresolved threads remain via
dev-loops gate capture-threadsbefore proceeding- if the refreshed snapshot reports unresolved threads, re-enter the reply/resolve loop for the missed threads
-
<!-- rule: COPILOT-FOLLOWUP-ROUND-CAP --> `COPILOT-FOLLOWUP-ROUND-CAP`: The agent MUST decide whether another Copilot pass is desired, applying the round-cap/signal-gating rules below, only after GitHub-side reply/resolve work is done for the addressed threads and the refreshed thread snapshot proves zero unresolved threads remain
- resolve the review-round cap from config via
resolveRefinementConfig(config, "maxCopilotRounds")from@dev-loops/core/config; default config shipsmaxCopilotRounds: 5. For a light-dispatched PR, resolveresolveEffectiveCopilotRoundCap(config, { lightweight: true })instead —min(localImplementation.lightMode.maxCopilotRounds ?? 1, maxCopilotRounds)(default lightweight cap: 1) — see the Artifact Authority Contract lightweight section (issue #1210) - for a light-dispatched PR, pass
--lightweighton every round-cap-consuming helper invocation —detect-copilot-loop-state.mjs,copilot-pr-handoff.mjs,detect-pr-gate-coordination-state.mjs,request-copilot-review.mjs, andupsert-checkpoint-verdict.mjs— otherwise those tools resolve the full-PR cap and the composed lightweight cap is never enforced - light-dispatched is a gate-dispatch fact, not a startup fact: a PR is light-dispatched only when
resolveGateDispatchModeresolvesinlinefor it (scope under the light-mode threshold, nogate:fulllabel). A PR started via--lightweight(PR-body-as-spec, including issue-less PR-first underlocalImplementation.issueless) whose scope is over the threshold is NOT light-dispatched: do not pass--lightweightto the round-cap-consuming helpers for it — it takes the full fan-out and the full-PR round cap - Opt out entirely:
maxCopilotRounds: 0disables the external Copilot review gate for the repo — the loop runsdraft_gate → pre_approval_gatewith the local harness only, never requesting or waiting on Copilot. Use this when the repo has no Copilot reviewer configured or prefers local-harness-only review. - use the completed Copilot review-round count from
detect-copilot-loop-state.mjs/copilot-pr-handoff.mjsas the current PR's review-round count - if completed review rounds have reached the resolved round cap above, do not re-request Copilot review within that concluded cycle
- if the loop already converged and then significant post-convergence changes land on a newer head (new/changed product or test logic, not doc/message/comment-only edits), treat that as a NEW cycle and re-request Copilot review when regular rounds are already > 0 (the prior cycle's cap does not suppress this new-cycle request)
- the inverse — a pure doc/prose post-convergence head bump must NOT force a fresh blocking Copilot round — is now enforced in code: at the round cap,
request-copilot-review.mjsconsultsresolveConvergenceCarryForward(@dev-loops/core/loop/gate-carry-forward) on the delta since the last Copilot-reviewed head and returnssuppressed_post_convergence_docs_onlywhen that delta is a provable pure-doc bump, even under--force-rerequest-review. The guard is fail-closed: any code/test/config/CI or unclassifiable file, a rename/copy, a non-linear (rebased/amended) advance, or an unavailable compare re-opens the round exactly as before - below the cap, that same carry-forward proof is NOT applied automatically — a below-cap head-advanced bump is normally expected to get a real Copilot pass. The one exception is an explicit, human-only operator withdrawal (issue 1441): see the "Head-advanced sibling case" in Merge Preconditions for the escape hatch and the marker it records; never invoke it as an automated substitute for a real re-request
- when the round limit is reached and the refreshed thread snapshot proves zero unresolved threads and current-head CI is green (a real
success), treat that clean state as eligible forpre_approval_gatefallback instead of deadlocking on another Copilot rerequest.crediblyGreendoes NOT qualify here: at the pre-approval/final boundary it fails closed toBLOCKED_NEEDS_USER_DECISION(unconfirmed CI, #552), so the fallback waits for CI to settle to a real green - when using that fallback, add a short round-exhaustion note to the visible
pre_approval_gategate evidence so the PR records why no further Copilot rerequest occurred - if the round cap is reached before the PR is thread-clean or before CI is a real green
success, reply-resolve any remaining intentionally deferred threads with a shortdeferred to follow-upnote, then stop and report that the Copilot round limit was reached - Signal-gated re-request suppression: the
detect-copilot-loop-state.mjsstate machine classifies review-thread comments by signal level (High/Mid/Low). High-signal (bugs, security, contract violations) always re-requests; Low-signal (cosmetic nits) never re-requests. When low-signal detection is enabled and thresholds are met, the machine returns a low-signal-converged terminal state routing topre_approval_gatewithout further re-requests. See Copilot Loop Operations for full signal-level semantics. - if that local validation is still known red, continue remediation instead of re-requesting Copilot
- after a fix push advances the PR head SHA, re-run
detect-copilot-loop-state.mjsfor the new head and apply the Copilot CI Status Contract. Previous-head CI is stale; only current-head results unblock CI-dependent steps. if GitHub CI/checks for the updated head are known red for a fixable issue, continue remediation instead of re-requesting Copilot. <!-- rule: COPILOT-FOLLOWUP-REREQUEST-GREEN-GATE -->COPILOT-FOLLOWUP-REREQUEST-GREEN-GATE: only once the updated head is green or credibly green, explicitly re-request Copilot review for the new head. Always userequest-copilot-review.mjs— nevergh api POST repos/.../requested_reviewersdirectly. - only enter a wait/watch loop if the request result is confirmed as
requestedoralready-requested - for
requested/already-requested, immediately re-baseline withdetect-copilot-loop-state.mjs; if the returned state iswaiting_for_copilot_review, usedev-loops loop watch-cycleor stop/resume later, and if the returned state iswaiting_for_ci, usedev-loops loop watch-ci(provider-agnostic CI wait;gh run watchis an Actions-only fallback) or stop/resume later after that single detector refresh - if the request result is
unavailable, report that limitation and stop unless the user explicitly wants passive waiting anyway - if the request command fails unexpectedly, stop and report the error rather than sleeping and hoping for a new review
- resolve the review-round cap from config via
- after a confirmed re-requested Copilot pass, refresh PR thread state again before reporting completion; if fresh Copilot threads exist, return to this follow-up loop rather than stopping at
review requested - after a confirmed re-request returns the PR to
waiting_for_copilot_review, jump back to Step 6 and keep the same session alive; do not exit onreview requestedalone - if scope has broadened, stop and ask before continuing
Do not treat fix applied locally as the end of the loop when the workflow also requires GitHub-side reviewer follow-up. If comment/reply authorization is withheld, report explicitly that the code may be fixed while the PR conversation state remains unresolved.
Mandatory gate-comment command contract
<!-- rule: COPILOT-FOLLOWUP-GATE-COMMENT-CANONICAL -->COPILOT-FOLLOWUP-GATE-COMMENT-CANONICAL: For every draft_gate or pre_approval_gate verdict, agents MUST run upsert-checkpoint-verdict.mjs and MUST NOT use gh pr comment, gh api, or gh pr review for gate verdicts. That helper posts the round's single visible surface — one PR review of type COMMENT carrying the verdict fields and, with --findings-ledger, the round's findings (GATE-COMMENT-SINGLE-SURFACE).
Per COPILOT-FOLLOWUP-GATE-COMMENT-CANONICAL above, run:
For a gate that ran via the fan-out/fan-in sub-loop, pass the structured per-angle review results via --findings-json (NOT the wall-of-text --findings-summary). That JSON file, and the severityCounts substituted below, come from the SAME single sanctioned fan-in CLI call — dev-loops gate consolidate-fanin --findings-dir <dir> --head-sha <headSha> --gate <gate> --out <path> --ledger-out <ledger-path> --jq '.severityCounts' — --head-sha per GATE-EXEC-ARTIFACT-HEAD-STAMP (see the Fan-in step below) — which consolidates the per-angle artifacts the fan-out reviewers wrote (tmp/gate-reviews/<repo-slug>/pr-<N>/<gate>-<headSha>/<angle>.json) into exactly the nested shape --findings-json accepts; never hand-author or mutate it with an inline interpreter, and never invoke the CLI a second time to re-extract a different shape it already returned. The helper renders a readable per-angle breakdown and derives the single-line **Findings summary:** digest itself:
node <resolved-skill-scripts>/github/upsert-checkpoint-verdict.mjs \
--repo <owner/name> \
--pr <number> \
--gate <draft_gate|pre_approval_gate> \
--head-sha <current_head_sha> \
--verdict <clean|findings_present|blocked> \
--findings-json <path-to-per-angle-results.json> \
--findings-ledger <findings-log-path> \
--next-action "<next action>" --findings-severity-counts '<consolidate-fanin severityCounts>' \
--execution-mode fanout_fanin
--findings-ledger is the durable findings log write-gate-findings-log.mjs reported as its output path in Phase 3 (tmp/gate-findings/<owner-name>/pr-<N>/<gate>-<headSha>.json) — NOT the flat consolidate-fanin --ledger-out array, which the helper rejects because it carries no repo/pr/gate/headSha identity. Pass it on every gate round: it turns the posted review into the round's single finding surface (in-diff findings as its inline comments, everything else body-filed, the per-angle breakdown reduced to counts). Omitting it posts a bare verdict body with the full per-angle breakdown and no finding threads at all.
Substitute <consolidate-fanin severityCounts> with the fan-in CLI's own severityCounts field (its output's true, unbudgeted totals) — never a literal all-zero placeholder. buildStructuredFindingsDigest only lets this value RAISE the posted **Findings summary:** total above --findings-json's own count, never lower it, but a placeholder that always sums to 0 defeats the point of passing it at all and, more importantly, must never be typed in by hand for a findings_present/blocked round.
--findings-json accepts the per-angle review-results array ([{ angle, verdict?, findings:[{severity, summary, file?, line?, disposition?}] }], the primary shape that feeds consolidateFanin); it also accepts the flat per-finding array that consolidateFanin/toFindingsLogShape produce ([{ severity, summary, angle?, ... }]), grouping it by each finding's .angle. A non-empty input matching neither shape is rejected rather than silently rendering all-clean. If the structured results are not available (an inline run), fall back to --findings-summary "<summary>". A fanout_fanin consolidate-fanin round withheld to tier 4 has neither shape available: --out was never written (or was removed), and the --ledger-out flat file is unbudgeted and MUST NOT be substituted for it — passing that file to --findings-json can itself exceed the render budget. Post that round with --findings-summary "<summary>" PLUS the mandatory --findings-ledger <findings-log-path> (the same durable log Phase 3 wrote via write-gate-findings-log.mjs --provenance) — never --findings-summary alone: when the gate configures mandatory angles, upsert-checkpoint-verdict.mjs proves coverage from that ledger's recorded provenance and refuses the post (naming the missing artifact/angle) when both --findings-json and --findings-ledger are omitted (see Phase 3 — Consolidation, which owns the full artifact/coverage rule).
For a gate that ran inline (single agent, not via the sub-loop):
node <resolved-skill-scripts>/github/upsert-checkpoint-verdict.mjs \
--repo <owner/name> \
--pr <number> \
--gate <draft_gate|pre_approval_gate> \
--head-sha <current_head_sha> \
--verdict <clean|findings_present|blocked> \
--findings-summary "<summary>" \
--findings-ledger <findings-log-path> \
--next-action "<next action>" --findings-severity-counts '<true severity counts tallied for this round>' \
--execution-mode inline_single_agent --inline-reason "<why>"
When passing --findings-severity-counts for an inline round, substitute the counts you actually tallied, never a copy-pasted all-zero literal — an inline run has no fan-in to source a placeholder from. See --help for when it is required.
--execution-mode <fanout_fanin|inline_single_agent> records how the gate inspection ran (default inline_single_agent). When the gate did not run via the fan-out/fan-in sub-loop (Gate Review Sub-Loop Contract), you MUST pass --execution-mode inline_single_agent --inline-reason "<why>" — silent inline runs are no longer allowed: inline mode requires a non-empty --inline-reason and emits a stderr warning. Because inline is the default mode, a bare call with neither flag now fails with an argument error, so always pass --execution-mode explicitly (and --inline-reason for inline). The recorded executionMode is surfaced by detect-checkpoint-evidence.mjs and gated by gates.requireFanoutEvidence.
--force --force-reason on upsert-checkpoint-verdict.mjs is a narrow operator-authorized CI override for the helper itself, not the default gate path. Use it only when the helper refuses gate entry solely because the current head is blocked_needs_user_decision with ciStatus="failure", and only after the user explicitly authorizes ignoring that current-head CI failure for this one gate-comment upsert. It does not bypass stale-head checks, unresolved-thread / unsettled-review refusal, non-draft draft_gate refusal, merge conflicts, or other legality checks.
Gate fan-out/fan-in procedure (agent-orchestrated)
Both gates run this same checkpoint review chain, owned end-to-end by Gate Review Sub-Loop Contract (GATE-EXEC-BUILD-ONCE-SEED, GATE-EXEC-BRIEFING-PREFIX, GATE-EXEC-SEPARATE-CHAINS, GATE-EXEC-POST-BEFORE-FIX, GATE-EXEC-REGATE-MANDATORY, GATE-EXEC-ANGLE-CARRY-FORWARD, GATE-EXEC-LIGHT-ESCALATION); this section owns only this skill's dispatch of that chain. It is an agent-orchestrated skill procedure — a node script cannot spawn the per-angle reviewers, so the conductor agent drives the fan-out and uses the pure @dev-loops/core/loop/gate-fanin helpers only for consolidation, batching, and ledger mapping.
- Context (Phase 1): before building the gate-context artifact, run
node <resolved-skill-scripts>/loop/run-gate-validation.mjs --repo <owner/name> --pr <number> --gate <gate> --head-sha <current_head_sha>ONCE for this round (GATE-EXEC-VALIDATION-ARTIFACT); reviewers consume its recorded result instead of each re-running the validation suites themselves. Then build/read the gate-context artifact viascripts/github/write-gate-context.mjs(buildGateContextresolves the angle set throughresolveGateAnglesDynamic; mandatory angles always survive), passing--validation-results <path>to that same artifact path so the briefing prefix points every reviewer at it, and--full-labelwhen the PR carries thegate:fulllabel (so tier resolution reportsgate_full_labeland the untriered angle set is used). Consume the resultingtmp/gate-context/<repo-slug>/pr-<N>/<gate>-<headSha>.jsonartifact: the FULL diff atscope.diffPathplus the top-level adjacent-code bundle (adjacentCode) are the build-once seed every reviewer uses verbatim — seeGATE-EXEC-BUILD-ONCE-SEEDfor the bundle contract; do not re-derive them per reviewer. The spec-of-record the briefing prefix carries — the PR body, every closing issue reference, and each of those issues' bodies — is resolved by the CLI itself (seescope.acceptanceCriteriaSourceunderGATE-EXEC-BUILD-ONCE-SEED), so the conductor does not thread--pr-body/--issue-body/--acceptance-criteriathrough; pass them only to override the live values, and expect a fail-closed error (no artifact) rather than a bundle that claims the PR has no description when GitHub cannot be read. - Carry-forward (Phase 1.2): whenever this gate already recorded a findings-log at an earlier head, resolve which angles still need a fresh reviewer before dispatching any:
node <resolved-skill-scripts>/github/resolve-angle-carry-forward.mjs --repo <owner/name> --pr <number> --gate <gate> --prev-head <prior_head_sha> --head-sha <current_head_sha>, run from the worktree checked out at the current head. Pass both SHAs in FULL 40-character form — the log filename the CLI resolves is keyed by the full SHA, so an abbreviated--prev-headfinds no log and refuses forever, silently turning carry-forward off.--prev-headMUST be this gate's most recently recorded head, never an older one that happens to beclean: reaching past an interveningfindings_presentround would carry an angle that round found problems in, which is exactly what the refusal-on-non-clean layer exists to prevent. In the single continuous conductor loop this procedure describes, that value is never guessed or discovered by scanningtmp/gate-findings/: it is the exact head SHA this SAME conductor recorded a findings-log for on the immediately preceding round of this chain (the head Phase 3 last wrote, or Phase 5's "fixed head" one iteration back) — carried in the conductor's own run state, not looked up. If the most recent log is not clean, the CLI refuses — take that refusal, do not go looking for an older log. The plan's universe is the PRIOR head's angle set, which is not necessarily this head's: subtract, never substitute. Phase 2 dispatches every angle Phase 1 resolved at the current head, minus the plan'scarriedangles — so an angle the current head resolved for the first time is reviewed even though the plan mentions it in neither list. Eachcarriedentry keeps its prior clean verdict and is recorded in Phase 3's provenance with that entry'scarriedFromHeadplus the prior reviewer identity it carries — never a fabricated fresh review. Skip this step on a gate's first round (no prior head). The rule, its fail-closed defaults (every refusal condition and per-angle must-re-run reason), and the provenance shape are owned byGATE-EXEC-ANGLE-CARRY-FORWARDin Gate Review Sub-Loop Contract — not restated here. On success the CLI emits{ carried, mustRerun };mustRerunis informational only — Phase 2 dispatches by subtractingcarriedfrom the current head's resolved angle set, never by consultingmustRerun. Operationally: on ANY non-zero exit (a stderr{"ok":false,...}refusal, or a bare parse/usage error), fan out every resolved angle exactly as if no prior head existed; never treat exit 1 as "nothing to re-run". - Cache primer (Phase 1.5, MANDATORY): every fan-out primes the shared prefix (
GATE-EXEC-PRIME). Default form = one-reviewer-as-primer (zero extra cost): dispatch one reviewer first, release the rest once its prefix write has landed (on its first streamed token if the harness streams, else await its completion — never off an unobservable "start") so they cache-read that write — turning the cold-cache race into 1-write-N-reads. (A dedicated angle-less primer is an alternative when preferred.) No verification pass (agent harnesses own caching; nothing to read or pin). - Fan-out (Phase 2): resolve this round's dispatch units by calling
resolveFanoutGroups(config, gate, angles, { fullLabel })(@dev-loops/core/config) over the current head's resolved angle set minus the plan'scarriedangles (the Phase 1.2 subtraction — nevermustRerun);fullLabelis whether the PR carriesgate:full(Phase 1's--full-labelinput). In grouped mode (gates.fanout.modeunset orgrouped, the shipped default), configuredgates.fanout.groupsare matched first (unchanged), then the leftover ungrouped angles are auto-chunked byresolveFanoutGroupsinto dispatch units of ≤gates.fanout.maxAnglesPerGroup(N, default 3) instead of singletons — an angle in no configured group joins the leftover pool.mode: per-anglebypasses the configured-groups table and emits one singleton unit per angle; it matchesmaxAnglesPerGroup: 1in dispatch unit size ONLY when no configured multi-angle group matches a resolved angle (otherwise per-angle bypasses configured groups while N=1 honors them — matched first, never split — so the two diverge when a configured multi-angle group matches; see the divergence test inpackages/core/test/config.test.mjs).gate:fullno longer restores per-angle dispatch (ADR 0048 supersedes 0047): it forces the full angle set upstream (resolveGateTier→gate_full_label) and dispatches GROUPED — configured groups first, then the leftover pool auto-chunked into units of ≤ N. The conductor dispatches wave-by-wave at mostgates.fanout.maxConcurrent(M, default 4) dispatch units concurrently per wave, using the wave plan emitted bywrite-gate-context.mjs(artifact.fanout.wavePlan, viascheduleFanoutWavesreusingscheduleParallelWaves); spawn one scopedreviewagent per dispatch unit (plain Agent tool), awaiting a free slot (wave completion) before launching the next — instead of fire-all-then-retry (record any degradation in the gate evidence). Whengates.fanout.sequentialis set (true), the conductor dispatches heavy reviewers one at a time — effective concurrency is one dispatch unit per wave regardless ofmaxConcurrent(the wave plan is built withresolveFanoutEffectiveConcurrency, emitted asartifact.fanout.effectiveConcurrency, issue #1726) — so each heavy reviewer completes and writes its evidence artifact before the next starts, keeping genuine distinct-reviewer fan-out alive under child-safe parallel overload (no collapse to inline; fan-in/ledger/provenance unchanged). Each reviewer follows review agent scoped angle-review mode: fresh context, read-only, briefed with every angle in its group (each angle's own prompt, all appended after the one shared invariant prefix —GATE-EXEC-BRIEFING-PREFIX); when every angle in a dispatch unit declares the SAME non-fullscope, the conductor ALSO seeds that reviewer with the matchingbriefingVariants[scope]file recorded on the context artifact, layered AFTER the invariant prefix as an additional narrow read — never a replacement (GATE-EXEC-BRIEFING-PREFIX's per-angle scoped variants rule: the reviewer's--prefix-hash/--prefix-filestill records the invariant-prefix bytes regardless of which variant, if any, it was also seeded with) — and any mixed-scope orfullunit is seeded with the invariant prefix alone, running the mandatory fresh-context guard ONCE perGATE-EXEC-BRIEFING-PREFIX's--scopenaming rule (<gate>-group-<name>for a group, the existing<gate>-<angle>for a per-angle dispatch) — not restated here. The reviewer writes its per-angle findings artifact totmp/gate-reviews/<repo-slug>/pr-<N>/<gate>-<headSha>/<angle>.jsononce per angle in its group — a 3-angle group therefore writes 3 artifacts, each with its own verdict and stamped with the reviewed head (GATE-EXEC-ARTIFACT-HEAD-STAMP) — never one merged artifact for the group. This keeps fan-in, the ledger, coverage checks, and the head-stamp guard byte-identical to per-angle mode, since all four read per-angle artifacts and never the reviewer that produced them. Grouped-round provenance records the group name on every angle a group's reviewer covered — the ORCHESTRATOR records it on Phase 3's--provenanceentries below, never the reviewer, whose findings artifact carries nogroupfield (fanoutReviewerPairingError's within-group exception in Gate Review Sub-Loop Contract) — not restated here. <!-- rule: COPILOT-FOLLOWUP-ADVERSARIAL-BRIEFING -->COPILOT-FOLLOWUP-ADVERSARIAL-BRIEFING: Each reviewer MUST be briefed to review like an external code reviewer hunting real bugs: read the FULL diff (fromscope.diffPath, orgit diffwhen null) and the bundled adjacent code (callers, callees, imports) rather than re-deriving them, then review adversarially for concrete defects (edge cases, input validation, numeric coercion incl. NaN/Infinity/floats/negatives, null/undefined, boundary conditions, mismatched caller/callee contracts, dedup/identity bugs) withfile:line+ the failing scenario — not process nits like "no test exists". Reviewers MAY widen scope (open adjacent repo files beyond the bundle) only when their angle genuinely needs more, recording in the optionalcontextWidenedfield only the widening that moved their judgment. The LAYOUT of this briefing — invariant block first, this adversarial angle prompt last, so every reviewer's prompt shares one byte-identical cache-aligned prefix (the pointer line itself, when a harness seeds via a file pointer rather than inline bytes) — and the--prefix-hash/--prefix-filesentinel recording are owned byGATE-EXEC-BRIEFING-PREFIX— not restated here. Each reviewer's briefing also carries a known-findings block, appended AFTER this angle-specific prompt and never into the byte-identical prefixGATE-EXEC-BRIEFING-PREFIXhashes, listing every currently open or resolved finding thread regardless of author so the reviewer does not re-raise what a thread already covers; build the block fromnode scripts/github/capture-review-threads.mjs --repo <owner/name> --pr <number>output (the full-bodies read, notlist-review-threads.mjs's 200-char listing excerpt), never an ad-hoc GraphQL call. The block's content, dedupe contract, and prefix-hash non-interference are owned byGATE-EXEC-FINDING-THREADSin Gate Review Sub-Loop Contract. - Fan-in (Phase 3):
consolidate-fanin.mjsnow runsverify-briefing-prefixes.mjs --head-sha <current_head_sha>itself before consolidation (#1618 — the verifier previously had ZERO callers, so the rule's own cited proof was unenforced); it fails closed on a divergent/hashless sentinel, or when the reviewer sentinel count is short of the dispatch units the conductor spawned. Pass--expected-dispatch-units <n>sourced from the Phase 1 context artifact'sfanout.pendingGroups.length— the dispatched dispatch-UNIT count (groups for grouped dispatch, angle count for per-angle dispatch, whereresolveFanoutGroupsemits one singleton per angle). When Phase 1.2 carry-forward carried angles, pass the dispatch-unit count over the plan's FRESH angles (pendingGroupsincludes carried angles and would overcount — carried angles get no reviewer/sentinel). NOTfanout.wavePlan.length(that is the WAVE count, typically 1, not the dispatch-unit count — passing it would weaken AC3 to a near-noop), and NOT the per-angle artifact count (which would false-fail every grouped round). Then consolidate via ONE call to the sanctioned fan-in CLI — its behavior (blocking severities, emitted shapes, fail-closed cases) is owned by Gate Review Sub-Loop Contract Phase 3, not restated here:dev-loops gate consolidate-fanin --findings-dir <dir> --head-sha <current_head_sha> --gate <gate> --expected-dispatch-units <n> --out <findings-json-path> --ledger-out <ledger-path> --jq '.severityCounts'(scripts/loop/consolidate-fanin.mjs;--head-shaactivates theGATE-EXEC-ARTIFACT-HEAD-STAMPstale-artifact guard — pass it on every round). That ONE invocation both writes--out/--ledger-outto disk and prints.severityCountson stdout via--jq— capture it (e.g.severity_counts=$(... --jq '.severityCounts')) for the verdict call's--findings-severity-countsbelow; never re-invoke the CLI a second time just to re-extract a value it already returned. When Phase 1.2 ran and returned a plan, pass BOTH--carried-angles <json>(that plan'scarriedangle names) AND--carry-forward-plan <json>(Phase 1.2's own result, or at least itscarriedarray) — required together, alongside--gate(already on this call): the CLI treats--carried-anglesas proof-carrying, not a bare trust-me list, and fails closed (exit 1) per the sub-loop contract's full refusal list (a configured mandatory or always-include angle, an unmapped name, a name absent from the plan'scarriedlist, or a raw artifact self-declaringcarriedFromHead). Phase 2 dispatched no artifact for a carried angle, so without--carried-anglesit is invisible to the findings-json/coverage checks and the posted verdict comment reads as a truncated fan-out instead of a full one; omit both flags on a gate's first round (no Phase 1.2 plan). Write the disposition ledger viawrite-gate-findings-log.mjs --findings-file <ledger-path> --provenance '<json>'(the CLI's--ledger-outfile, passed straight through — no improvised extraction) before the visible verdict review (GATE-EXEC-DISPOSITION-LEDGER,GATE-EXEC-POST-BEFORE-FIXown that ordering and the ledger's opt-out-proof durability).--provenanceis a SEPARATE flag on THIS write call — it does not exist onpost-gate-findings.mjsbelow (that CLI rejects it as an unknown argument); omit it here and everycarriedFromHeadattribution is dropped, which then silently disables the NEXT round's carry-forward too. Its shape is{ distinctReviewers: <int>, perAngle: [...] }:distinctReviewersis required, andperAngleMUST cover every resolved angle — a fresh entry for each angle Phase 2 dispatched, plus one entry per Phase 1.2carriedangle carrying that entry'scarriedFromHeadand its prior reviewer identity fields (reviewer/dispatchId/model) — every identity field it has, not a hand-picked subset, since an entry recorded only underdispatchIdwould otherwise land unattributed. A fresh entry produced by a GROUPED dispatch unit also carriesgroupset to that unit's name, repeated identically on every fresh entry the same reviewer covers — you (the conductor), not the reviewer, write this field, since a reviewer's findings artifact has none. On agate:fullround also pass--full-labelto this samewrite-gate-findings-log.mjscall (mirroring Phase 1'swrite-gate-context.mjs --full-label), so its write-timeresolvedGroupscross-check resolves the same untriered per-angle-singleton table Phase 2 actually dispatched against, instead of the tiered default. The plan'sreasonfield is explanatory and is not part of the accepted shape. Passing--provenanceis doubly load-bearing whenever the gate configuresmandatoryAngles:detect-checkpoint-evidence.mjsenforces mandatory-angle coverage from the ledger's provenance by default for such a gate, independent ofgates.requireFanoutProvenance, and a ledger with absent or invalid provenance fails closed there. The round's findings ride the verdict review posted in Phase 4, so no separate findings comment is posted; only when a repo has explicitly opted intogates.postFindingsComments(default false) also post the same ledger vianode <resolved-skill-scripts>/github/post-gate-findings.mjs --repo <owner/name> --pr <number> --gate <gate> --head-sha <current_head_sha> --findings-file <ledger-path>— no--provenanceflag on this call. - Verdict (Phase 4): check whether the fan-in's
--outfile exists before posting: a round withheld to tier 4 (see the Gate comment command's tier-4 note above) deletes--outand has no--findings-jsonshape to pass — post that round with--findings-summary "<summary>"PLUS--findings-ledger <findings-log-path>(the same durable log this same step passes below; never--findings-summaryalone — see the tier-4 note above for the coverage-proof rule that mandates it). Otherwise post via the Gate comment command using--execution-mode fanout_faninand--findings-json <path>built from the same per-angle artifacts consolidated in Phase 3 — that flag's accepted shapes are owned by the Gate comment command section above; do not restate them here. Pass that same durable log to the verdict call's--findings-ledgerso the round's findings ride the one posted review (GATE-EXEC-FINDING-THREADS). Do NOT run the disposition pass yet —close-gate-findings.mjsruns AFTER the Phase 5 (Retry) fixer triage below (#1585: the fixer must see every gate-authored finding, including low findings, before the disposition pass defer-closes them; running it here would silently auto-defer low findings before the fixer ever sees them, reintroducing the #1584 bug). - Retry / fixer triage (Phase 5): the fixer triages EVERY gate-authored defect finding (high, medium, AND low) and answers every gate-authored question on EVERY gate round — this is UNCONDITIONAL, not gated on "blocking findings" (#1585): on a clean verdict with open low/question threads (the exact #1584 scenario), the fixer STILL runs, receiving each gate-authored thread as a fix/triage/answer target (fix-if-cheap-in-the-same-commit when already touching that code, else defer, for a defect; an answer, promoting or escalating as needed, for a question). The fixer owes a nit thread no triage cycle — it is not handed to the fixer as a fix/triage target on the severity axis, unlike low (the one exception: a judge
acton a nit reaches the fixer through judge-pass's severity-blind act filter); the disposition pass defer-closes a still-unresolved nit thread immediately regardless. Defer is permitted from round 1 on for low findings (no forced fix window; the medium window (#1581) is unaffected). Drive blocking findings (high, in-window medium) through the SAME fix → reply-with-resolving-commit → resolve loop used for external Copilot review comments (Step 7 above). Then, at every gate close (clean or not), runnode <resolved-skill-scripts>/github/close-gate-findings.mjs --ledger <findings-log-path>against that same path as the closing sweep — AFTER the fixer triage (#1585): it defer-closes every still-open DEFERRABLE gate-authored thread (low, nit, and out-of-window medium — the fixer had its chance first on low/medium, owed nothing on nit; it never fix-closes, and leaves high / question / in-window medium unresolved) and REPORTSunresolvedGateThreadCount(gate-authored threads still unresolved after the defer pass); the gate-close assertion (fetchDraftGateEvidence/ready-for-review/pre-pr-ready-gate) refuses to mark the gate satisfied while that is non-zero. It posts nothing of its own and runs only the thread disposition pass (GATE-EXEC-THREAD-DISPOSITION). This is mandatory, not conditional on the verdict. Then re-enter the chain at Phase 1 for the fixed head — Phase 1.2 decides what re-runs. A round that had blocking findings carries nothing (its log is notclean), so the fixed head takes the full fan-out; carrying only becomes possible on the head bumps that follow a clean round. Context-builder and fan-in always re-run. Repeat until the consolidated verdict iscleanfor the current head SHA AND 0 unresolved gate-authored threads remain (GATE-EXEC-REGATE-MANDATORY,GATE-EXEC-THREAD-DISPOSITION).
Draft gate contract (before marking PR ready for review)
The canonical checkpoint verdict comment contract is Gate Review Comment Contract. This section summarizes the procedural integration only.
- Gate name: Draft gate
- Trigger / boundary: right before running
gh pr ready(draft → ready for review) - Skip rule: before entering the draft gate, run
detect-pr-gate-coordination-state.mjsand checkdraftGateAlreadySatisfied. Iftrue, skip the draft gate entirely — the draft→ready transition was already recorded.draft_gateis a one-time gate; do not re-post on new heads once clean draft-gate evidence exists for the transition record. (While the PR is still draft, advancing the head SHA does require a new draft-gate comment for the new head.) This skip rule applies only to the draft boundary. - Execution directive: run the Gate fan-out/fan-in procedure (the agent-orchestrated chain defined in Gate Review Sub-Loop Contract) with the draft gate inspection angles resolved from config.
- Review angles: resolved at runtime from config via
resolveGateAngles(config, "draft")from@dev-loops/core/config. Default config enables all configured draft gate angle families; consumer repos may opt out individual angles by settingenabled: falseon that angle's entry. Do not apply angles from the other gate; each gate owns its own angle list from config. - CI prerequisite: resolve the draft gate config first (
resolveGateConfig(config, "draft")). WhenrequireCi=true(default), wait for green current-head CI before enteringdraft_gate. WhenrequireCi=false, the draft gate may proceed without green CI. This draft-only override does not relaxpre_approval_gate— that gate has its own separategates.preApproval.requireCiknob (defaulttrue), which when setfalseopts the pre-approval boundary out of the CI precondition independently. - Pass criteria: all configured draft gate angles pass; all findings at severities in
blockCleanOnFindingSeveritiesare addressed; validation passes; no unrelated files are included. - Next step after passing: mark the PR ready for review.
- Board status sync (built-in, after ready-for-review): the In-Progress board move is now performed automatically as a deterministic tail of
ready-for-review.mjs— marking the PR ready couples the board move to the ready transition (#1069), so no separatesync-item-statusstep is needed. It stays best-effort and NON-FATAL: it uses localghauth (no CI/PAT), exits 0 when the board is not configured / the item is not on the board / the API fails, and never blocks marking the PR ready. - Non-substitution rule: a clean
draft_gatecomment only authorizes the draft → ready-for-review transition for that head SHA; cross-gate non-substitution is owned byGATE-COMMENT-NON-SUBSTITUTIONin Gate Review Comment Contract. This skill does not restate that rule. - Required PR comment: post a visible checkpoint verdict comment using the mandatory Gate comment command. Comment field content and validation-reporting format are owned by
GATE-COMMENT-VALIDATION-REPORTING; the draft-boundary comment requirement is owned byGATE-COMMENT-DRAFT-REQUIREMENTS; posting-failure fail-closed behavior is owned byGATE-COMMENT-FAIL-CLOSED— all in Gate Review Comment Contract. This skill does not restate those field/format/fail-closed rules.
Pre-approval gate contract
This is the default pre-approval gate for this workflow boundary. The canonical checkpoint verdict comment contract is Gate Review Comment Contract. This section summarizes the procedural integration only.
- Gate name: Pre-approval gate
- Trigger / boundary: right before calling a PR/branch review-complete, approval-ready, merge-ready, or ready for final handoff
- Execution directive: run the Gate fan-out/fan-in procedure (the agent-orchestrated chain defined in Gate Review Sub-Loop Contract) with the pre-approval gate inspection angles resolved from config. The
acceptance-criteriaangle is mandatory for this gate (see.devloopsgates.preApproval.angles— theacceptance-criteriaentry setsmandatory: true) and always survives dynamic resolution. Retry rule: in subsequent cycles, Phase 1.2 decides what re-runs. - Review angles: resolved at runtime from config via
resolveGateAngles(config, "preApproval")from@dev-loops/core/config. Default config enables all configured pre-approval gate angle families; consumer repos may opt out individual angles by settingenabled: falseon that angle's entry. - Persona mapping: each angle resolves to a reviewer persona via
resolveReviewerRole(config, angle)from@dev-loops/core/config. Include this prompt in each reviewer's briefing so the reviewer knows exactly what to look for.
- Model tier: resolve each reviewer's model via
resolveRoleModel(config, { role: angle, harness: "pi", kind: "angle" })from@dev-loops/core/config—kind: "angle"forces the review (high) tier for the gate activity even when the angle name collides with a routine role (thedocsangle resolves high, not thedocswriter role's low tier) — and pass it at dispatch only when non-null — a no-op on Pi until an operator setsmodels.tiers.<alias>.pi.
- Pass criteria: the sub-loop completes with verdict
clean; all configured angles pass, following the sequential-fallback rule owned byGATE-EXEC-FANOUT-SEQUENTIAL-FALLBACKin Gate Review Sub-Loop Contract. - Acceptance criteria verification: follow the canonical procedure in Acceptance Criteria Verification before posting the
pre_approval_gatecomment. After a clean verification this also ticks the verified PR-body checkboxes viascripts/github/tick-verified-checkboxes.mjs, so the merged PR shows checked AC. - Next step after passing: continue the Step 7 flow and then proceed to the human approval checkpoint below.
- Non-substitution rule: a clean
pre_approval_gatecomment governs final-approval readiness for that head SHA and is separate fromdraft_gateevidence; cross-gate non-substitution is owned byGATE-COMMENT-NON-SUBSTITUTIONin Gate Review Comment Contract. This skill does not restate that rule. - Required PR comment: post a visible checkpoint verdict comment using the mandatory Gate comment command. Comment field content and validation-reporting format are owned by
GATE-COMMENT-VALIDATION-REPORTING; the pre-approval-boundary comment requirement is owned byGATE-COMMENT-PREAPPROVAL-REQUIREMENTS; posting-failure fail-closed behavior is owned byGATE-COMMENT-FAIL-CLOSED— all in Gate Review Comment Contract. This skill does not restate those field/format/fail-closed rules. - <!-- rule: GATE-SKIP-NOT-RECOVERABLE-BY-CONVERGENCE --> `GATE-SKIP-NOT-RECOVERABLE-BY-CONVERGENCE`: Skipping the gate MUST NOT be treated as recoverable by asserting convergence.
Conflict-resolution gate
Before any merge-ready or final-approval claim, run detect-pr-gate-coordination-state.mjs for the current PR. If it reports gateBoundary=conflict_resolution or mergeStateStatus is conflicted, stop the normal gate path immediately and use this recovery flow:
- fetch fresh
origin/main, confirm the current PR head SHA, and summarize the conflict scope frommergeStateStatusplus any reportedconflictFiles - ask for explicit authorization before any merge commit or other branch-state-changing reconciliation command
- after authorization, reconcile locally on the PR branch; default to a merge commit (
git merge origin/main) per the behind-branch integration policy in Local Implementation Skill, unless the operator explicitly chooses another conflict-resolution command - auto-resolve simple conflicts when the correct fix is mechanical and clearly in scope; report complex conflicts explicitly and fix them manually only for in-scope files
- rerun the smallest honest local validation for the touched conflict slice
- rerun
detect-pr-gate-coordination-state.mjsfor the new head - because the head changed, rerun
pre_approval_gatefor the new head before any approval-ready or merge-ready claim - wait for current-head CI again before retrying merge evaluation
- if the chosen reconciliation rewrote branch history (rebase only — merge commits push as a normal fast-forward), ask for explicit authorization before
git push --force-with-lease(--force-with-leaseonly, never bare--force), then continue the loop on the updated head
mergeStateStatus: CLEAN alone is not enough to resume approval or merge claims. The existing merge-ready preconditions still apply: zero unresolved review threads, a clean current-head pre_approval_gate, and green current-head CI.
Merge-ready preconditions
See Merge Preconditions. Verify: zero unresolved threads (via dev-loops gate capture-threads), visible clean draft_gate + current-head pre_approval_gate, green CI. Fresh-context review follows Gate Review Sub-Loop Contract.
Human approval checkpoint
After merge-ready preconditions pass, verify Merge Preconditions authoritatively before reporting merge-ready. Stop at the human approval checkpoint by default. Cross-check via dev-loops gate capture-threads (not prose assertion).
Follow Merge Preconditions: stop at waiting_for_merge_authorization after approval unless merge explicitly authorized. Run pre-merge gate evidence check before any gh pr merge.
When approval.enabled is set, don't just park silently at this stop: run dev-loops gate offer-human-handoff --repo <owner/name> --pr <number> to surface candidate reviewers/assignees, then offer them to the operator. Only on operator confirmation, route the PR with --assign <login> / --request-review <login>. This is OFFER-only — never auto-assign. See the approval section in Merge Preconditions; it pairs with autonomy.humanMergeOnly.
Mechanical pre-merge gate evidence check
Immediately before any gh pr merge, run:
node <resolved-skill-scripts>/github/detect-checkpoint-evidence.mjs \
--repo <owner/name> \
--pr <number>
This helper is always-on: it uses gh api to read both verdict surfaces — the PR review stream (primary, per GATE-COMMENT-SINGLE-SURFACE) and visible PR issue comments (back-compat, for legacy and fallback-posted verdicts) — and fails closed unless both required gate verdicts are visible on either surface: a clean draft_gate verdict for the one-time draft boundary and a clean current-head pre_approval_gate verdict. Do not run gh pr merge if this command exits non-zero. There is no opt-out flag. Resolved threads, green CI, clean Copilot rereview, or local notes do not substitute for this successful helper output. If a final approval or merge boundary sees gh pr merge without a same-boundary successful check, treat that as a workflow violation and stop.
Stale runner-coordination lock held by a completed run
The pre-merge gate evidence check fails closed on the PR's runner-coordination claim (.pi/runner-coordination/<owner>/<name>/pr-<n>.json): a fresh merge re-dispatch (new run id) is refused with ownership_lost, or stale_runner once the claim ages past the max-age window.
The auto-loop now releases its claim best-effort when a run reaches a terminal stop (clean-converged, blocked, or done — including the stop at the human approval checkpoint), so a merge-authorized re-dispatch normally inherits a cleared claim and proceeds. The release is non-fatal: it never blocks the stop, and it never clears a claim owned by a genuinely active competing run.
Beyond the terminal release, #1706 removes the stall on the path here: copilot-pr-handoff acquires ownership with supersedeStale: true, so pre-flight handoff takes over a competing claim whose owning run is confirmed dead (recorded exit signal) or past the stale-max-age window — proceeding instead of returning a blocking stop against a leaked lock. The headless dev-loop driver also clears every claim its run still owns when the spawned run's process exits (release-on-death). A genuinely live owner still blocks (one-runner-per-PR preserved); only confirmed-dead or stale claims are superseded. The manual takeover below therefore only remains for a pre-#1706 leak or a live-but-unreleasable edge.
Anti-trap — a fresh runner-coordination claim heartbeat is not proof of a live driver. A runner-coordination claim/lock carrying a fresh heartbeat does NOT prove a live agent is driving: the lock may be held by a completed/control run that claimed at takeover and then ended without releasing, yet the heartbeat still reads fresh — which this drive saw as repeated false "live owner / standing down" stalls. LIVE requires a subagent run verified via subagent status (a harness command, not a repo script or CLI) showing an actively-updating EXECUTING child (a workflow child active now with a recent update). Before any stand-down or dispatch decision, confirm real execution via subagent status; never trust the claim heartbeat alone. Only genuinely-executing runs count as a live owner.
If a stale claim still blocks the merge because the completing run could not release (crash, killed process, or a pre-#1109 run), the sanctioned recovery for a lock held by a COMPLETED run is an explicit takeover by the merge run:
node <resolved-skill-scripts>/loop/pr-runner-coordination.mjs takeover \
--repo <owner/name> --pr <number>
takeover seizes ownership for the current run id and records the displaced run under previousRun. Only take over when the prior owner is genuinely completed/dead. A genuinely active (non-stale) run must still be allowed to block — do not take over to race a live run.
Mandatory post-merge retrospective checkpoint write
After a merge succeeds (or an explicit retrospective skip is authorized), write the durable retrospective checkpoint before exiting the subagent session. The retrospective gate is derived at the START of the NEXT loop by checking local git ancestry between this checkpoint's recorded identity.mergeCommit and the base branch — an identity-less record can never be verified, so it is treated the same as a stale one; carrying --repo/--pr/--merge-commit (the repo, this PR's number, and its full merge commit oid — the same oid node <resolved-skill-scripts>/github/view-pr.mjs --repo <owner/name> --pr <n> --json mergeCommit --jq .pr.mergeCommit.oid reports) is MUST, not optional (the CLI now rejects complete/skipped without it):
node <resolved-skill-scripts>/loop/checkpoint-contract.mjs --state complete --notes "<one-line retrospective summary>" \
--repo <owner/name> --pr <number> --merge-commit <full merge commit oid>
For an explicit skip:
node <resolved-skill-scripts>/loop/checkpoint-contract.mjs --state skipped --reason "<why retrospective is skipped>" \
--repo <owner/name> --pr <number> --merge-commit <full merge commit oid>
Do not report completion or advance to the next PR queue item until .pi/dev-loop-retrospective-checkpoint.json is updated to complete or skipped carrying this cycle's identity.
Post-merge board sync (best-effort)
After the retrospective checkpoint write, run the post-merge board sync and archive as standard steps of the post-merge hook (see Merge Preconditions "Post-merge"):
dev-loops queue sync-status --repo <owner/name> --pr <number> --item <linked-issue> --logical-column done || true
node <resolved-skill-scripts>/projects/archive-done-items.mjs --repo <owner/name> || true
queue sync-status --logical-column done (issue #1458) moves the merged item's board Status to the configured Done column right after merge — the logical name resolves through queue.statusColumns, so a board that renamed Done still converges. Omit --item when the merged PR is itself the queue item (issue-less / PR-is-the-queue-item case); an unfilled/empty --item falls back to --pr rather than failing the step. It must run from the main checkout, before the worktree-removal step below — it resolves .devloops relative to cwd and has no --repo-root flag, so running it afterwards would leave it with no cwd at all. Board and threshold resolve from .devloops (tracker.board/queue.board, queue.archiveOlderThanDays, default 7d), using local gh auth — no CI, cron, or PAT. Both steps are best-effort and NON-FATAL, but their exit contracts differ: queue sync-status exits 0 on any parsed invocation, including every board/API failure (the JSON result on stdout describes the skip) — only a usage/argument error (exit 1), an invalid --jq filter (exit 2), or a falsy --silent predicate is non-zero, which the || true above guards against. archive-done-items.mjs exits non-zero on a usage/argument error (1), a GitHub API error or invalid --jq filter (2), or a project-not-found (3) — its own || true is load-bearing, not redundant, and masks those failures deliberately so a failed archive run never blocks the merge. Neither step blocks the merge or the retrospective.
dev-loops queue reconcile (idempotent, run best-effort at loop startup) is the fallback convergence path when the sync above is ever skipped or missed — it re-derives every item's column from live GitHub state, so a merge that could not run this hook still lands on Done at the next startup.
The post-merge hook also fast-forwards the main checkout's local main to origin/main (#1596) so read-only gate scripts run current code; see Merge Preconditions "Post-merge" for the canonical step. Best-effort and non-blocking (--ff-only refuses a diverged main without rewriting history).
Validation policy
Follow Validation Policy. Default: npm run verify before PR creation, gate entry, and merge. For repo-local examples: npm run test:dev-loop for skill scripts, contract tests for templates, git diff --check for docs. When CI runs exist, use gh run watch or detect-copilot-loop-state.mjs instead of sleep-based polling. Distinguish: locally validated, full PR-equivalent checks, awaiting CI.
Confirmation checkpoints
See Confirmation Rules. Stop and ask before GitHub mutations (edits, assignments, labels, comments, reviews, thread resolution, commits, pushes, merges, workflows) unless explicitly authorized.
Stop conditions
Follow Stop Conditions. Genuine stops: blocked state, done, approval_ready without merge auth, ambiguous state, scope drift. Non-stops: waiting watcher states, quiet observations.
Anti-patterns
See Anti-patterns. Key repo-specific additions:
- Use
reply-resolve-review-thread.mjs/reply-resolve-review-threads.mjshelpers instead of ad hocgh api/gh api graphqlthread-mutation commands. Do NOT usegh pr comment,gh api, orgh pr reviewfor gate verdicts (useupsert-checkpoint-verdict.mjs). - Use
list-review-threads.mjsandwait-pr-checks.mjsinstead of ad hocgh api graphqlreview-thread queries orgh pr checksshell-pipe polling loops. - Do not declare merge-ready without visible
pre_approval_gatecomment on current head SHA. Do not declare merge-ready based solely onmergeable_state: clean+ CI green without gate evidence. CI green + resolved threads alone is insufficient. - Do not blind-run
gh pr merge/gh pr update-branch/unapproved rebase when conflicted. Do not dispatch async dev-loop tasks that omit the pre-approval gate requirement. - Do not assume generated wiki is authoritative over code or CI.
Output expectations
When using this skill, keep user-facing summaries concise and operational.
A good status update should say:
- what issue or PR you inspected
- current state
- what the next recommended action is
- whether authorization is needed before taking it