diff --git a/.github/CLAUDE.md b/.github/CLAUDE.md index 2f72bb54a..2559b87e8 100644 --- a/.github/CLAUDE.md +++ b/.github/CLAUDE.md @@ -35,7 +35,9 @@ load-bearing**, not the file the change lives in: it. `ai-loop`, `ai-loop-paused` and `deep-review` steer automation the same way. Deleting or renaming one of those disables a control **with no workflow diff at all**, which is the exact hazard this section exists to name. A new `documentation` label is inert; a label a workflow - reads is middle row. + reads is middle row. `review-converged` is written by `review-converged.yml` for the owner + to read. That workflow reads it back only to decide whether to add or remove it, and no + automation gates on it. - **Schedules are not uniformly inert.** A `schedule:` on `ai-scan` or the stale sweep decides when a security control runs. A docs-build cadence does not. - **`dependabot.yml` ignores are not uniformly inert.** A `semver-major` ignore only declines a @@ -320,7 +322,8 @@ the marker your workflow owns. More generally: when probing for a machine comment, match on **marker + (bestaxbot OR a Bot-type author)**. Never probe one specific login. bestaxbot is a machine _User_ account, not a Bot-type app, so a `type == 'Bot'` test alone misses it and a login test alone breaks the next -time the identity changes. +time the identity changes. A probe that grants trust rather than finding a comment pins the +identity instead, and `isDeepReviewAuthor` in `scripts/review-converged.mjs` says why. ### 7. Fork PRs never run with secrets @@ -532,7 +535,7 @@ jobs (`ci.yml`, `deploy.yml`, `test-deploy.yml`, `visual-regression.yml`, `story `security-txt-expiry` (`check`), `auto-close-duplicates` (`auto-close`), `claude` (`claude`), `claude-implement` (`implement`), `bestaxbot-reply` (`respond`), `claude-review` (`review`), `claude-pr-loop` (`fix` and `verify`), `mcp-registry` (`publish`), `codemod-registry` - (`validate` and `publish`). The command below lists them. + (`validate` and `publish`), `review-converged` (`sync`). The command below lists them. - **Audit, deliberately, pending a measured allowlist** — none, as of #578. That issue closed the group by measuring every member instead of guessing for them. They all now **use** the same allowlist, and the gap between that and what the measurement produced is the part worth diff --git a/.github/workflows/review-converged.yml b/.github/workflows/review-converged.yml new file mode 100644 index 000000000..2ccb8c8c8 --- /dev/null +++ b/.github/workflows/review-converged.yml @@ -0,0 +1,181 @@ +name: Review Converged Label + +# Keeps the `review-converged` label in step with PRs that opted into the +# Claude deep review through the `deep-review` label, so the owner can see in +# the PR list which ones are ready for human review. What "converged" means, +# and every decision, lives in scripts/review-converged.mjs behind a node +# --test sibling (rule 9 in .github/CLAUDE.md). This file only triggers it. +# +# PRs labeled `ai-loop` are skipped: claude-pr-loop.yml hands those off with +# `needs-human-review`. +# +# No pull_request or pull_request_target trigger, and no checkout of PR code. +# workflow_run and schedule run the default branch's copy of this file, and +# the job checks out main to run the script. Review bodies are model-authored +# text that the script only matches against fixed patterns and never prints. +# +# Runs no model and holds no secret beyond the job's GITHUB_TOKEN, so it is +# deliberately not gated on vars.AI_LOOP_ENABLED (the house rule for +# zero-Claude workflows, same as auto-close-duplicates.yml). Label writes made +# with GITHUB_TOKEN emit no workflow events, so nothing re-triggers on them. + +on: + workflow_run: + # A deep review or CI run starting or finishing is what changes the + # answer. Each entry must match that workflow's `name:`, which the test + # sibling checks: a renamed workflow would otherwise stop this trigger + # without a sound. + workflows: + - Claude Deep Review + - CI + # `requested` so a push clears the label when its CI run starts, not when + # it finishes: the newest summary is still pinned to the old head, so the + # script removes the label. The test sibling holds both types. + types: [requested, completed] + schedule: + # Watchdog: thread resolutions and commit statuses (CodeRabbit's among + # them) fire no event this workflow hears, so re-check every hour. + - cron: '47 * * * *' + workflow_dispatch: + # No actor allowlist needed: GitHub only lets users with write access + # dispatch a workflow. + inputs: + pr: + description: 'PR number to check (leave empty to check every open PR)' + required: false + default: '' + +# No workflow-level grants. The single job takes exactly what it needs. +permissions: {} + +jobs: + sync: + # The script leaves this job's own check run out of the checks it judges, + # matched by this name (OWN_CHECK_NAME). The test sibling holds them equal. + name: Sync review-converged label + # workflow_run: only a run for a PR whose head is in this repository can + # move a label this job writes. A push to main or a fork PR's run is + # skipped before the job starts. + if: | + github.event_name != 'workflow_run' || ( + github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.head_repository.full_name == github.repository) + # One group for every run, so two jobs can never write the same label at + # once. A per-PR group would need the PR number before the job starts, + # which the schedule trigger does not have. + # + # Declared on the job, not the workflow, and that placement is load-bearing. + # It relies on GitHub evaluating the job's `if:` before the job joins its + # concurrency group, so a run whose job is skipped (CI on a push to main, a + # fork PR's run) never enters the group. At workflow level such a run would + # still join, replace a pending run, and then do nothing. + # + # When GitHub replaces a pending job with a newer one, the newer job sweeps + # every open PR from live data and covers what the replaced one would have + # done. The exception is a dispatch naming a single PR: if it replaces a + # pending sweep, the next sweep catches up, at the latest the hourly one. + # + # No cancel-in-progress: a job is a handful of API calls, and cutting one + # short between its re-read and its label write buys nothing. + concurrency: + group: review-converged + cancel-in-progress: false + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read # check out main to run the script + pull-requests: write # read PRs, reviews and review threads, add and remove the label + checks: read # check runs on the head commit + statuses: read # commit statuses on the head commit + steps: + # Rule 10 (.github/CLAUDE.md): a new job starts at `block`. It runs only + # on workflow_run, schedule and workflow_dispatch, outside the + # untrusted-trigger class. + # + # api.github.com: every REST and GraphQL call the script makes, and the + # API calls actions/checkout makes. + # github.com: actions/checkout's git fetch of main. + # + # Nothing else, because nothing is installed. The script is + # dependency-free (node: builtins and the global fetch) and runs on the + # runner's preinstalled Node, so there is no setup-node step and none of + # the hosts its toolcache-miss path needs. auto-close-duplicates runs the + # same checkout-and-REST shape and reached only these two hosts under + # block (rule 10 cites the run). + # + # Derived from what the steps below reach rather than from a measured + # run of this job. Resolve anything you add here first: an unresolvable + # entry makes the agent revert the firewall while the pre-step still + # exits 0. + - name: Harden runner + uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: block + allowed-endpoints: > + api.github.com:443 + github.com:443 + + # Asserts the policy the pre-step decided (agent.json) AND that the agent + # actually came up (agent.status, written only once the firewall rules are + # installed). Either alone is a false pass: #487 was the first kind, and an + # unresolvable host in an allowlist is the second. + # + # Scope it honestly: this proves enforcement was armed AT THIS STEP. It does + # NOT prove the policy stays armed — the agent writes `Initialized` and then + # serves, and a later runtime error makes it revert the firewall with both + # files still reading exactly as they do here. Rule 10 in .github/CLAUDE.md + # carries the mechanism and what to check when a run looks wrong. + # + # Placement is rule 10's default (immediately after harden-runner): nothing + # `always()`-guarded keys off this job's outputs, and the job is not itself + # a fail-closed path, so neither placement exception applies. + # + # Linux-only paths (macOS uses /opt/step-security); all runners are ubuntu-latest. + - name: Assert egress policy is enforced + run: | + set -uo pipefail + # harden-runner has several deliberate "install nothing, exit 0" paths + # (StepSecurity unavailable, the skip-harden-runner repo property, a + # container or slim runner). None of them writes agent.json, so name + # that case rather than leaving a bare jq "could not open file". + if [ ! -e /home/agent/agent.json ]; then + echo "::error::harden-runner installed no agent, so nothing is enforcing egress. Usual causes: a StepSecurity outage (its pre-step returns green without installing), the skip-harden-runner repo property, or a container/slim runner. This job holds pull-requests: write and will not run unprotected (#487)." + exit 1 + fi + if ! jq -e '.egress_policy == "block"' /home/agent/agent.json; then + echo "::error::effective egress policy is not block — harden-runner downgraded it (#487)." + exit 1 + fi + # Poll rather than test once: the pre-step waits only for the file to + # EXIST and gives up after ~9s, while the agent resolves every + # allow-listed host before writing its status, so a cold resolver or a + # long list can leave the file absent or still empty here. + for _ in $(seq 1 30); do + if grep -q '^Initialized' /home/agent/agent.status 2>/dev/null; then + exit 0 + fi + sleep 1 + done + echo "::error::agent.json reads block but the agent never reported Initialized — the firewall is not up. Check the agent log for 'Reverted changes' (usually an unresolvable allow-listed host)." + exit 1 + + # main, never a PR branch, whatever ref a dispatch was started from. + - name: Checkout main for the script + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: main + persist-credentials: false + + # The PR number reaches the script through the environment, never + # interpolated into the shell, and the script rejects anything that is + # not a positive integer. Empty (every trigger but a dispatch naming a + # PR) means sweep. + - name: Sync the label + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + PR: ${{ inputs.pr }} + run: | + set -euo pipefail + node --version + node scripts/review-converged.mjs --repo="$REPO" --pr="$PR" diff --git a/CLAUDE.md b/CLAUDE.md index 9b6c36f4d..9da9650dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -196,7 +196,16 @@ green and every AI review thread is resolved. - **Labels:** `ai-loop` (in the loop), `needs-human-review` (converged or contested — owner reviews and squash-merges manually; the loop never merges), `ai-loop-paused` (cap/guard hit). AI-assisted PRs (bestaxbot author or the Claude Code attribution footer) also get - an auto-applied `claude-assisted` provenance label. + an auto-applied `claude-assisted` provenance label. Outside the loop, `review-converged` + marks a `deep-review` PR based on the default branch whose newest deep-review summary is + pinned to the head commit with nothing left open, with every review thread resolved and + every check green. A verify pass reviews no commits, so the PR also needs a fresh deep + review of the head commit with no blocking findings, or a fresh review whose blocking + findings later verify passes resolved, with the pass that resolved the last of them pinned + to the head commit. A stacked PR gets no CI run, so it is out of scope. + `review-converged.yml` adds it and removes it while the PR keeps `deep-review`, not + `ai-loop`, and the default branch as its base. `scripts/review-converged.mjs` holds the + full definition, and an `ai-loop` PR never gets it. - **Deep review on demand:** a triage+ user can apply the opt-in `deep-review` label to any same-repo PR to run the Claude deep review on it. Never a fork: the job gate requires the head repository to be this one, so labelling a fork PR is a no-op: the job diff --git a/docs/docs/guides/getting-started/ai-development.md b/docs/docs/guides/getting-started/ai-development.md index 14a656582..4065b1b48 100644 --- a/docs/docs/guides/getting-started/ai-development.md +++ b/docs/docs/guides/getting-started/ai-development.md @@ -65,6 +65,7 @@ PRs authored by the loop move through a small label lifecycle: | `needs-human-review` | PRs | The loop converged (or hit a disagreement) — awaiting maintainer review/merge | | `ai-loop-paused` | PRs | The loop hit its iteration cap or a guardrail — a maintainer must intervene | | `deep-review` | PRs | Opt-in: a triage+ user applies it to run the Claude deep review on any same-repo PR (never a fork — the job gate requires the head repository to be this one, so the label is a no-op there and the job reports skipped). The label is what starts a run: pushes and comments do not, and re-applying a label already present emits no event, so a re-run means removing it and adding it back. Re-applying settles that review's own open threads and raises nothing new; a steer comment starting `deep-review: fresh` asks for a full review of the current code instead, and that choice sticks — once a triage+ `fresh` steer exists, later toggles stay fresh for as long as it is still the newest triage+ steer the run can see. A steer the run cannot read leaves it unfocused and in verify rather than failing, so an unexpected verify pass can mean a lookup that did not resolve rather than a steer nobody posted. Steer it by pre-posting a PR comment starting with `deep-review:` (focus areas, suspected weak spots) — only comments from triage+ authors are used | +| `review-converged` | PRs | Auto-applied to a `deep-review` PR outside the loop whose base is the default branch, when its newest deep-review summary is pinned to the head commit with nothing left open, every review thread is resolved, every check has passed, and `needs-security-review` is absent. A verify pass reviews no commits, so the PR also needs a fresh deep review of the head commit with no blocking findings, or a fresh review whose blocking findings later verify passes resolved, with the pass that resolved the last of them pinned to the head commit. Once it is on, any later push needs another fresh review (a `deep-review: fresh` steer, then a label toggle) before it comes back. A stacked PR gets no CI run and is never labeled. On a PR that still has `deep-review`, not `ai-loop`, and the default branch as its base, the label comes off when any of this stops holding. Removing `deep-review`, adding `ai-loop` or changing the base leaves it, so take it off by hand then. The workflow that sets it runs no model, so `AI_LOOP_ENABLED` does not turn it off | | `ai-triage` | PRs & issues | Runs one-shot AI triage (related issues + duplicates): automatic on new issues/PRs in auto mode (daily budget), or applied by a triage+ user (budget-exempt; label auto-removes) | | `claude-repro` | issues | Triage+ user applies it: Claude drafts a candidate reproduction test and github-actions[bot] posts it for a human to run (author-only — CI does not run it). Auto-removes | | `needs-security-review` | PRs & issues | Auto-applied by the security scanner when it flags an item; blocks every entry point this repo controls — `claude-repro`, `claude-fix`, `@claude`, `@bestaxbot` — until a maintainer removes it (third-party reviewers are not gated) | diff --git a/scripts/coverage-floors.json b/scripts/coverage-floors.json index 540819d10..076a48dcd 100644 --- a/scripts/coverage-floors.json +++ b/scripts/coverage-floors.json @@ -34,6 +34,7 @@ "scripts/parse-scan-verdict.mjs": { "lines": 100, "branches": 100, "functions": 100 }, "scripts/render-triage-comment.mjs": { "lines": 95, "branches": 88, "functions": 93 }, "scripts/require-pnpm-publish.mjs": { "lines": 99, "branches": 78, "functions": 100 }, + "scripts/review-converged.mjs": { "lines": 100, "branches": 98, "functions": 100 }, "scripts/sanitize-repro-draft.mjs": { "lines": 100, "branches": 100, "functions": 100 }, "scripts/verify-attestation.mjs": { "lines": 98, "branches": 89, "functions": 100 }, "scripts/verify-oidc-context.mjs": { "lines": 98, "branches": 66, "functions": 100 } diff --git a/scripts/review-converged.mjs b/scripts/review-converged.mjs new file mode 100644 index 000000000..b205e7a91 --- /dev/null +++ b/scripts/review-converged.mjs @@ -0,0 +1,797 @@ +#!/usr/bin/env node +/** + * Keep the `review-converged` label in step with deep-review PRs. + * + * A triage+ user applies `deep-review` to a same-repo PR to get the Claude + * deep review on it, and then has to work out by hand when that review has + * settled. This answers it from live data and labels the PR, so a PR that is + * ready for human review shows up in the PR list. PRs labeled `ai-loop` are + * out of scope: claude-pr-loop.yml hands those off with `needs-human-review`. + * + * A PR is in scope when it is open, its head branch is in this repository, its + * base is the default branch, it carries `deep-review`, and it does not carry + * `ai-loop`. The base matters because CI runs only on pull requests to main + * (ci.yml): a PR stacked on another branch gets no CI, and the skipped check + * runs it does get would read as passing. An in-scope PR has converged when + * all of these hold: + * + * 1. Its newest deep-review summary (a review by the claude[bot] app that + * starts with the marker) is pinned to the current head commit and leaves + * nothing open: a fresh review reporting `0 blocking`, or a verify pass + * reporting `0 open`. + * 2. A fresh review stands behind the head. A verify pass settles the threads + * an earlier review left and reviews no commits, so on its own it proves + * nothing about the code, even though its summary is pinned to the head. + * Take the newest fresh summary: + * - If it reports `0 blocking`, it must be pinned to the head commit. + * Otherwise commits pushed since it would count as reviewed when nothing + * reviewed them. + * - If it reports blocking findings, the verify passes after it must have + * resolved at least that many between them, and the pass that brings + * the running total up to that count must be pinned to the head commit. + * That pass is the last review to read the code for those findings, so + * a push after it was read by no review, and only a new fresh review can + * cover it. Those findings are inline threads, and condition 3 already + * needs every thread resolved, so the count is the cross-check for a + * finding that never became a thread, which no verify pass can see. Its + * cost: a thread someone resolves by hand is in no verify count, so it + * holds the label back until a fresh review. Commits pushed alongside + * the fixes ride on that completing pass, which re-checked only the code + * its threads point at. + * A summary between it and the newest that does not parse fails closed, + * since it may have been a fresh review with blocking findings. + * 3. Every review thread on the PR is resolved. + * 4. On the head commit, the newest check run per app and name (latestRuns) + * and the newest status per context finished as success, neutral or + * skipped, and there is at least one. The check run this workflow creates + * is left out so it cannot hold itself back. + * 5. The PR does not carry `needs-security-review`. + * + * Converged without the label adds it. Not converged with the label removes + * it. Everything else is left alone, and that includes every PR out of scope. + * + * Fail closed. A summary this cannot parse, a missing field, or a check in any + * other state reads as not converged. An API error leaves that PR's label as + * it was and fails the run, so a transient error can neither add the label nor + * strip it. + * + * Review bodies are model-authored text on a public repository. They are only + * matched against the fixed patterns below. They are never evaluated and never + * printed. Values that do reach the log (check names, status contexts, API + * error text) go through forLog first, and every line starts with a fixed + * prefix, so no value can open a workflow command. + * + * Plain node and the global fetch with no npm dependencies, because the + * workflow runs it on the runner's own Node without installing anything. Pure + * helpers are exported for the test sibling, and main only runs when the file + * is executed directly. + * + * Usage: + * GITHUB_TOKEN=... node scripts/review-converged.mjs --repo=owner/name \ + * [--pr=N] [--dry-run] + * + * Without a PR number it sweeps every open PR. --dry-run reports what it would + * do and writes nothing. + * + * Exit codes: 0 clean run, 1 an API error, 2 bad usage. + */ +import process from 'node:process'; +import { pathToFileURL } from 'node:url'; + +export const LABEL = 'review-converged'; +export const SCOPE_LABEL = 'deep-review'; +export const LOOP_LABEL = 'ai-loop'; +export const FLAG_LABEL = 'needs-security-review'; +export const MARKER = ''; + +/** + * The job name in review-converged.yml, which is also the name of the check + * run its runs create. The test sibling holds the two equal. + */ +export const OWN_CHECK_NAME = 'Sync review-converged label'; + +/** Check run conclusions that count as passing. */ +export const PASSING_CONCLUSIONS = new Set(['success', 'neutral', 'skipped']); + +/** + * The sentence the review prompt puts in place of the table when a fresh + * review found nothing of any tier. + */ +export const NO_FINDINGS_LINE = 'No blocking defects found.'; + +/** + * The summary headings, after headingText has taken off the heading markup. + * The separators are the ones the prompt asks for plus their nearest ASCII + * stand-ins. A count longer than four digits does not match. + */ +const FRESH_RE = + /^Deep review[ \t]*[—–-]{1,2}[ \t]*(\d{1,4})[ \t]+blocking[ \t]*[·•|,][ \t]*(\d{1,4})[ \t]+advisory$/i; +const VERIFY_RE = + /^Deep review[ \t]+\(verify\)[ \t]*[—–-]{1,2}[ \t]*(\d{1,4})[ \t]+resolved[ \t]*[·•|,][ \t]*(\d{1,4})[ \t]+open$/i; + +const SHA_RE = /^[0-9a-f]{40}$/; +const API_BASE = 'https://api.github.com'; +const FETCH_TIMEOUT_MS = 30_000; +const MAX_PAGES = 50; +const TAG = 'review-converged:'; + +/** Raised for a bad command line, which exits 2 rather than 1. */ +export class UsageError extends Error {} + +/** + * Render a value for a log line. JSON.stringify escapes newlines, carriage + * returns, quotes and control characters, so the value stays one line of + * inert text and cannot end the line and start a workflow command. The same + * helper as check-consumer-sbom.mjs, kept local so this script imports + * nothing. + */ +export function forLog(value) { + return JSON.stringify(String(value ?? '')); +} + +/** A commit id cut to its short form, or the value made safe to log. */ +function shortSha(sha) { + return SHA_RE.test(sha ?? '') ? sha.slice(0, 7) : forLog(sha); +} + +/** Parse argv. Throws UsageError on misuse. */ +export function parseArgs(argv) { + let repo; + let pr = null; + let dryRun = false; + for (const arg of argv) { + if (arg.startsWith('--repo=')) repo = arg.slice('--repo='.length); + else if (arg.startsWith('--pr=')) { + // Empty means sweep, so the workflow can always pass its input. + const value = arg.slice('--pr='.length); + if (value !== '') { + if (!/^[1-9]\d{0,9}$/.test(value)) + throw new UsageError( + `--pr must be a PR number, got ${forLog(value)}` + ); + pr = Number(value); + } + } else if (arg === '--dry-run') dryRun = true; + else throw new UsageError(`unknown argument ${forLog(arg)}`); + } + if (!repo || !/^[\w.-]+\/[\w.-]+$/.test(repo)) + throw new UsageError('--repo=owner/name is required'); + return { repo, pr, dryRun }; +} + +/** + * True for the Claude GitHub App. The login alone is not enough: `claude` + * with no suffix is an ordinary User account on GitHub, so the account type + * is what ties a review to the app. REST spells the app `claude[bot]` and + * GraphQL spells it `claude`, and both carry type Bot. + * + * Pinning the login goes against rule 6 in .github/CLAUDE.md on purpose. That + * rule is for finding a machine comment. This probe grants trust instead, + * because the label certifies a review. Accepting any Bot-type author would + * let any app that can post a review, or a workflow's GITHUB_TOKEN, post a + * summary that counts by putting the marker on its first line. An identity + * change fails closed: no summary counts, so no PR converges. + */ +export function isDeepReviewAuthor(user) { + return user?.type === 'Bot' && /^claude(\[bot\])?$/.test(user.login ?? ''); +} + +/** + * The deep-review summaries in a PR's reviews, oldest first. A summary is a + * review by the app whose body contains the marker anywhere. parseSummary then + * requires the marker on the first line, so a review that only quotes it reads + * as unparseable instead of being skipped. + */ +export function summaries(reviews) { + const found = []; + for (const review of reviews ?? []) { + if (!isDeepReviewAuthor(review?.user)) continue; + if (typeof review.body !== 'string' || !review.body.includes(MARKER)) + continue; + // A pending review has no submitted_at and is not visible to us anyway. + const at = Date.parse(review.submitted_at ?? ''); + if (Number.isFinite(at)) found.push({ review, at }); + } + // Same second: the higher id is the later review. A missing id compares as + // NaN, which sort treats as equal, so the API's own order stands. + found.sort((a, b) => a.at - b.at || a.review.id - b.review.id); + return found.map(entry => entry.review); +} + +/** The newest deep-review summary, or null. */ +export function newestSummary(reviews) { + return summaries(reviews).at(-1) ?? null; +} + +/** + * The text of a heading line with its markup taken off. Covers the shapes the + * deep review has posted: an ATX heading (`## ...`), an HTML heading + * (`

