diff --git a/README.md b/README.md index 1b930dcc..d069ba73 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. 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). +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). The same people can comment `@ autorepin ` on a pull request that pins another tracked repository's crates to an unmerged pull request: once that pull request is merged, AutoCraft pushes a commit that repins them to its merge commit (docs/operations.md, Autorepin). | Variable | Meaning | |---|---| diff --git a/docs/operations.md b/docs/operations.md index 1b32b2bb..4811e347 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -53,6 +53,17 @@ The runner drains `sync_requests` every 5 seconds while rows exist (`webhookTick - 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, no app answer, or a head without a check suite) 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. +**Autorepin** (`src/repin`). A pull request that needs an unmerged change in another tracked repository (a craft-libs pull request, say) pins that repository's crates to a commit of its branch, and has to be repinned to the merge commit once the change is merged. A comment on the pull request with, on a line of its own, `@ autorepin ` (`auto-repin` works as well) has AutoCraft do that. The pull request is named as `owner/name#12`, `name#12` or its GitHub URL; `@ autorepin off` drops every autorepin still waiting on the pull request. It is a command like the one above (same commenters, same storage plus the named repository and number, same answer in the thread), with these differences: + +- Who may is the same rule (`settleRefusal`), for the pull request's repo. The command is refused on an issue, for a repository AutoCraft does not track, for a pull request the mirror has not read or that was closed without merging, for one in the pull request's own repo, where **Pushes** are not approved for the repo, and where no build worker would take its lockfile task (the repo is outside the pipeline's scope and the PR is not fast-tracked). A repo that leaves that scope before the task is queued fails the autorepin with the same reason. It does not wait for a re-read: nothing is written at a head when it is set. The comment read again must still name the same pull request (or still say `off`). +- One row per pull request and dependency repository is kept in `autorepins`; a second command for the same repository replaces the first, so a pull request can wait on one pull request in each of several repositories. Commands count in the order of their comments: one carried out late (a retried permission read) never sets again what a later `off` dropped, nor replaces a later command's pull request. The latest `off` of each pull request is kept in `autorepin_offs`, also when nothing was waiting, so a command written before it sets nothing. An `off`, a try that starts over, or any end cancels a lockfile task still running. +- Nothing happens while the named pull request is open. The runner looks at the rows on every pass of `webhookTick` from the database alone (`src/repin/due.ts`): a row is due when the mirror shows the named pull request merged or closed (the webhook's re-read of that repository brings that in within seconds, the poll otherwise), when its lockfile task ended or has run for 3 hours (no build worker took it, say: the autorepin then fails), or when its outcome is still to post. A pass takes at most 5 due rows. The drain starts after the pass's comment commands and runs on its own, so its git work never holds up the next pass's re-reads and commands. +- Once it is merged, the merge commit is read from GitHub. It must be on that repository's default branch: a merge into another branch fails the autorepin, and so does a merge commit that is no longer an ancestor of the branch as fetched now (a branch rewritten since). Then the access of the person who asked is read again (their AutoCraft login, still bound to the GitHub account that asked, their live write permission through the app, `settleRefusal`, and on a quiet pull request only an operator), the Pushes approval is checked again, and the pull request is read live: it must be open and its branch one AutoCraft may push to (the rule of fix-ups, `src/fixup/pushable.ts`). +- No model is involved. In every `Cargo.toml` of the pull request's head, the `rev` of each git source on the repository (dependencies of every kind, `[workspace.dependencies]`, `[patch]`) is set to the full merge commit id by a text edit that is accepted only if the manifest then parses to the same data with exactly those values replaced (`src/repin/manifest.ts`). Only dependency tables count; a `git` and `rev` elsewhere (`[package.metadata]`) are not touched. A `Cargo.toml` that cannot be read (a failed read, a link, over the size limit) ends the try, so a repin never covers only some manifests; one that names the repository but does not parse fails the autorepin, naming the file. Sources on the repository without a `rev` (a branch, a tag) are left alone; a pull request with no `rev` on it fails the autorepin. +- A `Cargo.lock` below the repository root fails the autorepin: the task updates only the root one. With a `Cargo.lock` at the repository root, a build task (step `autorepin`, one step with network, the fetch step's environment: no repository cargo config or toolchain file, nothing of the repository runs) gets the manifest edit as its patch, runs `cargo update --workspace` and returns `Cargo.lock`. The lockfile is read as TOML, before and after, and accepted only if every package of the repository is at the merge commit, pinned by rev (one on a branch or tag is refused with that reason), every other package is in the old lockfile with the same name, source, version and checksum, and the only packages added are crates.io packages whose name the old lockfile has from no source (crates.io under either index spelling, git or another registry). Packages may be dropped. Without a lockfile there is no task. +- The commit ("Repin to ", authored like the pipeline's other commits) changes only those manifests and the lockfile, and is pushed with a lease on the head it was made on (`pushRepin` in `src/github/write.ts`, audit action `autorepin-push`). A head that moved meanwhile, a failed lockfile task or a GitHub read that fails starts the autorepin over after a minute, at most 5 times; then it fails with the last reason. A reason AutoCraft did not word itself (git or database errors) is only logged; the comment then gives a fixed reason. +- The outcome is one comment on the pull request naming the person who asked (audit action `autorepin-comment`): the commit and the files it changed, why it failed, or that the named pull request was closed without merging. A quiet pull request gets no comment. A pull request that itself closed or merged first drops its autorepins without a comment. The new head goes through Review and Verify like any new head. A merge pre-approved at the old head (`@ merge queue`, Queue items) carries on to the repinned head as it does across the pipeline's own base merge (`ownPush` in `src/preapproval/index.ts`): the row goes back to `review`, and the review, the pre-merge review and CI must be clean at the new head before the PR reaches the merge queue. As for a base merge, this holds until the row is `queued`: a pre-approval whose Merge answer is already written for the old head is cancelled by the repin, with the reason in the PR's thread, and a person queues the PR again. So a pull request that has both commands needs nobody between the dependency's merge and its own. + 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. diff --git a/docs/pipeline.md b/docs/pipeline.md index 4ad001df..6ea4a132 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -763,6 +763,9 @@ Automated work waits only for the reasons below. A stage that is not running sho | Unsent comment | A fix-up, conflict or CI fix comment that never reached GitHub (no installation token for the GitHub App, so no request went out) is posted again (the CI fix posts its stored patch, with no new model or lint run); one whose request went out may have been posted and is final | 10 minutes after the first, 1 hour after the second; a third that is not sent is final and the PR waits for a person | Plan wait: the comment again after hh:mm | | Conflict merge cap for today | At most 2 merges of the base branch per PR per UTC day (over all heads); a busy base branch otherwise keeps a PR in a merge, check and review loop | Until the next UTC day | Plan wait: conflict merge cap for today reached | | CI results of earlier pushes | A repository with 3 pushes of ours whose required checks are not final yet gets no further push from Fix-up, CI fix or the default-branch fix | Until the checks of those pushes end (a push without a result is settled as unknown after 3 days) | Items skipped for another job or run; no state change | +| Autorepin waiting for its pull request | An `@ autorepin` command names a pull request of another tracked repo; nothing happens until that pull request is merged or closed, which the mirror reports (the webhook's re-read within seconds, the poll otherwise) | Until the named pull request is merged or closed (days, often), the PR itself closes, or `@ autorepin off` | none (the answer to the command, then the comment with the outcome) | +| Autorepin lockfile task | Once the pull request an `@ autorepin` command names is merged, a build worker runs `cargo update --workspace` on the repinned manifests; the commit is pushed when the task ends | Until the task ends (minutes); at most 3 hours, then the autorepin fails with a comment on the PR | Builds page (step autorepin) | +| Autorepin retry | An autorepin attempt that did not finish (GitHub could not be read, the head moved, the lockfile task failed) starts again | 1 minute between tries, at most 5; then the autorepin fails with a comment on the PR | none (the comment on the PR tells the outcome) | | Sandbox build | External | Until the task ends; a build-environment error queues it again once per head | Verification state `planned` or `running` | | PR build | External | Until the task ends; a build-environment error queues it again once per head | Our build on the item: running | | Screenshot render | External | Until both tasks end | Screenshot run `planned` or `running` | diff --git a/src/db.ts b/src/db.ts index 4a8e295a..81597459 100644 --- a/src/db.ts +++ b/src/db.ts @@ -249,6 +249,8 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [ ["mcp_tokens", "can_agent", "INTEGER NOT NULL DEFAULT 0"], ["runner_logins", "want_agent", "INTEGER NOT NULL DEFAULT 1"], ["runner_logins", "want_answer", "INTEGER NOT NULL DEFAULT 0"], + ["github_commands", "ref_repo", "TEXT"], + ["github_commands", "ref_number", "INTEGER"], ]; // Indexes on added columns: they can only be created once the column exists. diff --git a/src/github/actions.ts b/src/github/actions.ts index 41ff9823..1789b2da 100644 --- a/src/github/actions.ts +++ b/src/github/actions.ts @@ -33,6 +33,7 @@ export const GITHUB_ACTIONS: Record = { "ci-rerun": "Reran failed CI jobs", "cifix-push": "Pushed", "cifix-comment": "Commented", + "autorepin-push": "Pushed", "postmerge-file": "Opened issue", "act-open-issue": "Opened issue", "discord-issue-open": "Opened issue", diff --git a/src/github/commands.ts b/src/github/commands.ts index ad255289..cf9c9bc8 100644 --- a/src/github/commands.ts +++ b/src/github/commands.ts @@ -5,6 +5,12 @@ // 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 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. +// A second command, on a pull request only, +// +// @ autorepin (also auto-repin; `owner/name#12`, `name#12`, its URL, or `off`) +// +// has the pull request's Cargo dependencies on that pull request's repository repinned to its merge commit once it is merged +// (src/repin/index.ts). The answer says it is set; the outcome is a later comment. // // 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, the comment must still exist @@ -23,6 +29,7 @@ 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 { parsePrRef, type PrRef } from "../repin/manifest.ts"; import { appPermission, type AppPermission } from "../remote/permission.ts"; import { isQuiet } from "../security/quiet.ts"; import { settleRefusal } from "../settlers.ts"; @@ -44,8 +51,12 @@ 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"; +const NOT_SET = "it could not be set"; -export type Command = { command: "merge-queue"; weight: number | null }; +export type Command = { command: "merge-queue"; weight: number | null } | { command: "autorepin"; /** The pull request to wait for; null: `off`. */ ref: PrRef | null }; + +/** A command's pull request as stored in ref_repo: `owner/name` or `name`, as written. */ +const refText = (ref: PrRef): string => `${ref.owner ? `${ref.owner}/` : ""}${ref.name}`; const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -53,11 +64,12 @@ 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 (`> ...`), 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. + * after but spaces. `@ autorepin ` names the pull request as `owner/name#12`, `name#12` or its URL; `off` drops it. */ 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"); + const repin = new RegExp(`^@${escape(slug)}(?:\\[bot\\])?[\\s,:]+auto[-\\s]?repin\\s+(\\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/)) { @@ -84,6 +96,11 @@ export function parseCommand(body: unknown, slug: string): Command | null { if (/^(?: {4}| {0,3}\t)/.test(text)) continue; const m = re.exec(line); if (m) return { command: "merge-queue", weight: m[1] === undefined ? null : Number(m[1]) }; + const a = repin.exec(line)?.[1]; + if (a === undefined) continue; + if (a.toLowerCase() === "off") return { command: "autorepin", ref: null }; + const ref = parsePrRef(a); + if (ref) return { command: "autorepin", ref }; } return null; } @@ -110,14 +127,16 @@ export function queueCommand(db: DatabaseSync, repo: string, event: string, payl if (now.getTime() - created > STALE_MS) 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, created_at, requested_at, state) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued')`) - .run(commentId, repo, number, issue.pull_request ? 1 : 0, cmd.command, cmd.weight, login, githubId, new Date(created).toISOString(), now.toISOString()); + const ref = cmd.command === "autorepin" ? cmd.ref : null; + const r = db.prepare(`INSERT OR IGNORE INTO main.github_commands (comment_id, repo, number, pr, command, weight, ref_repo, ref_number, login, github_id, created_at, requested_at, state) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued')`) + .run(commentId, repo, number, issue.pull_request ? 1 : 0, cmd.command, cmd.command === "merge-queue" ? cmd.weight : null, + ref ? refText(ref) : null, ref ? ref.number : null, login, githubId, new Date(created).toISOString(), 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; created_at: string; requested_at: string; state: string; result: string | null; retries: number; allowed: number | null; reply: string | null }; -const COLS = "comment_id, repo, number, pr, command, weight, login, github_id, created_at, requested_at, state, result, retries, allowed, reply"; +type Row = { comment_id: number; repo: string; number: number; pr: number; command: string; weight: number | null; ref_repo: string | null; ref_number: number | null; login: string; github_id: number; created_at: string; requested_at: string; state: string; result: string | null; retries: number; allowed: number | null; reply: string | null }; +const COLS = "comment_id, repo, number, pr, command, weight, ref_repo, ref_number, login, github_id, created_at, requested_at, state, result, retries, allowed, reply"; /** * What carries out a queued merge-queue command: the Queue page's queueAdd, as the commenter. `canWrite`: GitHub's answer for `repo`, @@ -235,8 +254,8 @@ function settle(db: DatabaseSync, r: Row, state: "done" | "refused" | "ignored" const quietFor = (db: DatabaseSync, r: Row, qp: QueuePage): boolean => [r.number, ...(r.pr ? [] : qp.openPrsClosing(db, r.repo, r.number))].some((n) => isQuiet(db, r.repo, n)); -/** The commenter's access row while the login is bound to the commenter's GitHub id; a login never bound counts as unknown. */ -function boundAccess(db: DatabaseSync, r: Row): NonNullable> | null { +/** The access row of `login` while it is bound to the GitHub id `github_id`; a login never bound counts as unknown. */ +export function boundAccess(db: DatabaseSync, r: { login: string; github_id: number }): NonNullable> | null { 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; return access && bound !== null && Number(bound) === r.github_id ? access : null; @@ -249,7 +268,7 @@ function boundAccess(db: DatabaseSync, r: Row): NonNullable> | null { const access = boundAccess(db, r); if (!access) { settle(db, r, "ignored", null, now); return null; } - if (access.role !== "operator" && access.role !== "maintainer") { settle(db, r, "refused", "viewers cannot queue items", now); return null; } + if (access.role !== "operator" && access.role !== "maintainer") { settle(db, r, "refused", r.command === "autorepin" ? "viewers cannot set autorepin" : "viewers cannot queue items", now); return null; } if (access.role !== "operator" && quietFor(db, r, qp)) { settle(db, r, "refused", "the pull request is quiet until its fix is published", now); return null; } return access; } @@ -285,13 +304,14 @@ async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date, } const slug = deps.slug === undefined ? appSlug() : deps.slug; const cmd = c.kind === "ok" && c.authorId === r.github_id ? parseCommand(c.body, slug ?? "") : null; - if (!cmd || cmd.command !== r.command || cmd.weight !== r.weight) { + if (!cmd || !sameCommand(cmd, r)) { settle(db, r, "ignored", c.kind === "gone" ? "the comment was deleted" : "the comment no longer holds the command", clock()); return "settled"; } // A role or setting that refuses whatever GitHub says is answered without the head and permission reads. const first = knownCommenter(db, r, clock(), qp); if (!first) return "settled"; + if (cmd.command === "autorepin") return carryOutRepin(db, r, cmd.ref, deps, clock, qp); if (await refusal(db, r, first.role as Role, true, qp)) return refuse(db, r, clock(), first.role as Role, true, qp); // The head each PR had when the comment was written: the PR itself, or for an issue its one closing PR, which must also be older // than the comment. A PR opened or pushed to later maps to null and is not queued. @@ -333,6 +353,40 @@ async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date, return "settled"; } +/** The command a comment holds now is the stored one: an edit that names another pull request or weight runs nothing. */ +function sameCommand(cmd: Command, r: Row): boolean { + if (cmd.command !== r.command) return false; + if (cmd.command === "merge-queue") return cmd.weight === r.weight; + return cmd.ref === null ? r.ref_repo === null && r.ref_number === null : refText(cmd.ref) === r.ref_repo && cmd.ref.number === r.ref_number; +} + +/** + * Carries out an autorepin command (src/repin/index.ts). Nothing is written at a head here, so no head is pinned and no read since + * the comment is waited for: the push later reads the pull request live and checks the asker again. + */ +async function carryOutRepin(db: DatabaseSync, r: Row, ref: PrRef | null, deps: CommandDeps, clock: () => Date, qp: QueuePage): Promise { + const perm = await liveWrite(db, r, deps); + if (perm === "transient") return "retry"; + const now = clock(); + if (now.getTime() - Date.parse(r.requested_at) >= EXPIRE_MS) { expire(db, r, now, qp); return "settled"; } + const access = knownCommenter(db, r, now, qp); + if (!access) return "settled"; + const role = access.role as Role; + const what = `sets autorepin on ${r.repo}`; + const no = await settleRefusal(db, userOf({ login: r.login, role, repo: r.repo, canWrite: perm === "ok" }), [r.repo], what); + const quiet = quietFor(db, r, qp); + if (no) { settle(db, r, "refused", no, now, { reply: !quiet }); return "settled"; } + try { + const { requestRepin } = await import("../repin/index.ts"); + const label = await requestRepin(db, { login: r.login, githubId: r.github_id, role, canWrite: perm === "ok", repo: r.repo, number: r.number, pr: r.pr === 1, ref, at: new Date(r.created_at) }); + settle(db, r, "done", `${oneLine(label)}.`, now, { reply: !quiet, allowed: true }); + } catch (e) { + if (!(e instanceof HttpError)) deps.log?.(`github command ${refOf(r)}: ${oneLine(String((e as Error)?.message ?? e))}`); + settle(db, r, "refused", (e instanceof HttpError ? oneLine(e.message) : "") || NOT_SET, now, { reply: !quiet, allowed: true }); + } + return "settled"; +} + /** The queue rule's refusal for the commenter with `role` and GitHub's write answer `canWrite`, or null. */ const refusal = (db: DatabaseSync, r: Row, role: Role, canWrite: boolean, qp: QueuePage): Promise => settleRefusal(db, userOf({ login: r.login, role, repo: r.repo, canWrite }), [r.repo], qp.queueWhat(r.repo)); @@ -367,8 +421,8 @@ function waitsForRead(db: DatabaseSync, r: Row, now: Date, qp: QueuePage): boole } /** 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}.`; +export function answerText(r: { login: string; state: string; result: string | null; command?: string }): string { + return r.state === "done" ? `@${r.login} ${r.result}` : `@${r.login} ${r.command === "autorepin" ? "Autorepin not changed" : "Not added to the merge queue"}: ${r.result}.`; } /** @@ -421,9 +475,9 @@ export async function drainCommands(db: DatabaseSync, deps: CommandDeps): Promis let r = r0; if (r.state === "queued") { if (now.getTime() - Date.parse(r.requested_at) >= EXPIRE_MS) expire(db, r, now, qp); - else if (r.command !== "merge-queue") settle(db, r, "ignored", null, now); - // No GitHub call while an item waits for a read since the comment (see waitsForRead). - else if (waitsForRead(db, r, now, qp)) continue; + else if (r.command !== "merge-queue" && r.command !== "autorepin") settle(db, r, "ignored", null, now); + // No GitHub call while an item waits for a read since the comment (see waitsForRead); an autorepin pins no head and does not wait. + else if (r.command === "merge-queue" && waitsForRead(db, r, now, qp)) continue; else { calls++; const out = await carryOut(db, r, deps, now, qp); diff --git a/src/github/write.ts b/src/github/write.ts index c314c5ea..8d91c6f0 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -617,6 +617,17 @@ export function pushBranch(w: Writer, git: Pick, action: string, g: return pushed(w, g, git, action, refOf(g.repo, g.number), o, `--force-with-lease=refs/heads/${o.branch}:${g.head}`, details, { repo: g.repo, number: g.number }); } +/** + * Pushes an autorepin commit (src/repin) to a PR's branch: `sha` on top of `head`, the head the commit was made on, which git + * refuses when the branch has moved. Under a repo grant for pushes, made for the person who asked for the repin. + */ +export function pushRepin(w: Writer, g: GuardedRepo, git: Pick, o: { repo: string; number: number; remote: string; branch: string; head: string; sha: string }, details: Details = {}): Promise { + covers(g, o.repo); + if (g.need !== "push") throw new Error(`a grant for ${g.need ?? "no approval"} does not allow a push`); + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9._-]+$/.test(o.remote) || o.branch.startsWith("-") || !/^[0-9a-f]{40,64}$/.test(o.sha) || !/^[0-9a-f]{40,64}$/.test(o.head)) throw new Error("the push target is not a repository and branch"); + return pushed(w, g, git, "autorepin-push", refOf(o.repo, o.number), o, `--force-with-lease=refs/heads/${o.branch}:${o.head}`, { ...details, from: o.head }, { repo: o.repo, number: o.number }); +} + /** Pushes `sha` to `branch` of the pipeline's own fork, replacing the branch. */ export function pushOwnBranch(w: Writer, g: Grant, git: Pick, action: string, o: { repo: string; number?: number; remote: string; branch: string; sha: string }, details: Details = {}, /** The push needs the box account whatever the repo's identity (an advisory's private fork, which the app cannot reach). */ asBox = false): Promise { opensOwnPr(g, o.repo); diff --git a/src/preapproval/index.ts b/src/preapproval/index.ts index b7d582af..b758d309 100644 --- a/src/preapproval/index.ts +++ b/src/preapproval/index.ts @@ -349,13 +349,15 @@ function reviewAt(db: DatabaseSync, p: Row, head: string): ReviewRead { } /** - * "base merge" or "fix-up for the review's fixes" when the pipeline itself pushed `cur` on top of the row's head without adding code a person did not see, else null. + * "base merge", "autorepin" or "fix-up for the review's fixes" when the pipeline itself pushed `cur` on top of the row's head without adding code a person did not see, else null. * The review's fix-up counts only for a row that began with the operator's own fix-up: a plain Merge answer carried across a base merge never covered model-written code. */ function ownPush(db: DatabaseSync, p: Row, cur: string): string | null { if (p.fix_id !== null && db.prepare("SELECT 1 FROM fixups WHERE repo = ? AND number = ? AND from_head = ? AND to_head = ? AND COALESCE(source, 'review') = 'review' AND state IN ('pushing', 'pushed')").get(p.repo, p.number, p.head, cur)) return "fix-up for the review's fixes"; // Only a base merge that left the PR's own diff unchanged continues an answer; a CI fix or a resolved conflict is model-written code nobody saw. if (db.prepare("SELECT 1 FROM conflict_merges WHERE repo = ? AND number = ? AND from_head = ? AND to_head = ? AND state = 'merged' AND own_diff = 'same'").get(p.repo, p.number, p.head, cur)) return "base merge"; + // An autorepin (src/repin) is no model's code either: the revs of a dependency moved to a merge commit on its default branch, as someone who may queue the PR asked. + if (db.prepare("SELECT 1 FROM main.autorepins WHERE repo = ? AND number = ? AND head = ? AND to_head = ? AND state IN ('waiting', 'locking', 'pushed')").get(p.repo, p.number, p.head, cur)) return "autorepin"; return null; } diff --git a/src/repin/due.ts b/src/repin/due.ts new file mode 100644 index 00000000..4b9431ca --- /dev/null +++ b/src/repin/due.ts @@ -0,0 +1,33 @@ +// Which autorepins (src/repin/index.ts) have something to do now. Read from the database alone and without the modules the +// work needs, so the runner can ask on every tick. +import type { DatabaseSync } from "node:sqlite"; + +/** An attempt that did not finish is tried again after this long. */ +export const RETRY_MS = 60_000; +/** A lockfile task that has not ended this long after it was queued (no build worker took it, say) ends the autorepin. */ +export const LOCK_MAX_MS = 3 * 3600_000; + +export type RepinRow = { + repo: string; number: number; ref_repo: string; ref_number: number; login: string; github_id: number; requested_at: string; + state: "waiting" | "locking" | "pushed" | "failed" | "cancelled"; + sha: string | null; head: string | null; task_id: number | null; tries: number; to_head: string | null; result: string | null; notice: string | null; +}; + +// waiting: the dependency's pull request is no longer open (merged or closed), or this one is; locking: the lockfile task +// has ended, or has run out of time; ended: the comment that tells the outcome is still to post. +const DUE = `(a.state = 'waiting' AND (a.tried_at IS NULL OR a.tried_at <= ?1) AND ( + EXISTS (SELECT 1 FROM main.items i WHERE i.repo = a.ref_repo AND i.number = a.ref_number AND i.state != 'OPEN') + OR NOT EXISTS (SELECT 1 FROM main.items i WHERE i.repo = a.repo AND i.number = a.number AND i.kind = 'pr' AND i.state = 'OPEN'))) + OR (a.state = 'locking' AND NOT EXISTS (SELECT 1 FROM main.build_tasks t WHERE t.id = a.task_id AND t.state IN ('queued', 'claimed', 'running') AND t.queued_at > ?2)) + OR (a.state IN ('pushed', 'failed', 'cancelled') AND a.notice IS NULL)`; + +const before = (now: Date): [string, string] => [new Date(now.getTime() - RETRY_MS).toISOString(), new Date(now.getTime() - LOCK_MAX_MS).toISOString()]; + +/** The autorepins with a step to take, oldest first. */ +export function repinsDue(db: DatabaseSync, now: Date = new Date()): RepinRow[] { + return db.prepare(`SELECT a.* FROM main.autorepins a WHERE ${DUE} ORDER BY a.requested_at, a.repo, a.number`).all(...before(now)) as RepinRow[]; +} + +export function anyRepinDue(db: DatabaseSync, now: Date = new Date()): boolean { + return !!db.prepare(`SELECT 1 FROM main.autorepins a WHERE ${DUE} LIMIT 1`).get(...before(now)); +} diff --git a/src/repin/index.ts b/src/repin/index.ts new file mode 100644 index 00000000..489d2187 --- /dev/null +++ b/src/repin/index.ts @@ -0,0 +1,422 @@ +// Autorepin: a pull request that depends on an unmerged pull request of another tracked repository (a craft-libs change, +// say) pins that repository's crates to a commit of its branch. Someone who may queue items on the repo comments +// +// @ autorepin storytold/craft-libs#12 (also `craft-libs#12`, the pull request's URL, or `off`) +// +// and once that pull request is merged into its default branch, this one gets a commit that sets the `rev` of every Cargo +// git dependency on that repository to the merge commit, with Cargo.lock updated to match. No model is involved: +// - the manifests are rewritten here (src/repin/manifest.ts): only `rev` strings change; +// - Cargo.lock is written by `cargo update --workspace` in a build environment, never on this host, and is accepted only +// if it adds nothing but crates.io packages and the dependency at the merge commit; +// - the commit is pushed with a lease on the head it was made on (pushRepin in src/github/write.ts), under the repo's +// Pushes approval, after the access of the person who asked is read again. +// The outcome (pushed, failed with the reason, or dropped because the dependency's pull request closed unmerged) is a +// comment on the pull request, unless the pull request is quiet. Only reasons written here reach the comment; any other +// error is logged and the comment gives a fixed reason. +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import type { DatabaseSync } from "node:sqlite"; +import { absolute } from "../build/artifacts.ts"; +import { cancelTask, createTask, getTask, TERMINAL } from "../build/tasks.ts"; +import { guardRepo } from "../core/guard.ts"; +import { audit } from "../dash/audit.ts"; +import { WRITE_PERMISSIONS } from "../dash/server/provider.ts"; +import { HttpError } from "../dash/server/util.ts"; +import { ensureAuthorWrites, type PermissionReader } from "../fixup/author-permission.ts"; +import { exec as defaultExec, fixupDir, Git, type Exec } from "../fixup/git.ts"; +import { longLivedOf, pushable } from "../fixup/pushable.ts"; +import { boundAccess } from "../github/commands.ts"; +import { commitIdentity } from "../github/identity.ts"; +import { pipelineAccount } from "../github/pipeline-account.ts"; +import { ghComment, pushRepin, WritePacedError } from "../github/write.ts"; +import type { Querier } from "../mirror.ts"; +import { ownerOf, slugOf } from "../owners.ts"; +import { appPermission } from "../remote/permission.ts"; +import { isFastTracked } from "../fasttrack.ts"; +import { baseScopeRepos } from "../pilot.ts"; +import { isQuiet } from "../security/quiet.ts"; +import { settleRefusal } from "../settlers.ts"; +import { fetchScript } from "../worker/rust.ts"; +import { LOCK_MAX_MS, repinsDue, type RepinRow } from "./due.ts"; +import { lockRefusal, repinManifest, safePath, type PrRef } from "./manifest.ts"; + +/** Attempts that may end unfinished (GitHub unreadable, the head moved, the lockfile task failed) before the repin is given up. */ +export const MAX_TRIES = 5; +/** Cargo.toml files read in one pull request. */ +const MAX_MANIFESTS = 500; +const LOCK = "Cargo.lock"; +const AUDIT_LOGIN = "autorepin"; +/** The reason given on GitHub for an attempt that ended on an error this module did not word. */ +const UNEXPECTED = "an unexpected error stopped it (the AutoCraft log has the details)"; + +/** + * The lockfile step: the manifests arrive repinned (the task's patch), Cargo brings Cargo.lock in line with them, changing + * nothing else it does not have to (`--workspace`), and the result is the task's artifact. The environment is the fetch + * step's (src/worker/rust.ts): no repository cargo config, no toolchain file, and nothing of the repository runs. + */ +export const LOCK_SCRIPT = fetchScript(["/usr/local/cargo/bin/cargo update --workspace", `/bin/cp ${LOCK} /out/${LOCK}`]); + +const MERGE_QUERY = `query($owner: String!, $name: String!, $n: Int!) { + repository(owner: $owner, name: $name) { + defaultBranchRef { name } + pullRequest(number: $n) { state baseRefName mergeCommit { oid } } + } +}`; +const PR_QUERY = `query($owner: String!, $name: String!, $n: Int!) { + repository(owner: $owner, name: $name) { + pullRequest(number: $n) { + state headRefOid headRefName maintainerCanModify + headRepository { nameWithOwner } + headRef { branchProtectionRule { id } } + } + } +}`; +type MergeRead = { repository?: { defaultBranchRef?: { name: string } | null; pullRequest?: { state: string; baseRefName: string; mergeCommit?: { oid: string } | null } | null } | null }; +type PrRead = { repository?: { pullRequest?: { state: string; headRefOid: string; headRefName: string; maintainerCanModify: boolean; headRepository: { nameWithOwner: string } | null; headRef?: { branchProtectionRule?: { id: string } | null } | null } | null } | null }; + +const oneLine = (s: string): string => s.replace(/\s+/g, " ").trim().slice(0, 300).replace(/[.\s]+$/, ""); +const short = (sha: string): string => sha.slice(0, 12); +const refOf = (r: { repo: string; number: number }): string => `${r.repo}#${r.number}`; +const depRefOf = (r: { ref_repo: string; ref_number: number }): string => `${slugOf(r.ref_repo)}#${r.ref_number}`; +type Item = { kind: string; state: string }; +const itemOf = (db: DatabaseSync, repo: string, number: number): Item | undefined => + db.prepare("SELECT kind, state FROM main.items WHERE repo = ? AND number = ?").get(repo, number) as Item | undefined; + +// ---- the command --------------------------------------------------------------- + +/** + * Why no build worker would take the pull request's lockfile task, or null: workers take pipeline tasks only for repos in + * scope or for fast-tracked items (claim in src/build/tasks.ts). + */ +function outOfBuildScope(db: DatabaseSync, repo: string, number: number): string | null { + return baseScopeRepos(db).has(repo) || isFastTracked(db, repo, number) ? null : `AutoCraft's pipeline is off for ${slugOf(repo)}, so no build worker would write its lockfile`; +} + +/** Cancels a lockfile task that is no longer wanted; one that already ended is left as it is. */ +function stopTask(db: DatabaseSync, id: number | null): void { + if (id === null) return; + try { cancelTask(db, id, AUDIT_LOGIN); } catch { /* already ended, or gone */ } +} + +/** A refusal worded for the answer on GitHub. */ +const refused = (why: string): HttpError => new HttpError(409, why); + +/** + * Sets (or with `ref` null, drops) the autorepin of a pull request for the commenter of a command. Who may is the rule of + * every write a person starts (settleRefusal in src/settlers.ts). Returns what the answer says; throws an HttpError with the + * reason when refused. `at` orders the commands of a pull request: a command older than an `off` or than the command that set + * the row sets nothing. + */ +export async function requestRepin(db: DatabaseSync, o: { login: string; githubId: number; role: string; canWrite: boolean; repo: string; number: number; pr: boolean; ref: PrRef | null; /** When the command was given (the comment's time). */ at?: Date }): Promise { + if (!o.pr) throw refused("autorepin is for pull requests"); + const refusal = await settleRefusal(db, { login: o.login, role: o.role, canWrite: async (r) => r === o.repo && o.canWrite }, [o.repo], `sets autorepin on ${o.repo}`); + if (refusal) throw refused(refusal); + const at = (o.at ?? new Date()).toISOString(); + const me = itemOf(db, o.repo, o.number); + if (me?.kind !== "pr" || me.state !== "OPEN") throw refused("this pull request is not open"); + if (!o.ref) { + // Kept even when nothing waits, so an older `autorepin` command still to be carried out (a retry) does not set it again. + db.prepare(`INSERT INTO main.autorepin_offs (repo, number, off_at) VALUES (?, ?, ?) + ON CONFLICT (repo, number) DO UPDATE SET off_at = excluded.off_at WHERE excluded.off_at > autorepin_offs.off_at`).run(o.repo, o.number, at); + const tasks = db.prepare("SELECT task_id FROM main.autorepins WHERE repo = ?2 AND number = ?3 AND state = 'locking' AND requested_at <= ?1").all(at, o.repo, o.number) as { task_id: number | null }[]; + const n = db.prepare("UPDATE main.autorepins SET state = 'cancelled', result = NULL, done_at = ?1, requested_at = ?1, notice = 'none' WHERE repo = ?2 AND number = ?3 AND state IN ('waiting', 'locking') AND requested_at <= ?1").run(at, o.repo, o.number).changes; + for (const t of tasks) stopTask(db, t.task_id); + audit(db, o.login, "autorepin-off", refOf(o), { cancelled: Number(n) }); + return n ? "Autorepin is off for this pull request" : "No autorepin was waiting on this pull request; it stays off"; + } + const off = (db.prepare("SELECT off_at FROM main.autorepin_offs WHERE repo = ? AND number = ?").get(o.repo, o.number) as { off_at: string } | undefined)?.off_at; + if (off !== undefined && off > at) throw refused("a later autorepin off on this pull request stands"); + const dep = (db.prepare("SELECT name FROM main.tracked_repos WHERE name = ? COLLATE NOCASE").get(o.ref.name) as { name: string } | undefined)?.name; + if (!dep || (o.ref.owner !== null && o.ref.owner.toLowerCase() !== ownerOf(dep).toLowerCase())) throw refused(`${o.ref.owner ? `${o.ref.owner}/` : ""}${o.ref.name} is not a repository AutoCraft tracks`); + const depRef = `${slugOf(dep)}#${o.ref.number}`; + if (dep === o.repo) throw refused("the pull request to wait for must be in another repository"); + const other = itemOf(db, dep, o.ref.number); + if (other?.kind !== "pr") throw refused(`${depRef} is not a pull request AutoCraft has read`); + if (other.state === "CLOSED") throw refused(`${depRef} was closed without merging`); + const g = guardRepo(db, o.repo, "push", { operator: o.login }, undefined, o.login); + if ("refused" in g) throw refused(g.refused); + const scope = outOfBuildScope(db, o.repo, o.number); + if (scope) throw refused(scope); + // Only over a row of an earlier command: a later `off`, or a later command for the same repository, stands. + const set = db.prepare(`INSERT INTO main.autorepins (repo, number, ref_repo, ref_number, login, github_id, requested_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting') + ON CONFLICT (repo, number, ref_repo) DO UPDATE SET ref_number = excluded.ref_number, login = excluded.login, github_id = excluded.github_id, requested_at = excluded.requested_at, state = 'waiting', + sha = NULL, head = NULL, task_id = NULL, tries = 0, tried_at = NULL, to_head = NULL, result = NULL, done_at = NULL, notice = NULL + WHERE excluded.requested_at >= autorepins.requested_at`) + .run(o.repo, o.number, dep, o.ref.number, o.login, o.githubId, at).changes; + if (!set) throw refused(`a later autorepin command for ${slugOf(dep)} on this pull request stands`); + audit(db, o.login, "autorepin-set", refOf(o), { on: depRef }); + return other.state === "MERGED" + ? `Autorepin set: ${depRef} is already merged, so ${slugOf(dep)} is repinned to its merge commit here now` + : `Autorepin set: once ${depRef} is merged, ${slugOf(dep)} is repinned to its merge commit here, in a commit pushed to this branch`; +} + +// ---- the work ------------------------------------------------------------------ + +export type RepinDeps = { + querier: Querier; + /** Runs git and gh. */ + exec?: Exec; + /** Directory holding one bare cache repository per repo (default: the fix-ups'). */ + root?: string; + /** Reads the asker's live write permission (default: through the app installation, as comment commands read it). */ + permission?: (q: Querier, repo: string, login: string) => Promise<"ok" | "no" | "transient">; + /** Reads a same-repo PR author's permission (default: gh). */ + authorPermission?: PermissionReader; + now?: () => Date; + log?: (l: string) => void; + /** Autorepins that call GitHub in one drain. */ + limit?: number; +}; + +/** The step ended for good; `notice` "none": nothing is said on GitHub (the pull request itself is closed). */ +class Ended extends Error { + readonly state: "failed" | "cancelled" | "pushed"; + readonly notice: "none" | null; + readonly toHead: string | null; + constructor(state: "failed" | "cancelled" | "pushed", result: string | null, o: { notice?: "none"; toHead?: string } = {}) { + super(result ?? ""); + this.state = state; + this.notice = o.notice ?? null; + this.toHead = o.toHead ?? null; + } +} +/** `why` is worded here and safe to post. */ +const failed = (why: string): Ended => new Ended("failed", oneLine(why)); +/** The attempt did not finish and is tried again; the reason is worded here and is the outcome's when the tries run out. */ +class Retry extends Error {} + +const KEY = "repo = ? AND number = ? AND ref_repo = ?"; +const keyOf = (r: RepinRow): [string, number, string] => [r.repo, r.number, r.ref_repo]; + +function finish(db: DatabaseSync, r: RepinRow, e: Ended, at: Date): void { + stopTask(db, r.task_id); + db.prepare(`UPDATE main.autorepins SET state = ?, result = ?, done_at = ?, to_head = ?, notice = ? WHERE ${KEY}`).run(e.state, e.message || null, at.toISOString(), e.toHead, e.notice, ...keyOf(r)); + audit(db, AUDIT_LOGIN, "autorepin", refOf(r), { on: depRefOf(r), by: r.login, state: e.state, ...(e.message ? { result: e.message } : {}), ...(e.toHead ? { commit: e.toHead } : {}) }); +} + +/** One step of an autorepin: from `waiting` it queues the lockfile task (or pushes, without a lockfile); from `locking` it takes the task's lockfile and pushes. Throws `Ended` when it is over, anything else to try again. */ +async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise { + const q = d.querier, run = d.exec ?? defaultExec; + const dep = slugOf(r.ref_repo), depRef = depRefOf(r); + if (r.state === "locking" && r.task_id !== null) { + // A task no build worker finished in time ends the autorepin instead of holding it. + const t = getTask(db, r.task_id); + if (t && !TERMINAL.includes(t.state) && (d.now ?? (() => new Date()))().getTime() - Date.parse(t.queuedAt) > LOCK_MAX_MS) { + try { cancelTask(db, t.id, AUDIT_LOGIN); } catch { /* it ended meanwhile */ } + throw failed("the lockfile task did not end within 3 hours"); + } + } + const me = itemOf(db, r.repo, r.number); + if (me?.kind !== "pr" || me.state !== "OPEN") throw new Ended("cancelled", null, { notice: "none" }); + const other = itemOf(db, r.ref_repo, r.ref_number); + if (!other) throw failed(`AutoCraft no longer has ${depRef}`); + if (other.state === "CLOSED") throw new Ended("cancelled", `${depRef} was closed without merging, so nothing was repinned`); + + // The merge commit, from GitHub: it must be on the default branch, where the dependency's revs are to come from. + const m = await q.query(MERGE_QUERY, { owner: ownerOf(r.ref_repo), name: r.ref_repo, n: r.ref_number }) as MergeRead; + const merged = m.repository?.pullRequest; + if (!merged) throw new Retry(`GitHub returned no ${depRef}`); + if (merged.state === "CLOSED") throw new Ended("cancelled", `${depRef} was closed without merging, so nothing was repinned`); + if (merged.state !== "MERGED") throw new Retry(`${depRef} is not merged on GitHub yet`); + const main = m.repository?.defaultBranchRef?.name; + if (!main) throw new Retry(`GitHub returned no default branch for ${dep}`); + if (merged.baseRefName !== main) throw failed(`${depRef} was merged into ${merged.baseRefName}, not into ${dep}'s default branch ${main}`); + const sha = merged.mergeCommit?.oid ?? ""; + if (!/^[0-9a-f]{40}$/.test(sha)) throw new Retry(`GitHub returned no merge commit for ${depRef}`); + // The branch as it is now: a default branch rewritten since the merge may no longer hold the commit. + const root = d.root ?? fixupDir(); + mkdirSync(root, { recursive: true }); + const depGit = new Git(run, root, r.ref_repo); + const tip = await depGit.fetchBase(ownerOf(r.ref_repo), r.ref_repo, main); + // The fetch brought every commit the branch holds: one that is not here is not on it. + const have = (await depGit.git(["cat-file", "-e", `${sha}^{commit}`])).code === 0; + const on = have ? await depGit.git(["merge-base", "--is-ancestor", sha, tip]) : { code: 1, stderr: "" }; + if (on.code === 1) throw failed(`the merge commit of ${depRef} is no longer on ${dep}'s default branch ${main}`); + if (on.code !== 0) throw new Error(`the merge commit of ${depRef} could not be looked up on ${dep}'s ${main}: ${oneLine(on.stderr)}`); + + // Whoever asked must still be allowed to, with the login still bound to the GitHub account that asked, and the repo must + // still approve pushes. + const permission = d.permission ?? (async (_q: Querier, repo: string, login: string) => { + const a = await appPermission(db, login, repo); + return a.kind === "ok" ? (WRITE_PERMISSIONS.has(a.permission) ? "ok" as const : "no" as const) : "transient" as const; + }); + const p = await permission(q, r.repo, r.login).catch(() => "transient" as const); + if (p === "transient") throw new Retry(`GitHub could not tell ${r.login}'s access to ${slugOf(r.repo)}`); + const access = boundAccess(db, r); + if (!access) throw failed(`${r.login} no longer has an AutoCraft login bound to the GitHub account that asked`); + if (access.role !== "operator" && isQuiet(db, r.repo, r.number)) throw failed("the pull request is quiet until its fix is published"); + const refusal = await settleRefusal(db, { login: r.login, role: access.role, canWrite: async (x) => x === r.repo && p === "ok" }, [r.repo], `repins on ${r.repo}`); + if (refusal) throw failed(refusal); + const g = guardRepo(db, r.repo, "push", { operator: r.login }, undefined, r.login); + if ("refused" in g) throw failed(g.refused); + + const l = await q.query(PR_QUERY, { owner: ownerOf(r.repo), name: r.repo, n: r.number }) as PrRead; + const pr = l.repository?.pullRequest; + if (!pr) throw new Retry(`GitHub returned no ${refOf(r)}`); + if (pr.state !== "OPEN") throw new Ended("cancelled", null, { notice: "none" }); + const head = pr.headRefOid; + if (r.state === "locking" && r.head !== head) throw new Retry("the head moved while the lockfile was written"); + const headRepo = pr.headRepository?.nameWithOwner; + const writes = headRepo ? await ensureAuthorWrites(db, r.repo, r.number, headRepo, d.authorPermission) : "no"; + if (writes === "unknown") throw new Retry("the author's permission could not be read yet"); + if (!headRepo || !pushable(headRepo, r.repo, pr.maintainerCanModify, pr.headRefName, longLivedOf(db, r.repo), !!pr.headRef?.branchProtectionRule, writes === "yes")) { + throw failed("AutoCraft cannot push to this pull request's branch (a fork that does not allow maintainer edits, or a protected or shared branch)"); + } + + const git = new Git(run, root, r.repo); + const fetched = await git.fetchPr(ownerOf(r.repo), r.repo, r.number); + if (fetched !== head) throw new Retry(`the fetched head ${short(fetched)} is not the head GitHub reports`); + const paths = (await git.must(["ls-tree", "-r", "--name-only", "-z", head])).split("\0").filter(Boolean); + const manifests = paths.filter((p) => /(^|\/)Cargo\.toml$/.test(p)); + if (manifests.length > MAX_MANIFESTS) throw failed(`the pull request has more than ${MAX_MANIFESTS} Cargo.toml files`); + // Only the root Cargo.lock is written by the task; a workspace below the root with its own lockfile would keep a stale one. + const nested = paths.find((x) => x !== LOCK && /\/Cargo\.lock$/.test(x)); + if (nested) throw failed(`${safePath(nested, "a Cargo.lock")} is a lockfile below the repository root, which autorepin does not update`); + const name = r.ref_repo.toLowerCase(); + const files: { path: string; mode: string; content: string }[] = []; + let pinned = 0, unpinned = 0; + for (const path of manifests) { + const f = await git.file(head, path); + // Every manifest is read: one that cannot be (a failed read, a link, too large) ends the try, so a repin never covers only some of them. + if (!f.ok) { + d.log?.(`autorepin ${refOf(r)}: ${path}: ${oneLine(f.reason)}`); + throw new Retry(`${safePath(path, "a Cargo.toml")} could not be read`); + } + // A manifest that never names the repository (a test fixture, say) is not read as TOML at all. + if (!f.content.toLowerCase().includes(name)) continue; + const out = repinManifest(f.content, dep, sha); + if (!out.ok) { + d.log?.(`autorepin ${refOf(r)}: ${path}: ${out.reason}${out.detail ? `: ${oneLine(out.detail)}` : ""}`); + throw failed(`${safePath(path, "a Cargo.toml")}: ${out.reason}`); + } + pinned += out.pinned; + unpinned += out.unpinned; + if (out.from.length) files.push({ path, mode: f.mode, content: out.text }); + } + if (!pinned) throw failed(`no Cargo.toml of this pull request pins ${dep} by rev${unpinned ? ` (${unpinned} use a branch, a tag or no rev, which autorepin leaves alone)` : ""}`); + if (!files.length) { + // The head is the commit an earlier try pushed (the outcome was not recorded): keep it, so a merge pre-approved at the old head carries on (ownPush in src/preapproval). + if (r.to_head !== null && r.to_head === head) throw new Ended("pushed", `Repinned ${dep} to ${short(sha)}, the merge of ${depRef}, in ${short(head)}`, { toHead: head }); + throw new Ended("pushed", `${dep} is already pinned to ${short(sha)}, the merge of ${depRef}; nothing to change`); + } + + const scratch = mkdtempSync(join(root, ".index-")); + try { + let tree = await git.withFiles(head, files, join(scratch, "index")); + const changed = files.map((f) => f.path); + if (paths.includes(LOCK)) { + const lock = await git.file(head, LOCK); + if (!lock.ok) { + d.log?.(`autorepin ${refOf(r)}: ${LOCK}: ${oneLine(lock.reason)}`); + throw failed(`${LOCK} could not be read`); + } + if (r.state !== "locking") { + const scope = outOfBuildScope(db, r.repo, r.number); + if (scope) throw failed(scope); + const id = createTask(db, { + step: "autorepin", repo: r.repo, number: r.number, headSha: head, requires: { os: "linux", toolchains: ["rust-stable"] }, patch: await git.diffText(head, tree), + plan: [{ name: "lock", cmd: ["sh", "-c", LOCK_SCRIPT], network: "fetch", timeoutSec: 900, artifacts: [LOCK] }], + }); + db.prepare(`UPDATE main.autorepins SET state = 'locking', sha = ?, head = ?, to_head = NULL, task_id = ? WHERE ${KEY}`).run(sha, head, id, ...keyOf(r)); + d.log?.(`autorepin ${refOf(r)}: lockfile task ${id} queued for ${dep} at ${short(sha)}`); + return; + } + const t = db.prepare("SELECT state FROM main.build_tasks WHERE id = ?").get(r.task_id) as { state: string } | undefined; + if (t?.state !== "done") throw new Retry(`the lockfile task ${t ? t.state : "is gone"}`); + const art = db.prepare("SELECT file FROM main.build_artifacts WHERE task_id = ? AND name = ?").get(r.task_id, LOCK) as { file: string } | undefined; + const file = art ? absolute(art.file) : null; + if (!file) throw new Retry("the lockfile task returned no Cargo.lock"); + const after = readFileSync(file, "utf8"); + const no = lockRefusal(lock.content, after, dep, sha); + if (no) throw failed(no); + if (after !== lock.content) { + tree = await git.withFiles(tree, [{ path: LOCK, mode: lock.mode, content: after }], join(scratch, "index")); + changed.push(LOCK); + } + } + const who = await commitIdentity(db, r.repo, () => pipelineAccount(run)); + const commit = await git.commit(tree, head, `Repin ${r.ref_repo} to ${short(sha)}\n\nThe merge commit of ${depRef}.\n`, { name: who.name, email: who.email }); + // The commit is exactly the rewritten manifests and the lockfile: contents of files that exist, nothing added, removed or re-moded. + const changes = await git.rawChanges(head, commit); + if (changes.some((x) => x[2] !== "M" || x[0] !== x[1]) || changes.map((x) => x[3]!).sort().join("\n") !== [...changed].sort().join("\n")) throw failed("the commit would change more than the revs and the lockfile"); + // Written before the push, so a head that reaches the mirror before the outcome is recorded is already known as this commit (ownPush in src/preapproval). + db.prepare(`UPDATE main.autorepins SET head = ?, to_head = ? WHERE ${KEY}`).run(head, commit, ...keyOf(r)); + const push = await pushRepin({ db, login: AUDIT_LOGIN }, g, git, { repo: r.repo, number: r.number, remote: headRepo, branch: pr.headRefName, head, sha: commit }, { on: depRef, rev: sha, files: changed, by: r.login }); + if (push.code !== 0) { + const err = oneLine(push.stderr); + if (/stale info|rejected|fetch first/i.test(err)) throw new Retry("the branch moved before the push"); + if (/denied|403|permission|not allowed|protected branch|declined|GH013/i.test(err)) throw failed("GitHub refused the push to this pull request's branch"); + throw new Error(`the push failed: ${err}`); + } + throw new Ended("pushed", `Repinned ${dep} to ${short(sha)}, the merge of ${depRef}, in ${short(commit)} (${changed.join(", ")})`, { toHead: commit }); + } finally { + // A scratch folder that cannot be removed must not replace the outcome (a push that was made, a task that was queued). + try { rmSync(scratch, { recursive: true, force: true }); } catch (e) { d.log?.(`autorepin ${refOf(r)}: scratch folder not removed: ${oneLine(String((e as Error)?.message ?? e))}`); } + } +} + +/** The comment that tells the outcome on the pull request. */ +export function noticeText(r: Pick): string { + if (r.state === "pushed") return `@${r.login} ${r.result}.`; + return r.state === "cancelled" ? `@${r.login} Autorepin is off: ${r.result}.` : `@${r.login} Autorepin of ${slugOf(r.ref_repo)} failed: ${r.result}.`; +} + +/** Posts the outcome. A paced write leaves it for the next drain; any other failure is logged and not retried. Nothing is posted on a quiet pull request. */ +async function notify(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<"posted" | "failed" | "paced" | "none"> { + // A quiet pull request (a security fix not yet published) gets no comment. + if (isQuiet(db, r.repo, r.number)) { + db.prepare(`UPDATE main.autorepins SET notice = 'none' WHERE ${KEY}`).run(...keyOf(r)); + return "none"; + } + const g = guardRepo(db, r.repo, null, { operator: r.login }, undefined, r.login); + let notice: "posted" | "failed" = "failed"; + if ("refused" in g) d.log?.(`autorepin ${refOf(r)}: no comment: ${g.refused}`); + else { + try { + const out = await ghComment({ db, login: AUDIT_LOGIN }, g, d.exec ?? defaultExec, "autorepin-comment", { repo: r.repo, number: r.number, pr: true }, { by: "fixed-operator" }, noticeText(r), { on: depRefOf(r), state: r.state }); + if (out.code === 0) notice = "posted"; + else d.log?.(`autorepin ${refOf(r)}: the comment failed: ${oneLine(out.stderr || out.stdout)}`); + } catch (e) { + if (e instanceof WritePacedError) return "paced"; + d.log?.(`autorepin ${refOf(r)}: the comment failed: ${oneLine(String((e as Error)?.message ?? e))}`); + } + } + db.prepare(`UPDATE main.autorepins SET notice = ? WHERE ${KEY}`).run(notice, ...keyOf(r)); + return notice; +} + +/** Takes the next step of every autorepin that has one (src/repin/due.ts) and posts the outcomes. Returns how many ended. */ +export async function drainRepins(db: DatabaseSync, deps: RepinDeps): Promise { + const clock = deps.now ?? (() => new Date()); + let ended = 0, calls = 0; + for (const r0 of repinsDue(db, clock())) { + if (calls++ >= (deps.limit ?? 5)) break; + let r = r0; + if (r.state === "waiting" || r.state === "locking") { + try { + await step(db, r, deps); + continue; + } catch (e) { + if (e instanceof WritePacedError) break; + if (e instanceof Ended) finish(db, r, e, clock()); + else { + // Not finished: from the start again after a minute, and given up with the reason after MAX_TRIES. Only a reason + // worded here (Retry) is posted. head and to_head stay: a push that went out before the error is still known as ours. + const raw = oneLine(String((e as Error)?.message ?? e)); + deps.log?.(`autorepin ${refOf(r)}: try ${r.tries + 1} of ${MAX_TRIES}: ${raw}`); + if (r.tries + 1 >= MAX_TRIES) finish(db, r, failed(e instanceof Retry ? raw : UNEXPECTED), clock()); + else { + stopTask(db, r.task_id); + db.prepare(`UPDATE main.autorepins SET state = 'waiting', task_id = NULL, tries = tries + 1, tried_at = ? WHERE ${KEY}`).run(clock().toISOString(), ...keyOf(r)); + continue; + } + } + } + ended++; + r = db.prepare(`SELECT * FROM main.autorepins WHERE ${KEY}`).get(...keyOf(r)) as RepinRow; + deps.log?.(`autorepin ${refOf(r)}: ${r.state}${r.result ? `: ${r.result}` : ""}`); + } + if (r.notice === null && (await notify(db, r, deps)) === "paced") break; + } + return ended; +} diff --git a/src/repin/manifest.ts b/src/repin/manifest.ts new file mode 100644 index 00000000..e2cbee7c --- /dev/null +++ b/src/repin/manifest.ts @@ -0,0 +1,132 @@ +// The text side of autorepin (src/repin/index.ts): the pull request a command names, the `rev` of a Cargo manifest's git +// dependencies moved to a commit, and what a lockfile written for that move may change. Pure. +import { parseToml, type TomlTable } from "../core/toml.ts"; + +/** A pull request as a command names it: `owner/name#12`, `name#12` (owner null: whichever owner the tracked repo has) or its GitHub URL. */ +export type PrRef = { owner: string | null; name: string; number: number }; + +const NAME = "[A-Za-z0-9][A-Za-z0-9._-]{0,99}"; +const OWNER = "[A-Za-z0-9][A-Za-z0-9-]{0,38}"; +const REF = new RegExp(`^(?:(?:(${OWNER})/)?(${NAME})#(\\d{1,9})|https://github\\.com/(${OWNER})/(${NAME})/pull/(\\d{1,9})/?)$`); + +export function parsePrRef(s: string): PrRef | null { + const m = REF.exec(s); + if (!m) return null; + const number = Number(m[3] ?? m[6]); + return number > 0 ? { owner: m[1] ?? m[4] ?? null, name: (m[2] ?? m[5])!, number } : null; +} + +const isTable = (v: unknown): v is TomlTable => !!v && typeof v === "object" && !Array.isArray(v); +const SHA = /^[0-9a-f]{40}$/; + +/** `owner/name` (lowercase) of a GitHub repository URL as a manifest or a lockfile writes it, or null for any other source. */ +export function githubSlug(url: string): string | null { + const m = /^(?:git\+)?(?:https:\/\/(?:[^@/]+@)?github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([^/?#]+)\/([^/?#]+?)(?:\.git)?\/?(?:[?#].*)?$/i.exec(url.trim()); + return m ? `${m[1]}/${m[2]}`.toLowerCase() : null; +} + +const DEP_TABLES = ["dependencies", "dev-dependencies", "dev_dependencies", "build-dependencies", "build_dependencies"]; + +/** + * Every dependency of the manifest with a `git` source on `slug`: the dependency tables of the package, of each target and of + * the workspace, and the `[patch]` entries. No other table counts (`[package.metadata]` may hold a `git` and a `rev` of its own). + */ +function sourcesOn(data: TomlTable, slug: string): TomlTable[] { + const tables: unknown[] = DEP_TABLES.map((t) => data[t]); + if (isTable(data["workspace"])) tables.push(data["workspace"]["dependencies"]); + if (isTable(data["target"])) for (const t of Object.values(data["target"])) if (isTable(t)) tables.push(...DEP_TABLES.map((d) => t[d])); + if (isTable(data["patch"])) tables.push(...Object.values(data["patch"])); + const out: TomlTable[] = []; + for (const deps of tables) { + if (!isTable(deps)) continue; + for (const spec of Object.values(deps)) if (isTable(spec) && typeof spec["git"] === "string" && githubSlug(spec["git"]) === slug.toLowerCase()) out.push(spec); + } + return out; +} + +export type Repinned = + /** `text`: the manifest with every `rev` on the repository set to the commit. `from`: the revs it replaced (none: nothing to change). `unpinned`: sources on the repository without a `rev` (a branch, a tag or the default branch), left as they are. */ + | { ok: true; text: string; from: string[]; pinned: number; unpinned: number } + /** `reason` is worded here, safe to post; `detail` (the parser's message) is for the log only. */ + | { ok: false; reason: string; detail?: string }; + +/** + * The manifest with the `rev` of every git source on `slug` (`owner/name`) set to `sha`. Only the rev strings change: the + * rewritten text must parse to the same manifest with exactly those values replaced, or it is refused. + */ +export function repinManifest(text: string, slug: string, sha: string): Repinned { + if (!SHA.test(sha)) return { ok: false, reason: "the commit is not a full commit id" }; + const before = parseToml(text); + if (!before.ok) return { ok: false, reason: "the manifest does not parse as TOML", detail: before.error }; + const sources = sourcesOn(before.data, slug); + const revs = sources.flatMap((t) => (typeof t["rev"] === "string" ? [t["rev"]] : [])); + const unpinned = sources.filter((t) => t["rev"] === undefined).length; + if (sources.some((t) => t["rev"] !== undefined && typeof t["rev"] !== "string")) return { ok: false, reason: "a rev of the manifest is not a string" }; + const from = [...new Set(revs.filter((r) => r !== sha))]; + if (!from.length) return { ok: true, text, from, pinned: revs.length, unpinned }; + if (from.some((r) => !/^[0-9a-fA-F]{7,64}$/.test(r))) return { ok: false, reason: "a rev of the manifest is not a commit id" }; + let out = text; + for (const r of from) out = out.replace(new RegExp(`(\\brev\\s*=\\s*)(["'])${r}\\2`, "g"), `$1"${sha}"`); + // What the edit must amount to: the same manifest with those revs replaced, and nothing else. + for (const t of sources) if (typeof t["rev"] === "string") t["rev"] = sha; + const after = parseToml(out); + if (!after.ok || JSON.stringify(after.data) !== JSON.stringify(before.data)) return { ok: false, reason: "the rev could not be rewritten without changing something else in the manifest" }; + return { ok: true, text: out, from, pinned: revs.length, unpinned }; +} + +type Locked = { name: string; version: string; source: string | null; checksum: string | null }; + +/** The packages of a Cargo.lock, read as TOML; null when it does not parse or a package's name, version, source or checksum is not what Cargo writes. */ +function lockedPackages(text: string): Locked[] | null { + const r = parseToml(text); + if (!r.ok) return null; + const list = r.data["package"] ?? []; + if (!Array.isArray(list)) return null; + const out: Locked[] = []; + for (const p of list) { + if (!isTable(p) || typeof p["name"] !== "string" || typeof p["version"] !== "string") return null; + const source = p["source"] ?? null, checksum = p["checksum"] ?? null; + if ((source !== null && typeof source !== "string") || (checksum !== null && typeof checksum !== "string")) return null; + out.push({ name: p["name"], version: p["version"], source, checksum }); + } + return out; +} + +const CRATES_IO = new Set(["registry+https://github.com/rust-lang/crates.io-index", "sparse+https://index.crates.io/"]); + +/** A package name as Cargo writes it, else a neutral word, so a reason never repeats arbitrary file text. */ +export const safeName = (s: string): string => (/^[A-Za-z0-9_-]{1,64}$/.test(s) ? s : "a package"); +/** A repository path of plain characters, else a neutral word. */ +export const safePath = (s: string, what: string): string => (/^[A-Za-z0-9._/-]{1,200}$/.test(s) ? s : what); + +/** + * Why the lockfile `after`, written by Cargo for the repinned manifests, is not accepted in place of `before`, or null. + * Every package of `slug` must be at `sha`, pinned by rev. Any other package must be in `before` with the same name, source, + * version and checksum, except a crates.io package whose name `before` has from no source at all: Cargo may add those for the + * dependency's new requirements. Packages may be dropped. + */ +export function lockRefusal(before: string, after: string, slug: string, sha: string): string | null { + const was = lockedPackages(before), now = lockedPackages(after); + if (!was || !now) return "the lockfile does not read as a Cargo.lock"; + if (!now.length) return "the new lockfile lists no packages"; + const exact = (p: Locked): string => `${p.name}\0${p.source ?? ""}\0${p.version}\0${p.checksum ?? ""}`; + const kept = new Set(was.map(exact)); + // Names the old lockfile has from crates.io (either index's spelling) or from any other source but a local path. + const known = new Set(was.filter((p) => p.source !== null).map((p) => p.name)); + const want = slug.toLowerCase(); + for (const p of now) { + const name = safeName(p.name); + const repo = p.source === null ? null : githubSlug(p.source.split("?")[0]!.split("#")[0]!); + if (p.source !== null && p.source.startsWith("git+") && repo === want) { + // Cargo writes `git+?rev=#`. + if (p.source.endsWith(`?rev=${sha}#${sha}`)) continue; + if (!/\?rev=/.test(p.source)) return `the new lockfile has ${name} from ${slug} by branch, tag or default branch; autorepin moves only revs, so pin it by rev to use autorepin`; + return `the new lockfile has ${name} from ${slug} at another commit`; + } + if (kept.has(exact(p))) continue; + if (p.source === null) return `the new lockfile adds or changes the local package ${name}`; + if (!CRATES_IO.has(p.source)) return `the new lockfile adds ${name} from a source outside crates.io and ${slug}`; + if (known.has(p.name)) return `the new lockfile changes the version, source or checksum of ${name}`; + } + return null; +} diff --git a/src/runner/runner.ts b/src/runner/runner.ts index 611a62bd..e086ded4 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -29,6 +29,7 @@ import { jobBlock } from "./concurrency.ts"; import { queueRoomPass } from "../agents/call.ts"; import { stepDeadlineMin, stepNoProgressMin } from "./deadlines.ts"; import { envVar } from "../env.ts"; +import { anyRepinDue } from "../repin/due.ts"; import { jobRemoteQueue, REMOTE_WAIT_CAP_MS, withdrawJobCalls } from "../remote/calls.ts"; export const logsDir = (): string => envVar("RUNNER_LOGS") ?? join(homedir(), ".cache/autocraft-logs/jobs"); @@ -103,6 +104,8 @@ export class Runner { private flowAt = 0; private webhookAt = 0; private webhooking: Promise | null = null; + /** The autorepin drain (src/repin), apart from the webhook pass so its git work never delays re-reads and comment commands. */ + private repinning: Promise | null = null; private webhookClient: import("../mirror.ts").Client | null = null; private reconcileAt = 0; private reconciling: Promise | null = null; @@ -191,7 +194,9 @@ export class Runner { if (this.webhooking || Date.now() - this.webhookAt < WEBHOOK_DRAIN_MS) return; this.webhookAt = Date.now(); const commands = !!this.db.prepare(`SELECT 1 FROM main.github_commands WHERE ${COMMAND_WORK_SQL} LIMIT 1`).get(); - if (!commands && !this.db.prepare("SELECT 1 FROM main.sync_requests LIMIT 1").get()) return; + // Autorepins whose pull request was merged or closed, or whose lockfile task ended (src/repin). + const repins = !this.repinning && anyRepinDue(this.db); + if (!commands && !repins && !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; @@ -200,9 +205,19 @@ export class Runner { 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 k = await drainCommands(this.db, { querier: c, log: this.o.log }); - if (k) this.o.log(`webhooks: carried out ${k} commands from comments`); + if (commands) { + const k = await drainCommands(this.db, { querier: c, log: this.o.log }); + if (k) this.o.log(`webhooks: carried out ${k} commands from comments`); + } + // Started after the commands, so an autorepin set on a pull request that is already merged starts in this pass, and not + // waited for: the next pass's re-reads and commands do not wait on its git work. + if ((repins || commands) && !this.repinning) { + this.repinning = (async () => { + const { drainRepins } = await import("../repin/index.ts"); + const k = await drainRepins(this.db, { querier: c, log: this.o.log }); + if (k) this.o.log(`autorepin: ${k} ended`); + })().catch((e) => this.o.log(`autorepin: ${(e as Error).message}`)).finally(() => (this.repinning = null)); + } })().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 f72f95d5..6c0bbb56 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -563,14 +563,14 @@ CREATE TABLE IF NOT EXISTS sync_requests ( requested_at TEXT NOT NULL, PRIMARY KEY (repo, number) ) WITHOUT ROWID; --- Commands a person wrote to the GitHub App in a comment (`@ merge queue`, src/github/commands.ts), for the runner to +-- Commands a person wrote to the GitHub App in a comment (`@ merge queue`, `@ autorepin `, 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 + command TEXT NOT NULL, -- merge-queue | autorepin 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 @@ -582,9 +582,42 @@ CREATE TABLE IF NOT EXISTS github_commands ( tried_at TEXT, -- the last try that waited on GitHub (a re-read or a read that failed); the next one waits a minute retries INTEGER NOT NULL DEFAULT 0, -- tries GitHub could not settle (permission, comment or head read) allowed INTEGER, -- 1: the commenter may queue on the repo, so the answer needs no comment approval - reply TEXT -- posted | failed | none (no answer is given); null while the answer is still to post + reply TEXT, -- posted | failed | none (no answer is given); null while the answer is still to post + ref_repo TEXT, -- autorepin: the repository of the pull request it names, as written (`owner/name` or `name`); null with ref_number: autorepin off + ref_number INTEGER ); CREATE INDEX IF NOT EXISTS github_commands_state ON github_commands(state, reply); +-- Autorepin (src/repin): once the pull request `ref_repo#ref_number` is merged, the pull request `repo#number` gets a commit that +-- sets the `rev` of its Cargo dependencies on `ref_repo` to that merge commit. One row per pull request and dependency repository; +-- a new command for the same pair replaces it. Bookkeeping: no live topic. +CREATE TABLE IF NOT EXISTS autorepins ( + repo TEXT NOT NULL, + number INTEGER NOT NULL, + ref_repo TEXT NOT NULL, -- tracked repo name of the dependency + ref_number INTEGER NOT NULL, + login TEXT NOT NULL, -- who asked; their access is checked again before the push + github_id INTEGER NOT NULL, -- the asker's numeric GitHub id: the login must still be bound to it at the push + requested_at TEXT NOT NULL, + state TEXT NOT NULL, -- waiting (for the merge) | locking (the lockfile task runs) | pushed | failed | cancelled + sha TEXT, -- the merge commit, once read + head TEXT, -- the PR head the task works on (locking) and the commit was made on (pushed) + task_id INTEGER, -- locking: the build task that writes Cargo.lock + tries INTEGER NOT NULL DEFAULT 0, -- attempts that did not finish (GitHub unreadable, the head moved, the task failed) + tried_at TEXT, -- the last such attempt; the next one waits a minute + to_head TEXT, -- the commit pushed, written right before the push (pushed with null: nothing needed changing) + result TEXT, -- what the comment on the pull request says + done_at TEXT, + notice TEXT, -- posted | failed | none; null while the comment is still to post + PRIMARY KEY (repo, number, ref_repo) +) WITHOUT ROWID; +-- The latest `autorepin off` per pull request: a command written before it (one carried out late, after retries) sets nothing. +-- Bookkeeping: no live topic. +CREATE TABLE IF NOT EXISTS autorepin_offs ( + repo TEXT NOT NULL, + number INTEGER NOT NULL, + off_at TEXT NOT NULL, -- the creation time of the off command's comment + PRIMARY KEY (repo, number) +) WITHOUT ROWID; -- 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/src/stages/registry.ts b/src/stages/registry.ts index 16871e21..c5180bed 100644 --- a/src/stages/registry.ts +++ b/src/stages/registry.ts @@ -312,6 +312,9 @@ export const STAGES: StageDef[] = [ { name: "Unsent comment", why: "A fix-up, conflict or CI fix comment that never reached GitHub (no installation token for the GitHub App, so no request went out) is posted again (the CI fix posts its stored patch, with no new model or lint run); one whose request went out may have been posted and is final", howLong: "10 minutes after the first, 1 hour after the second; a third that is not sent is final and the PR waits for a person", showsAs: "Plan wait: the comment again after hh:mm", kind: "backoff" }, { name: "Conflict merge cap for today", why: "At most 2 merges of the base branch per PR per UTC day (over all heads); a busy base branch otherwise keeps a PR in a merge, check and review loop", howLong: "Until the next UTC day", showsAs: "Plan wait: conflict merge cap for today reached", kind: "external" }, { name: "CI results of earlier pushes", why: "A repository with 3 pushes of ours whose required checks are not final yet gets no further push from Fix-up, CI fix or the default-branch fix", howLong: "Until the checks of those pushes end (a push without a result is settled as unknown after 3 days)", showsAs: "Items skipped for another job or run; no state change", kind: "external" }, + { name: "Autorepin waiting for its pull request", why: "An `@ autorepin` command names a pull request of another tracked repo; nothing happens until that pull request is merged or closed, which the mirror reports (the webhook's re-read within seconds, the poll otherwise)", howLong: "Until the named pull request is merged or closed (days, often), the PR itself closes, or `@ autorepin off`", showsAs: "none (the answer to the command, then the comment with the outcome)", kind: "external" }, + { name: "Autorepin lockfile task", why: "Once the pull request an `@ autorepin` command names is merged, a build worker runs `cargo update --workspace` on the repinned manifests; the commit is pushed when the task ends", howLong: "Until the task ends (minutes); at most 3 hours, then the autorepin fails with a comment on the PR", showsAs: "Builds page (step autorepin)", kind: "external" }, + { name: "Autorepin retry", why: "An autorepin attempt that did not finish (GitHub could not be read, the head moved, the lockfile task failed) starts again", howLong: "1 minute between tries, at most 5; then the autorepin fails with a comment on the PR", showsAs: "none (the comment on the PR tells the outcome)", kind: "backoff" }, ], writes: [{ what: "Push to the PR branch", approval: "push" }, { what: "Comment with the fixes", approval: "comment" }, { what: "Rerun failed CI jobs", approval: "ci" }, { what: "Rerun a red default branch's failed jobs; open a fix PR from the pipeline account's fork; open an issue on an operator's answer", approval: "main-fix" }], person: "Per-repo approval", diff --git a/test/autorepin.test.ts b/test/autorepin.test.ts new file mode 100644 index 00000000..e91b4494 --- /dev/null +++ b/test/autorepin.test.ts @@ -0,0 +1,411 @@ +// Autorepin: `@ autorepin ` on a PR, and the commit that repins its Cargo dependencies once that pull request is merged. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, describe, test } from "node:test"; +import { storeArtifact, tempPath } from "../src/build/artifacts.ts"; +import { safeEqual } from "../src/dash/server/crypto.ts"; +import { exec, type Exec, type ExecResult } from "../src/fixup/git.ts"; +import { drainCommands, parseCommand } from "../src/github/commands.ts"; +import { handleDelivery, signatureOf } from "../src/github/webhooks.ts"; +import type { Querier } from "../src/mirror.ts"; +import { advancePreapprovals, preapprovalOf, preapproveMerge } from "../src/preapproval/index.ts"; +import { anyRepinDue } from "../src/repin/due.ts"; +import { drainRepins, MAX_TRIES, requestRepin, type RepinDeps } from "../src/repin/index.ts"; +import { lockRefusal, repinManifest } from "../src/repin/manifest.ts"; +import { validating } from "./gql.ts"; +import { SCRATCH } from "./scratch.ts"; +import { OPERATOR, world, type World } from "./world-db.ts"; + +process.env.AUTOCRAFT_ARTIFACT_DIR = join(SCRATCH, "artifacts"); + +const SLUG = "autocraft-bot"; +const OLD = "1".repeat(40); +/** The dependency's repository as GitHub has it: `main` holds the merge commit SHA; STRAY is a commit no branch of it holds any more. */ +const LIBS_GIT = join(SCRATCH, "libs.git"); +const [SHA, STRAY] = (() => { + const work = mkdtempSync(join(SCRATCH, "libs-work-")); + git(work, "init", "-q", "-b", "main"); + git(work, "commit", "-q", "--allow-empty", "-m", "the merge of #12"); + const sha = git(work, "rev-parse", "HEAD"); + git(work, "clone", "-q", "--bare", work, LIBS_GIT); + git(work, "commit", "-q", "--allow-empty", "-m", "dropped from main since"); + const stray = git(work, "rev-parse", "HEAD"); + git(work, "push", "-q", LIBS_GIT, `${stray}:refs/heads/elsewhere`); + return [sha, stray]; +})(); +const LIBS = "https://github.com/storytold/libs"; +const MANIFEST = `[workspace]\nmembers = ["app"]\n\n[workspace.dependencies]\ncraft-ui = { git = "${LIBS}", rev = "${OLD}" }\nserde = "1"\n`; +const CRATES = 'source = "registry+https://github.com/rust-lang/crates.io-index"'; +const lockOf = (rev: string, extra = ""): string => + `version = 4\n\n[[package]]\nname = "app"\nversion = "0.1.0"\n\n[[package]]\nname = "craft-ui"\nversion = "0.1.0"\nsource = "git+${LIBS}?rev=${rev}#${rev}"\n\n[[package]]\nname = "serde"\nversion = "1.0.0"\n${CRATES}\nchecksum = "aa"\n${extra}`; + +describe("the autorepin command", () => { + test("names the pull request by slug, bare repo name or URL; off drops it", () => { + const ref = { owner: "storytold", name: "libs", number: 12 }; + assert.deepEqual(parseCommand(`@${SLUG} autorepin storytold/libs#12`, SLUG), { command: "autorepin", ref }); + assert.deepEqual(parseCommand(`thanks!\n@${SLUG} auto-repin ${LIBS}/pull/12`, SLUG), { command: "autorepin", ref }); + assert.deepEqual(parseCommand(`@${SLUG} autorepin libs#12`, SLUG), { command: "autorepin", ref: { ...ref, owner: null } }); + assert.deepEqual(parseCommand(`@${SLUG} autorepin OFF`, SLUG), { command: "autorepin", ref: null }); + }); + test("a number alone, a missing target or a quoted line is no command", () => { + for (const body of [`@${SLUG} autorepin 12`, `@${SLUG} autorepin #12`, `@${SLUG} autorepin`, `> @${SLUG} autorepin libs#12`, `@${SLUG} autorepin libs#12 please`]) assert.equal(parseCommand(body, SLUG), null, body); + }); +}); + +describe("repinManifest", () => { + test("moves every rev on the repository, in inline and section tables, and nothing else", () => { + const text = `[dependencies]\ncraft-ui = { git = "${LIBS}.git", rev = "${OLD}" } # ui\nother = { git = "https://github.com/storytold/elsewhere", rev = "2222222" }\n\n[dev-dependencies.craft-test]\ngit = "${LIBS}"\nrev = '${OLD}'\n`; + const r = repinManifest(text, "storytold/libs", SHA); + assert.ok(r.ok); + assert.deepEqual(r.from, [OLD]); + assert.equal(r.text, text.replace(`"${OLD}"`, `"${SHA}"`).replace(`'${OLD}'`, `"${SHA}"`)); + }); + test("a manifest already at the commit, or with no rev on the repository, comes back unchanged", () => { + const at = MANIFEST.replace(OLD, SHA); + const same = repinManifest(at, "storytold/libs", SHA); + assert.ok(same.ok && same.text === at && same.from.length === 0 && same.pinned === 1); + const branch = repinManifest(`[dependencies]\ncraft-ui = { git = "${LIBS}", branch = "wip" }\n`, "storytold/libs", SHA); + assert.ok(branch.ok && branch.from.length === 0 && branch.pinned === 0 && branch.unpinned === 1); + }); + test("a git and rev outside the dependency tables are not a dependency", () => { + const text = `[package] +name = "app" + +[package.metadata.release] +git = "${LIBS}" +rev = "${OLD}" + +[target.'cfg(unix)'.dependencies] +craft-ui = { git = "${LIBS}", rev = "${OLD}" } + +[patch.crates-io] +craft-io = { git = "${LIBS}", rev = "${OLD}" } +`; + const r = repinManifest(text, "storytold/libs", SHA); + // Refused, not rewritten: the metadata's rev is the same text, so the edit cannot leave it alone. + assert.ok(!r.ok); + const apart = repinManifest(text.replace(`rev = "${OLD}"`, 'rev = "2222222"'), "storytold/libs", SHA); + assert.ok(apart.ok && apart.pinned === 2 && apart.text.includes('rev = "2222222"') && !apart.text.includes(OLD)); + }); + test("is refused when the rewrite would also change another repository's rev", () => { + const r = repinManifest(`[dependencies]\ncraft-ui = { git = "${LIBS}", rev = "${OLD}" }\nother = { git = "https://github.com/else/where", rev = "${OLD}" }\n`, "storytold/libs", SHA); + assert.ok(!r.ok); + }); +}); + +describe("lockRefusal", () => { + const ok = (after: string) => lockRefusal(lockOf(OLD), after, "storytold/libs", SHA); + test("accepts the dependency at the commit, with new crates.io packages", () => { + assert.equal(ok(lockOf(SHA, `\n[[package]]\nname = "itoa"\nversion = "1.0.0"\n${CRATES}\nchecksum = "bb"\n`)), null); + }); + test("refuses another source, the dependency at another commit, and a changed checksum", () => { + assert.ok(ok(lockOf(SHA, `\n[[package]]\nname = "evil"\nversion = "1.0.0"\nsource = "git+https://github.com/else/where?rev=abc#abc"\n`))); + assert.ok(ok(lockOf(OLD))); + assert.ok(ok(lockOf(SHA).replace('"aa"', '"zz"'))); + }); + test("refuses a new version of a package the old lockfile has from the same source, a downgrade included", () => { + assert.ok(ok(lockOf(SHA).replace('version = "1.0.0"', 'version = "0.9.0"'))); + assert.ok(ok(lockOf(SHA, `\n[[package]]\nname = "serde"\nversion = "2.0.0"\n${CRATES}\nchecksum = "cc"\n`))); + }); + test("reads the lockfile as TOML: a source written another way than Cargo writes it still counts", () => { + const app = 'name = "app"\nversion = "0.1.0"\n'; + assert.ok(ok(lockOf(SHA).replace(app, `${app}source = "git+https://example.org/foreign#abc" # source\n`))); + assert.ok(ok(`${lockOf(SHA)}\n[[package]]\nname = 1\n`)); + }); +}); + +// ---- the whole flow against real git, with GitHub replaced --------------------- + +function git(cwd: string, ...args: string[]): string { + const r = spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd, encoding: "utf8" }); + if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr}`); + return r.stdout.trim(); +} + +type Setup = { w: World; fork: string; head: string; comments: string[]; pushes: number; live: { head: string; state: string; ref: string; base: string; sha: string }; deps: RepinDeps; branch: () => string; at: (path: string) => string }; +let current: World | null = null; +afterEach(() => current?.close()); + +/** app#1 from the fork contrib/app (branch `fix`), pinned to libs at OLD; libs#12 is open in the mirror. */ +function setup(o: { lock?: boolean; off?: Parameters[0] } = {}): Setup { + const root = mkdtempSync(join(SCRATCH, "repin-")); + const work = join(root, "work"); + mkdirSync(work); + git(work, "init", "-q", "-b", "fix"); + writeFileSync(join(work, "Cargo.toml"), MANIFEST); + if (o.lock !== false) writeFileSync(join(work, "Cargo.lock"), lockOf(OLD)); + git(work, "add", "-A"); + git(work, "commit", "-q", "-m", "contributor"); + const head = git(work, "rev-parse", "HEAD"); + const fork = join(root, "fork.git"); + git(root, "clone", "-q", "--bare", work, fork); + git(fork, "update-ref", "refs/pull/1/head", head); + + const w = (current = world().repo(o.off).pr(1, { head })); + w.db.prepare("UPDATE access SET github_id = 101 WHERE login = ?").run(OPERATOR); + w.db.prepare("INSERT INTO tracked_repos (name, added_by, added_at) VALUES ('libs', ?, '2026-01-01T00:00:00Z')").run(OPERATOR); + w.db.prepare("INSERT INTO repos (name, visibility, default_branch) VALUES ('libs', 'public', 'main')").run(); + w.db.prepare("INSERT INTO items (repo, number, kind, state, title, created_at, updated_at) VALUES ('libs', 12, 'pr', 'OPEN', 'lib change', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')").run(); + + const s: Setup = { + w, fork, head, comments: [], pushes: 0, live: { head, state: "OPEN", ref: "MERGED", base: "main", sha: SHA }, + deps: null as never, + branch: () => git(fork, "rev-parse", "refs/heads/fix"), + at: (path) => git(fork, "show", `refs/heads/fix:${path}`), + }; + const querier: Querier = validating({ + spent: 0, remaining: 5000, + async query(q: string) { + if (q.includes("mergeCommit")) return { repository: { defaultBranchRef: { name: "main" }, pullRequest: { state: s.live.ref, baseRefName: s.live.base, mergeCommit: s.live.ref === "MERGED" ? { oid: s.live.sha } : null } } }; + return { repository: { pullRequest: { state: s.live.state, headRefOid: s.live.head, headRefName: "fix", maintainerCanModify: true, headRepository: { nameWithOwner: "contrib/app" }, headRef: null } } }; + }, + }); + const run: Exec = async (cmd, args, opts = {}): Promise => { + if (cmd === "gh") { + if (args[0] === "api") return { code: 0, stdout: JSON.stringify({ login: "pipeline-bot", id: 42, node_id: "U42" }), stderr: "" }; + s.comments.push(String(opts.input ?? "")); + return { code: 0, stdout: "https://github.com/storytold/app/pull/1#issuecomment-9", stderr: "" }; + } + if (args.includes("push")) s.pushes++; + const net = args.some((a) => a.startsWith("https://github.com/")); + const local = args.map((a) => (a.startsWith("https://github.com/storytold/libs") ? LIBS_GIT : a.startsWith("https://github.com/") ? fork : a)).filter((a, i, all) => !(a === "-c" && all[i + 1] === "protocol.file.allow=never") && a !== "protocol.file.allow=never"); + return exec("git", net ? local : args, { ...opts }); + }; + s.deps = { querier, exec: run, root: join(root, "cache"), permission: async () => "ok" }; + return s; +} + +const set = (s: Setup) => requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: { owner: "storytold", name: "libs", number: 12 } }); +const merged = (s: Setup, state = "MERGED") => s.w.db.prepare("UPDATE items SET state = ? WHERE repo = 'libs' AND number = 12").run(state); +const row = (s: Setup) => ({ ...s.w.db.prepare("SELECT state, tries, to_head, result, notice FROM autorepins").get() }) as { state: string; tries: number; to_head: string | null; result: string | null; notice: string | null }; +const task = (s: Setup) => s.w.db.prepare("SELECT id, patch, plan, head_sha FROM build_tasks WHERE step = 'autorepin' ORDER BY id DESC").get() as { id: number; patch: string; plan: string; head_sha: string } | undefined; +/** The lockfile task ended with `lock` as its Cargo.lock. */ +function locked(s: Setup, lock: string | null, state = "done"): void { + const id = task(s)!.id; + s.w.db.prepare("UPDATE build_tasks SET state = ?, ended_at = '2026-01-03T00:00:00Z' WHERE id = ?").run(state, id); + if (lock === null) return; + const tmp = tempPath(id); + writeFileSync(tmp, lock); + storeArtifact(s.w.db, id, "Cargo.lock", tmp); +} + +/** Delivers a comment on app#1 holding `body` and carries it out; `now`: the comment's text when the runner reads it again. */ +async function comment(s: Setup, body: string, now = body): Promise { + const raw = Buffer.from(JSON.stringify({ + action: "created", repository: { full_name: "storytold/app", name: "app" }, issue: { number: 1, pull_request: { url: "x" } }, + comment: { id: 5000, body, created_at: new Date().toISOString(), user: { login: OPERATOR, id: 101, type: "User" } }, + })); + handleDelivery(s.w.db, "secret", { event: "issue_comment", signature: signatureOf("secret", raw) }, raw, safeEqual, SLUG); + await drainCommands(s.w.db, { + querier: s.deps.querier, exec: s.deps.exec, slug: SLUG, + permission: async () => ({ kind: "ok", permission: "write" }), + comment: async () => ({ kind: "ok", authorId: 101, body: now }), + }); +} + +describe("autorepin", () => { + test("a comment sets it, and nothing happens while the dependency's pull request is open", async () => { + const s = setup(); + await comment(s, `@${SLUG} autorepin storytold/libs#12`); + assert.equal(s.comments.length, 1); + assert.match(s.comments[0]!, new RegExp(`@${OPERATOR} Autorepin set: once storytold/libs#12 is merged`)); + assert.equal(row(s).state, "waiting"); + assert.equal(anyRepinDue(s.w.db), false); + assert.equal(await drainRepins(s.w.db, s.deps), 0); + assert.equal(task(s), undefined); + }); + + test("after the merge the lockfile task gets the repinned manifest, and its lockfile is pushed with it on top of the head", async () => { + const s = setup(); + await set(s); + merged(s); + await drainRepins(s.w.db, s.deps); + const t = task(s)!; + assert.equal(row(s).state, "locking"); + assert.equal(t.head_sha, s.head); + assert.ok(t.patch.includes(`+craft-ui = { git = "${LIBS}", rev = "${SHA}" }`) && !t.patch.includes("Cargo.lock"), t.patch); + assert.equal((JSON.parse(t.plan) as { network: string }[])[0]!.network, "fetch"); + assert.equal(s.pushes, 0, "nothing is pushed before the lockfile is back"); + assert.equal(anyRepinDue(s.w.db), false, "it waits for the task"); + + locked(s, lockOf(SHA)); + assert.equal(await drainRepins(s.w.db, s.deps), 1); + const r = row(s); + assert.equal(r.state, "pushed"); + assert.equal(s.branch(), r.to_head); + assert.equal(git(s.fork, "rev-parse", `${r.to_head}^`), s.head, "one commit on the head"); + assert.equal(s.at("Cargo.toml"), MANIFEST.replace(OLD, SHA).trim()); + assert.equal(s.at("Cargo.lock"), lockOf(SHA).trim()); + assert.deepEqual(git(s.fork, "diff-tree", "-r", "--name-only", s.head, r.to_head!).split("\n").sort(), ["Cargo.lock", "Cargo.toml"]); + assert.equal(s.comments.length, 1); + assert.ok(s.comments[0]!.includes(`@${OPERATOR} Repinned storytold/libs`), s.comments[0]); + assert.equal(await drainRepins(s.w.db, s.deps), 0, "done once"); + assert.equal(s.pushes, 1); + }); + + test("a merge pre-approved at the old head goes on at the repinned head, to be reviewed again", async () => { + const s = setup({ lock: false }); + preapproveMerge(s.w.db, { repo: "app", number: 1, by: OPERATOR }); + await set(s); + merged(s); + await drainRepins(s.w.db, s.deps); + const to = row(s).to_head!; + s.w.synced(1, to); + advancePreapprovals(s.w.db); + const p = preapprovalOf(s.w.db, "app", 1)!; + assert.deepEqual([p.state, p.head], ["review", to]); + }); + + test("without a lockfile the manifest is pushed at once", async () => { + const s = setup({ lock: false }); + await set(s); + merged(s); + await drainRepins(s.w.db, s.deps); + assert.equal(row(s).state, "pushed"); + assert.equal(task(s), undefined); + assert.equal(s.at("Cargo.toml"), MANIFEST.replace(OLD, SHA).trim()); + }); + + test("a lockfile that names another source is not pushed, and the comment says why", async () => { + const s = setup(); + await set(s); + merged(s); + await drainRepins(s.w.db, s.deps); + locked(s, lockOf(SHA, `\n[[package]]\nname = "evil"\nversion = "1.0.0"\nsource = "git+https://github.com/else/where?rev=abc#abc"\n`)); + await drainRepins(s.w.db, s.deps); + assert.equal(row(s).state, "failed"); + assert.equal(s.pushes, 0); + assert.equal(s.branch(), s.head); + assert.match(s.comments[0]!, /Autorepin of storytold\/libs failed: .*evil/); + }); + + test("a head that moved while the lockfile was written starts over instead of pushing", async () => { + const s = setup(); + await set(s); + merged(s); + await drainRepins(s.w.db, s.deps); + locked(s, lockOf(SHA)); + s.live.head = "d".repeat(40); + await drainRepins(s.w.db, s.deps); + assert.deepEqual([row(s).state, row(s).tries, s.pushes], ["waiting", 1, 0]); + assert.equal(anyRepinDue(s.w.db), false, "not again within the minute"); + assert.equal(anyRepinDue(s.w.db, new Date(Date.now() + 120_000)), true); + }); + + test("a lockfile task that keeps failing ends it with a comment", async () => { + const s = setup(); + await set(s); + merged(s); + for (let i = 0; i < MAX_TRIES; i++) { + const later = () => new Date(Date.now() + (i + 1) * 120_000); + await drainRepins(s.w.db, { ...s.deps, now: later }); + locked(s, null, "failed"); + await drainRepins(s.w.db, { ...s.deps, now: later }); + } + assert.equal(row(s).state, "failed"); + assert.equal(s.pushes, 0); + assert.equal(s.comments.length, 1); + }); + + test("a dependency pull request closed without merging drops it and says so", async () => { + const s = setup(); + await set(s); + merged(s, "CLOSED"); + await drainRepins(s.w.db, s.deps); + assert.equal(row(s).state, "cancelled"); + assert.equal(s.pushes, 0); + assert.match(s.comments[0]!, /closed without merging/); + }); + + test("a merge into another branch than the default one is not repinned to", async () => { + const s = setup(); + await set(s); + merged(s); + s.live.base = "release-1"; + await drainRepins(s.w.db, s.deps); + assert.equal(row(s).state, "failed"); + assert.equal(task(s), undefined); + }); + + test("a merge commit the default branch no longer holds is not repinned to", async () => { + const s = setup(); + await set(s); + merged(s); + s.live.sha = STRAY; + await drainRepins(s.w.db, s.deps); + assert.equal(row(s).state, "failed"); + assert.equal(task(s), undefined); + assert.match(s.comments[0]!, /no longer on/); + }); + + test("whoever asked must still have write access when the merge comes", async () => { + const s = setup(); + await set(s); + merged(s); + await drainRepins(s.w.db, { ...s.deps, permission: async () => "no" }); + assert.equal(row(s).state, "failed"); + assert.equal(task(s), undefined); + }); + + test("is refused on an issue, for a repo that is not tracked, and where pushes are not approved", async () => { + const s = setup({ off: ["push"] }); + const ask = (o: Partial[1]>) => requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: { owner: null, name: "libs", number: 12 }, ...o }); + await assert.rejects(ask({ pr: false }), /pull requests/); + await assert.rejects(ask({ ref: { owner: null, name: "nowhere", number: 1 } }), /not a repository AutoCraft tracks/); + await assert.rejects(ask({ ref: { owner: "someone-else", name: "libs", number: 12 } }), /not a repository AutoCraft tracks/); + await assert.rejects(ask({ canWrite: false }), /write access/); + await assert.rejects(ask({}), /not approved/); + assert.equal(s.w.db.prepare("SELECT COUNT(*) AS n FROM autorepins").get()!.n, 0); + }); + + test("is refused while the repo is outside the pipeline's scope and the pull request is not fast-tracked, since no worker would take its task", async () => { + const s = setup(); + s.w.db.prepare("UPDATE tracked_repos SET pipeline = 0 WHERE name = 'app'").run(); + await assert.rejects(set(s), /pipeline is off for storytold\/app/); + assert.equal(s.w.db.prepare("SELECT COUNT(*) AS n FROM autorepins").get()!.n, 0); + }); + + test("an autorepin command carried out after a later off does not set it again", async () => { + const s = setup(); + const ask = (ref: Parameters[1]["ref"], at: string) => requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref, at: new Date(at) }); + const libs = { owner: null, name: "libs", number: 12 }; + await ask(libs, "2026-02-01T10:00:00Z"); + await ask(null, "2026-02-01T10:10:00Z"); + // The command of 10:05, whose permission read GitHub settled only now. + await assert.rejects(ask(libs, "2026-02-01T10:05:00Z"), /later autorepin/); + assert.equal(row(s).state, "cancelled"); + await ask(libs, "2026-02-01T10:20:00Z"); + assert.equal(row(s).state, "waiting"); + }); + + test("off drops a waiting autorepin", async () => { + const s = setup(); + await set(s); + await requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: null }); + merged(s); + assert.equal(await drainRepins(s.w.db, s.deps), 0); + assert.equal(row(s).state, "cancelled"); + assert.equal(s.comments.length, 0); + }); + + test("an off given before any autorepin was set still stops an older command carried out later", async () => { + const s = setup(); + const ask = (ref: Parameters[1]["ref"], at: string) => requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref, at: new Date(at) }); + const libs = { owner: null, name: "libs", number: 12 }; + await ask(null, "2026-02-01T10:10:00Z"); + await assert.rejects(ask(libs, "2026-02-01T10:05:00Z"), /later autorepin off/); + assert.equal(s.w.db.prepare("SELECT COUNT(*) AS n FROM autorepins").get()!.n, 0); + await ask(libs, "2026-02-01T10:20:00Z"); + assert.equal(row(s).state, "waiting"); + }); + + test("a comment edited to name another pull request before it is carried out sets nothing", async () => { + const s = setup(); + s.w.db.prepare("INSERT INTO items (repo, number, kind, state, title, created_at, updated_at) VALUES ('libs', 13, 'pr', 'OPEN', 'other change', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')").run(); + await comment(s, `@${SLUG} autorepin storytold/libs#12`, `@${SLUG} autorepin storytold/libs#13`); + assert.equal(s.w.db.prepare("SELECT COUNT(*) AS n FROM autorepins").get()!.n, 0); + assert.equal(s.w.db.prepare("SELECT state FROM github_commands").get()!.state, "ignored"); + }); +});