diff --git a/docs/operations.md b/docs/operations.md index ae2665dc4..823adb38e 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -43,13 +43,15 @@ The poll stays the backup and serves repos without the GitHub App. With webhooks The runner drains `sync_requests` every 5 seconds while rows exist (`webhookTick` in `src/runner/runner.ts`). It skips a pass while a sync run holds its lock and stops when fewer than 1,000 rate-limit points are left. Each item is read with the sync's single-item document and written by the sync's writer, so the live topics update open pages. A failed read stays queued until it is 6 hours old; the next poll reads the item anyway. Both the poll and the re-read write `item_reads.synced_at` (one statement per page): the time the read started, before its first GitHub request (the start of the whole run for a paged read), so a read that began before a change never counts as made after it. A read that started before the one already stored for an item writes nothing for that item (not its row, its comments or its read time), so the mirror never goes back to an older snapshot. A re-read rewrites the item's comments even when the item row is unchanged. The runner uses one GitHub client seeded from the last sync's rate-limit reading and also skips a pass while the full-sync lock is held. A read that fails for a reason other than a transient one is dropped from the queue and logged. The item page shows it as "updated hh:mm" beside "On GitHub". -**Commands in comments** (`src/github/commands.ts`). Anyone who may use Queue items on the repo adds a pull request or an issue to the merge queue from GitHub with a comment that has, on a line of its own, `@ merge queue` (`merge-queue` and `mergequeue` work as well, in any case). An optional weight from 1 to 10 follows the words `merge queue`, as `@ merge queue 8` or `@ merge queue weight 8`; a weight on its own (`@ weight 8`) is no command. Quoted lines and fenced code do not count. Only a new comment (`issue_comment`, action `created`) by a user account in a tracked repo counts; edits and comments by bots or apps do not. The webhook stores the comment's id, the repo, the number, whether it is a pull request, the weight and the commenter's login and numeric GitHub id in `github_commands`, never the comment's text; a redelivery of the same comment adds nothing. The runner carries the command out in the same pass that drains `sync_requests`, after the item's own re-read (see the last point): +**Commands in comments** (`src/github/commands.ts`). Anyone who may use Queue items on the repo adds a pull request or an issue to the merge queue from GitHub with a comment that has, on a line of its own, `@ merge queue` (`merge-queue` and `mergequeue` work as well, in any case). An optional weight from 1 to 10 follows the words `merge queue`, as `@ merge queue 8` or `@ merge queue weight 8`; a weight on its own (`@ weight 8`) is no command. Quoted lines, fenced and indented code (four spaces or a tab) and HTML comments (``, also across lines) do not count. Only a new comment (`issue_comment`, action `created`) by a user account in a tracked repo counts; edits and comments by bots or apps do not, and neither does a comment created more than 5 minutes before its delivery arrives (a redelivery of an old comment). The webhook stores the comment's id and creation time, the repo, the number, whether it is a pull request, the weight and the commenter's login and numeric GitHub id in `github_commands`, never the comment's text; a redelivery of the same comment adds nothing. The runner carries the command out in the same pass that drains `sync_requests`, after the item's own re-read (see the last point): -- A commenter without an AutoCraft login, or whose GitHub id is not the one bound to that login, gets no answer (audited as `github-command` `ignored`), so nobody outside the access list can make the app write. -- A login whose GitHub id was never bound (no dashboard sign-in yet) is refused, with the reason in the answer. -- Otherwise the commenter's write permission on the repo is read from GitHub (as for conversation cards) and the item is added exactly as a line of **Queue items** on the Queue page (`queueAdd`, see docs/pipeline.md, Merge queue), as that login with its current role. The role and the login's binding are read again once GitHub has answered, with the same outcomes as above, so a login demoted or rebound meanwhile queues nothing. Who may is queueAdd's rule, the one every person-started write uses (`settleRefusal` in `src/settlers.ts`): an operator with write access on the repo, or a maintainer with `maintainer_writes` on, the app identity and write access; anyone else is refused with its reason. A PR is pre-approved at its current head and fast-tracked with the weight (default 5); an issue is fast-tracked and its one open closing PR queued. Its refusals (outside the scope, no merge approval for the repo, a pre-approved merge already in progress, …) are the answer. Audit rows are queueAdd's own under the commenter's login with `via: "github"`, plus one `github-command` row. -- The app answers in the same thread, naming the commenter: what was done and the item's fast-track place, or why not. The answer goes through `src/github/write.ts` (`ghComment`, audit action `github-command-reply`, note line "Automated reply") under a grant in the commenter's name; it needs no Comments approval, because a known person asked for it. A paced write is retried on the next pass; another failed answer is logged and not retried. -- A command waits until the item, and for an issue every open PR that closes it (the one Queue items would queue), was read from GitHub after the comment, by the webhook's re-read or by the poll when that re-read failed. `item_reads.synced_at` must be strictly after the command's time: a read stamped at the same instant may have started before it. This is checked again after the permission read, right before `queueAdd`, with nothing waiting on I/O between that check and the pre-approval, because a read that started earlier (a reconcile) may have written an older snapshot meanwhile, which also sets the item's read time back. So the command never pre-approves a head the mirror read before the comment. While no such read exists and none is queued (the re-read failed, or started within the comment's second, which the second-precision `synced_at` counts as before it), the command queues a re-read itself, at most once a minute (`tried_at`). A command that GitHub's permission read cannot settle is tried again after a minute (`tried_at`). Waiting commands cost no GitHub call and never keep newer ones out: a pass carries out at most 10 commands that call GitHub, oldest first among those that are due. One not carried out within an hour of the comment is dropped unanswered (`expired`). +- A commenter without an AutoCraft login, with a login whose GitHub id was never bound (no dashboard sign-in yet), or whose GitHub id is not the one bound to that login, gets no answer (audited as `github-command` `ignored`), so nobody outside the access list can make the app write. A viewer's command is refused without an answer. +- The comment is read again by its id (REST, through the app installation). A deleted comment, another author, or a body that no longer holds the same command (with the same weight) runs nothing and gets no answer (`ignored`). +- A pull request is pinned to the head it had when the comment was written. GitHub keeps no push time for a commit, so the PR counts as changed after the comment when any of three signals is later than the comment's creation time: a force push (`HeadRefForcePushedEvent`, stamped by GitHub), a commit's committer date (set by the pusher, so a back-dated commit passes this one) or the head's first check suite (stamped by GitHub when a push starts CI; a merge needs green CI at the head). A changed PR is refused with "the PR changed after your comment; comment again"; otherwise exactly that head is pre-approved, and a mirror head that differs from it is refused the same way. On an issue, its one open closing PR is queued only when it was opened before the comment and has not changed since; otherwise the issue is still fast-tracked and the answer names the PR to comment on. +- Then the commenter's write permission on the repo is read from GitHub through the app installation (`appPermission`, the collaborator permission, which writes `repo_permissions`, so a maintainer's pre-approval keeps the fresh row `refreshSettlers` then keeps alive) and the item is added exactly as a line of **Queue items** on the Queue page (`queueAdd`, see docs/pipeline.md, Merge queue), as that login with its current role. The role and the login's binding are read again once GitHub has answered, with the same outcomes as above, so a login demoted or rebound meanwhile queues nothing. Who may is queueAdd's rule, the one every person-started write uses (`settleRefusal` in `src/settlers.ts`): an operator with write access on the repo, or a maintainer with `maintainer_writes` on, the app identity and write access; anyone else is refused with its reason. A role or setting that refuses whatever GitHub says is answered before the head and permission reads. A PR is fast-tracked with the weight (default 5); an issue is fast-tracked and its one open closing PR queued. Its refusals (outside the scope, no merge approval for the repo, a pre-approved merge already in progress, …) are the answer; any other error is logged and answered "it could not be queued". Audit rows are queueAdd's own under the commenter's login with `via: "github"`, plus one `github-command` row. +- On a quiet pull request (a security fix not yet published), or an issue whose closing PR is one, only an operator's command is carried out, and nothing is answered. +- The app answers in the same thread, naming the commenter: what was done and the item's fast-track place, or why not. The answer goes through `src/github/write.ts` (`ghComment`, audit action `github-command-reply`, note line "Automated reply") under a grant in the commenter's name. An answer to a person the queue rule lets queue on the repo needs no Comments approval; any other answer (a refusal by the rule, an expiry) needs it. A paced write is retried on the next pass; another failed answer is logged and not retried. `reply` is `none` for a command that gets no answer. +- A command waits until the item, and for an issue every open PR that closes it (the one Queue items would queue), was read from GitHub after the delivery, by the webhook's re-read or by the poll when that re-read failed. `item_reads.synced_at` must be strictly after the command's arrival: a read stamped at the same instant may have started before it. This is checked again after the GitHub reads, right before `queueAdd`, with nothing waiting on I/O between that check and the pre-approval, because a read that started earlier (a reconcile) may have written an older snapshot meanwhile, which also sets the item's read time back. While no such read exists and none is queued (the re-read failed, or started within the delivery's second, which the second-precision `synced_at` counts as before it), the command queues a re-read itself, at most once a minute (`tried_at`). A command whose comment, head or permission read GitHub cannot settle (an error, or no app answer) is tried again after a minute (`tried_at`, `retries`). Waiting commands cost no GitHub call and never keep newer ones out: a pass carries out at most 10 commands that call GitHub, oldest first among those that are due. One not carried out within an hour of its arrival is dropped (`expired`): unanswered when it only waited, answered once with "could not check your access; comment again" when GitHub's reads kept failing. Settled commands are deleted after 30 days by the runner's hourly pruning. The app's slug is `github_app_slug` in the secrets file; without the app there are no commands. The **Issue comment** event must be subscribed (it is in the list above). diff --git a/docs/pipeline.md b/docs/pipeline.md index 7b53f9739..fc4782be2 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -405,7 +405,7 @@ Operators control what merges next from the Queue page, the CLI or the API. Ever **Fast track** (`autocraft-server fasttrack add [--weight N]|weight |remove |list`) marks PRs or issues, given as a GitHub URL, `repo#n` or `owner/repo#n`. Fast-tracked items go first in every stage that orders work by the work rank (Decide, Review, Opus review, Fix, Fix-up, Verify, merges and single merges). Each mark has a **weight** from 1 to 10 (default 5): heavier items go first, and items of equal weight keep the order they were added in (a new one joins the end of its weight). The Merge queue tab shows the weight beside the fast-track marker, and operators change it there (`POST /api/fast-track/weight` `{item, weight}`, audited as `fasttrack-weight`). Removing the mark returns the item to normal ranking. -**Queue items** (a button on the Merge queue tab) is for whoever may answer decisions on the item's repo, under the one rule every person-started write uses (`settleRefusal` in `src/settlers.ts`: answers, Backlog, conversation cards and choices, Queue items, `queue_pr`): an operator with live write access on the repo, or a maintainer with `maintainer_writes` on, the app identity and live write access on the repo; any other line is refused with 403. The button shows for operators, and for maintainers with write access on some repo while `/api/me` says `maintainerSettles` (the server's own reading of `maintainer_writes` and the app identity). It opens a dialog that takes PRs and issues, one GitHub URL, `repo#n` or `owner/repo#n` per line, and, for an operator, a weight, and adds each in turn (`POST /api/queue/add` `{item, weight}`); each line gets its own answer, and refused lines stay in the box. A PR line starts a pre-approved merge at the PR's current head with no fix-up: a row in `review`, as for a carried Merge answer (see [Pre-approved merge](#pre-approved-merge)), so the PR merges only after a sure take review at that head, a clean pre-merge review and green CI, and a take-fix review, a defect or a red head asks the Merge? question instead. It is refused for a PR outside the pipeline's scope or that cannot be reviewed, in a repo without merge approval, or with a pre-approved merge already in progress. An issue line fast-tracks the issue, so Fix works it first. When exactly one open PR of the repo closes the issue (GitHub's closing references), that PR is queued as a PR line would be; when several do, none is queued and the answer lists them for a person to pick one; a PR that closes it later is not queued on its own. Every line fast-tracks its items with the weight; an item already fast-tracked keeps a heavier weight it has, so Queue items never lowers a weight. Weights are set by operators: a maintainer's line fast-tracks an item not on the list yet with the default weight (5), leaves an existing weight as it is, and ignores a weight it names (the line's answer says so). Anyone who may use Queue items on the repo can do the same for one item from GitHub with a comment `@ merge queue` on it (optionally with a weight); the app answers in the thread (see docs/operations.md, Webhooks, Commands in comments). +**Queue items** (a button on the Merge queue tab) is for whoever may answer decisions on the item's repo, under the one rule every person-started write uses (`settleRefusal` in `src/settlers.ts`: answers, Backlog, conversation cards and choices, Queue items, `queue_pr`): an operator with live write access on the repo, or a maintainer with `maintainer_writes` on, the app identity and live write access on the repo; any other line is refused with 403. The button shows for operators, and for maintainers with write access on some repo while `/api/me` says `maintainerSettles` (the server's own reading of `maintainer_writes` and the app identity). It opens a dialog that takes PRs and issues, one GitHub URL, `repo#n` or `owner/repo#n` per line, and, for an operator, a weight, and adds each in turn (`POST /api/queue/add` `{item, weight}`); each line gets its own answer, and refused lines stay in the box. A PR line starts a pre-approved merge at the PR's current head with no fix-up: a row in `review`, as for a carried Merge answer (see [Pre-approved merge](#pre-approved-merge)), so the PR merges only after a sure take review at that head, a clean pre-merge review and green CI, and a take-fix review, a defect or a red head asks the Merge? question instead. It is refused for a PR outside the pipeline's scope or that cannot be reviewed, in a repo without merge approval, or with a pre-approved merge already in progress. An issue line fast-tracks the issue, so Fix works it first. When exactly one open PR of the repo closes the issue (GitHub's closing references), that PR is queued as a PR line would be; when several do, none is queued and the answer lists them for a person to pick one; a PR that closes it later is not queued on its own. Every line fast-tracks its items with the weight; an item already fast-tracked keeps a heavier weight it has, so Queue items never lowers a weight. Weights are set by operators: a maintainer's line fast-tracks an item not on the list yet with the default weight (5), leaves an existing weight as it is, and ignores a weight it names (the line's answer says so). Anyone who may use Queue items on the repo can do the same for one item from GitHub with a comment `@ merge queue` on it (optionally with a weight); a command pre-approves the head the PR had when the comment was written, is refused when the PR changed after it, and on an issue queues the closing PR only when that PR is older than the comment and unchanged since; the app answers in the thread (see docs/operations.md, Webhooks, Commands in comments). Each merge queue row says how the PR came in, by whom and when (`added` on the row; the login for staff only): **Queued** (Queue items, from its pre-approval), **Pre-approved** (a pre-approval with a fix-up), **Merge answer** (an operator answered Merge?, also when the answer was carried to a new head), or **Take review** (it came in with its take review, at the review's time). diff --git a/src/dash/api/queue-page.ts b/src/dash/api/queue-page.ts index b4405d2c5..d6dd91a9d 100644 --- a/src/dash/api/queue-page.ts +++ b/src/dash/api/queue-page.ts @@ -7,7 +7,7 @@ import type { DatabaseSync } from "node:sqlite"; import type { FastPosition, MergeWait, NextMerge, QueueMergeRow, QueueOrigin, QueuePage, QueueRepos, QueueTab, QueueWorkRow, TypeLabel } from "../../../web/src/api/types.ts"; import { cachedQueue, openViews, type CachedEntry } from "../../core/plan-read.ts"; import { addFastTrack, fastPositions, fastTrackList, FastTrackError, parseItemRef, parseWeight, removeFastTrack, setFastTrackWeight, WEIGHT_DEFAULT } from "../../fasttrack.ts"; -import { preapproveMerge } from "../../preapproval/index.ts"; +import { HEAD_CHANGED, preapproveMerge } from "../../preapproval/index.ts"; import { requireSettle } from "../../settlers.ts"; import type { Exec } from "../../fixup/git.ts"; import { ControlError, holdMerge, releaseMerge, removeFromBatch, stopBatch } from "../../merge/controls.ts"; @@ -283,13 +283,18 @@ export function openPrsClosing(db: DatabaseSync, repo: string, issue: number): n .sort((a, b) => a - b); } +/** What Queue items does, as the refusal of `settleRefusal` names it. */ +export const queueWhat = (repo: string): string => `queues items on ${repo}`; + /** * "Queue items", one line, for an operator or a maintainer who settles on the repo. A PR is pre-approved at its current head (it merges once the review says take, the pre-merge review is clean * and CI is green) and fast-tracked with the weight, so its review, checks and merge come first. An issue is fast-tracked, so Fix works it * first; when exactly one open PR closes it, that PR is queued as above. Several closing PRs are only listed: a person picks one. * Weights stay with operators: a maintainer's line fast-tracks with the default weight and ignores a weight it names. + * `pin` (a command in a comment) names the one head each PR may be pre-approved at, or null for a PR that may not be queued: one + * opened or pushed to after the comment. */ -export async function queueAdd(db: DatabaseSync, req: Req, via?: string): Promise<{ label: string; fast: string[] }> { +export async function queueAdd(db: DatabaseSync, req: Req, via?: string, pin?: (pr: number) => string | null): Promise<{ label: string; fast: string[] }> { const r = item(req); const operator = req.user.role === "operator"; const w = operator ? weightOf(req) : null; @@ -297,7 +302,7 @@ export async function queueAdd(db: DatabaseSync, req: Req, via?: string): Promis const ignored = !operator && raw !== undefined && raw !== null && raw !== "" ? ". The weight was ignored: only operators set fast-track weights" : ""; await needVisible(db, req, r.repo); // A pre-approved merge is a Merge answer given ahead, so it takes the rule of an answer (src/settlers.ts): an operator with write access, or a maintainer where they settle decisions. - await requireSettle(db, req.user, [r.repo], `queues items on ${r.repo}`); + await requireSettle(db, req.user, [r.repo], queueWhat(r.repo)); const by = req.user.login; const kind = (db.prepare("SELECT kind FROM main.items WHERE repo = ? AND number = ?").get(r.repo, r.number) as { kind: string } | undefined)?.kind; if (kind === "issue") { @@ -306,9 +311,10 @@ export async function queueAdd(db: DatabaseSync, req: Req, via?: string): Promis let rest: string; if (!prs.length) rest = "no open PR closes it yet"; else if (prs.length > 1) rest = `${prs.map((n) => `#${n}`).join(", ")} close it; queue one of them`; + else if (pin && pin(prs[0]!) === null) rest = `#${prs[0]} closes it but was opened or pushed to after your comment, so it was not queued; comment on #${prs[0]} to queue it`; else { try { - preapproveMerge(db, { repo: r.repo, number: prs[0]!, by, via }); + preapproveMerge(db, { repo: r.repo, number: prs[0]!, by, via, ...(pin ? { head: pin(prs[0]!)! } : {}) }); try { await markFast(db, by, r.repo, prs[0]!, w, via); rest = `queued #${prs[0]}, which closes it`; @@ -322,8 +328,10 @@ export async function queueAdd(db: DatabaseSync, req: Req, via?: string): Promis return { label: `Fast-tracked the issue; ${rest}${ignored}`, fast: await fastTrackRefs(db, req) }; } let done: { label: string }; + const head = pin ? pin(r.number) : undefined; + if (head === null) throw new HttpError(409, HEAD_CHANGED); try { - done = preapproveMerge(db, { repo: r.repo, number: r.number, by, via }); + done = preapproveMerge(db, { repo: r.repo, number: r.number, by, via, ...(head === undefined ? {} : { head }) }); } catch (e) { throw new HttpError(409, (e as Error).message); } diff --git a/src/github/commands.ts b/src/github/commands.ts index b7e675e81..82e6d4e19 100644 --- a/src/github/commands.ts +++ b/src/github/commands.ts @@ -3,31 +3,47 @@ // @ merge queue (also merge-queue, mergequeue; optional weight: `@ merge queue 8`) // // on a pull request or an issue, and the item goes into the merge queue as "Queue items" on the Queue page puts it there -// (queueAdd: a PR is pre-approved at its current head and fast-tracked; an issue is fast-tracked and its one closing PR queued). -// The app answers in the same thread with the outcome. +// (queueAdd: a PR is pre-approved and fast-tracked; an issue is fast-tracked and its one closing PR queued). A PR is pre-approved at +// the head it had when the comment was written, never at one pushed later. The app answers in the same thread with the outcome. // // The webhook keeps only the fields of github_commands, never the comment's text, and nothing of it reaches a prompt. The runner -// carries the command out: the commenter must have an AutoCraft login with the GitHub id bound to it, and then queueAdd applies the -// same rule as for Queue items (src/settlers.ts: an operator with write access on the repo, or a maintainer who settles decisions -// there), with the write permission read from GitHub now. A commenter without an AutoCraft login, or whose GitHub id is not the -// bound one, gets no answer, so a stranger cannot make the app write. The answer is the only write and goes through write.ts. +// carries the command out: the commenter must have an AutoCraft login with the GitHub id bound to it, the comment must still exist +// with the command in it, and then queueAdd applies the same rule as for Queue items (src/settlers.ts: an operator with write access +// on the repo, or a maintainer who settles decisions there), with the write permission read from GitHub through the app now. A +// commenter without a bound AutoCraft login, or a viewer, gets no answer, so a stranger cannot make the app write. The answer is the +// only write and goes through write.ts. import type { DatabaseSync } from "node:sqlite"; import { getAccess, LOGIN } from "../access.ts"; import type { Role } from "../dash/types.ts"; import { guardRepo } from "../core/guard.ts"; import { audit } from "../dash/audit.ts"; +import { HttpError } from "../dash/server/util.ts"; +import { WRITE_PERMISSIONS } from "../dash/server/provider.ts"; import { fastPositions } from "../fasttrack.ts"; import { exec as defaultExec, type Exec } from "../fixup/git.ts"; import type { Querier } from "../mirror.ts"; +import { ownerOf, slugOf } from "../owners.ts"; +import { appPermission, type AppPermission } from "../remote/permission.ts"; +import { isQuiet } from "../security/quiet.ts"; +import { settleRefusal } from "../settlers.ts"; +import { AppError, call, GITHUB_API } from "./app.ts"; +import { appSlug } from "./identity.ts"; +import { installationToken } from "./install-token.ts"; import { ghComment, WritePacedError } from "./write.ts"; /** Comments read for a command: GitHub caps a body at 65536 characters. */ const BODY_MAX = 65_536; -/** A command not carried out before this long has passed is dropped unanswered (the runner was down, or GitHub could not tell the permission). */ +/** A command not carried out before this long has passed is dropped (the runner was down, or GitHub could not be read). */ const EXPIRE_MS = 3600_000; -/** A command whose permission read GitHub could not settle is tried again after this long. */ +/** A comment older than this when its delivery arrives is a redelivery of an old comment: no command is queued. */ +export const STALE_MS = 5 * 60_000; +/** A command whose GitHub reads could not be settled is tried again after this long. */ const RETRY_MS = 60_000; +/** Settled commands are kept this long. */ +const KEEP_MS = 30 * 86400_000; const AUDIT_LOGIN = "github-command"; +const NO_ACCESS_READ = "could not check your access; comment again"; +const NOT_QUEUED = "it could not be queued"; export type Command = { command: "merge-queue"; weight: number | null }; @@ -35,21 +51,37 @@ const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); /** * The command in a comment addressed to the app, or null. The command is a line of its own: `@ merge queue`, with an - * optional weight (`8` or `weight 8`). Quoted lines (`> ...`) and fenced code are skipped, so quoting a command repeats nothing. - * A fence closes as CommonMark closes it: the opening character, at least as many of it, and nothing after but spaces. + * optional weight (`8` or `weight 8`). Quoted lines (`> ...`), fenced and indented code and HTML comments are skipped, so quoting or + * hiding a command runs nothing. A fence closes as CommonMark closes it: the opening character, at least as many of it, and nothing + * after but spaces. */ export function parseCommand(body: unknown, slug: string): Command | null { if (typeof body !== "string" || !slug) return null; const re = new RegExp(`^@${escape(slug)}(?:\\[bot\\])?[\\s,:]+merge[-\\s]?queue(?:\\s+(?:weight\\s+)?(\\d{1,2}))?\\s*[.!]?$`, "i"); let fence: { ch: string; len: number } | null = null; + let comment = false; for (const raw of body.slice(0, BODY_MAX).split(/\r?\n/)) { - const line = raw.trim(); + let text = raw; + if (!fence) { + if (comment) { + const end = text.indexOf("-->"); + if (end < 0) continue; + comment = false; + text = text.slice(end + 3); + } + text = text.replace(//g, ""); + const open = text.indexOf("", "", "\n" + cmd, "\n" + cmd, " " + cmd]) assert.notEqual(parseCommand(body, SLUG), null, body); + }); + + test("a redelivered old comment, or one without a creation time, queues nothing", () => { + const w = fresh().pr(1); + deliver(w, payload({ body: `@${SLUG} merge queue`, created: new Date(Date.now() - STALE_MS - 1000) })); + const p = payload({ body: `@${SLUG} merge queue`, comment: 5001 }) as { comment: { created_at?: string } }; + delete p.comment.created_at; + deliver(w, p); + assert.deepEqual(rows(w), []); + }); + + test("a deleted comment, another author or a body that no longer holds the command runs nothing and gets no answer", async () => { + const w = fresh().pr(1); + for (const c of [5001, 5002, 5003, 5004]) deliver(w, payload({ body: `@${SLUG} merge queue`, comment: c })); + const now: Record = { + 5001: { kind: "gone" }, + 5002: { kind: "ok", authorId: 999, body: `@${SLUG} merge queue` }, + 5003: { kind: "ok", authorId: OP_ID, body: "never mind" }, + 5004: { kind: "ok", authorId: OP_ID, body: `@${SLUG} merge queue 9` }, + }; + const gh = ghFake(); + await drained(w, { exec: gh.exec, comment: async (_repo, id) => now[id]! }); + assert.deepEqual(rows(w).map((r) => [r.state, r.reply]), [["ignored", "none"], ["ignored", "none"], ["ignored", "none"], ["ignored", "none"]]); + assert.equal(gh.posted.length, 0); + assert.equal(preapprovalOf(w.db, "app", 1), null); + }); + + test("a PR pushed to after the comment, or whose mirror head is not GitHub's, is refused; the unchanged head is pre-approved", async () => { + const w = fresh().pr(1).pr(2).pr(3); + for (const n of [1, 2, 3]) deliver(w, payload({ body: `@${SLUG} merge queue`, number: n, comment: 6000 + n })); + const gh = ghFake(); + const head = (n: number) => (w.db.prepare("SELECT head_oid FROM items WHERE repo = 'app' AND number = ?").get(n) as { head_oid: string }).head_oid; + const pr = async (_q: unknown, _repo: string, n: number): Promise => + n === 1 ? { head: head(1), opened: "2020-01-01T00:00:00Z", changed: true } : { head: n === 2 ? "f".repeat(40) : head(3), opened: "2020-01-01T00:00:00Z", changed: false }; + await drained(w, { exec: gh.exec, pr }); + assert.deepEqual(rows(w).map((r) => r.state), ["refused", "refused", "done"]); + for (const b of gh.posted.slice(0, 2).map((p) => p.body)) assert.match(b, /Not added to the merge queue: the PR changed after your comment; comment again\.$/); + assert.equal(preapprovalOf(w.db, "app", 1), null); + assert.equal(preapprovalOf(w.db, "app", 2), null); + assert.equal(preapprovalOf(w.db, "app", 3)?.head, head(3)); + }); + + test("on an issue, a closing PR opened or pushed to after the comment is named, not queued", async () => { + const w = fresh().issue(3).pr(4); + w.db.prepare("UPDATE items SET closing_issues = '[3]' WHERE repo = 'app' AND number = 4").run(); + deliver(w, payload({ body: `@${SLUG} merge queue`, number: 3, pr: false })); + const gh = ghFake(); + readAt(w, 4, new Date(Date.now() + 1000)); + const pr = async (): Promise => ({ head: "a".repeat(40), opened: new Date(Date.now() + 1000).toISOString(), changed: false }); + await drained(w, { exec: gh.exec, pr }); + assert.equal(rows(w)[0]!.state, "done"); + assert.equal(preapprovalOf(w.db, "app", 4), null); + assert.deepEqual(fastTrackList(w.db).map((f) => f.number), [3]); + assert.match(gh.posted[0]!.body, /#4 closes it but was opened or pushed to after your comment, so it was not queued; comment on #4 to queue it/); + }); + + test("an access GitHub cannot read is retried, and the command that expires that way is answered once", async () => { + const w = fresh().pr(1); + deliver(w, payload({ body: `@${SLUG} merge queue` })); + const gh = ghFake(); + await drained(w, { exec: gh.exec, permission: async () => ({ kind: "unavailable" }) }); + assert.equal(rows(w)[0]!.state, "queued"); + await drained(w, { exec: gh.exec, now: () => new Date(Date.now() + 3600_000) }); + assert.deepEqual(rows(w).map((r) => [r.state, r.reply]), [["expired", "posted"]]); + assert.match(gh.posted[0]!.body, /@op Not added to the merge queue: could not check your access; comment again\.$/); + await drained(w, { exec: gh.exec, now: () => new Date(Date.now() + 3600_000) }); + assert.equal(gh.posted.length, 1); + }); + + test("a quiet PR: a maintainer's command is refused without an answer, an operator's is carried out without one", async () => { + const w = fresh().pr(1); + w.db.prepare("INSERT INTO access (login, role, github_id) VALUES ('maint', 'maintainer', 202)").run(); + w.db.prepare(`INSERT INTO security_findings (repo, number, scan_id, area, title, severity, state, refs, reach, impact, fingerprint, fix_pr, created_at, updated_at) + VALUES ('app', 1, 1, 'a', 't', 'high', 'landing', '[]', 'r', 'i', 'f', 1, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z')`).run(); + deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202, comment: 5001 })); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5002 })); + const gh = ghFake(); + await drained(w, { exec: gh.exec }); + assert.deepEqual(rows(w).map((r) => [r.state, r.reply]), [["refused", "none"], ["done", "none"]]); + assert.equal(gh.posted.length, 0); + assert.equal(preapprovalOf(w.db, "app", 1)?.by, OPERATOR); + }); + + test("an unexpected error is answered with a fixed text; a refused person's answer needs the repo's comment approval", async () => { + const w = fresh(["comment"]).pr(1); + w.db.prepare("INSERT INTO access (login, role, github_id) VALUES ('maint', 'maintainer', 202)").run(); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5001 })); + deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202, comment: 5002 })); + const gh = ghFake(); + await drained(w, { exec: gh.exec, queue: async () => { throw new Error("SQLITE_BUSY: database is locked"); } }); + assert.deepEqual(rows(w).map((r) => [r.state, r.result, r.reply]), [["refused", "it could not be queued", "posted"], ["refused", rows(w)[1]!.result, "failed"]]); + assert.equal(gh.posted.length, 1); + assert.match(gh.posted[0]!.body, /@op Not added to the merge queue: it could not be queued\.$/); + }); + + test("prSince sees a force push, a later commit or a later first check suite on the head", async () => { + const since = "2026-01-01T12:00:00Z", before = "2026-01-01T11:00:00Z", after = "2026-01-01T13:00:00Z"; + const answer = (o: { push?: string; date?: string; suites?: string[] }) => validating({ + spent: 0, remaining: 5000, + async query() { + return { repository: { pullRequest: { createdAt: before, headRefOid: "h1", timelineItems: { nodes: o.push ? [{ createdAt: o.push }] : [] }, + commits: { nodes: [{ commit: { oid: "h0", committedDate: before, checkSuites: { nodes: [] } } }, { commit: { oid: "h1", committedDate: o.date ?? before, checkSuites: { nodes: (o.suites ?? []).map((createdAt) => ({ createdAt })) } } }] } } } }; + }, + }); + const changed = async (o: Parameters[0]) => (await prSince(answer(o), "app", 1, since))?.changed; + assert.equal(await changed({ suites: [before, after] }), false); + assert.equal(await changed({}), false); + assert.equal(await changed({ push: after }), true); + assert.equal(await changed({ push: before, date: after }), true); + assert.equal(await changed({ suites: [after] }), true); + assert.deepEqual(await prSince(answer({}), "app", 1, since), { head: "h1", opened: before, changed: false }); + }); +});