...

`), and a bare line, which is how a setext heading's first + * line reads. Bold wrapping is taken off too. + */ +function headingText(line) { + let text = line.trim(); + const atx = /^#{1,6}[ \t]+(.*?)(?:[ \t]+#+)?$/.exec(text); + const html = /^(.*)<\/h\1>$/i.exec(text); + if (atx) text = atx[1]; + else if (html) text = html[2]; + text = text.trim(); + const bold = /^\*\*(.+)\*\*$/.exec(text); + return bold ? bold[1].trim() : text; +} + +/** + * Read a summary body. Returns one of + * { kind: 'fresh', blocking, advisory } + * { kind: 'verify', resolved, open } + * { kind: 'unparseable', why } + * The heading is the first non-blank line after the marker line. + */ +export function parseSummary(body) { + const lines = String(body ?? '').split(/\r?\n/); + if (lines[0].trim() !== MARKER) + return { kind: 'unparseable', why: 'the marker is not its first line' }; + const at = lines.findIndex((line, i) => i > 0 && line.trim() !== ''); + if (at === -1) return { kind: 'unparseable', why: 'it has no heading' }; + const heading = headingText(lines[at]); + const fresh = FRESH_RE.exec(heading); + if (fresh) { + const blocking = Number(fresh[1]); + // The zero-findings sentence beside a heading that counts blocking + // findings is a contradiction, and a contradiction is not a zero. + if (blocking > 0 && lines.some(line => line.trim() === NO_FINDINGS_LINE)) + return { + kind: 'unparseable', + why: `its heading counts blocking findings beside "${NO_FINDINGS_LINE}"`, + }; + return { kind: 'fresh', blocking, advisory: Number(fresh[2]) }; + } + const verify = VERIFY_RE.exec(heading); + if (verify) + return { + kind: 'verify', + resolved: Number(verify[1]), + open: Number(verify[2]), + }; + return { kind: 'unparseable', why: 'its heading matches neither shape' }; +} + +/** The label names on a PR, ignoring anything that is not a string. */ +export function labelNames(pr) { + return (pr?.labels ?? []) + .map(label => label?.name) + .filter(name => typeof name === 'string'); +} + +/** + * Why a PR is out of scope, or null when it is in scope. `defaultBranch` is + * the repository's, read once per run. Without it the PR is out of scope + * rather than in: skipping the base check when a caller forgets the argument + * would reopen the stacked-PR gap silently, and out of scope leaves the label + * as it was instead of guessing either way. + */ +export function scopeOf(pr, repo, defaultBranch) { + const labels = labelNames(pr); + if (pr?.state !== 'open') return 'not open'; + // A fork whose repository was deleted has a null head repo, and lands here. + const head = String(pr?.head?.repo?.full_name ?? '').toLowerCase(); + if (head !== repo.toLowerCase()) return 'head branch is not in this repo'; + if (typeof defaultBranch !== 'string' || defaultBranch === '') + return 'the default branch is unknown'; + if (pr?.base?.ref !== defaultBranch) + return `based on ${forLog(pr?.base?.ref)}, not ${forLog(defaultBranch)}`; + if (!labels.includes(SCOPE_LABEL)) return `no ${SCOPE_LABEL} label`; + if (labels.includes(LOOP_LABEL)) + return `${LOOP_LABEL} PR, which claude-pr-loop.yml hands off`; + return null; +} + +/** + * True for a check run this workflow created. workflow_run, schedule and a + * dispatch from main run on the default branch's commit, so theirs never + * reach a PR head. A dispatch started from a PR's own branch runs on that + * branch's tip, so this job's check run sits on the head, still running, + * while the script judges it. + */ +function isOwnCheck(run) { + return run?.name === OWN_CHECK_NAME && run?.app?.slug === 'github-actions'; +} + +/** + * The newest check run per app and name. A commit keeps the check runs of + * every workflow run on it, so one that a later run of the same workflow + * replaced is still listed: cancelling a deep review and toggling the label + * leaves a cancelled `review` beside the fresh one. Newest is the latest + * started_at, then the higher id. + * + * A check run does not name its workflow, and some job names are shared + * between workflows, so one key can hold runs of more than one workflow. A + * skipped run therefore wins only when every run under its key was skipped, + * so a same-named job skipped on a later event cannot hide a failure. A newer + * same-named job that ran still decides. + */ +export function latestRuns(checkRuns) { + const byKey = new Map(); + for (const run of checkRuns ?? []) { + const key = JSON.stringify([ + String(run?.app?.slug ?? ''), + String(run?.name ?? ''), + ]); + const rank = [ + run?.conclusion === 'skipped' ? 0 : 1, + Date.parse(run?.started_at ?? '') || 0, + run?.id ?? 0, + ]; + const prev = byKey.get(key); + if (!prev || outranks(rank, prev.rank)) byKey.set(key, { run, rank }); + } + return [...byKey.values()].map(entry => entry.run); +} + +/** True when rank `a` is greater than `b`, comparing in order. */ +function outranks(a, b) { + const at = a.findIndex((value, i) => value !== b[i]); + return at !== -1 && a[at] > b[at]; +} + +/** + * The newest status per context. The combined status endpoint already + * returns one per context, and this keeps the answer right if it ever + * returns more. + */ +export function latestStatuses(statuses) { + const byContext = new Map(); + for (const status of statuses ?? []) { + const key = String(status?.context ?? ''); + const at = Date.parse(status?.updated_at ?? status?.created_at ?? '') || 0; + const prev = byContext.get(key); + if ( + !prev || + at > prev.at || + (at === prev.at && (status?.id ?? 0) > (prev.status?.id ?? 0)) + ) + byContext.set(key, { status, at }); + } + return [...byContext.values()].map(entry => entry.status); +} + +/** Everything about the head commit's checks that stops convergence. */ +export function checkProblems(checkRuns, statuses) { + const problems = []; + const runs = latestRuns((checkRuns ?? []).filter(run => !isOwnCheck(run))); + for (const run of runs) { + if (run?.status !== 'completed') + problems.push(`check ${forLog(run?.name)} is ${forLog(run?.status)}`); + else if (!PASSING_CONCLUSIONS.has(run.conclusion)) + problems.push( + `check ${forLog(run.name)} concluded ${forLog(run.conclusion)}` + ); + } + const latest = latestStatuses(statuses); + for (const status of latest) { + if (status?.state !== 'success') + problems.push( + `status ${forLog(status?.context)} is ${forLog(status?.state)}` + ); + } + // Nothing reported yet is not the same as everything passed. + if (!runs.length && !latest.length) + problems.push('no check runs or statuses on the head commit'); + return problems; +} + +/** + * Condition 2 in the header: what stops the newest fresh review from standing + * behind the head. `found` is summaries() with each one parsed, oldest first. + * When the newest fresh summary is also the newest summary, condition 1 has + * already judged it and this adds nothing. + */ +function freshProblems(found, head) { + let at = found.length - 1; + while (at >= 0 && found[at].parsed.kind !== 'fresh') at--; + if (at === -1) + return ['no fresh deep review, and a verify pass reviews no code']; + const after = found.slice(at + 1); + if (!after.length) return []; + const problems = []; + // The newest summary's own parse is condition 1's to report. + if (after.slice(0, -1).some(entry => entry.parsed.kind === 'unparseable')) + problems.push('a summary after the newest fresh review did not parse'); + const { review, parsed } = found[at]; + if (parsed.blocking === 0) { + if (review.commit_id !== head) + problems.push( + `the newest fresh review is for ${shortSha(review.commit_id)}, and ` + + 'no fresh review covers the commits since' + ); + return problems; + } + // Walk the verify passes in order to the one whose running total first + // reaches the blocking count. It must be pinned to the head. A pass after + // it adds no review of the commits in between, so it cannot stand in. + let resolved = 0; + for (const entry of after) { + if (entry.parsed.kind !== 'verify') continue; + resolved += entry.parsed.resolved; + if (resolved < parsed.blocking) continue; + // When it is the newest summary, condition 1 has judged its commit. + if (entry !== after.at(-1) && entry.review.commit_id !== head) + problems.push( + 'the verify pass that resolved the last of the newest fresh ' + + `review's findings is for ${shortSha(entry.review.commit_id)}, ` + + 'and no fresh review covers the commits since' + ); + return problems; + } + problems.push( + `the newest fresh review reports ${parsed.blocking} blocking and the ` + + `verify passes since resolved ${resolved}` + ); + return problems; +} + +/** Every reason an in-scope PR has not converged. Empty means converged. */ +export function convergenceProblems({ + pr, + reviews, + threads, + checkRuns, + statuses, +}) { + const problems = []; + const head = pr?.head?.sha; + const found = summaries(reviews).map(review => ({ + review, + parsed: parseSummary(review.body), + })); + const newest = found.at(-1); + if (!newest) problems.push('no deep-review summary'); + else { + const { review, parsed } = newest; + if (!SHA_RE.test(head ?? '') || review.commit_id !== head) + problems.push( + `the newest summary is for ${shortSha(review.commit_id)}, ` + + `not the head ${shortSha(head)}` + ); + if (parsed.kind === 'unparseable') + problems.push(`the newest summary did not parse: ${parsed.why}`); + else if (parsed.kind === 'fresh' && parsed.blocking > 0) + problems.push(`the newest summary reports ${parsed.blocking} blocking`); + else if (parsed.kind === 'verify' && parsed.open > 0) + problems.push(`the newest summary leaves ${parsed.open} open`); + problems.push(...freshProblems(found, head)); + } + // A thread with no isResolved field counts as open. + const unresolved = (threads ?? []).filter(t => t?.isResolved !== true); + if (unresolved.length) + problems.push(`${unresolved.length} unresolved review thread(s)`); + problems.push(...checkProblems(checkRuns, statuses)); + problems.push(...flagProblems(pr)); + return problems; +} + +/** + * Condition 5 in the header. apply() asks it again of the PR as re-read, so a + * flag that lands after the evaluation stops an add the same way. + */ +function flagProblems(pr) { + return labelNames(pr).includes(FLAG_LABEL) ? [`carries ${FLAG_LABEL}`] : []; +} + +/** 'add', 'remove' or 'none'. */ +export function planAction(hasLabel, converged) { + if (converged && !hasLabel) return 'add'; + if (!converged && hasLabel) return 'remove'; + return 'none'; +} + +/** + * The whole decision for one PR over data already fetched. Returns + * { number, skip, problems, action }, where skip is the out-of-scope reason + * or null. + */ +export function decide({ + repo, + defaultBranch, + pr, + reviews, + threads, + checkRuns, + statuses, +}) { + const number = pr?.number; + const skip = scopeOf(pr, repo, defaultBranch); + if (skip) return { number, skip, problems: [], action: 'none' }; + const problems = convergenceProblems({ + pr, + reviews, + threads, + checkRuns, + statuses, + }); + const hasLabel = labelNames(pr).includes(LABEL); + return { + number, + skip: null, + problems, + action: planAction(hasLabel, problems.length === 0), + }; +} + +// --------------------------------------------------------------------------- +// GitHub API client. The token only ever goes to API_BASE: a pagination link +// pointing anywhere else is refused. +// --------------------------------------------------------------------------- + +/** The rel="next" URL in a Link header, or null. */ +export function nextLink(header) { + return /<([^>]+)>;\s*rel="next"/.exec(header ?? '')?.[1] ?? null; +} + +export function createClient({ + token, + fetchImpl = globalThis.fetch, + base = API_BASE, +}) { + async function request(method, url, body, allowed = []) { + const full = url.startsWith(`${base}/`) ? url : `${base}${url}`; + if (!full.startsWith(`${base}/`)) + throw new Error(`refusing a request outside ${base}`); + const res = await fetchImpl(full, { + method, + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'bestax-review-converged', + ...(body ? { 'Content-Type': 'application/json' } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + // A hung request must not hold the run until the job timeout. + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + if (!res.ok && !allowed.includes(res.status)) { + const text = await res.text().catch(() => ''); + throw new Error( + `${method} ${url} failed with HTTP ${res.status} ` + + forLog(text.slice(0, 200)) + ); + } + return res; + } + + return { + async json(path) { + return (await request('GET', path)).json(); + }, + + /** Every item across pages, taken from `key` when the page is an object. */ + async pages(path, key) { + const items = []; + let url = path; + for (let page = 0; url; page++) { + if (page >= MAX_PAGES) + throw new Error(`GET ${path} ran past ${MAX_PAGES} pages`); + const res = await request('GET', url); + const data = await res.json(); + const list = key ? data?.[key] : data; + if (!Array.isArray(list)) + throw new Error(`GET ${path} returned no ${key ?? 'array'}`); + items.push(...list); + url = nextLink(res.headers.get('link')); + if (url && !url.startsWith(`${base}/`)) + throw new Error(`GET ${path} paginated off ${base}, refusing`); + } + return items; + }, + + async graphql(query, variables) { + const res = await request('POST', '/graphql', { query, variables }); + const data = await res.json(); + if (data?.errors?.length || !data?.data) + throw new Error( + `GraphQL query failed: ${forLog(data?.errors?.[0]?.message)}` + ); + return data.data; + }, + + async addLabel(repo, number, label) { + await request('POST', `/repos/${repo}/issues/${number}/labels`, { + labels: [label], + }); + }, + + /** A label that is already gone is not an error. */ + async removeLabel(repo, number, label) { + await request( + 'DELETE', + `/repos/${repo}/issues/${number}/labels/${encodeURIComponent(label)}`, + undefined, + [404] + ); + }, + }; +} + +const THREADS_QUERY = `query($owner: String!, $name: String!, $number: Int!, $after: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + reviewThreads(first: 100, after: $after) { + pageInfo { hasNextPage endCursor } + nodes { isResolved } + } + } + } +}`; + +/** Every review thread on a PR, as { isResolved } nodes. */ +export async function fetchThreads(client, repo, number) { + const [owner, name] = repo.split('/'); + const threads = []; + let after = null; + for (let page = 0; page < MAX_PAGES; page++) { + const data = await client.graphql(THREADS_QUERY, { + owner, + name, + number, + after, + }); + const conn = data?.repository?.pullRequest?.reviewThreads; + if (!conn || !Array.isArray(conn.nodes)) + throw new Error('the GraphQL response has no reviewThreads'); + threads.push(...conn.nodes); + if (!conn.pageInfo?.hasNextPage) return threads; + const cursor = conn.pageInfo.endCursor; + if (!cursor || cursor === after) + throw new Error('reviewThreads pagination did not advance'); + after = cursor; + } + throw new Error(`reviewThreads ran past ${MAX_PAGES} pages`); +} + +/** Fetch what decide needs for one PR and decide. */ +export async function evaluate(client, repo, pr, defaultBranch) { + if (scopeOf(pr, repo, defaultBranch)) + return decide({ repo, defaultBranch, pr }); + const sha = pr.head.sha; + if (!SHA_RE.test(sha ?? '')) throw new Error('the head is not a commit id'); + const reviews = await client.pages( + `/repos/${repo}/pulls/${pr.number}/reviews?per_page=100` + ); + const threads = await fetchThreads(client, repo, pr.number); + const checkRuns = await client.pages( + `/repos/${repo}/commits/${sha}/check-runs?per_page=100`, + 'check_runs' + ); + const statuses = await client.pages( + `/repos/${repo}/commits/${sha}/status?per_page=100`, + 'statuses' + ); + return decide({ + repo, + defaultBranch, + pr, + reviews, + threads, + checkRuns, + statuses, + }); +} + +/** + * Apply a decision. The PR is read again before either write, dry run + * included. The write is dropped as stale when the state it was decided on is + * gone: scopeOf no longer accepts the PR (closed, a new base, `deep-review` + * removed or `ai-loop` added), or its head moved. So a PR that left scope + * while it was evaluated keeps its label, as every out-of-scope PR does, and a + * later run judges a moved head. An add is also dropped when the PR now + * carries `needs-security-review`, read by the same flagProblems the + * evaluation used. A removal goes ahead then, since the flag only stops + * convergence. + */ +async function apply(client, repo, defaultBranch, pr, decision, dryRun) { + const now = await client.json(`/repos/${repo}/pulls/${pr.number}`); + if (scopeOf(now, repo, defaultBranch) || now.head?.sha !== pr.head.sha) + return 'stale'; + const hasLabel = labelNames(now).includes(LABEL); + if (decision.action === 'add') { + if (flagProblems(now).length) return 'stale'; + if (hasLabel) return 'already set'; + } else if (!hasLabel) return 'already gone'; + if (dryRun) return 'dry run, not written'; + if (decision.action === 'add') await client.addLabel(repo, pr.number, LABEL); + else await client.removeLabel(repo, pr.number, LABEL); + return 'written'; +} + +/** Summarize problems for one log line, capped so a long list stays short. */ +function describe(problems) { + const shown = problems.slice(0, 5).join(', '); + const more = problems.length - 5; + return more > 0 ? `${shown}, and ${more} more` : shown; +} + +/** + * Run the sync. Returns the exit code. `fetchImpl` and `log` are injectable so + * the test sibling can drive it end to end without the network. + */ +export async function run({ + argv, + env, + fetchImpl = globalThis.fetch, + log = console.log, +}) { + const { repo, pr: only, dryRun } = parseArgs(argv); + if (!env.GITHUB_TOKEN) throw new UsageError('GITHUB_TOKEN is not set'); + const client = createClient({ token: env.GITHUB_TOKEN, fetchImpl }); + // Read once per run. A failure here throws before any PR is looked at, so + // the run fails and no label is touched. + const defaultBranch = (await client.json(`/repos/${repo}`))?.default_branch; + if (typeof defaultBranch !== 'string' || defaultBranch === '') + throw new Error(`/repos/${repo} returned no default_branch`); + const prs = only + ? [await client.json(`/repos/${repo}/pulls/${only}`)] + : await client.pages(`/repos/${repo}/pulls?state=open&per_page=100`); + + log( + `${TAG} repo=${repo} ${only ? `pr=${only}` : 'sweep'}` + + (dryRun ? ' dry-run' : '') + ); + let failed = 0; + for (const pr of prs) { + const number = Number(pr?.number); + try { + const decision = await evaluate(client, repo, pr, defaultBranch); + const labels = labelNames(pr); + if (decision.skip) { + // A sweep passes every open PR, so only name the ones that have + // something to do with this label. + if (only || labels.includes(SCOPE_LABEL) || labels.includes(LABEL)) + log(`${TAG} #${number} skipped (${decision.skip})`); + continue; + } + const state = decision.problems.length + ? `not converged: ${describe(decision.problems)}` + : 'converged'; + if (decision.action === 'none') { + log(`${TAG} #${number} ${state}, label unchanged`); + continue; + } + const outcome = await apply( + client, + repo, + defaultBranch, + pr, + decision, + dryRun + ); + log(`${TAG} #${number} ${state}, ${decision.action} label: ${outcome}`); + // A notice carries only the PR number and fixed text. + if (outcome === 'written') + log( + `::notice title=${LABEL}::#${number} ${decision.action === 'add' ? 'labeled' : 'unlabeled'}` + ); + } catch (err) { + failed++; + log( + `${TAG} #${number} error, label left as it was: ${forLog(err?.message)}` + ); + } + } + return failed ? 1 : 0; +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + run({ argv: process.argv.slice(2), env: process.env }).then( + code => { + process.exitCode = code; + }, + err => { + const usage = err instanceof UsageError; + console.error( + `${TAG} ${usage ? 'usage error: ' : ''}${forLog(err?.message)}` + ); + process.exitCode = usage ? 2 : 1; + } + ); +} diff --git a/scripts/review-converged.test.mjs b/scripts/review-converged.test.mjs new file mode 100644 index 000000000..1ab52ae4e --- /dev/null +++ b/scripts/review-converged.test.mjs @@ -0,0 +1,1595 @@ +/** + * Guards on the review-converged label sync (review-converged.mjs). + * + * The decision is a pure function over fetched data, so most of this file + * hands it fixtures and checks the verdict. The heading fixtures are the + * shapes real deep-review summaries on this repository have used, because a + * shape the parser misses fails closed and the label never appears. The end + * of the file drives run() against a fake fetch, so the label writes, the + * dry run and the re-read before each write are covered without the network, + * and reads review-converged.yml so the names and the trigger it shares with + * the script cannot drift apart. + * + * `.mjs` and `node --test` rather than jest: these are root-level scripts with + * no package of their own, matching auto-close-duplicates.test.mjs. + */ +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import assert from 'node:assert/strict'; +import { + FLAG_LABEL, + LABEL, + MARKER, + NO_FINDINGS_LINE, + OWN_CHECK_NAME, + UsageError, + checkProblems, + convergenceProblems, + createClient, + decide, + fetchThreads, + forLog, + isDeepReviewAuthor, + labelNames, + latestRuns, + latestStatuses, + newestSummary, + nextLink, + parseArgs, + parseSummary, + planAction, + run, + scopeOf, +} from './review-converged.mjs'; +import { yamlGet, yamlItems, yamlScalar } from './check-conformance.mjs'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const ROOT = join(HERE, '..'); +const SCRIPT = join(HERE, 'review-converged.mjs'); +const REPO = 'allxsmith/bestax'; +const HEAD = 'a'.repeat(40); +const OLD = 'b'.repeat(40); +const MID = 'c'.repeat(40); +const BOT = { login: 'claude[bot]', type: 'Bot' }; + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +function pr(overrides = {}) { + const { labels = ['deep-review'], ...rest } = overrides; + return { + number: 870, + state: 'open', + head: { sha: HEAD, repo: { full_name: REPO } }, + base: { ref: 'main' }, + labels: labels.map(name => ({ name })), + ...rest, + }; +} + +function summary(body, overrides = {}) { + return { + id: 2, + user: BOT, + body, + commit_id: HEAD, + submitted_at: '2026-10-03T12:00:00Z', + state: 'COMMENTED', + ...overrides, + }; +} + +const FRESH_CLEAN = `${MARKER}\n## Deep review — 0 blocking · 5 advisory\n\n| # |`; +const VERIFY_CLEAN = `${MARKER}\n\n## Deep review (verify) — 2 resolved · 0 open\n`; + +/** A clean fresh review on the head, posted before the summary() default. */ +const EARLIER = summary(FRESH_CLEAN, { + id: 1, + submitted_at: '2026-10-03T10:00:00Z', +}); + +const GREEN_RUN = { + name: 'Build and Test', + status: 'completed', + conclusion: 'success', + app: { slug: 'github-actions' }, +}; +const GREEN_STATUS = { + context: 'CodeRabbit', + state: 'success', + updated_at: '2026-10-03T12:00:00Z', +}; + +function converged(overrides = {}) { + return { + repo: REPO, + defaultBranch: 'main', + pr: pr(), + reviews: [summary(FRESH_CLEAN)], + threads: [{ isResolved: true }], + checkRuns: [GREEN_RUN], + statuses: [GREEN_STATUS], + ...overrides, + }; +} + +// --------------------------------------------------------------------------- +// parseArgs and forLog +// --------------------------------------------------------------------------- + +test('parseArgs reads the repo, an optional PR and the dry-run flag', () => { + assert.deepEqual(parseArgs([`--repo=${REPO}`]), { + repo: REPO, + pr: null, + dryRun: false, + }); + assert.deepEqual(parseArgs([`--repo=${REPO}`, '--pr=870', '--dry-run']), { + repo: REPO, + pr: 870, + dryRun: true, + }); + // The workflow always passes --pr, empty outside a dispatch. + assert.equal(parseArgs([`--repo=${REPO}`, '--pr=']).pr, null); +}); + +test('parseArgs refuses anything else', () => { + for (const argv of [ + [], + ['--repo=nope'], + ['--repo=a/b c'], + [`--repo=${REPO}`, '--pr=0'], + [`--repo=${REPO}`, '--pr=12a'], + [`--repo=${REPO}`, '--pr=-1'], + [`--repo=${REPO}`, '--sweep'], + ]) { + assert.throws(() => parseArgs(argv), UsageError, argv.join(' ')); + } +}); + +test('forLog keeps a value on one inert line', () => { + assert.equal(forLog('a\n::error::x'), '"a\\n::error::x"'); + assert.equal(forLog(undefined), '""'); + assert.ok(!forLog('x\r\ny').includes('\n')); +}); + +// --------------------------------------------------------------------------- +// Who wrote the summary, and which one is newest +// --------------------------------------------------------------------------- + +test('only the Claude app counts as the deep reviewer', () => { + assert.equal(isDeepReviewAuthor(BOT), true); + assert.equal(isDeepReviewAuthor({ login: 'claude', type: 'Bot' }), true); + // `claude` is also an ordinary User account on GitHub. + assert.equal(isDeepReviewAuthor({ login: 'claude', type: 'User' }), false); + assert.equal( + isDeepReviewAuthor({ login: 'claude[bot]', type: 'User' }), + false + ); + assert.equal( + isDeepReviewAuthor({ login: 'coderabbitai[bot]', type: 'Bot' }), + false + ); + assert.equal(isDeepReviewAuthor({ type: 'Bot' }), false); + assert.equal(isDeepReviewAuthor(null), false); +}); + +test('newestSummary picks the newest marker review by the app', () => { + const older = summary(FRESH_CLEAN, { + id: 1, + submitted_at: '2026-10-03T10:00:00Z', + }); + const newer = summary(VERIFY_CLEAN, { id: 9 }); + assert.equal(newestSummary([newer, older]), newer); + assert.equal(newestSummary([older, newer]), newer); + // Same second: the higher id is the later review. + const twin = summary(FRESH_CLEAN, { id: 10 }); + assert.equal(newestSummary([twin, newer]), twin); +}); + +test('newestSummary ignores reviews that are not summaries', () => { + const later = '2026-10-03T13:00:00Z'; + const real = summary(FRESH_CLEAN); + const noise = [ + summary(FRESH_CLEAN, { user: { login: 'claude', type: 'User' } }), + summary('', { submitted_at: later }), + summary('inline finding', { submitted_at: later }), + summary(FRESH_CLEAN, { submitted_at: null }), + summary(null, { submitted_at: later }), + null, + ]; + assert.equal(newestSummary([real, ...noise]), real); + assert.equal(newestSummary(noise), null); + assert.equal(newestSummary(undefined), null); +}); + +// --------------------------------------------------------------------------- +// parseSummary +// --------------------------------------------------------------------------- + +test('parseSummary reads every heading shape the deep review has used', () => { + const fresh = (blocking, advisory) => ({ + kind: 'fresh', + blocking, + advisory, + }); + const verify = (resolved, open) => ({ kind: 'verify', resolved, open }); + const cases = [ + ['## Deep review — 0 blocking · 5 advisory', fresh(0, 5)], + ['## Deep review — 2 blocking · 5 advisory', fresh(2, 5)], + ['

