mirror of
https://github.com/storytold/autocraft.git
synced 2026-12-01 10:33:55 +01:00
Merge queue from GitHub comments: @<app-slug> 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
8635323e6e
commit
a8ab84a50c
9 files changed
+432
-10
No files matched your search
@@ -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,
|
||||
//
|
||||
// @<app-slug> merge queue (also merge-queue, mergequeue; optional weight: `@<app-slug> 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: `@<slug> 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<string, unknown>;
|
||||
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<string>;
|
||||
|
||||
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<boolean> => 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<boolean> {
|
||||
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<number> {
|
||||
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;
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
Reference in new issue
Block a user