From a8ab84a50c6d6d413d84fc7d102b8b35dd3becbf Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 20 Nov 2026 13:10:42 +0100 Subject: [PATCH] Merge queue from GitHub comments: `@ merge queue [weight]` on a PR or issue queues it as a line of Queue items, as the commenter, under the same rule (settleRefusal); the webhook keeps only the comment id, item, weight and commenter in github_commands (never the text), the runner carries it out after the item's re-read with the commenter's write permission read from GitHub, and the app answers in the thread through write.ts; commenters without an AutoCraft login, or with another GitHub id than the bound one, get no answer Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/operations.md | 10 ++ docs/pipeline.md | 2 +- src/dash/server/index.ts | 2 +- src/github/commands.ts | 188 +++++++++++++++++++++++++++++++++ src/github/webhooks.ts | 15 +-- src/runner/runner.ts | 8 +- src/schema.sql | 17 +++ test/github-commands.test.ts | 198 +++++++++++++++++++++++++++++++++++ 9 files changed, 432 insertions(+), 10 deletions(-) create mode 100644 src/github/commands.ts create mode 100644 test/github-commands.test.ts diff --git a/README.md b/README.md index 472055d03..1b930dcc9 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ Write the client ID, client secret and a random session key (at least 32 charact Point `AUTOCRAFT_SECRETS_FILE` at it. The server refuses to start if the file is missing, incomplete, or readable by group or others. -To sign in through a GitHub App instead, register it from the dashboard's GitHub App page (operators only). The dashboard then adds the `github_app_*` keys (`github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret`, `github_app_owner`) to the same file itself, so the file's directory must be writable by the server user. Then choose "GitHub App" as the GitHub identity on the same page; it is refused unless the app covers every tracked repo. `AUTOCRAFT_GITHUB_APP_NAME` sets the name the registration form suggests. +To sign in through a GitHub App instead, register it from the dashboard's GitHub App page (operators only). The dashboard then adds the `github_app_*` keys (`github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret`, `github_app_owner`) to the same file itself, so the file's directory must be writable by the server user. Then choose "GitHub App" as the GitHub identity on the same page; it is refused unless the app covers every tracked repo. `AUTOCRAFT_GITHUB_APP_NAME` sets the name the registration form suggests. With the app's webhooks on, anyone who may use Queue items on the merge queue page can add a pull request or issue to the merge queue from GitHub by commenting `@ merge queue` on it; the app answers in the thread (docs/operations.md, Webhooks). | Variable | Meaning | |---|---| diff --git a/docs/operations.md b/docs/operations.md index 7cb5a1704..a4097c647 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -43,6 +43,16 @@ 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), and 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` (also `merge-queue` or `mergequeue`, any case; an optional weight from 1 to 10 follows: `@ merge queue 8` or `... weight 8`). 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: + +- 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. 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 that GitHub's permission read cannot settle stays queued and is retried; one not carried out within an hour is dropped unanswered (`expired`). + +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). + Sync also stores the hashes the planner compares, on the item row: `embed_hash` (the embedded text, `src/embed/text.ts`) and `class_hash` with `class_scheme` (the classifier's input hash, `src/itemhash.ts`). `classify-new` and `embed` select changed items from these columns on covering indexes instead of hashing every body. The first `connect()` after an upgrade fills them for existing rows (about 6 s for 56,000 items). An edit of title, body or size outside sync clears the row's hashes, and the readers fill them again. Schema: `src/schema.sql`. Full-text search uses the FTS5 tables `items_fts` and `comments_fts`, kept current by triggers; the first `connect()` after an upgrade builds them (about 16 s for 56k items and 65k comments). Mirror tables are overwritten by sync; work tables (classifications, stages, whitelist overrides, token use) are ours. diff --git a/docs/pipeline.md b/docs/pipeline.md index dcc7f7056..f43904060 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. It opens a dialog that takes PRs and issues, one GitHub URL, `repo#n` or `owner/repo#n` per line, and 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. +**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. It opens a dialog that takes PRs and issues, one GitHub URL, `repo#n` or `owner/repo#n` per line, and 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. 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). 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/server/index.ts b/src/dash/server/index.ts index 56a1baefe..14f5ece23 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -676,7 +676,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { throw e; } const one = (v: string | string[] | undefined): string | undefined => (Array.isArray(v) ? v[0] : v); - const v = handleDelivery(db, config.secrets.app?.webhookSecret ?? null, { signature: one(req.headers["x-hub-signature-256"]), event: one(req.headers["x-github-event"]) }, raw, safeEqual); + const v = handleDelivery(db, config.secrets.app?.webhookSecret ?? null, { signature: one(req.headers["x-hub-signature-256"]), event: one(req.headers["x-github-event"]) }, raw, safeEqual, config.secrets.app?.slug ?? null); return reply(v.status); } diff --git a/src/github/commands.ts b/src/github/commands.ts new file mode 100644 index 000000000..d03468916 --- /dev/null +++ b/src/github/commands.ts @@ -0,0 +1,188 @@ +// Commands to the GitHub App in a GitHub comment. Someone who may use Queue items on the repo writes, on a line of its own, +// +// @ 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. +// +// 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. +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 { fastPositions } from "../fasttrack.ts"; +import { exec as defaultExec, type Exec } from "../fixup/git.ts"; +import type { Querier } from "../mirror.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 within this long is dropped unanswered (the runner was down, or GitHub could not tell the permission). */ +const EXPIRE_MS = 3600_000; +const AUDIT_LOGIN = "github-command"; + +export type Command = { command: "merge-queue"; weight: number | null }; + +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. + */ +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 fenced = false; + for (const raw of body.slice(0, BODY_MAX).split(/\r?\n/)) { + const line = raw.trim(); + if (/^(```|~~~)/.test(line)) { fenced = !fenced; continue; } + if (fenced) continue; + const m = re.exec(line); + if (m) return { command: "merge-queue", weight: m[1] === undefined ? null : Number(m[1]) }; + } + return null; +} + +type Obj = Record; +const obj = (v: unknown): Obj => (v && typeof v === "object" && !Array.isArray(v) ? (v as Obj) : {}); +const posInt = (v: unknown): number | null => (typeof v === "number" && Number.isSafeInteger(v) && v > 0 ? v : null); + +/** + * Queues the command of a new `issue_comment` in a tracked repo (`repo`, as webhooks.ts resolved it). A redelivery of the same + * comment adds nothing. Comments by bots and apps are left alone. Returns true when a command was queued. + */ +export function queueCommand(db: DatabaseSync, repo: string, event: string, payload: unknown, slug: string | null | undefined, now: Date = new Date()): boolean { + if (event !== "issue_comment" || !slug) return false; + const p = obj(payload); + if (p.action !== "created") return false; + const comment = obj(p.comment), user = obj(comment.user), issue = obj(p.issue); + if (user.type !== "User" || comment.performed_via_github_app) return false; + const login = typeof user.login === "string" && LOGIN.test(user.login) ? user.login : null; + const githubId = posInt(user.id), commentId = posInt(comment.id), number = posInt(issue.number); + if (!login || !githubId || !commentId || !number) return false; + const cmd = parseCommand(comment.body, slug); + if (!cmd) return false; + const r = db.prepare(`INSERT OR IGNORE INTO main.github_commands (comment_id, repo, number, pr, command, weight, login, github_id, requested_at, state) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued')`) + .run(commentId, repo, number, issue.pull_request ? 1 : 0, cmd.command, cmd.weight, login, githubId, now.toISOString()); + return r.changes > 0; +} + +type Row = { comment_id: number; repo: string; number: number; pr: number; command: string; weight: number | null; login: string; github_id: number; requested_at: string; state: string; result: string | null }; + +/** What carries out a queued merge-queue command: the Queue page's queueAdd, as the commenter. `canWrite`: GitHub's answer for `repo`, read just before. Injectable for tests. */ +export type QueueFn = (db: DatabaseSync, o: { login: string; role: Role; canWrite: boolean; repo: string; item: string; weight: number | null }) => Promise; + +const defaultQueue: QueueFn = async (db, o) => { + const { queueAdd } = await import("../dash/api/queue-page.ts"); + // The permission read covers the item's repo only; any other repo counts as no access. + const has = async (repo: string): Promise => repo === o.repo && o.canWrite; + const user = { login: o.login, role: o.role, canWrite: has, canRead: has }; + const req = { method: "POST" as const, path: "/webhooks/github", params: {}, query: new URLSearchParams(), form: new URLSearchParams(), json: { item: o.item, ...(o.weight === null ? {} : { weight: o.weight }) }, user, csrf: "", nonce: "" }; + return (await queueAdd(db, req, "github")).label; +}; + +export type CommandDeps = { + /** Reads the commenter's permission on the repo from GitHub. */ + querier: Querier; + /** Runs `gh` for the answer. */ + exec?: Exec; + queue?: QueueFn; + /** Reads the live permission (default: the conversation cards' read, src/conversations/act.ts). */ + permission?: (q: Querier, repo: string, login: string) => Promise<"ok" | "no" | "transient">; + now?: () => Date; + log?: (l: string) => void; + limit?: number; +}; + +const oneLine = (s: string): string => s.replace(/\s+/g, " ").trim().slice(0, 300).replace(/[.\s]+$/, ""); +const refOf = (r: { repo: string; number: number }): string => `${r.repo}#${r.number}`; + +function settle(db: DatabaseSync, r: Row, state: "done" | "refused" | "ignored" | "expired", result: string | null, at: Date): void { + db.prepare("UPDATE main.github_commands SET state = ?, result = ?, done_at = ? WHERE comment_id = ?").run(state, result, at.toISOString(), r.comment_id); + audit(db, state === "ignored" || state === "expired" ? AUDIT_LOGIN : r.login, "github-command", refOf(r), { comment: r.comment_id, command: r.command, by: r.login, state, ...(result ? { result } : {}) }); +} + +/** + * Decides one queued command and carries it out. Who may queue is not decided here: queueAdd applies the rule of every person-started write + * (settleRefusal in src/settlers.ts) to the commenter's current role and the write permission read from GitHub now. This only settles what a + * comment adds: who the commenter is. Returns false when GitHub could not tell the permission: the row stays queued. + */ +async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date): Promise { + const access = getAccess(db, r.login); + const bound = (db.prepare("SELECT github_id FROM main.access WHERE login = ?").get(r.login) as { github_id: number | null } | undefined)?.github_id ?? null; + // Not someone AutoCraft knows (no login, or the login now belongs to another GitHub account): no answer. + if (!access || (bound !== null && Number(bound) !== r.github_id)) { settle(db, r, "ignored", null, now); return true; } + if (bound === null) { settle(db, r, "refused", "sign in to the AutoCraft dashboard once first, so your GitHub account is bound to your login", now); return true; } + const permission = deps.permission ?? (await import("../conversations/act.ts")).liveWrite; + const p = await permission(deps.querier, r.repo, r.login).catch(() => "transient" as const); + if (p === "transient") return false; + try { + const label = await (deps.queue ?? defaultQueue)(db, { login: r.login, role: access.role, canWrite: p === "ok", repo: r.repo, item: refOf(r), weight: r.weight }); + const f = fastPositions(db).get(refOf(r)); + settle(db, r, "done", `${oneLine(label)}.${f ? ` Fast-tracked with weight ${f.weight}, ${f.position} of ${f.of}.` : ""}`, now); + } catch (e) { + settle(db, r, "refused", oneLine(String((e as Error)?.message ?? e)) || "it could not be queued", now); + } + return true; +} + +/** The answer posted on GitHub for a carried-out command. */ +export function answerText(r: { login: string; state: string; result: string | null }): string { + return r.state === "done" ? `@${r.login} ${r.result}` : `@${r.login} Not added to the merge queue: ${r.result}.`; +} + +/** Posts the answer. A paced write leaves it for the next drain; any other failure is recorded (write.ts audits it) and not retried. */ +async function answer(db: DatabaseSync, r: Row, deps: CommandDeps): Promise<"posted" | "failed" | "paced"> { + const g = guardRepo(db, r.repo, null, { operator: r.login }, undefined, r.login); + let reply: "posted" | "failed"; + if ("refused" in g) { + deps.log?.(`github command ${refOf(r)}: no answer: ${g.refused}`); + reply = "failed"; + } else { + try { + const out = await ghComment({ db, login: r.login }, g, deps.exec ?? defaultExec, "github-command-reply", { repo: r.repo, number: r.number, pr: r.pr === 1 }, { by: "fixed-operator" }, answerText(r), { comment: r.comment_id, command: r.command }); + reply = out.code === 0 ? "posted" : "failed"; + if (out.code !== 0) deps.log?.(`github command ${refOf(r)}: the answer failed: ${oneLine(out.stderr || out.stdout)}`); + } catch (e) { + if (e instanceof WritePacedError) return "paced"; + deps.log?.(`github command ${refOf(r)}: the answer failed: ${oneLine(String((e as Error)?.message ?? e))}`); + reply = "failed"; + } + } + db.prepare("UPDATE main.github_commands SET reply = ? WHERE comment_id = ?").run(reply, r.comment_id); + return reply; +} + +/** + * Carries out the queued commands, oldest first, and posts their answers. Run after the webhook's re-reads, so the item is in the + * mirror at its current head. Returns how many commands were settled. + */ +export async function drainCommands(db: DatabaseSync, deps: CommandDeps): Promise { + const clock = deps.now ?? (() => new Date()); + const rows = db.prepare(`SELECT comment_id, repo, number, pr, command, weight, login, github_id, requested_at, state, result FROM main.github_commands + WHERE state = 'queued' OR (state IN ('done', 'refused') AND reply IS NULL) ORDER BY requested_at LIMIT ?`).all(deps.limit ?? 10) as Row[]; + let settled = 0; + for (const r0 of rows) { + const now = clock(); + let r = r0; + if (r.state === "queued") { + if (now.getTime() - Date.parse(r.requested_at) > EXPIRE_MS) { settle(db, r, "expired", null, now); continue; } + if (r.command !== "merge-queue") { settle(db, r, "ignored", null, now); continue; } + // The webhook's re-read of the item comes first, so the command sees the item at its current head. + if (db.prepare("SELECT 1 FROM main.sync_requests WHERE repo = ? AND number = ?").get(r.repo, r.number)) continue; + if (!(await carryOut(db, r, deps, now))) continue; + settled++; + r = db.prepare("SELECT comment_id, repo, number, pr, command, weight, login, github_id, requested_at, state, result FROM main.github_commands WHERE comment_id = ?").get(r.comment_id) as Row; + if (r.state !== "done" && r.state !== "refused") continue; + } + if ((await answer(db, r, deps)) === "paced") break; + } + return settled; +} diff --git a/src/github/webhooks.ts b/src/github/webhooks.ts index cfaf7986e..26bf743ae 100644 --- a/src/github/webhooks.ts +++ b/src/github/webhooks.ts @@ -1,7 +1,9 @@ // GitHub App webhooks. A delivery is verified, reduced to the repo and item number it names, and queued; the -// runner re-reads those items from GitHub. Nothing else in the payload is stored or read, and none of it reaches a prompt. +// runner re-reads those items from GitHub. A new comment addressed to the app with a command (src/github/commands.ts) also +// queues that command, with the commenter and the comment's id. Nothing else in the payload is stored, and none of it reaches a prompt. import { createHmac } from "node:crypto"; import type { DatabaseSync } from "node:sqlite"; +import { queueCommand } from "./commands.ts"; import { ONE_QUERY, Transient, writeItemNode, type Querier } from "../mirror.ts"; import { ownerOf } from "../owners.ts"; @@ -57,11 +59,12 @@ export function itemNumbers(db: DatabaseSync, repo: string, event: string, paylo } } -/** Queues the items one delivery names, one row per item. Returns how many were queued. */ -export function queueDelivery(db: DatabaseSync, event: string, payload: unknown, now: Date = new Date()): number { +/** Queues the items one delivery names, one row per item, and a command to the app (`appSlug`) in a new comment. Returns how many items were queued. */ +export function queueDelivery(db: DatabaseSync, event: string, payload: unknown, now: Date = new Date(), appSlug?: string | null): number { const p = obj(payload); const repo = trackedName(db, p); if (!repo) return 0; + queueCommand(db, repo, event, p, appSlug, now); const numbers = itemNumbers(db, repo, event, p); if (!numbers.length) return 0; const at = now.toISOString().replace(/\.\d+Z$/, "Z"); @@ -73,8 +76,8 @@ export function queueDelivery(db: DatabaseSync, event: string, payload: unknown, export type Verdict = { status: number; queued?: number }; -/** One delivery: verifies the signature over the raw body, then queues. Never throws on bad input. */ -export function handleDelivery(db: DatabaseSync, secret: string | null, headers: { signature?: string; event?: string }, raw: Buffer, safeEqual: (a: string, b: string) => boolean): Verdict { +/** One delivery: verifies the signature over the raw body, then queues. `appSlug` is the app's slug, which comments address commands to. Never throws on bad input. */ +export function handleDelivery(db: DatabaseSync, secret: string | null, headers: { signature?: string; event?: string }, raw: Buffer, safeEqual: (a: string, b: string) => boolean, appSlug?: string | null): Verdict { if (!secret) return { status: 401 }; if (!headers.signature || !safeEqual(headers.signature, signatureOf(secret, raw))) return { status: 401 }; const event = headers.event ?? ""; @@ -85,7 +88,7 @@ export function handleDelivery(db: DatabaseSync, secret: string | null, headers: } catch { return { status: 400 }; } - return { status: 202, queued: queueDelivery(db, event, payload) }; + return { status: 202, queued: queueDelivery(db, event, payload, new Date(), appSlug) }; } /** Requests older than this are dropped: the poll has read the item since. */ diff --git a/src/runner/runner.ts b/src/runner/runner.ts index b1af92191..42ed69f3d 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -189,7 +189,8 @@ export class Runner { private webhookTick(): void { if (this.webhooking || Date.now() - this.webhookAt < WEBHOOK_DRAIN_MS) return; this.webhookAt = Date.now(); - if (!this.db.prepare("SELECT 1 FROM main.sync_requests LIMIT 1").get()) return; + const commands = !!this.db.prepare("SELECT 1 FROM main.github_commands WHERE state = 'queued' OR (state IN ('done', 'refused') AND reply IS NULL) LIMIT 1").get(); + if (!commands && !this.db.prepare("SELECT 1 FROM main.sync_requests LIMIT 1").get()) return; this.webhooking = (async () => { const { lockHeld, lockPath, fullLockPath, Client, SYNC_RESERVE } = await import("../mirror.ts"); if (lockHeld(lockPath()) || lockHeld(fullLockPath())) return; @@ -197,6 +198,11 @@ export class Runner { const { drainSyncRequests } = await import("../github/webhooks.ts"); const n = await drainSyncRequests(this.db, c, { limit: 10, log: this.o.log }); if (n) this.o.log(`webhooks: read ${n} items again`); + // Commands in comments (`@ merge queue`) after the re-reads, so the item is read at its current head. + if (!commands) return; + const { drainCommands } = await import("../github/commands.ts"); + const k = await drainCommands(this.db, { querier: c, log: this.o.log }); + if (k) this.o.log(`webhooks: carried out ${k} commands from comments`); })().catch((e) => this.o.log(`webhooks: ${(e as Error).message}`)).finally(() => (this.webhooking = null)); } diff --git a/src/schema.sql b/src/schema.sql index 62deee263..46ac6a1f3 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -563,6 +563,23 @@ CREATE TABLE IF NOT EXISTS sync_requests ( requested_at TEXT NOT NULL, PRIMARY KEY (repo, number) ) WITHOUT ROWID; +-- Commands an operator wrote to the GitHub App in a comment (`@ merge queue`, src/github/commands.ts), for the runner to +-- carry out and answer. Only these fields of the delivery are kept, never the comment's text. Bookkeeping: no live topic. +CREATE TABLE IF NOT EXISTS github_commands ( + comment_id INTEGER PRIMARY KEY, -- GitHub's id of the comment: a redelivery adds nothing + repo TEXT NOT NULL, + number INTEGER NOT NULL, + pr INTEGER NOT NULL, -- 1: the comment is on a pull request + command TEXT NOT NULL, -- merge-queue + weight INTEGER, -- the fast-track weight given, or null for the default + login TEXT NOT NULL, -- the commenter, as GitHub sent it + github_id INTEGER NOT NULL, -- the commenter's numeric GitHub id + requested_at TEXT NOT NULL, + state TEXT NOT NULL, -- queued | done | refused | ignored (unknown commenter: no answer) | expired + result TEXT, -- what the answer says + done_at TEXT, + reply TEXT -- posted | failed; null while the answer is still to post +); -- A tracked repo the last sync could not read: skipped for the run, retried by the next. Bookkeeping: no live topic. CREATE TABLE IF NOT EXISTS sync_repo_errors ( repo TEXT PRIMARY KEY, diff --git a/test/github-commands.test.ts b/test/github-commands.test.ts new file mode 100644 index 000000000..d67869d2a --- /dev/null +++ b/test/github-commands.test.ts @@ -0,0 +1,198 @@ +// Commands in GitHub comments: `@ merge queue` from an operator queues the item as Queue items does and the app answers. +import assert from "node:assert/strict"; +import { afterEach, describe, test } from "node:test"; +import { safeEqual } from "../src/dash/server/crypto.ts"; +import { drainCommands, parseCommand, type CommandDeps } from "../src/github/commands.ts"; +import { handleDelivery, signatureOf } from "../src/github/webhooks.ts"; +import type { Exec } from "../src/fixup/git.ts"; +import { fastTrackList } from "../src/fasttrack.ts"; +import { preapprovalOf } from "../src/preapproval/index.ts"; +import { OPERATOR, world, type World } from "./world-db.ts"; + +const SLUG = "autocraft-bot"; +const SECRET = "hook-secret"; +const OP_ID = 101; + +let current: World | null = null; +const fresh = (off: Parameters[0] = []): World => { + const w = (current = world().repo(off)); + w.db.prepare("UPDATE access SET github_id = ? WHERE login = ?").run(OP_ID, OPERATOR); + return w; +}; +afterEach(() => current?.close()); + +const payload = (o: { body: string; number?: number; login?: string; id?: number; comment?: number; action?: string; type?: string; pr?: boolean; repo?: string }) => ({ + action: o.action ?? "created", + repository: { full_name: o.repo ?? "storytold/app", name: "app" }, + issue: { number: o.number ?? 1, ...(o.pr === false ? {} : { pull_request: { url: "x" } }) }, + comment: { id: o.comment ?? 5000, body: o.body, user: { login: o.login ?? OPERATOR, id: o.id ?? OP_ID, type: o.type ?? "User" } }, +}); +const deliver = (w: World, p: unknown, slug: string | null = SLUG) => { + const raw = Buffer.from(JSON.stringify(p)); + return handleDelivery(w.db, SECRET, { event: "issue_comment", signature: signatureOf(SECRET, raw) }, raw, safeEqual, slug); +}; +const rows = (w: World) => w.db.prepare("SELECT comment_id, number, pr, weight, login, state, result, reply FROM github_commands ORDER BY comment_id").all().map((r) => ({ ...r })); + +/** A fake gh that records the comments it posts. */ +function ghFake(code = 0) { + const posted: { args: string[]; body: string }[] = []; + const exec: Exec = async (_cmd, args, opts) => { + posted.push({ args, body: String(opts?.input ?? "") }); + return { code, stdout: code ? "" : "https://github.com/storytold/app/pull/1#issuecomment-9", stderr: code ? "boom" : "" }; + }; + return { posted, exec }; +} +const deps = (w: World, o: Partial & { perm?: "ok" | "no" | "transient" } = {}): CommandDeps => ({ + querier: w.gh.querier, permission: async () => o.perm ?? "ok", ...o, +}); +const drained = async (w: World, o: Parameters[1] = {}) => { + w.db.exec("DELETE FROM sync_requests"); + return drainCommands(w.db, deps(w, o)); +}; + +describe("parseCommand", () => { + test("a line of its own addressed to the app, any case and spelling, with an optional weight", () => { + assert.deepEqual(parseCommand(`@${SLUG} merge queue`, SLUG), { command: "merge-queue", weight: null }); + assert.deepEqual(parseCommand(`Looks good.\n\n @Autocraft-Bot Merge-Queue! \nthanks`, SLUG), { command: "merge-queue", weight: null }); + assert.deepEqual(parseCommand(`@${SLUG} mergequeue 8`, SLUG), { command: "merge-queue", weight: 8 }); + assert.deepEqual(parseCommand(`@${SLUG}[bot]: merge queue weight 3`, SLUG), { command: "merge-queue", weight: 3 }); + assert.deepEqual(parseCommand(`@${SLUG} merge queue 42`, SLUG), { command: "merge-queue", weight: 42 }, "the range is checked when it is carried out"); + }); + + test("other apps, other words, quotes, code and text around the command do not count", () => { + for (const body of [ + "@other-bot merge queue", `@${SLUG}x merge queue`, `please @${SLUG} merge queue`, `@${SLUG} merge queue now please`, + `> @${SLUG} merge queue`, "```\n@" + SLUG + " merge queue\n```", `@${SLUG} merge`, "", `@${SLUG} merge queue 123`, + ]) assert.equal(parseCommand(body, SLUG), null, body); + assert.equal(parseCommand(`@${SLUG} merge queue`, ""), null); + assert.equal(parseCommand(null, SLUG), null); + assert.equal(parseCommand(`@a.b merge queue`, "a-b"), null, "the slug is matched literally"); + }); +}); + +describe("webhook", () => { + test("a new comment with a command is queued once with the commenter, never its text; other comments queue none", () => { + const w = fresh().pr(1); + assert.equal(deliver(w, payload({ body: `@${SLUG} merge queue 7` })).status, 202); + assert.equal(deliver(w, payload({ body: `@${SLUG} merge queue 7` })).status, 202, "a redelivery"); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5001, action: "edited" })); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5002, type: "Bot" })); + deliver(w, payload({ body: "just a comment", comment: 5003 })); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5004, repo: "someoneelse/app" })); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5005 }), null); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5006, login: "bad login" })); + assert.deepEqual(rows(w), [{ comment_id: 5000, number: 1, pr: 1, weight: 7, login: OPERATOR, state: "queued", result: null, reply: null }]); + const cols = (w.db.prepare("SELECT name FROM pragma_table_info('github_commands')").all() as { name: string }[]).map((c) => c.name); + assert.ok(!cols.includes("body"), "the comment's text has no column"); + assert.deepEqual(w.db.prepare("SELECT number FROM sync_requests").all().map((r) => ({ ...r })), [{ number: 1 }], "the item is still re-read"); + }); +}); + +describe("drainCommands", () => { + test("an operator with write access queues the PR as Queue items does, and the app answers in the thread", async () => { + const w = fresh().pr(1); + deliver(w, payload({ body: `@${SLUG} merge queue 7` })); + const gh = ghFake(); + assert.equal(await drained(w, { exec: gh.exec }), 1); + assert.equal(preapprovalOf(w.db, "app", 1)?.state, "review"); + assert.deepEqual(fastTrackList(w.db).map((f) => [f.number, f.weight]), [[1, 7]]); + const [r] = rows(w) as { state: string; reply: string; result: string }[]; + assert.equal(r!.state, "done"); + assert.equal(r!.reply, "posted"); + assert.equal(gh.posted.length, 1); + assert.deepEqual(gh.posted[0]!.args.slice(0, 5), ["pr", "comment", "1", "--repo", "storytold/app"]); + assert.match(gh.posted[0]!.body, /^_Automated reply_\n\n@op Added to the merge queue; .*Fast-tracked with weight 7, 1 of 1\.$/); + const audit = w.db.prepare("SELECT action, login, details FROM audit WHERE action IN ('preapproval', 'fasttrack-add', 'github-command', 'github-command-reply') ORDER BY rowid").all() as { action: string; login: string; details: string }[]; + assert.deepEqual(audit.map((a) => [a.action, a.login]), [["preapproval", OPERATOR], ["fasttrack-add", OPERATOR], ["github-command", OPERATOR], ["github-command-reply", OPERATOR]]); + assert.equal(JSON.parse(audit[1]!.details).via, "github"); + assert.equal(JSON.parse(audit[3]!.details).state, "done"); + assert.equal(await drained(w, { exec: gh.exec }), 0, "nothing is left"); + assert.equal(gh.posted.length, 1); + }); + + test("the command waits for the item's re-read", async () => { + const w = fresh().pr(1); + deliver(w, payload({ body: `@${SLUG} merge queue` })); + const gh = ghFake(); + assert.equal(await drainCommands(w.db, deps(w, { exec: gh.exec })), 0); + assert.equal(rows(w)[0]!.state, "queued"); + }); + + test("a stranger, or a login now held by another GitHub account, gets no answer and changes nothing", async () => { + const w = fresh().pr(1); + deliver(w, payload({ body: `@${SLUG} merge queue`, login: "stranger", id: 999 })); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5001, id: 998 })); + const gh = ghFake(); + await drained(w, { exec: gh.exec }); + assert.deepEqual(rows(w).map((r) => r.state), ["ignored", "ignored"]); + assert.equal(gh.posted.length, 0); + assert.equal(preapprovalOf(w.db, "app", 1), null); + }); + + test("Queue items' rule decides: a maintainer without maintainer writes, a viewer and an operator without write access are refused; so is an unbound login", async () => { + const w = fresh().pr(1); + w.db.prepare("INSERT INTO access (login, role, github_id) VALUES ('maint', 'maintainer', 202), ('view', 'viewer', 404), ('newop', 'operator', NULL)").run(); + deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202 })); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5001, login: "view", id: 404 })); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5002, login: "newop", id: 303 })); + const gh = ghFake(); + await drained(w, { exec: gh.exec }); + deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5003 })); + await drained(w, { exec: gh.exec, perm: "no" }); + assert.deepEqual(rows(w).map((r) => r.state), ["refused", "refused", "refused", "refused"]); + assert.equal(preapprovalOf(w.db, "app", 1), null); + const bodies = gh.posted.map((p) => p.body); + assert.match(bodies[0]!, /@maint Not added to the merge queue: only an operator, or a maintainer with write access where the app acts for them, queues items on app\.$/); + assert.match(bodies[1]!, /@view Not added to the merge queue: only an operator, or a maintainer/); + assert.match(bodies[2]!, /@newop Not added to the merge queue: sign in to the AutoCraft dashboard once first/); + assert.match(bodies[3]!, /@op Not added to the merge queue: no write access to storytold\/app/); + assert.equal((w.db.prepare("SELECT github_id FROM access WHERE login = 'newop'").get() as { github_id: number | null }).github_id, null, "a comment never binds an id"); + }); + + test("a maintainer who settles decisions on the repo queues, as with Queue items; without write access they do not", async () => { + const w = fresh().pr(1).pr(2); + w.db.prepare("INSERT INTO access (login, role, github_id) VALUES ('maint', 'maintainer', 202)").run(); + w.db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('maintainer_writes', '1'), ('github_identity', 'app')").run(); + deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202, number: 2, comment: 6000 })); + await drained(w, { exec: ghFake().exec, perm: "no" }); + assert.equal(rows(w)[0]!.state, "refused"); + assert.equal(preapprovalOf(w.db, "app", 2), null); + deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202, comment: 6001 })); + await drained(w, { exec: ghFake().exec }); + assert.equal(rows(w)[1]!.state, "done"); + assert.equal(preapprovalOf(w.db, "app", 1)?.by, "maint"); + }); + + test("queueAdd's refusal is the answer; an unclear permission keeps the command for later", async () => { + const w = fresh(["merge"]).pr(1); + deliver(w, payload({ body: `@${SLUG} merge queue` })); + const gh = ghFake(); + await drained(w, { exec: gh.exec, perm: "transient" }); + assert.equal(rows(w)[0]!.state, "queued"); + assert.equal(gh.posted.length, 0); + await drained(w, { exec: gh.exec }); + assert.equal(rows(w)[0]!.state, "refused"); + assert.match(gh.posted[0]!.body, /@op Not added to the merge queue: merging is not approved for app\.$/); + }); + + test("an issue is fast-tracked; an answer that fails is recorded and not posted again", async () => { + const w = fresh().issue(3); + deliver(w, payload({ body: `@${SLUG} merge queue`, number: 3, pr: false })); + const gh = ghFake(1); + await drained(w, { exec: gh.exec }); + assert.deepEqual(fastTrackList(w.db).map((f) => f.number), [3]); + assert.equal(gh.posted[0]!.args[0], "issue"); + assert.deepEqual(rows(w).map((r) => [r.state, r.reply]), [["done", "failed"]]); + await drained(w, { exec: gh.exec }); + assert.equal(gh.posted.length, 1); + }); + + test("a command not carried out within an hour is dropped unanswered", async () => { + const w = fresh().pr(1); + deliver(w, payload({ body: `@${SLUG} merge queue` })); + const gh = ghFake(); + await drained(w, { exec: gh.exec, now: () => new Date(Date.now() + 2 * 3600_000) }); + assert.deepEqual(rows(w).map((r) => r.state), ["expired"]); + assert.equal(gh.posted.length, 0); + }); +});