Deep review — 0 blocking · 5 advisory

', fresh(0, 5)], + ['Deep review — 1 blocking · 6 advisory\n---', fresh(1, 6)], + ['Deep review — 0 blocking · 3 advisory\n===', fresh(0, 3)], + ['## Deep review (verify) — 2 resolved · 0 open', verify(2, 0)], + ['

Deep review (verify) — 1 resolved · 0 open

', verify(1, 0)], + ['Deep review (verify) — 1 resolved · 0 open\n------', verify(1, 0)], + ['## Deep review (verify) — 0 resolved · 3 open', verify(0, 3)], + // Close variants of the same heading. + ['### Deep review – 0 blocking · 1 advisory ###', fresh(0, 1)], + ['**Deep review - 0 blocking | 2 advisory**', fresh(0, 2)], + ['# deep review -- 0 blocking, 0 advisory', fresh(0, 0)], + ]; + for (const [heading, want] of cases) { + assert.deepEqual(parseSummary(`${MARKER}\n${heading}\n\n| x |`), want); + // A blank line after the marker and CRLF line ends read the same. + assert.deepEqual( + parseSummary(`${MARKER}\r\n\r\n${heading.replace(/\n/g, '\r\n')}`), + want, + heading + ); + } +}); + +test('the zero-findings form reads as zero blocking', () => { + const body = `${MARKER}\n## Deep review — 0 blocking · 0 advisory\n\n${NO_FINDINGS_LINE}\n\n**Overall:** fine.`; + assert.deepEqual(parseSummary(body), { + kind: 'fresh', + blocking: 0, + advisory: 0, + }); +}); + +test('parseSummary fails closed on anything it cannot read', () => { + const unparseable = body => { + const got = parseSummary(body); + assert.equal(got.kind, 'unparseable', JSON.stringify(body)); + assert.equal(typeof got.why, 'string'); + }; + unparseable(''); + unparseable(undefined); + unparseable(`\n${MARKER}\n## Deep review — 0 blocking · 0 advisory`); + unparseable(`quoted ${MARKER}\n## Deep review — 0 blocking · 0 advisory`); + unparseable(`${MARKER}\n\n \n`); + unparseable(`${MARKER}\n## Deep review`); + unparseable(`${MARKER}\n## Deep review — no blocking · 0 advisory`); + unparseable(`${MARKER}\n## Deep review — 0 blocking · 0 advisory, honest`); + unparseable(`${MARKER}\n## Deep review — 12345 blocking · 0 advisory`); + unparseable(`${MARKER}\n## Deep review (verify) — 1 resolved`); + unparseable( + `${MARKER}\n| # | Severity |\n## Deep review — 0 blocking · 0 advisory` + ); + // A heading that counts blocking findings beside the zero-findings line + // contradicts itself. + unparseable( + `${MARKER}\n## Deep review — 2 blocking · 0 advisory\n\n${NO_FINDINGS_LINE}` + ); +}); + +// --------------------------------------------------------------------------- +// Scope +// --------------------------------------------------------------------------- + +test('scopeOf keeps open same-repo deep-review PRs on main outside the loop', () => { + const scope = (p, branch = 'main') => scopeOf(p, REPO, branch); + assert.equal(scope(pr()), null); + assert.equal( + scope(pr({ head: { sha: HEAD, repo: { full_name: 'AllxSmith/Bestax' } } })), + null + ); + assert.equal(scope(pr({ state: 'closed' })), 'not open'); + assert.equal(scope(undefined), 'not open'); + assert.equal( + scope(pr({ head: { sha: HEAD, repo: { full_name: 'fork/bestax' } } })), + 'head branch is not in this repo' + ); + assert.equal( + scope(pr({ head: { sha: HEAD, repo: null } })), + 'head branch is not in this repo' + ); + assert.equal(scope(pr({ labels: [] })), 'no deep-review label'); + assert.match( + scope(pr({ labels: ['deep-review', 'ai-loop'] })), + /^ai-loop PR/ + ); +}); + +test('a PR stacked on another branch is out of scope', () => { + // CI runs only on pull requests to main, so a stacked PR has no CI to judge. + assert.equal( + scopeOf(pr({ base: { ref: 'feat/base' } }), REPO, 'main'), + 'based on "feat/base", not "main"' + ); + assert.equal( + scopeOf(pr({ base: undefined }), REPO, 'main'), + 'based on "", not "main"' + ); + // A base name reaches the reason escaped. + assert.ok( + !scopeOf(pr({ base: { ref: 'x\n::error::y' } }), REPO, 'main').includes( + '\n' + ) + ); + // The same PR is in scope when its base is the default branch. + assert.equal(scopeOf(pr({ base: { ref: 'trunk' } }), REPO, 'trunk'), null); +}); + +test('without the default branch every open same-repo PR is out of scope', () => { + for (const branch of [undefined, null, '', 7]) + assert.equal( + scopeOf(pr(), REPO, branch), + 'the default branch is unknown', + String(branch) + ); + assert.deepEqual( + decide( + converged({ + defaultBranch: undefined, + pr: pr({ labels: ['deep-review', LABEL] }), + }) + ), + { + number: 870, + skip: 'the default branch is unknown', + problems: [], + action: 'none', + } + ); +}); + +test('labelNames skips labels without a string name', () => { + assert.deepEqual( + labelNames({ labels: [{ name: 'a' }, { name: 3 }, null, {}] }), + ['a'] + ); + assert.deepEqual(labelNames(undefined), []); +}); + +// --------------------------------------------------------------------------- +// Checks and statuses +// --------------------------------------------------------------------------- + +test('checks pass only when every one finished well', () => { + const run = (status, conclusion, name = 'x') => ({ + name, + status, + conclusion, + app: { slug: 'github-actions' }, + }); + assert.deepEqual( + checkProblems( + [ + run('completed', 'success', 'a'), + run('completed', 'neutral', 'b'), + run('completed', 'skipped', 'c'), + ], + [] + ), + [] + ); + for (const conclusion of [ + 'failure', + 'cancelled', + 'timed_out', + 'action_required', + 'stale', + null, + ]) { + assert.equal( + checkProblems([run('completed', conclusion)], []).length, + 1, + String(conclusion) + ); + } + for (const status of ['queued', 'in_progress', 'waiting', 'pending']) { + assert.match( + checkProblems([run(status, null)], [])[0], + new RegExp(`is "${status}"`) + ); + } +}); + +test('this workflow’s own check run is left out, and only that one', () => { + const own = { + name: OWN_CHECK_NAME, + status: 'in_progress', + conclusion: null, + app: { slug: 'github-actions' }, + }; + assert.deepEqual(checkProblems([own, GREEN_RUN], []), []); + // Leaving it out leaves nothing, and nothing is not a pass. + assert.deepEqual(checkProblems([own], []), [ + 'no check runs or statuses on the head commit', + ]); + // The same name from another app still counts. + assert.equal( + checkProblems([{ ...own, app: { slug: 'other' } }, GREEN_RUN], []).length, + 1 + ); +}); + +test('statuses pass only on success, newest per context', () => { + assert.deepEqual(checkProblems([], [GREEN_STATUS]), []); + for (const state of ['pending', 'failure', 'error', undefined]) { + assert.equal( + checkProblems([], [{ ...GREEN_STATUS, state }]).length, + 1, + String(state) + ); + } + const stale = { + ...GREEN_STATUS, + state: 'pending', + updated_at: '2026-10-03T11:00:00Z', + }; + assert.deepEqual(checkProblems([], [stale, GREEN_STATUS]), []); + assert.deepEqual(checkProblems([], [GREEN_STATUS, stale]), []); +}); + +/** A deep-review check run, as GitHub lists one on the head commit. */ +const reviewRun = (id, startedAt, conclusion) => ({ + id, + name: 'review', + status: 'completed', + conclusion, + started_at: `2026-10-03T${startedAt}Z`, + app: { slug: 'github-actions' }, +}); + +test('a deep review cancelled and then run again converges', () => { + // PR #879's head: the review was cancelled for a re-steer, and the label + // toggle ran a fresh one that succeeded. The cancelled run stays listed. + const cancelled = reviewRun(111230277145, '15:14:03', 'cancelled'); + const fresh = reviewRun(111232410036, '15:26:25', 'success'); + for (const checkRuns of [ + [GREEN_RUN, cancelled, fresh], + [fresh, GREEN_RUN, cancelled], + ]) { + const latest = latestRuns(checkRuns); + assert.equal(latest.length, 2); + assert.ok(latest.includes(GREEN_RUN) && latest.includes(fresh)); + assert.deepEqual(convergenceProblems(converged({ checkRuns })), []); + } +}); + +test('a newer failure of the same check is not hidden by an older success', () => { + const passed = reviewRun(1, '15:14:03', 'success'); + const failed = reviewRun(2, '15:26:25', 'failure'); + for (const checkRuns of [ + [passed, failed], + [failed, passed], + ]) + assert.deepEqual(convergenceProblems(converged({ checkRuns })), [ + 'check "review" concluded "failure"', + ]); +}); + +test('a skipped run only stands in when every run under its name was skipped', () => { + // Some job names are shared between workflows, and a skipped `gate` from one + // of them must not hide a failed `gate` that ran. + const failed = { ...reviewRun(1, '15:14:03', 'failure'), name: 'gate' }; + const skipped = { ...reviewRun(2, '15:26:25', 'skipped'), name: 'gate' }; + assert.deepEqual(latestRuns([failed, skipped]), [failed]); + assert.deepEqual(latestRuns([skipped, failed]), [failed]); + const later = { ...skipped, id: 3, started_at: '2026-10-03T15:30:00Z' }; + assert.deepEqual(latestRuns([later, skipped]), [later]); +}); + +test('latestRuns keys by app and name, and breaks a tie by id', () => { + const a = reviewRun(1, '15:00:00', 'failure'); + const b = reviewRun(2, '15:00:00', 'success'); + assert.deepEqual(latestRuns([a, b]), [b]); + assert.deepEqual(latestRuns([b, a]), [b]); + // A run with no start time is older than any that has one. + const undated = { ...b, id: 9, started_at: undefined }; + assert.deepEqual(latestRuns([undated, a]), [a]); + // The same name from another app is a different check. + const other = { ...a, app: { slug: 'other' } }; + assert.deepEqual(latestRuns([b, other]), [b, other]); + assert.deepEqual(latestRuns([{}, null]), [{}]); + assert.deepEqual(latestRuns(undefined), []); +}); + +test('latestStatuses breaks a timestamp tie by id', () => { + const a = { context: 'c', state: 'pending', id: 1 }; + const b = { context: 'c', state: 'success', id: 2 }; + assert.deepEqual(latestStatuses([a, b]), [b]); + assert.deepEqual(latestStatuses([b, a]), [b]); + assert.deepEqual(latestStatuses([{}, null]), [{}]); + assert.deepEqual(latestStatuses(undefined), []); +}); + +test('missing lists read as empty, and empty checks are not a pass', () => { + assert.deepEqual(checkProblems(undefined, undefined), [ + 'no check runs or statuses on the head commit', + ]); + assert.deepEqual(convergenceProblems(converged({ threads: undefined })), []); +}); + +test('check names reach the problem text escaped', () => { + const [problem] = checkProblems( + [{ name: 'evil\n::error::x', status: 'queued' }], + undefined + ); + assert.ok(!problem.includes('\n')); +}); + +// --------------------------------------------------------------------------- +// Convergence and the decision +// --------------------------------------------------------------------------- + +test('a clean fresh review on the head converges', () => { + assert.deepEqual(convergenceProblems(converged()), []); + assert.deepEqual(convergenceProblems(converged({ threads: [] })), []); +}); + +test('each condition on its own stops convergence', () => { + const cases = [ + [{ reviews: [] }, /^no deep-review summary$/], + [ + { reviews: [summary(FRESH_CLEAN, { commit_id: OLD })] }, + /^the newest summary is for bbbbbbb, not the head aaaaaaa$/, + ], + [ + { reviews: [summary(FRESH_CLEAN, { commit_id: null })] }, + /is for "", not the head/, + ], + [ + { + pr: pr({ head: { repo: { full_name: REPO } } }), + reviews: [summary(FRESH_CLEAN, { commit_id: undefined })], + }, + /is for "", not the head ""$/, + ], + [ + { + reviews: [ + summary(`${MARKER}\n## Deep review — 1 blocking · 0 advisory`), + ], + }, + /reports 1 blocking/, + ], + [ + { + reviews: [ + EARLIER, + summary(`${MARKER}\n## Deep review (verify) — 0 resolved · 2 open`), + ], + }, + /leaves 2 open/, + ], + [ + { reviews: [EARLIER, summary(`${MARKER}\nsomething else`)] }, + /did not parse: its heading matches neither shape/, + ], + [{ threads: [{ isResolved: false }, {}] }, /^2 unresolved review thread/], + [ + { checkRuns: [{ ...GREEN_RUN, conclusion: 'failure' }] }, + /concluded "failure"/, + ], + [{ statuses: [{ ...GREEN_STATUS, state: 'pending' }] }, /is "pending"/], + [ + { pr: pr({ labels: ['deep-review', 'needs-security-review'] }) }, + /^carries needs-security-review$/, + ], + ]; + for (const [overrides, want] of cases) { + const problems = convergenceProblems(converged(overrides)); + assert.equal(problems.length, 1, JSON.stringify(problems)); + assert.match(problems[0], want); + } +}); + +test('a newer summary that does not parse is not covered by an older one', () => { + const older = summary(FRESH_CLEAN, { + id: 1, + submitted_at: '2026-10-03T10:00:00Z', + }); + const newer = summary( + `> quoting\n${MARKER}\n## Deep review — 0 blocking · 0 advisory` + ); + const problems = convergenceProblems(converged({ reviews: [older, newer] })); + assert.deepEqual(problems, [ + 'the newest summary did not parse: the marker is not its first line', + ]); +}); + +// --------------------------------------------------------------------------- +// The fresh review behind the head +// --------------------------------------------------------------------------- + +/** A summary posted at the given minute, so the order is explicit. */ +const posted = (body, minute, overrides = {}) => + summary(body, { + id: minute, + submitted_at: `2026-10-03T11:${String(minute).padStart(2, '0')}:00Z`, + ...overrides, + }); +const freshWith = (blocking, advisory = 0) => + `${MARKER}\n## Deep review — ${blocking} blocking · ${advisory} advisory`; +const verifyWith = (resolved, open) => + `${MARKER}\n## Deep review (verify) — ${resolved} resolved · ${open} open`; +const problemsFor = reviews => convergenceProblems(converged({ reviews })); +const NO_FRESH = 'no fresh deep review, and a verify pass reviews no code'; + +test('a verify pass alone does not converge', () => { + assert.deepEqual(problemsFor([posted(verifyWith(0, 0), 1)]), [NO_FRESH]); + // A summary that does not parse is not a fresh review either. + assert.deepEqual( + problemsFor([ + posted(`${MARKER}\nsomething`, 1), + posted(verifyWith(0, 0), 2), + ]), + [NO_FRESH] + ); +}); + +test('a clean fresh review then a verify pass on the same head converges', () => { + assert.deepEqual( + problemsFor([posted(freshWith(0, 3), 1), posted(verifyWith(0, 0), 2)]), + [] + ); +}); + +test('commits pushed after a clean fresh review need another fresh review', () => { + // Re-applying deep-review after a push runs a verify pass, pinned to the + // new head, that reviewed none of the new commits. + const stale = posted(freshWith(0), 1, { commit_id: OLD }); + assert.deepEqual(problemsFor([stale, posted(verifyWith(0, 0), 2)]), [ + 'the newest fresh review is for bbbbbbb, and no fresh review covers ' + + 'the commits since', + ]); + // A fresh review of the new head clears it. + assert.deepEqual( + problemsFor([stale, posted(verifyWith(0, 0), 2), posted(freshWith(0), 3)]), + [] + ); +}); + +test('blocking findings converge once verify passes resolve them and every thread is resolved', () => { + // The fixes moved the head, and the verify pass on the new head resolved + // both findings. + const fresh = posted(freshWith(2, 1), 1, { commit_id: OLD }); + assert.deepEqual(problemsFor([fresh, posted(verifyWith(2, 0), 2)]), []); + // Resolved across more than one pass counts the same. + assert.deepEqual( + problemsFor([ + fresh, + posted(verifyWith(1, 1), 2, { commit_id: OLD }), + posted(verifyWith(1, 0), 3), + ]), + [] + ); + // An open thread holds it back whatever the summaries say. + assert.deepEqual( + convergenceProblems( + converged({ + reviews: [fresh, posted(verifyWith(2, 0), 2)], + threads: [{ isResolved: true }, { isResolved: false }], + }) + ), + ['1 unresolved review thread(s)'] + ); + // Fewer resolved than the fresh review counted leaves a finding no thread + // carries, and no verify pass can see that one. + for (const resolved of [0, 1]) { + assert.deepEqual(problemsFor([fresh, posted(verifyWith(resolved, 0), 2)]), [ + 'the newest fresh review reports 2 blocking and the verify passes ' + + `since resolved ${resolved}`, + ]); + } +}); + +test('the verify pass that resolves the last finding must be on the head', () => { + const fresh = posted(freshWith(2), 1, { commit_id: OLD }); + // Resolved at MID, then an unrelated push to the head and a verify pass + // there that touched nothing. No review has read the head. + assert.deepEqual( + problemsFor([ + fresh, + posted(verifyWith(2, 0), 2, { commit_id: MID }), + posted(verifyWith(0, 0), 3), + ]), + [ + "the verify pass that resolved the last of the newest fresh review's " + + 'findings is for ccccccc, and no fresh review covers the commits since', + ] + ); + // The same, with the last finding resolved on the head before a later + // verify pass on the same head. + assert.deepEqual( + problemsFor([ + fresh, + posted(verifyWith(1, 1), 2, { commit_id: MID }), + posted(verifyWith(1, 0), 3), + posted(verifyWith(0, 0), 4), + ]), + [] + ); + // When the completing pass is the newest summary, condition 1 reports its + // commit once. + assert.deepEqual( + convergenceProblems( + converged({ + pr: pr({ head: { sha: 'd'.repeat(40), repo: { full_name: REPO } } }), + reviews: [fresh, posted(verifyWith(2, 0), 2, { commit_id: MID })], + }) + ), + ['the newest summary is for ccccccc, not the head ddddddd'] + ); +}); + +test('the newest fresh review decides, and only verify passes after it count', () => { + assert.deepEqual( + problemsFor([ + posted(freshWith(0), 1), + posted(freshWith(1), 2), + posted(verifyWith(0, 0), 3), + ]), + [ + 'the newest fresh review reports 1 blocking and the verify passes ' + + 'since resolved 0', + ] + ); + assert.deepEqual( + problemsFor([ + posted(freshWith(1), 1), + posted(verifyWith(1, 0), 2), + posted(freshWith(1), 3), + posted(verifyWith(0, 0), 4), + ]), + [ + 'the newest fresh review reports 1 blocking and the verify passes ' + + 'since resolved 0', + ] + ); +}); + +test('a fresh summary from anyone but the app is ignored', () => { + const human = { login: 'claude', type: 'User' }; + assert.deepEqual( + problemsFor([ + posted(freshWith(0), 1, { user: human }), + posted(verifyWith(0, 0), 2), + ]), + [NO_FRESH] + ); + // Nor can one stand in for a genuine fresh review with findings. + assert.deepEqual( + problemsFor([ + posted(freshWith(2), 1), + posted(freshWith(0), 2, { user: human }), + posted(verifyWith(0, 0), 3), + ]), + [ + 'the newest fresh review reports 2 blocking and the verify passes ' + + 'since resolved 0', + ] + ); +}); + +test('a summary that does not parse after the newest fresh review fails closed', () => { + assert.deepEqual( + problemsFor([ + posted(freshWith(0), 1), + posted(`${MARKER}\n## Deep review — lots`, 2), + posted(verifyWith(0, 0), 3), + ]), + ['a summary after the newest fresh review did not parse'] + ); + // The same when the fresh review had findings that a later pass resolved. + assert.deepEqual( + problemsFor([ + posted(freshWith(2), 1, { commit_id: OLD }), + posted(`${MARKER}\n## Deep review — lots`, 2), + posted(verifyWith(2, 0), 3), + ]), + ['a summary after the newest fresh review did not parse'] + ); +}); + +test('planAction only writes when the label disagrees', () => { + assert.equal(planAction(false, true), 'add'); + assert.equal(planAction(true, false), 'remove'); + assert.equal(planAction(true, true), 'none'); + assert.equal(planAction(false, false), 'none'); +}); + +test('decide composes scope, convergence and the action', () => { + assert.deepEqual(decide(converged()), { + number: 870, + skip: null, + problems: [], + action: 'add', + }); + const labeled = pr({ labels: ['deep-review', LABEL] }); + assert.equal(decide(converged({ pr: labeled })).action, 'none'); + assert.equal( + decide(converged({ pr: labeled, threads: [{ isResolved: false }] })).action, + 'remove' + ); + // Out of scope is left alone even when it carries the label. + assert.deepEqual( + decide({ repo: REPO, pr: pr({ state: 'closed', labels: [LABEL] }) }), + { number: 870, skip: 'not open', problems: [], action: 'none' } + ); +}); + +test('a run that starts with CI takes the label off and never adds it', () => { + // The workflow also runs when a CI run is requested, so it sees a push + // before CI on it finishes: the newest summary is pinned to the old head, + // and the new head's checks are queued, running or not created yet. + const moved = { sha: MID, repo: { full_name: REPO } }; + const running = status => ({ ...GREEN_RUN, status, conclusion: null }); + for (const checkRuns of [[running('queued')], [running('in_progress')], []]) { + const state = { checkRuns, statuses: [] }; + const labeled = decide( + converged({ + ...state, + pr: pr({ labels: ['deep-review', LABEL], head: moved }), + }) + ); + assert.equal(labeled.action, 'remove', JSON.stringify(checkRuns)); + assert.equal( + labeled.problems[0], + 'the newest summary is for aaaaaaa, not the head ccccccc' + ); + assert.equal( + decide(converged({ ...state, pr: pr({ head: moved }) })).action, + 'none' + ); + } + // CI started again on a reviewed head holds the label back until it ends. + assert.equal( + decide( + converged({ + pr: pr({ labels: ['deep-review', LABEL] }), + checkRuns: [running('in_progress')], + }) + ).action, + 'remove' + ); +}); + +// --------------------------------------------------------------------------- +// The API client, against a fake fetch +// --------------------------------------------------------------------------- + +function response(status, body, headers = {}) { + return { + ok: status >= 200 && status < 300, + status, + headers: { get: name => headers[name.toLowerCase()] ?? null }, + json: async () => body, + text: async () => + typeof body === 'string' ? body : JSON.stringify(body ?? ''), + }; +} + +/** A fetch that answers from a route table and records every call. */ +function fakeFetch(routes) { + const calls = []; + const fetchImpl = async (url, init) => { + const method = init?.method ?? 'GET'; + const path = url.replace('https://api.github.com', ''); + const body = init?.body ? JSON.parse(init.body) : undefined; + calls.push({ method, path, body, headers: init?.headers }); + const route = routes[`${method} ${path}`]; + if (!route) return response(404, { message: 'Not Found' }); + const answer = typeof route === 'function' ? route(body) : route; + if (answer instanceof Error) throw answer; + return answer; + }; + return { fetchImpl, calls }; +} + +test('nextLink reads the next page out of a Link header', () => { + assert.equal( + nextLink( + '; rel="prev", ; rel="next"' + ), + 'https://api.github.com/x?page=3' + ); + assert.equal(nextLink('; rel="last"'), null); + assert.equal(nextLink(null), null); +}); + +test('pages follows Link headers and reads a keyed list', async () => { + const next = 'https://api.github.com/list?page=2'; + const { fetchImpl, calls } = fakeFetch({ + 'GET /list': response( + 200, + { items: [1, 2] }, + { link: `<${next}>; rel="next"` } + ), + 'GET /list?page=2': response(200, { items: [3] }), + }); + const client = createClient({ token: 't', fetchImpl }); + assert.deepEqual(await client.pages('/list', 'items'), [1, 2, 3]); + assert.equal(calls[0].headers.Authorization, 'Bearer t'); + assert.equal(calls[0].headers['Content-Type'], undefined); +}); + +test('pages refuses a missing list, an off-host link and a runaway', async () => { + const offHost = createClient({ + token: 't', + fetchImpl: fakeFetch({ + 'GET /list': response(200, [], { + link: '; rel="next"', + }), + }).fetchImpl, + }); + await assert.rejects(offHost.pages('/list'), /paginated off/); + + const notList = createClient({ + token: 't', + fetchImpl: fakeFetch({ 'GET /list': response(200, { items: 3 }) }) + .fetchImpl, + }); + await assert.rejects(notList.pages('/list', 'items'), /returned no items/); + await assert.rejects(notList.pages('/list'), /returned no array/); + + const loop = createClient({ + token: 't', + fetchImpl: fakeFetch({ + 'GET /list': response(200, [1], { + link: '; rel="next"', + }), + }).fetchImpl, + }); + await assert.rejects(loop.pages('/list'), /ran past/); +}); + +test('an HTTP error throws with its status, escaped', async () => { + const client = createClient({ + token: 't', + fetchImpl: fakeFetch({ + 'GET /x': response(403, 'Resource not accessible\n::error::x'), + }).fetchImpl, + }); + await assert.rejects(client.json('/x'), err => { + assert.match(err.message, /HTTP 403/); + assert.ok(!err.message.includes('\n')); + return true; + }); + // A body that cannot be read still reports the status. + const unreadable = createClient({ + token: 't', + fetchImpl: async () => ({ + ok: false, + status: 500, + text: async () => { + throw new Error('reset'); + }, + }), + }); + await assert.rejects(unreadable.json('/x'), /HTTP 500 ""$/); +}); + +test('the client sends nothing outside the API host', async () => { + const { fetchImpl, calls } = fakeFetch({}); + const client = createClient({ token: 't', fetchImpl }); + await assert.rejects(client.json('@example.com/x'), /outside/); + assert.deepEqual(calls, []); +}); + +test('graphql returns data and throws on errors', async () => { + const { fetchImpl, calls } = fakeFetch({ + 'POST /graphql': body => + body.variables.ok + ? response(200, { data: { hello: 1 } }) + : response(200, { errors: [{ message: 'bad' }] }), + }); + const client = createClient({ token: 't', fetchImpl }); + assert.deepEqual(await client.graphql('q', { ok: true }), { hello: 1 }); + assert.equal(calls[0].headers['Content-Type'], 'application/json'); + await assert.rejects(client.graphql('q', { ok: false }), /"bad"/); +}); + +test('label writes hit the issue labels endpoints, and a gone label is fine', async () => { + const { fetchImpl, calls } = fakeFetch({ + [`POST /repos/${REPO}/issues/870/labels`]: response(200, []), + }); + const client = createClient({ token: 't', fetchImpl }); + await client.addLabel(REPO, 870, LABEL); + await client.removeLabel(REPO, 870, LABEL); + assert.deepEqual(calls[0].body, { labels: [LABEL] }); + assert.equal(calls[1].method, 'DELETE'); + assert.equal(calls[1].path, `/repos/${REPO}/issues/870/labels/${LABEL}`); +}); + +test('fetchThreads pages through every thread', async () => { + const page = (nodes, hasNextPage, endCursor) => + response(200, { + data: { + repository: { + pullRequest: { + reviewThreads: { pageInfo: { hasNextPage, endCursor }, nodes }, + }, + }, + }, + }); + const { fetchImpl, calls } = fakeFetch({ + 'POST /graphql': body => + body.variables.after === null + ? page([{ isResolved: true }], true, 'c1') + : page([{ isResolved: false }], false, null), + }); + const client = createClient({ token: 't', fetchImpl }); + assert.deepEqual(await fetchThreads(client, REPO, 870), [ + { isResolved: true }, + { isResolved: false }, + ]); + assert.deepEqual(calls[0].body.variables, { + owner: 'allxsmith', + name: 'bestax', + number: 870, + after: null, + }); + assert.equal(calls[1].body.variables.after, 'c1'); +}); + +test('fetchThreads fails on a missing connection or a stuck cursor', async () => { + const empty = createClient({ + token: 't', + fetchImpl: fakeFetch({ + 'POST /graphql': response(200, { data: { repository: null } }), + }).fetchImpl, + }); + await assert.rejects(fetchThreads(empty, REPO, 1), /no reviewThreads/); + const stuck = createClient({ + token: 't', + fetchImpl: fakeFetch({ + 'POST /graphql': response(200, { + data: { + repository: { + pullRequest: { + reviewThreads: { + pageInfo: { hasNextPage: true, endCursor: null }, + nodes: [], + }, + }, + }, + }, + }), + }).fetchImpl, + }); + await assert.rejects(fetchThreads(stuck, REPO, 1), /did not advance/); +}); + +test('fetchThreads gives up after the page cap', async () => { + let n = 0; + const client = createClient({ + token: 't', + fetchImpl: fakeFetch({ + 'POST /graphql': () => + response(200, { + data: { + repository: { + pullRequest: { + reviewThreads: { + pageInfo: { hasNextPage: true, endCursor: `c${n++}` }, + nodes: [], + }, + }, + }, + }, + }), + }).fetchImpl, + }); + await assert.rejects(fetchThreads(client, REPO, 1), /ran past/); +}); + +// --------------------------------------------------------------------------- +// run(), end to end against a fake repository +// --------------------------------------------------------------------------- + +/** Routes for one in-scope PR's reads. */ +function prRoutes(number, { sha = HEAD, reviews, threads, runs, statuses }) { + return { + [`GET /repos/${REPO}/pulls/${number}/reviews?per_page=100`]: response( + 200, + reviews + ), + [`GET /repos/${REPO}/commits/${sha}/check-runs?per_page=100`]: response( + 200, + { check_runs: runs } + ), + [`GET /repos/${REPO}/commits/${sha}/status?per_page=100`]: response(200, { + statuses, + }), + [`threads ${number}`]: threads, + }; +} + +/** Answers the threads query per PR number from `thread ` entries. */ +function withThreads(routes) { + return { + ...routes, + 'POST /graphql': body => + response(200, { + data: { + repository: { + pullRequest: { + reviewThreads: { + pageInfo: { hasNextPage: false, endCursor: null }, + nodes: routes[`threads ${body.variables.number}`], + }, + }, + }, + }, + }), + }; +} + +/** The repository read every run makes for its default branch. */ +const REPO_ROUTE = { + [`GET /repos/${REPO}`]: response(200, { default_branch: 'main' }), +}; +const repoReads = calls => + calls.filter(c => c.method === 'GET' && c.path === `/repos/${REPO}`).length; + +const CLEAN = { + reviews: [summary(FRESH_CLEAN)], + threads: [{ isResolved: true }], + runs: [GREEN_RUN], + statuses: [GREEN_STATUS], +}; + +function sweepRoutes() { + const ready = pr({ number: 1 }); + const stale = pr({ number: 2, labels: ['deep-review', LABEL] }); + const loop = pr({ number: 3, labels: ['deep-review', 'ai-loop', LABEL] }); + const plain = pr({ number: 4, labels: [] }); + const settled = pr({ number: 5, labels: ['deep-review', LABEL] }); + const stacked = pr({ + number: 6, + labels: ['deep-review', LABEL], + base: { ref: 'feat/base' }, + }); + return withThreads({ + ...REPO_ROUTE, + [`GET /repos/${REPO}/pulls?state=open&per_page=100`]: response(200, [ + ready, + stale, + loop, + plain, + settled, + stacked, + ]), + ...prRoutes(1, CLEAN), + ...prRoutes(2, { ...CLEAN, threads: [{ isResolved: false }] }), + ...prRoutes(5, CLEAN), + // The re-read before each write. + [`GET /repos/${REPO}/pulls/1`]: response(200, ready), + [`GET /repos/${REPO}/pulls/2`]: response(200, stale), + [`GET /repos/${REPO}/pulls/5`]: response(200, settled), + [`POST /repos/${REPO}/issues/1/labels`]: response(200, []), + [`DELETE /repos/${REPO}/issues/2/labels/${LABEL}`]: response(200, []), + }); +} + +const writes = calls => + calls.filter(c => c.method !== 'GET' && c.path !== '/graphql'); + +test('a sweep adds, removes and leaves alone as the decision says', async () => { + const { fetchImpl, calls } = fakeFetch(sweepRoutes()); + const lines = []; + const code = await run({ + argv: [`--repo=${REPO}`, '--pr='], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }); + assert.equal(code, 0); + assert.deepEqual( + writes(calls).map(c => `${c.method} ${c.path}`), + [ + `POST /repos/${REPO}/issues/1/labels`, + `DELETE /repos/${REPO}/issues/2/labels/${LABEL}`, + ] + ); + const text = lines.join('\n'); + assert.match(text, /^review-converged: repo=allxsmith\/bestax sweep$/m); + assert.match(text, /#1 converged, add label: written/); + assert.match(text, /^::notice title=review-converged::#1 labeled$/m); + assert.match( + text, + /#2 not converged: 1 unresolved review thread\(s\), remove label: written/ + ); + assert.match(text, /^::notice title=review-converged::#2 unlabeled$/m); + assert.match(text, /#3 skipped \(ai-loop PR/); + assert.match(text, /#5 converged, label unchanged/); + // A stacked PR keeps its label: it is out of scope, not unconverged. + assert.match(text, /#6 skipped \(based on "feat\/base", not "main"\)/); + assert.equal(repoReads(calls), 1); + // A PR with nothing to do with the label is not named in a sweep. + assert.doesNotMatch(text, /#4/); + // Every line but the notices starts with the fixed prefix. + for (const line of lines) + assert.match( + line, + /^(review-converged: |::notice title=review-converged::#\d+ )/ + ); +}); + +test('a dry run decides the same and writes nothing', async () => { + const { fetchImpl, calls } = fakeFetch(sweepRoutes()); + const lines = []; + const code = await run({ + argv: [`--repo=${REPO}`, '--dry-run'], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }); + assert.equal(code, 0); + assert.deepEqual(writes(calls), []); + assert.match(lines.join('\n'), /sweep dry-run/); + assert.match( + lines.join('\n'), + /#1 converged, add label: dry run, not written/ + ); + assert.match(lines.join('\n'), /#2 .*remove label: dry run, not written/); + assert.doesNotMatch(lines.join('\n'), /::notice/); +}); + +test('a PR that moved or changed while it was checked is not labeled', async () => { + for (const [now, outcome] of [ + [pr({ number: 1, head: { sha: OLD, repo: { full_name: REPO } } }), 'stale'], + [pr({ number: 1, labels: ['deep-review', 'ai-loop'] }), 'stale'], + [pr({ number: 1, state: 'closed' }), 'stale'], + [pr({ number: 1, base: { ref: 'feat/base' } }), 'stale'], + [pr({ number: 1, labels: ['deep-review', LABEL] }), 'already set'], + ]) { + // A sweep, so the PR under test comes from the list and the single read + // of /pulls/1 is the re-read before adding. + const routes = sweepRoutes(); + routes[`GET /repos/${REPO}/pulls/1`] = response(200, now); + const { fetchImpl, calls } = fakeFetch(routes); + const lines = []; + await run({ + argv: [`--repo=${REPO}`], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }); + assert.deepEqual( + writes(calls).filter(c => c.path.includes('/issues/1/')), + [], + outcome + ); + assert.match( + lines.join('\n'), + new RegExp(`#1 converged, add label: ${outcome}`) + ); + } +}); + +test('a flag that lands while a PR is checked stops an add, not a removal', async () => { + // The evaluation saw no needs-security-review on either PR, and the re-read + // before each write does. #1 was going to get the label and #2 to lose it. + const routes = sweepRoutes(); + routes[`GET /repos/${REPO}/pulls/1`] = response( + 200, + pr({ number: 1, labels: ['deep-review', FLAG_LABEL] }) + ); + routes[`GET /repos/${REPO}/pulls/2`] = response( + 200, + pr({ number: 2, labels: ['deep-review', LABEL, FLAG_LABEL] }) + ); + const { fetchImpl, calls } = fakeFetch(routes); + const lines = []; + await run({ + argv: [`--repo=${REPO}`], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }); + assert.deepEqual( + writes(calls).map(c => `${c.method} ${c.path}`), + [`DELETE /repos/${REPO}/issues/2/labels/${LABEL}`] + ); + const text = lines.join('\n'); + assert.match(text, /#1 converged, add label: stale/); + assert.match(text, /#2 not converged: .*, remove label: written/); +}); + +test('a PR that left scope or moved while it was checked keeps its label', async () => { + // #2 carries the label and has an open thread, so the decision is to take + // the label off. The re-read before removing finds the PR changed. + const labels = ['deep-review', LABEL]; + for (const [now, outcome] of [ + [pr({ number: 2, labels: [LABEL] }), 'stale'], + [pr({ number: 2, labels: [...labels, 'ai-loop'] }), 'stale'], + [pr({ number: 2, labels, base: { ref: 'feat/base' } }), 'stale'], + [pr({ number: 2, labels, state: 'closed' }), 'stale'], + [ + pr({ number: 2, labels, head: { sha: OLD, repo: { full_name: REPO } } }), + 'stale', + ], + [pr({ number: 2 }), 'already gone'], + ]) { + const routes = sweepRoutes(); + routes[`GET /repos/${REPO}/pulls/2`] = response(200, now); + const { fetchImpl, calls } = fakeFetch(routes); + const lines = []; + await run({ + argv: [`--repo=${REPO}`], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }); + assert.deepEqual( + writes(calls).filter(c => c.path.includes('/issues/2/')), + [], + outcome + ); + assert.match( + lines.join('\n'), + new RegExp(`#2 not converged: .*, remove label: ${outcome}`) + ); + } +}); + +test('a targeted run names an out-of-scope PR', async () => { + const routes = sweepRoutes(); + routes[`GET /repos/${REPO}/pulls/4`] = response( + 200, + pr({ number: 4, labels: [] }) + ); + const { fetchImpl, calls } = fakeFetch(routes); + const lines = []; + const code = await run({ + argv: [`--repo=${REPO}`, '--pr=4'], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }); + assert.equal(code, 0); + assert.deepEqual(lines, [ + 'review-converged: repo=allxsmith/bestax pr=4', + 'review-converged: #4 skipped (no deep-review label)', + ]); + assert.equal(repoReads(calls), 1); +}); + +test('a failed default-branch read fails the run before any PR is read', async () => { + for (const answer of [ + response(500, 'boom'), + response(200, { name: 'bestax' }), + response(200, { default_branch: '' }), + ]) { + const routes = sweepRoutes(); + routes[`GET /repos/${REPO}`] = answer; + const { fetchImpl, calls } = fakeFetch(routes); + const lines = []; + await assert.rejects( + run({ + argv: [`--repo=${REPO}`], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }), + /HTTP 500|returned no default_branch/ + ); + assert.deepEqual( + calls.map(c => `${c.method} ${c.path}`), + [`GET /repos/${REPO}`] + ); + assert.deepEqual(lines, []); + } +}); + +test('an API error on one PR leaves its label and fails the run', async () => { + const routes = sweepRoutes(); + routes[`GET /repos/${REPO}/pulls/1/reviews?per_page=100`] = response( + 502, + 'bad gateway' + ); + const { fetchImpl, calls } = fakeFetch(routes); + const lines = []; + const code = await run({ + argv: [`--repo=${REPO}`], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }); + assert.equal(code, 1); + const text = lines.join('\n'); + assert.match(text, /#1 error, label left as it was: ".*HTTP 502/); + assert.deepEqual( + writes(calls).map(c => `${c.method} ${c.path}`), + [`DELETE /repos/${REPO}/issues/2/labels/${LABEL}`] + ); +}); + +test('a head that is not a commit id is an error, not a decision', async () => { + const odd = pr({ + number: 7, + head: { sha: '../../x', repo: { full_name: REPO } }, + }); + const { fetchImpl } = fakeFetch({ + ...REPO_ROUTE, + [`GET /repos/${REPO}/pulls/7`]: response(200, odd), + }); + const lines = []; + assert.equal( + await run({ + argv: [`--repo=${REPO}`, '--pr=7'], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }), + 1 + ); + assert.match(lines.join('\n'), /#7 error.*not a commit id/); + + const none = pr({ number: 8, head: { repo: { full_name: REPO } } }); + const missing = fakeFetch({ + ...REPO_ROUTE, + [`GET /repos/${REPO}/pulls/8`]: response(200, none), + }); + assert.equal( + await run({ + argv: [`--repo=${REPO}`, '--pr=8'], + env: { GITHUB_TOKEN: 't' }, + fetchImpl: missing.fetchImpl, + log: () => {}, + }), + 1 + ); +}); + +test('a long list of problems is cut short in the log', async () => { + const many = Array.from({ length: 7 }, (_, i) => ({ + ...GREEN_RUN, + name: `job ${i}`, + status: 'queued', + })); + const routes = sweepRoutes(); + routes[`GET /repos/${REPO}/commits/${HEAD}/check-runs?per_page=100`] = + response(200, { check_runs: many }); + const { fetchImpl } = fakeFetch(routes); + const lines = []; + await run({ + argv: [`--repo=${REPO}`, '--dry-run'], + env: { GITHUB_TOKEN: 't' }, + fetchImpl, + log: line => lines.push(line), + }); + const line = lines.find(l => l.includes('#5 ')); + assert.match(line, /"job 4" is "queued", and 2 more, remove label/); + assert.doesNotMatch(line, /job 5/); +}); + +test('run refuses to start without a token or with bad arguments', async () => { + await assert.rejects(run({ argv: [`--repo=${REPO}`], env: {} }), UsageError); + await assert.rejects( + run({ argv: ['--bogus'], env: { GITHUB_TOKEN: 't' } }), + UsageError + ); +}); + +/** + * Run the script as a command. `fetchStub` is the body of a module preloaded + * with --import that replaces the global fetch, so no request leaves. The + * parent environment is passed on so coverage of the child is still + * collected, with GITHUB_TOKEN set explicitly either way. + */ +function cli(args, { token = '', fetchStub } = {}) { + const preload = fetchStub + ? ['--import', `data:text/javascript,${encodeURIComponent(fetchStub)}`] + : []; + return spawnSync(process.execPath, [...preload, SCRIPT, ...args], { + encoding: 'utf8', + env: { ...process.env, GITHUB_TOKEN: token }, + }); +} + +test('the command line exits 2 on bad usage', () => { + const bad = cli([]); + assert.equal(bad.status, 2); + assert.match(bad.stderr, /^review-converged: usage error: /); + const noToken = cli([`--repo=${REPO}`]); + assert.equal(noToken.status, 2); + assert.match(noToken.stderr, /GITHUB_TOKEN is not set/); +}); + +test('the command line exits 1 when the API cannot be reached', () => { + const result = cli([`--repo=${REPO}`], { + token: 't', + fetchStub: + 'globalThis.fetch = async () => { throw new Error("offline"); };', + }); + assert.equal(result.status, 1); + assert.match(result.stderr, /^review-converged: "offline"/); +}); + +test('the command line exits 0 on a clean sweep', () => { + const result = cli([`--repo=${REPO}`], { + token: 't', + fetchStub: + 'globalThis.fetch = async url => new Response(' + + 'url.endsWith("/repos/allxsmith/bestax") ' + + '? \'{"default_branch":"main"}\' : "[]");', + }); + assert.equal(result.status, 0, result.stderr); + assert.equal( + result.stdout, + 'review-converged: repo=allxsmith/bestax sweep\n' + ); +}); + +// --------------------------------------------------------------------------- +// The workflow +// --------------------------------------------------------------------------- + +function workflowLines(file) { + return readFileSync(join(ROOT, '.github/workflows', file), 'utf8').split( + /\r?\n/ + ); +} + +test('the workflow job is named as the check run the script leaves out', () => { + const lines = workflowLines('review-converged.yml'); + const jobs = yamlGet(lines, 'jobs'); + assert.ok(jobs, 'review-converged.yml has no jobs'); + const names = [...jobs.lines.join('\n').matchAll(/^ {4}name: (.+)$/gm)].map( + m => m[1] + ); + assert.deepEqual(names, [OWN_CHECK_NAME]); + assert.equal( + yamlScalar(yamlGet(lines, 'jobs', 'sync', 'name')), + OWN_CHECK_NAME + ); +}); + +test('the workflow_run trigger names workflows that exist', () => { + const lines = workflowLines('review-converged.yml'); + // A comment after the last item reads as part of it, so comments are left + // out. + const listed = yamlItems( + yamlGet(lines, 'on', 'workflow_run', 'workflows')?.lines ?? [] + ).map(item => + item + .filter(line => !line.trim().startsWith('#')) + .join('\n') + .trim() + ); + const names = ['claude-review.yml', 'ci.yml'].map(file => + yamlScalar(yamlGet(workflowLines(file), 'name')) + ); + assert.deepEqual(listed.sort(), names.sort()); +}); + +test('the workflow_run trigger fires when a run starts and when it ends', () => { + // `requested` is what takes the label off as soon as a push starts CI, + // rather than leaving it on the unreviewed head until CI completes. + const types = yamlGet( + workflowLines('review-converged.yml'), + 'on', + 'workflow_run', + 'types' + ); + const flow = /^\[(.*)\]$/.exec(types?.value ?? ''); + assert.ok(flow, 'workflow_run.types is not a flow list'); + assert.deepEqual( + flow[1] + .split(',') + .map(type => type.trim()) + .sort(), + ['completed', 'requested'] + ); +});