From 7f02969357bae65e2d4a6d06ac0960d444f6f297 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 20 Nov 2026 14:24:16 +0100 Subject: [PATCH 1/4] @ autorepin in a comment on a PR: once that pull request of another tracked repo is merged into its default branch, the PR gets a commit that sets the rev of its Cargo dependencies on that repo to the merge commit, with Cargo.lock updated by cargo in a build task; no model, the push has a lease on the head, and a merge pre-approved at the old head carries on to the repinned one Co-Authored-By: Claude Fable 5.2 --- README.md | 2 +- docs/operations.md | 11 ++ src/db.ts | 2 + src/github/actions.ts | 1 + src/github/commands.ts | 52 +++++-- src/github/write.ts | 11 ++ src/preapproval/index.ts | 4 +- src/repin/due.ts | 31 ++++ src/repin/index.ts | 328 +++++++++++++++++++++++++++++++++++++++ src/repin/manifest.ts | 122 +++++++++++++++ src/runner/runner.ts | 20 ++- src/schema.sql | 30 +++- test/autorepin.test.ts | 311 +++++++++++++++++++++++++++++++++++++ 13 files changed, 903 insertions(+), 22 deletions(-) create mode 100644 src/repin/due.ts create mode 100644 src/repin/index.ts create mode 100644 src/repin/manifest.ts create mode 100644 test/autorepin.test.ts 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 be1218dd..149ff168 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -51,6 +51,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; it needs no Comments approval, because a known person asked for it. A paced write is retried on the next pass; another failed answer is logged and not retried. - A command waits until the item, and for an issue every open PR that closes it (the one Queue items would queue), was read from GitHub after the comment, by the webhook's re-read or by the poll when that re-read failed. `item_reads.synced_at` must be strictly after the command's time: a read stamped at the same instant may have started before it. This is checked again after the permission read, right before `queueAdd`, with nothing waiting on I/O between that check and the pre-approval, because a read that started earlier (a reconcile) may have written an older snapshot meanwhile, which also sets the item's read time back. So the command never pre-approves a head the mirror read before the comment. While no such read exists and none is queued (the re-read failed, or started within the comment's second, which the second-precision `synced_at` counts as before it), the command queues a re-read itself, at most once a minute (`tried_at`). A command that GitHub's permission read cannot settle is tried again after a minute (`tried_at`). Waiting commands cost no GitHub call and never keep newer ones out: a pass carries out at most 10 commands that call GitHub, oldest first among those that are due. One not carried out within an hour of the comment is dropped unanswered (`expired`). +**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, and where **Pushes** are not approved for the repo. It does not wait for a re-read: nothing is written at a head when it is set. +- 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. +- 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 when its outcome is still to post. A pass takes at most 5 due rows. +- 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. Then the access of the person who asked is read again (their AutoCraft login, their live write permission, `settleRefusal`), 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`). 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. +- 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 accepted only if every package it adds comes from crates.io or from the repository at the merge commit, no package of the repository stays at another commit, and no kept package changes its checksum. 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. +- 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 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. 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/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 b7e675e8..18dacd66 100644 --- a/src/github/commands.ts +++ b/src/github/commands.ts @@ -4,7 +4,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 at its current head and fast-tracked; an issue is fast-tracked and its one closing PR queued). -// The app answers in the same thread with the outcome. +// The 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, and then queueAdd applies the @@ -19,6 +24,7 @@ import { audit } from "../dash/audit.ts"; import { fastPositions } from "../fasttrack.ts"; import { exec as defaultExec, type Exec } from "../fixup/git.ts"; import type { Querier } from "../mirror.ts"; +import { parsePrRef, type PrRef } from "../repin/manifest.ts"; import { ghComment, WritePacedError } from "./write.ts"; /** Comments read for a command: GitHub caps a body at 65536 characters. */ @@ -29,7 +35,7 @@ const EXPIRE_MS = 3600_000; const RETRY_MS = 60_000; const AUDIT_LOGIN = "github-command"; -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 }; const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -37,10 +43,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 (`> ...`) and fenced code are skipped, so quoting a command repeats nothing. * A fence closes as CommonMark closes it: the opening character, at least as many of it, and nothing after but spaces. + * `@ 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; for (const raw of body.slice(0, BODY_MAX).split(/\r?\n/)) { const line = raw.trim(); @@ -52,6 +60,11 @@ export function parseCommand(body: unknown, slug: string): Command | null { if (f) { fence = { ch: f[0]!, len: f.length }; 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; } @@ -75,13 +88,16 @@ export function queueCommand(db: DatabaseSync, repo: string, event: string, payl if (!login || !githubId || !commentId || !number) return false; const cmd = parseCommand(comment.body, slug); if (!cmd) return false; - const r = db.prepare(`INSERT OR IGNORE INTO main.github_commands (comment_id, repo, number, pr, command, weight, login, github_id, requested_at, state) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued')`) - .run(commentId, repo, number, issue.pull_request ? 1 : 0, cmd.command, cmd.weight, login, githubId, now.toISOString()); + 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, requested_at, state) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued')`) + .run(commentId, repo, number, issue.pull_request ? 1 : 0, cmd.command, cmd.command === "merge-queue" ? cmd.weight : null, + ref ? `${ref.owner ? `${ref.owner}/` : ""}${ref.name}` : null, ref ? ref.number : null, login, githubId, now.toISOString()); return r.changes > 0; } -type Row = { comment_id: number; repo: string; number: number; pr: number; command: string; weight: number | null; login: string; github_id: number; requested_at: string; state: string; result: string | null }; +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; requested_at: string; state: string; result: string | null }; +const COLS = "comment_id, repo, number, pr, command, weight, ref_repo, ref_number, login, github_id, requested_at, state, result"; /** What carries out a queued merge-queue command: the Queue page's queueAdd, as the commenter. `canWrite`: GitHub's answer for `repo`, read just before. Injectable for tests. */ export type QueueFn = (db: DatabaseSync, o: { login: string; role: Role; canWrite: boolean; repo: string; item: string; weight: number | null }) => Promise; @@ -137,6 +153,18 @@ async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date, // checks is the one read here. const access = knownCommenter(db, r, now); if (!access) return "settled"; + if (r.command === "autorepin") { + // Nothing is written at a head here, so no read since the comment is waited for: the push reads the pull request live. + try { + const { requestRepin } = await import("../repin/index.ts"); + const ref = r.ref_repo === null || r.ref_number === null ? null : parsePrRef(`${r.ref_repo}#${r.ref_number}`); + if (r.ref_repo !== null && !ref) throw new Error("the pull request to wait for could not be read"); + settle(db, r, "done", `${oneLine(await requestRepin(db, { login: r.login, role: access.role, canWrite: p === "ok", repo: r.repo, number: r.number, pr: r.pr === 1, ref, now }))}.`, now); + } catch (e) { + settle(db, r, "refused", oneLine(String((e as Error)?.message ?? e)) || "it could not be set", now); + } + return "settled"; + } // Again after the permission read: a read may have been written meanwhile. The mirror never goes back to a read that started // earlier (writePage), so an item that passes here keeps a read from after the comment until queueAdd's pre-approval reads it. if (waitsForRead(db, r, now, qp)) return "wait"; @@ -186,8 +214,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}.`; } /** Posts the answer. A paced write leaves it for the next drain; any other failure is recorded (write.ts audits it) and not retried. */ @@ -222,7 +250,7 @@ export async function drainCommands(db: DatabaseSync, deps: CommandDeps): Promis // Every waiting row is read (an hour's commands at most): rows that wait for a re-read or a retry are passed over without // a GitHub call, so they never keep a newer command out. `limit` bounds the rows that call GitHub in one drain. Rows never tried // come first, oldest first, then retries by their last try, so due retries cannot fill the limit drain after drain either. - const rows = db.prepare(`SELECT comment_id, repo, number, pr, command, weight, login, github_id, requested_at, state, result FROM main.github_commands + const rows = db.prepare(`SELECT ${COLS} FROM main.github_commands WHERE (state = 'queued' AND (tried_at IS NULL OR tried_at <= ?)) OR (state IN ('done', 'refused') AND reply IS NULL) ORDER BY tried_at IS NOT NULL, COALESCE(tried_at, requested_at)`) .all(new Date(t0.getTime() - RETRY_MS).toISOString()) as Row[]; @@ -234,9 +262,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) { settle(db, r, "expired", null, now); continue; } - if (r.command !== "merge-queue") { settle(db, r, "ignored", null, now); continue; } + if (r.command !== "merge-queue" && r.command !== "autorepin") { settle(db, r, "ignored", null, now); continue; } // No GitHub call while an item waits for a read since the comment (see waitsForRead). - if (waitsForRead(db, r, now, qp)) continue; + if (r.command === "merge-queue" && waitsForRead(db, r, now, qp)) continue; calls++; const out = await carryOut(db, r, deps, now, qp); if (out === "wait") continue; @@ -246,7 +274,7 @@ export async function drainCommands(db: DatabaseSync, deps: CommandDeps): Promis continue; } settled++; - r = db.prepare("SELECT comment_id, repo, number, pr, command, weight, login, github_id, requested_at, state, result FROM main.github_commands WHERE comment_id = ?").get(r.comment_id) as Row; + r = db.prepare(`SELECT ${COLS} FROM main.github_commands WHERE comment_id = ?`).get(r.comment_id) as Row; if (r.state !== "done" && r.state !== "refused") continue; } else calls++; if ((await answer(db, r, deps)) === "paced") break; diff --git a/src/github/write.ts b/src/github/write.ts index f4fec6f0..c37c51f7 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -611,6 +611,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 6e39ab72..e4db0395 100644 --- a/src/preapproval/index.ts +++ b/src/preapproval/index.ts @@ -340,13 +340,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..f12399a1 --- /dev/null +++ b/src/repin/due.ts @@ -0,0 +1,31 @@ +// 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; + +export type RepinRow = { + repo: string; number: number; ref_repo: string; ref_number: number; login: string; 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; 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'))) + OR (a.state IN ('pushed', 'failed', 'cancelled') AND a.notice IS NULL)`; + +const before = (now: Date): string => new Date(now.getTime() - RETRY_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..8d9e7215 --- /dev/null +++ b/src/repin/index.ts @@ -0,0 +1,328 @@ +// 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. +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import type { DatabaseSync } from "node:sqlite"; +import { getAccess } from "../access.ts"; +import { absolute } from "../build/artifacts.ts"; +import { createTask } from "../build/tasks.ts"; +import { guardRepo } from "../core/guard.ts"; +import { audit } from "../dash/audit.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 { 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 { settleRefusal } from "../settlers.ts"; +import { fetchScript } from "../worker/rust.ts"; +import { repinsDue, type RepinRow } from "./due.ts"; +import { lockRefusal, repinManifest, 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 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 --------------------------------------------------------------- + +/** + * 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 with the reason when refused. + */ +export async function requestRepin(db: DatabaseSync, o: { login: string; role: string; canWrite: boolean; repo: string; number: number; pr: boolean; ref: PrRef | null; now?: Date }): Promise { + if (!o.pr) throw new Error("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 new Error(refusal); + const at = (o.now ?? new Date()).toISOString(); + const me = itemOf(db, o.repo, o.number); + if (me?.kind !== "pr" || me.state !== "OPEN") throw new Error("this pull request is not open"); + if (!o.ref) { + const n = db.prepare("UPDATE main.autorepins SET state = 'cancelled', result = NULL, done_at = ?, notice = 'none' WHERE repo = ? AND number = ? AND state IN ('waiting', 'locking')").run(at, o.repo, o.number).changes; + if (!n) throw new Error("no autorepin is waiting on this pull request"); + audit(db, o.login, "autorepin-off", refOf(o), {}); + return "Autorepin is off for this pull request"; + } + 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 new Error(`${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 new Error("the pull request to wait for must be in another repository"); + const other = itemOf(db, dep, o.ref.number); + if (other?.kind !== "pr") throw new Error(`${depRef} is not a pull request AutoCraft has read`); + if (other.state === "CLOSED") throw new Error(`${depRef} was closed without merging`); + const g = guardRepo(db, o.repo, "push", { operator: o.login }, undefined, o.login); + if ("refused" in g) throw new Error(g.refused); + db.prepare(`INSERT INTO main.autorepins (repo, number, ref_repo, ref_number, login, requested_at, state) VALUES (?, ?, ?, ?, ?, ?, 'waiting') + ON CONFLICT (repo, number, ref_repo) DO UPDATE SET ref_number = excluded.ref_number, login = excluded.login, 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`) + .run(o.repo, o.number, dep, o.ref.number, o.login, at); + 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 permission (default: the conversation cards' read, src/conversations/act.ts). */ + 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; + } +} +const failed = (why: string): Ended => new Ended("failed", oneLine(why)); + +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 { + 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); + 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 Error(`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 Error(`${depRef} is not merged on GitHub yet`); + const main = m.repository?.defaultBranchRef?.name; + if (!main) throw new Error(`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 Error(`GitHub returned no merge commit for ${depRef}`); + + // Whoever asked must still be allowed to, and the repo must still approve pushes. + const access = getAccess(db, r.login); + if (!access) throw failed(`${r.login} no longer has an AutoCraft login`); + const permission = d.permission ?? (await import("../conversations/act.ts")).liveWrite; + const p = await permission(q, r.repo, r.login).catch(() => "transient" as const); + if (p === "transient") throw new Error(`GitHub could not tell ${r.login}'s access to ${slugOf(r.repo)}`); + 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 Error(`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 Error("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 Error("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 root = d.root ?? fixupDir(); + mkdirSync(root, { recursive: true }); + 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 Error(`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`); + 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); + // A manifest that never names the repository (a test fixture, say) is not read as TOML at all. + if (!f.ok) { if (f.tooLarge) throw failed(f.reason); continue; } + if (!f.content.toLowerCase().includes(name)) continue; + const out = repinManifest(f.content, dep, sha); + if (!out.ok) throw failed(`${path}: ${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) 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) throw failed(lock.reason); + if (r.state !== "locking") { + 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 = ?, 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 Error(`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 Error("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 Error("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 { + rmSync(scratch, { recursive: true, force: true }); + } +} + +/** 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. */ +async function notify(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<"posted" | "failed" | "paced"> { + 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. + const why = oneLine(String((e as Error)?.message ?? e)); + deps.log?.(`autorepin ${refOf(r)}: try ${r.tries + 1} of ${MAX_TRIES}: ${why}`); + if (r.tries + 1 >= MAX_TRIES) finish(db, r, failed(why), clock()); + else { db.prepare(`UPDATE main.autorepins SET state = 'waiting', head = NULL, to_head = NULL, 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..7052da61 --- /dev/null +++ b/src/repin/manifest.ts @@ -0,0 +1,122 @@ +// 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; +} + +/** Every table of the manifest with a `git` source on `slug`: dependencies of every kind, workspace dependencies and `[patch]` entries. */ +function sourcesOn(data: unknown, slug: string, out: TomlTable[] = []): TomlTable[] { + if (Array.isArray(data)) for (const x of data) sourcesOn(x, slug, out); + else if (isTable(data)) { + if (typeof data["git"] === "string" && githubSlug(data["git"]) === slug.toLowerCase()) out.push(data); + for (const v of Object.values(data)) sourcesOn(v, slug, out); + } + 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 } + | { ok: false; reason: 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: ${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; null when a `[[package]]` has no name or version. */ +function lockedPackages(text: string): Locked[] | null { + const out: Locked[] = []; + let cur: Partial | null = null; + const close = (): boolean => { + if (!cur) return true; + if (cur.name === undefined || cur.version === undefined) return false; + out.push({ name: cur.name, version: cur.version, source: cur.source ?? null, checksum: cur.checksum ?? null }); + cur = null; + return true; + }; + for (const raw of text.split(/\r?\n/)) { + const l = raw.trim(); + if (l.startsWith("[")) { + if (!close()) return null; + if (l === "[[package]]") cur = {}; + continue; + } + if (!cur) continue; + const m = /^(name|version|source|checksum) = "([^"\\]*)"$/.exec(l); + if (m) (cur as Record)[m[1]!] = m[2]!; + } + return close() ? out : null; +} + +const CRATES_IO = new Set(["registry+https://github.com/rust-lang/crates.io-index", "sparse+https://index.crates.io/"]); + +/** + * Why the lockfile `after`, written by Cargo for the repinned manifests, is not accepted in place of `before`, or null. + * It may add packages from crates.io and from `slug` at `sha`, and drop packages. It may not name another new source, + * keep a package of `slug` at another commit, or change the checksum of a package it keeps. + */ +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 key = (p: Locked): string => `${p.name}@${p.version}@${p.source ?? ""}`; + const known = new Map(was.map((p) => [key(p), p])); + const want = slug.toLowerCase(); + for (const p of now) { + 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}`)) return `the new lockfile has ${p.name} from ${slug} at another commit`; + continue; + } + const old = known.get(key(p)); + if (!old) { + if (p.source === null) return `the new lockfile adds the local package ${p.name}`; + if (!CRATES_IO.has(p.source)) return `the new lockfile adds ${p.name} from a source outside crates.io and ${slug}`; + } else if (old.checksum !== p.checksum) return `the new lockfile changes the checksum of ${p.name} ${p.version}`; + } + return null; +} diff --git a/src/runner/runner.ts b/src/runner/runner.ts index 42ed69f3..fbc652b0 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -28,6 +28,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"); @@ -190,7 +191,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 state = 'queued' OR (state IN ('done', 'refused') AND reply IS NULL) LIMIT 1").get(); - if (!commands && !this.db.prepare("SELECT 1 FROM main.sync_requests LIMIT 1").get()) return; + // Autorepins whose pull request was merged or closed, or whose lockfile task ended (src/repin). + const repins = 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; @@ -199,10 +202,17 @@ 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 { drainCommands } = await import("../github/commands.ts"); - const k = await drainCommands(this.db, { querier: c, log: this.o.log }); - if (k) this.o.log(`webhooks: carried out ${k} commands from comments`); + if (commands) { + const { drainCommands } = await import("../github/commands.ts"); + const k = await drainCommands(this.db, { querier: c, log: this.o.log }); + if (k) this.o.log(`webhooks: carried out ${k} commands from comments`); + } + // After the commands: an autorepin set on a pull request that is already merged starts in this pass. + if (repins || commands) { + 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(`webhooks: ${(e as Error).message}`)).finally(() => (this.webhooking = null)); } diff --git a/src/schema.sql b/src/schema.sql index b50dadaf..8a7e0511 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 an operator wrote to the GitHub App in a comment (`@ merge queue`, src/github/commands.ts), for the runner to +-- Commands an operator 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 @@ -579,8 +579,32 @@ CREATE TABLE IF NOT EXISTS github_commands ( result TEXT, -- what the answer says done_at TEXT, tried_at TEXT, -- the last try GitHub could not settle the permission for; the next one waits a minute - reply TEXT -- posted | failed; null while the answer is still to post + reply TEXT, -- posted | failed; 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 ); +-- 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 + 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; -- A tracked repo the last sync could not read: skipped for the run, retried by the next. Bookkeeping: no live topic. CREATE TABLE IF NOT EXISTS sync_repo_errors ( repo TEXT PRIMARY KEY, diff --git a/test/autorepin.test.ts b/test/autorepin.test.ts new file mode 100644 index 00000000..af37dbc9 --- /dev/null +++ b/test/autorepin.test.ts @@ -0,0 +1,311 @@ +// 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); +const SHA = "c".repeat(40); +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("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"'))); + }); +}); + +// ---- 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 }; 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" }, + 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: 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/") ? 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, 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); +} + +describe("autorepin", () => { + test("a comment sets it, and nothing happens while the dependency's pull request is open", async () => { + const s = setup(); + 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: `@${SLUG} autorepin storytold/libs#12`, 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, permission: async () => "ok" }); + 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("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, 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("off drops a waiting autorepin", async () => { + const s = setup(); + await set(s); + await requestRepin(s.w.db, { login: OPERATOR, 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); + }); +}); From 8372456a31c4af23087a8e86c6b5400181d5b8ed Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 20 Nov 2026 14:47:45 +0100 Subject: [PATCH 2/4] Autorepin: commands count in the order of their comments (a late retry never undoes a later off), the merge commit must still be an ancestor of the default branch as fetched now, only dependency tables are repinned, the lockfile is read as TOML, an unreadable Cargo.toml ends the try instead of being skipped, and a scratch folder that cannot be removed does not replace the outcome Co-Authored-By: Claude Fable 5.2 --- docs/operations.md | 10 +++--- src/github/commands.ts | 2 +- src/repin/index.ts | 34 ++++++++++++++------ src/repin/manifest.ts | 52 +++++++++++++++---------------- test/autorepin.test.ts | 71 +++++++++++++++++++++++++++++++++++++++--- 5 files changed, 122 insertions(+), 47 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 149ff168..a14d7ba6 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -54,13 +54,13 @@ The runner drains `sync_requests` every 5 seconds while rows exist (`webhookTick **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, and where **Pushes** are not approved for the repo. It does not wait for a re-read: nothing is written at a head when it is set. -- 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. +- 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. - 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 when its outcome is still to post. A pass takes at most 5 due rows. -- 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. Then the access of the person who asked is read again (their AutoCraft login, their live write permission, `settleRefusal`), 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`). 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. -- 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 accepted only if every package it adds comes from crates.io or from the repository at the merge commit, no package of the repository stays at another commit, and no kept package changes its checksum. Without a lockfile there is no task. +- 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, their live write permission, `settleRefusal`), 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. 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. +- 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 it adds comes from crates.io or from the repository at the merge commit, no package of the repository stays at another commit, and no kept package changes its checksum. 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. -- 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 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. So a pull request that has both commands needs nobody between the dependency's merge and its own. +- 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 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). diff --git a/src/github/commands.ts b/src/github/commands.ts index 18dacd66..59e3b9f5 100644 --- a/src/github/commands.ts +++ b/src/github/commands.ts @@ -159,7 +159,7 @@ async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date, const { requestRepin } = await import("../repin/index.ts"); const ref = r.ref_repo === null || r.ref_number === null ? null : parsePrRef(`${r.ref_repo}#${r.ref_number}`); if (r.ref_repo !== null && !ref) throw new Error("the pull request to wait for could not be read"); - settle(db, r, "done", `${oneLine(await requestRepin(db, { login: r.login, role: access.role, canWrite: p === "ok", repo: r.repo, number: r.number, pr: r.pr === 1, ref, now }))}.`, now); + settle(db, r, "done", `${oneLine(await requestRepin(db, { login: r.login, role: access.role, canWrite: p === "ok", repo: r.repo, number: r.number, pr: r.pr === 1, ref, at: new Date(r.requested_at) }))}.`, now); } catch (e) { settle(db, r, "refused", oneLine(String((e as Error)?.message ?? e)) || "it could not be set", now); } diff --git a/src/repin/index.ts b/src/repin/index.ts index 8d9e7215..21a01713 100644 --- a/src/repin/index.ts +++ b/src/repin/index.ts @@ -79,15 +79,16 @@ const itemOf = (db: DatabaseSync, repo: string, number: number): Item | undefine * 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 with the reason when refused. */ -export async function requestRepin(db: DatabaseSync, o: { login: string; role: string; canWrite: boolean; repo: string; number: number; pr: boolean; ref: PrRef | null; now?: Date }): Promise { +export async function requestRepin(db: DatabaseSync, o: { login: string; role: string; canWrite: boolean; repo: string; number: number; pr: boolean; ref: PrRef | null; /** When the command was given (the comment's time): a command never undoes a later one. */ at?: Date }): Promise { if (!o.pr) throw new Error("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 new Error(refusal); - const at = (o.now ?? new Date()).toISOString(); + const at = (o.at ?? new Date()).toISOString(); const me = itemOf(db, o.repo, o.number); if (me?.kind !== "pr" || me.state !== "OPEN") throw new Error("this pull request is not open"); if (!o.ref) { - const n = db.prepare("UPDATE main.autorepins SET state = 'cancelled', result = NULL, done_at = ?, notice = 'none' WHERE repo = ? AND number = ? AND state IN ('waiting', 'locking')").run(at, o.repo, o.number).changes; + // The row takes this command's time, so an older `autorepin` command still to be carried out (a retry) does not set it again. + 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; if (!n) throw new Error("no autorepin is waiting on this pull request"); audit(db, o.login, "autorepin-off", refOf(o), {}); return "Autorepin is off for this pull request"; @@ -101,10 +102,13 @@ export async function requestRepin(db: DatabaseSync, o: { login: string; role: s if (other.state === "CLOSED") throw new Error(`${depRef} was closed without merging`); const g = guardRepo(db, o.repo, "push", { operator: o.login }, undefined, o.login); if ("refused" in g) throw new Error(g.refused); - db.prepare(`INSERT INTO main.autorepins (repo, number, ref_repo, ref_number, login, requested_at, state) VALUES (?, ?, ?, ?, ?, ?, 'waiting') + // 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, requested_at, state) VALUES (?, ?, ?, ?, ?, ?, 'waiting') ON CONFLICT (repo, number, ref_repo) DO UPDATE SET ref_number = excluded.ref_number, login = excluded.login, 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`) - .run(o.repo, o.number, dep, o.ref.number, o.login, at); + 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, at).changes; + if (!set) throw new Error(`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` @@ -172,6 +176,16 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise 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 Error(`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 found on ${dep}'s ${main}: ${oneLine(on.stderr)}`); // Whoever asked must still be allowed to, and the repo must still approve pushes. const access = getAccess(db, r.login); @@ -197,8 +211,6 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise 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 root = d.root ?? fixupDir(); - mkdirSync(root, { recursive: true }); 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 Error(`the fetched head ${short(fetched)} is not the head GitHub reports`); @@ -210,8 +222,9 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise 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) throw new Error(`${path}: ${f.reason}`); // A manifest that never names the repository (a test fixture, say) is not read as TOML at all. - if (!f.ok) { if (f.tooLarge) throw failed(f.reason); continue; } if (!f.content.toLowerCase().includes(name)) continue; const out = repinManifest(f.content, dep, sha); if (!out.ok) throw failed(`${path}: ${out.reason}`); @@ -267,7 +280,8 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise } throw new Ended("pushed", `Repinned ${dep} to ${short(sha)}, the merge of ${depRef}, in ${short(commit)} (${changed.join(", ")})`, { toHead: commit }); } finally { - rmSync(scratch, { recursive: true, force: true }); + // 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))}`); } } } diff --git a/src/repin/manifest.ts b/src/repin/manifest.ts index 7052da61..d0a69daa 100644 --- a/src/repin/manifest.ts +++ b/src/repin/manifest.ts @@ -25,12 +25,21 @@ export function githubSlug(url: string): string | null { return m ? `${m[1]}/${m[2]}`.toLowerCase() : null; } -/** Every table of the manifest with a `git` source on `slug`: dependencies of every kind, workspace dependencies and `[patch]` entries. */ -function sourcesOn(data: unknown, slug: string, out: TomlTable[] = []): TomlTable[] { - if (Array.isArray(data)) for (const x of data) sourcesOn(x, slug, out); - else if (isTable(data)) { - if (typeof data["git"] === "string" && githubSlug(data["git"]) === slug.toLowerCase()) out.push(data); - for (const v of Object.values(data)) sourcesOn(v, slug, out); +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; } @@ -66,29 +75,20 @@ export function repinManifest(text: string, slug: string, sha: string): Repinned type Locked = { name: string; version: string; source: string | null; checksum: string | null }; -/** The packages of a Cargo.lock; null when a `[[package]]` has no name or version. */ +/** 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[] = []; - let cur: Partial | null = null; - const close = (): boolean => { - if (!cur) return true; - if (cur.name === undefined || cur.version === undefined) return false; - out.push({ name: cur.name, version: cur.version, source: cur.source ?? null, checksum: cur.checksum ?? null }); - cur = null; - return true; - }; - for (const raw of text.split(/\r?\n/)) { - const l = raw.trim(); - if (l.startsWith("[")) { - if (!close()) return null; - if (l === "[[package]]") cur = {}; - continue; - } - if (!cur) continue; - const m = /^(name|version|source|checksum) = "([^"\\]*)"$/.exec(l); - if (m) (cur as Record)[m[1]!] = m[2]!; + 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 close() ? out : null; + return out; } const CRATES_IO = new Set(["registry+https://github.com/rust-lang/crates.io-index", "sparse+https://index.crates.io/"]); diff --git a/test/autorepin.test.ts b/test/autorepin.test.ts index af37dbc9..aa337c89 100644 --- a/test/autorepin.test.ts +++ b/test/autorepin.test.ts @@ -22,7 +22,19 @@ process.env.AUTOCRAFT_ARTIFACT_DIR = join(SCRATCH, "artifacts"); const SLUG = "autocraft-bot"; const OLD = "1".repeat(40); -const SHA = "c".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"'; @@ -57,6 +69,26 @@ describe("repinManifest", () => { 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); @@ -73,6 +105,11 @@ describe("lockRefusal", () => { assert.ok(ok(lockOf(OLD))); assert.ok(ok(lockOf(SHA).replace('"aa"', '"zz"'))); }); + 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 --------------------- @@ -83,7 +120,7 @@ function git(cwd: string, ...args: string[]): string { 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 }; deps: RepinDeps; branch: () => string; at: (path: string) => string }; +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()); @@ -109,7 +146,7 @@ function setup(o: { lock?: boolean; off?: Parameters[0] } = {}): 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" }, + 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}`), @@ -117,7 +154,7 @@ function setup(o: { lock?: boolean; off?: Parameters[0] } = {}): 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: SHA } : null } } }; + 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 } } }; }, }); @@ -129,7 +166,7 @@ function setup(o: { lock?: boolean; off?: Parameters[0] } = {}): } 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/") ? fork : a)).filter((a, i, all) => !(a === "-c" && all[i + 1] === "protocol.file.allow=never") && a !== "protocol.file.allow=never"); + 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" }; @@ -279,6 +316,17 @@ describe("autorepin", () => { 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); @@ -299,6 +347,19 @@ describe("autorepin", () => { 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, 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 command/); + 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); From ce1e4db5c0c2508c170d24253e61afd083949ffc Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:25:36 +0000 Subject: [PATCH 3/4] Autorepin: an edited comment must still name the stored pull request, a lockfile may not change the version or checksum of a package it had, an off is kept per pull request, quiet pull requests get no comment, only reasons worded by AutoCraft reach GitHub, the asker's login must stay bound to their GitHub id with write access read through the app, a lockfile task ends after 3 hours, a recorded push survives a crash, and a nested Cargo.lock is refused --- docs/operations.md | 69 ++++++++++++------ docs/pipeline.md | 2 + src/github/commands.ts | 2 +- src/repin/due.ts | 14 ++-- src/repin/index.ts | 159 +++++++++++++++++++++++++++-------------- src/repin/manifest.ts | 35 +++++---- src/schema.sql | 9 +++ src/stages/registry.ts | 2 + test/autorepin.test.ts | 54 +++++++++++--- 9 files changed, 241 insertions(+), 105 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index a14d7ba6..83f16f93 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -43,24 +43,26 @@ The poll stays the backup and serves repos without the GitHub App. With webhooks The runner drains `sync_requests` every 5 seconds while rows exist (`webhookTick` in `src/runner/runner.ts`). It skips a pass while a sync run holds its lock and stops when fewer than 1,000 rate-limit points are left. Each item is read with the sync's single-item document and written by the sync's writer, so the live topics update open pages. A failed read stays queued until it is 6 hours old; the next poll reads the item anyway. Both the poll and the re-read write `item_reads.synced_at` (one statement per page): the time the read started, before its first GitHub request (the start of the whole run for a paged read), so a read that began before a change never counts as made after it. A read that started before the one already stored for an item writes nothing for that item (not its row, its comments or its read time), so the mirror never goes back to an older snapshot. A re-read rewrites the item's comments even when the item row is unchanged. The runner uses one GitHub client seeded from the last sync's rate-limit reading and also skips a pass while the full-sync lock is held. A read that fails for a reason other than a transient one is dropped from the queue and logged. The item page shows it as "updated hh:mm" beside "On GitHub". -**Commands in comments** (`src/github/commands.ts`). Anyone who may use Queue items on the repo adds a pull request or an issue to the merge queue from GitHub with a comment that has, on a line of its own, `@ merge queue` (`merge-queue` and `mergequeue` work as well, in any case). An optional weight from 1 to 10 follows the words `merge queue`, as `@ merge queue 8` or `@ merge queue weight 8`; a weight on its own (`@ weight 8`) is no command. Quoted lines and fenced code do not count. Only a new comment (`issue_comment`, action `created`) by a user account in a tracked repo counts; edits and comments by bots or apps do not. The webhook stores the comment's id, the repo, the number, whether it is a pull request, the weight and the commenter's login and numeric GitHub id in `github_commands`, never the comment's text; a redelivery of the same comment adds nothing. The runner carries the command out in the same pass that drains `sync_requests`, after the item's own re-read (see the last point): +**Commands in comments** (`src/github/commands.ts`). Anyone who may use Queue items on the repo adds a pull request or an issue to the merge queue from GitHub with a comment that has, on a line of its own, `@ merge queue` (`merge-queue` and `mergequeue` work as well, in any case). An optional weight from 1 to 10 follows the words `merge queue`, as `@ merge queue 8` or `@ merge queue weight 8`; a weight on its own (`@ weight 8`) is no command. Quoted lines, fenced and indented code (four spaces or a tab) and HTML comments (``, also across lines) do not count. Only a new comment (`issue_comment`, action `created`) by a user account in a tracked repo counts; edits and comments by bots or apps do not, and neither does a comment created more than 5 minutes before its delivery arrives (a redelivery of an old comment). The webhook stores the comment's id and creation time, the repo, the number, whether it is a pull request, the weight and the commenter's login and numeric GitHub id in `github_commands`, never the comment's text; a redelivery of the same comment adds nothing. The runner carries the command out in the same pass that drains `sync_requests`, after the item's own re-read (see the last point): -- A commenter without an AutoCraft login, or whose GitHub id is not the one bound to that login, gets no answer (audited as `github-command` `ignored`), so nobody outside the access list can make the app write. -- A login whose GitHub id was never bound (no dashboard sign-in yet) is refused, with the reason in the answer. -- Otherwise the commenter's write permission on the repo is read from GitHub (as for conversation cards) and the item is added exactly as a line of **Queue items** on the Queue page (`queueAdd`, see docs/pipeline.md, Merge queue), as that login with its current role. The role and the login's binding are read again once GitHub has answered, with the same outcomes as above, so a login demoted or rebound meanwhile queues nothing. Who may is queueAdd's rule, the one every person-started write uses (`settleRefusal` in `src/settlers.ts`): an operator with write access on the repo, or a maintainer with `maintainer_writes` on, the app identity and write access; anyone else is refused with its reason. A PR is pre-approved at its current head and fast-tracked with the weight (default 5); an issue is fast-tracked and its one open closing PR queued. Its refusals (outside the scope, no merge approval for the repo, a pre-approved merge already in progress, …) are the answer. Audit rows are queueAdd's own under the commenter's login with `via: "github"`, plus one `github-command` row. -- The app answers in the same thread, naming the commenter: what was done and the item's fast-track place, or why not. The answer goes through `src/github/write.ts` (`ghComment`, audit action `github-command-reply`, note line "Automated reply") under a grant in the commenter's name; it needs no Comments approval, because a known person asked for it. A paced write is retried on the next pass; another failed answer is logged and not retried. -- A command waits until the item, and for an issue every open PR that closes it (the one Queue items would queue), was read from GitHub after the comment, by the webhook's re-read or by the poll when that re-read failed. `item_reads.synced_at` must be strictly after the command's time: a read stamped at the same instant may have started before it. This is checked again after the permission read, right before `queueAdd`, with nothing waiting on I/O between that check and the pre-approval, because a read that started earlier (a reconcile) may have written an older snapshot meanwhile, which also sets the item's read time back. So the command never pre-approves a head the mirror read before the comment. While no such read exists and none is queued (the re-read failed, or started within the comment's second, which the second-precision `synced_at` counts as before it), the command queues a re-read itself, at most once a minute (`tried_at`). A command that GitHub's permission read cannot settle is tried again after a minute (`tried_at`). Waiting commands cost no GitHub call and never keep newer ones out: a pass carries out at most 10 commands that call GitHub, oldest first among those that are due. One not carried out within an hour of the comment is dropped unanswered (`expired`). +- A commenter without an AutoCraft login, with a login whose GitHub id was never bound (no dashboard sign-in yet), or whose GitHub id is not the one bound to that login, gets no answer (audited as `github-command` `ignored`), so nobody outside the access list can make the app write. A viewer's command is refused without an answer. +- The comment is read again by its id (REST, through the app installation). A deleted comment, another author, or a body that no longer holds the same command (with the same weight) runs nothing and gets no answer (`ignored`). +- A pull request is pinned to the head it had when the comment was written. GitHub keeps no push time for a commit, so the PR counts as changed after the comment when any of three signals is later than the comment's creation time: a force push (`HeadRefForcePushedEvent`, stamped by GitHub), a commit's committer date (set by the pusher, so a back-dated commit passes this one) or the head's first check suite (stamped by GitHub when a push starts CI; a merge needs green CI at the head). While the head has no check suite yet and neither other signal shows a change, its push time is unknown: the command is tried again (see the last point) until CI registers the head. A changed PR is refused with "the PR changed after your comment; comment again"; otherwise exactly that head is pre-approved, and a mirror head that differs from it is refused the same way. On an issue, its one open closing PR is queued only when it was opened before the comment and has not changed since; otherwise the issue is still fast-tracked and the answer names the PR to comment on. +- Then the commenter's write permission on the repo is read from GitHub through the app installation (`appPermission`, the collaborator permission, which writes `repo_permissions`, so a maintainer's pre-approval keeps the fresh row `refreshSettlers` then keeps alive) and the item is added exactly as a line of **Queue items** on the Queue page (`queueAdd`, see docs/pipeline.md, Merge queue), as that login with its current role. The role and the login's binding are read again once GitHub has answered, with the same outcomes as above, so a login demoted or rebound meanwhile queues nothing. Who may is queueAdd's rule, the one every person-started write uses (`settleRefusal` in `src/settlers.ts`): an operator with write access on the repo, or a maintainer with `maintainer_writes` on, the app identity and write access; anyone else is refused with its reason. A role or setting that refuses whatever GitHub says is answered before the head and permission reads. A PR is fast-tracked with the weight (default 5); an issue is fast-tracked and its one open closing PR queued. Its refusals (outside the scope, no merge approval for the repo, a pre-approved merge already in progress, …) are the answer; any other error is logged and answered "it could not be queued". Audit rows are queueAdd's own under the commenter's login with `via: "github"`, plus one `github-command` row. +- On a quiet pull request (a security fix not yet published), or an issue whose closing PR is one, only an operator's command is carried out, and nothing is answered. +- The app answers in the same thread, naming the commenter: what was done and the item's fast-track place, or why not. The answer goes through `src/github/write.ts` (`ghComment`, audit action `github-command-reply`, note line "Automated reply") under a grant in the commenter's name. An answer to a person the queue rule lets queue on the repo needs no Comments approval; any other answer (a refusal by the rule, an expiry) needs it. A paced write is retried on the next pass; another failed answer is logged and not retried. `reply` is `none` for a command that gets no answer. +- A command waits until the item, and for an issue every open PR that closes it (the one Queue items would queue), was read from GitHub after the delivery, by the webhook's re-read or by the poll when that re-read failed. `item_reads.synced_at` must be strictly after the command's arrival: a read stamped at the same instant may have started before it. This is checked again after the GitHub reads, right before `queueAdd`, with nothing waiting on I/O between that check and the pre-approval, because a read that started earlier (a reconcile) may have written an older snapshot meanwhile, which also sets the item's read time back. While no such read exists and none is queued (the re-read failed, or started within the delivery's second, which the second-precision `synced_at` counts as before it), the command queues a re-read itself, at most once a minute (`tried_at`). A command whose comment, head or permission read GitHub cannot settle (an error, 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, and where **Pushes** are not approved for the repo. It does not wait for a re-read: nothing is written at a head when it is set. -- 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. -- 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 when its outcome is still to post. A pass takes at most 5 due rows. -- 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, their live write permission, `settleRefusal`), 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. 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. -- 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 it adds comes from crates.io or from the repository at the merge commit, no package of the repository stays at another commit, and no kept package changes its checksum. 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. -- 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 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. +- 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, and where **Pushes** are not approved for the repo. 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. +- 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. +- 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 does not have from crates.io. 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). @@ -153,7 +155,7 @@ Feedback (picks and text) is display-only. The pipeline reads answers with `auto - **Tokens.** A maintainer or operator makes a Connector token in the MCP Connector block of the Connect page (`/connect`, opened from the user menu), which shows it once with the `claude mcp add --transport http ... --header "Authorization: Bearer "` command and a JSON config for other clients. Connector tokens are `acmcp_` plus 32 random bytes, stored as a SHA-256 hash in `mcp_tokens` (`kind` `connector`), valid for 90 days, at most 5 per login, and revocable by their owner. A Task Runner credential (`acrun_`) works on `/mcp` only with Agent access (see [Task Runner credentials](#task-runner-credentials)); without it, `/mcp` answers 403. Client configs that call the server `autocraft-inbox` keep working: the name exists only in the client, and their tools keep the prefix `mcp__autocraft-inbox__`. An operator can tick **Can answer decisions** to make an answering token (`can_answer`), which lasts 7 days, the longest an operator's dashboard session lasts. A token counts only while its login is on the access list, and its role is read from the list on every call; removing a login deletes its tokens, ending a session of a login (Access page) deletes that login's tokens, and a lowered role deletes its answering tokens and takes answering from its Task Runners. Operators list and revoke any login's tokens on the Access page (`POST /api/access/tokens/revoke` `{id}`, audited as `mcp-token-revoke`; token audit rows are operator-only). A token has no GitHub token of its own: without a live dashboard session of its login, only recently cached permissions count. - **Transport.** One JSON-RPC message per POST, answered with one JSON body (no event stream: `GET` is 405; notifications get 202; batches get 400). The token goes in `Authorization: Bearer`; the session cookie is never accepted here, and a request whose `Origin` or `Sec-Fetch-Site` names another site is refused. Limits: 120 calls a minute per login, and 300 failed authentications a minute per client address. - **Tools.** `list_repos` (visible tracked repos with open decisions by kind and fix-ups waiting), `list_inbox` (open decisions, oldest first; `repo`, `kind`, `limit` up to 25, `cursor`), `get_inbox_item` (one decision: question, option keys, summary and recommendation, item text, facts, risks, related items, picks and comments), `send_feedback` (`id`, `option?`, `text?`), `list_merge_queue` (the Queue page's Merge tab: each PR's state, merge path, CI, verify, fast-track weight and place, hold, how it came in and who added it (logins for maintainers and operators only), why it does not merge yet, the next merges with what each waits for, the batches in flight, and pre-approved merges whose PR is no queue row on any page yet, from every visible repo or the one asked for; `repo`, `limit` up to 25 for each list, `cursor` `:` with `x` for a list that is done), and `list_fixups` (open PRs at their current head that the planner holds in the fix-up `hold` bucket with no push of ours under way, with the review's fix list and why the step stopped; viewers get the state only, as on the item page). While answering is available (`answering.enabled`), an answering token of a login that is an operator at the time of the call is also offered `answer_decision` (`id`, `option`, `note?`, `textsHash?` for a duplicate group, `exceptions?` for a batch) and `undo_answer` (`id`); for it, `get_inbox_item` adds `undoable`, the comment the answer would post, and each option's duplicate-group texts with their `textsHash`. Answering is the user's own action and has to execute as that GitHub user, which needs GitHub App user tokens that AutoCraft does not have yet. Until then no token can be made with `answer: true`, the Connect page hides the switch, the answer tools are not listed and the instructions do not mention them; a call to either refuses with a message that the user must sign in again with GitHub App sign-in. The switch is `answering.enabled` in `src/dash/mcp/index.ts`, and the checks below stay ready. Any other token is not offered them and gets an error if it calls them. `list_repos`, `list_fixups` and `list_merge_queue` share a per-login budget of a burst of 20 then 30 a minute. Every result frames GitHub text, and the pipeline's text about it (option labels and what an answer writes included), as untrusted, as the item tools do. -- **Merge queue.** A token whose login is an operator at the time of the call is also offered `set_weight` and the instructions describe it. `queue_pr` and `cancel_queued` are offered and allowed only to an answering token (`McpEnv.canAnswer`, with `answering.enabled`), because a pre-approved merge is a Merge answer given ahead; a call also refuses unless the user has live write permission on the repo (`queue_pr`). A maintainer's answering token (answering needs `maintainer_writes` on) is offered `queue_pr` as well, but not `set_weight` or `cancel_queued`; the call takes the dashboard's rule for Queue items, so it is refused (403) on a repo without the app identity or the maintainer's write access. `queue_pr` (`item`, `weight?`) is "Queue items" (`POST /api/queue/add`): a PR is pre-approved at its current head and fast-tracked with the weight (default 5), keeping a heavier weight it has; an issue is fast-tracked and its one open closing PR is queued. `set_weight` (`item`, `weight?` or `remove: true`) changes a fast-tracked item's weight, fast-tracks an item not on the list with that weight without approving its merge, or takes it off; it calls `setFastTrackWeight`, `addFastTrack` and `removeFastTrack` directly (the dashboard's `/api/fast-track` routes call the same functions); it checks the repo is visible first and then decides between adding and changing in the same write, so a `queue_pr` of the same item meanwhile cannot leave its weight in place of the one asked for. `cancel_queued` (`item`) is the item page's cancel of a pre-approved merge (`POST /api/items///preapproval/cancel`); the weight stays. `item` is a GitHub URL, `repo#number` or `owner/repo#number`. The role is read on every call, so a login that stopped being an operator is refused (403) even if its agent still lists the tools (a demoted operator keeps `queue_pr` only where a maintainer may queue). Audit rows are the handlers' own (`preapproval`, `fasttrack-add`, `fasttrack-weight`, `fasttrack-remove`), under the operator's login, with `via: "mcp"` in their details. Batch summaries, which can hold raw push and GitHub errors, go to operators and maintainers only, on the dashboard and in `list_merge_queue`. +- **Merge queue.** A token whose login is an operator at the time of the call is also offered `set_weight` and the instructions describe it. `queue_pr` and `cancel_queued` are offered and allowed only to an answering token (`McpEnv.canAnswer`, with `answering.enabled`), because a pre-approved merge is a Merge answer given ahead; a call also refuses unless the user has live write permission on the repo (`queue_pr`). A maintainer's answering token (answering needs `maintainer_writes` on) is offered `queue_pr` as well, without its `weight`, and not `set_weight` or `cancel_queued`; the call takes the dashboard's rule for Queue items, so it is refused (403) on a repo without the app identity or the maintainer's write access. Weights are set by operators: a maintainer's `queue_pr` fast-tracks an item not on the list yet with the default weight, leaves an existing weight as it is, and ignores a weight it is sent (the reply says so). `queue_pr` (`item`, `weight?`) is "Queue items" (`POST /api/queue/add`): a PR is pre-approved at its current head and fast-tracked with the weight (default 5), keeping a heavier weight it has; an issue is fast-tracked and its one open closing PR is queued. `set_weight` (`item`, `weight?` or `remove: true`) changes a fast-tracked item's weight, fast-tracks an item not on the list with that weight without approving its merge, or takes it off; it calls `setFastTrackWeight`, `addFastTrack` and `removeFastTrack` directly (the dashboard's `/api/fast-track` routes call the same functions); it checks the repo is visible first and then decides between adding and changing in the same write, so a `queue_pr` of the same item meanwhile cannot leave its weight in place of the one asked for. `cancel_queued` (`item`) is the item page's cancel of a pre-approved merge (`POST /api/items///preapproval/cancel`); the weight stays. `item` is a GitHub URL, `repo#number` or `owner/repo#number`. The role is read on every call, so a login that stopped being an operator is refused (403) even if its agent still lists the tools (a demoted operator keeps `queue_pr` only where a maintainer may queue). Audit rows are the handlers' own (`preapproval`, `fasttrack-add`, `fasttrack-weight`, `fasttrack-remove`), under the operator's login, with `via: "mcp"` in their details. Batch summaries, which can hold raw push and GitHub errors, go to operators and maintainers only, on the dashboard and in `list_merge_queue`. - **Model calls.** In the `user-local` mode every token is offered `list_model_calls` (the Queue page's Model calls view through the same handler, `GET /api/model-queue`: each waiting call's id, items, step, tier, model, estimated cost, minutes waited, why it waits, its pick and whether the user may pick it, with the ready Task Runner counts and the user's picks; viewers get no picker logins, errors or repo-less calls). A login that is a maintainer or operator when the tools are listed is also offered `pick_model_call` and `unpick_model_call` (`id`), the dashboard's pick and unpick with the same refusals (403 for viewers and for ending another user's pick unless an operator, 409 with the reason a call cannot be picked); audited as `remote-pick` and `remote-unpick` with `via: "mcp"`. - **Same rules as the dashboard.** The tools call the dashboard's own handlers as the token's user: repo visibility, the decision checks and audit rows are the same. `send_feedback` is the Feedback box (audit `via: "mcp"`; the stored pick or comment carries `via` too, and the item thread marks it "via agent"), so it is display-only until an operator answers or uses the pick; viewers get an error, and maintainers get 60 posts an hour per login, counted together with the dashboard's own feedback. A token has no GitHub token of its own: permission checks use the login's newest live dashboard session, and without one only a recent cached permission counts (a private repo is then hidden and a pick shows as `none`). An answer through `answer_decision` is the operator's answer, made through the same handler as the dashboard's: it needs write, maintain or admin on every repo the decision covers (checked live with the operator's dashboard session, so without a live session it is refused), the duplicate-group texts check and batch exceptions apply, it is audited as `answer` with `source: "dashboard"` and `via: "mcp"`, and the pipeline acts on it like any operator answer. `undo_answer` is the dashboard's Undo (audit `undo` with `via: "mcp"`). Nothing here approves a repo or changes settings, and only `cancel_queued` writes to GitHub itself (it closes the batch PR of a PR it takes out of a batch, as the dashboard's cancel does). A fix-up's result lands on GitHub as the contributor's own commit or suggestion, and the pipeline reviews the new head as usual. @@ -209,11 +211,12 @@ A Task Runner needs a maintainer or operator login on the dashboard. The Connect Requirements: Node 22 or later, `git` and `tar`, a signed-in harness (`claude` or `codex`), and a sandbox tool: bubblewrap (`/usr/bin/bwrap`) on Linux and WSL, `sandbox-exec` on macOS. Other systems are refused. -1. Install the Task Runner: +1. Install the Task Runner and set up the machine: ```sh - mkdir -p ~/.local/bin && curl -fsSL /worker/autocraft.mjs -o ~/.local/bin/autocraft && chmod +x ~/.local/bin/autocraft + mkdir -p ~/.local/bin && curl -fsSL /worker/autocraft.mjs -o ~/.local/bin/autocraft && chmod +x ~/.local/bin/autocraft && ~/.local/bin/autocraft setup ``` -2. Log in: `autocraft login `, then approve the code on the Connect page. The URL must be `https` (`http` only for localhost). + `setup` looks at what the machine lacks and, one item at a time, prints the problem and the command that fixes it, and runs the command only when you answer yes (see [setup](#setup)). It ends with `doctor`. +2. Log in: `setup` runs `autocraft login `; approve the code on the Connect page. The URL must be `https` (`http` only for localhost). 3. Choose how the harness signs in: | Command | Harness login | @@ -224,7 +227,30 @@ Requirements: Node 22 or later, `git` and `tar`, a signed-in harness (`claude` o | `autocraft harness codex [--device-auth]` | Logs Codex in to the Task Runner's own `CODEX_HOME`, a login separate from `~/.codex`, so refreshes never invalidate your own session. `--device-auth` is for a machine without a browser. | 4. Models. Claude defaults to `opus`, `sonnet` and `haiku` for the three tiers. Codex has no defaults: add `"tiers": {"top": "...", "mid": "...", "small": "..."}` to `$XDG_CONFIG_HOME/autocraft-runner/config.json` (mode 0600; default `~/.config/autocraft-runner/config.json`). The config also takes `repos` (claim only calls on these repos), `claudeBin`, `codexBin` and `treeCacheGb` (the tree cache cap, default 20). `AUTOCRAFT_RUNNER_CLAUDE_BIN` and `AUTOCRAFT_RUNNER_CODEX_BIN` override the binaries. -5. Run `autocraft doctor`, then `autocraft work`, or `autocraft service install [--parallel N]` to keep it running. +5. Run `autocraft doctor`, then `autocraft work` in a terminal (Ctrl-C stops it), `autocraft run` for one call, or `autocraft service install [--parallel N]` to keep it running. + +### setup + +`autocraft setup []` checks the machine and offers one fix at a time, in this order. Each offer prints the problem, what the fix does and the exact command, and asks `Run it now?`. A command that runs `sudo` or downloads and runs an installer asks `[y/N]`: only a typed `y` runs it, and an empty line is no. The others ask `[Y/n]`. Input typed before a question appears is discarded, so an answer typed ahead, or a line left over from the step before, never answers it. After each offer setup looks at the machine again, so a fix that made the next one unnecessary is not offered. Each item is offered once per run. + +| Missing | Command offered | +|---|---| +| Windows or another system | None: install and run `autocraft` inside WSL | +| bubblewrap (Linux), `git`, `tar`, and `curl` and `bash` when Claude Code must be installed | The package manager's install, run with `sudo sh -c '…'` unless run as root: `apt-get update && apt-get install -y`, `dnf install -y`, `pacman -Sy --needed --noconfirm`, `zypper --non-interactive install` or `apk add`; `xcode-select --install` on macOS, also when the `git` found on `PATH` is, after following symlinks, the stub `/usr/bin/git` that macOS has without the developer tools (`xcode-select -p` fails) | +| A sandbox that does not start because AppArmor restricts unprivileged user namespaces (`/proc/sys/kernel/apparmor_restrict_unprivileged_userns` is 1, Ubuntu 23.10 and later) | Installs Ubuntu's `bwrap-userns-restrict` AppArmor profile as `/etc/apparmor.d/bwrap-userns-restrict` and loads it with `apparmor_parser -r`. It copies `/usr/share/apparmor/extra-profiles/bwrap-userns-restrict` when that exists (apparmor 4.x, package `apparmor-profiles`), else writes the same rules. The profile lets any program on the machine run `/usr/bin/bwrap` to create user namespaces; everything bwrap starts runs under the `unpriv_bwrap` profile, which denies every capability, so bwrap gives a sandbox but never a privileged namespace. Programs inside a call therefore cannot start a sandbox of their own. Setup writes a temporary file and hard-links it into place, so a profile that exists by then is never overwritten and a failed write leaves none; when loading fails, it removes only the profile it linked, so the next `setup` offers it again. When the file already exists, it offers `sudo apparmor_parser -r` on it; for another cause it only shows bubblewrap's error | +| `claude` on `PATH` | Claude Code's native installer (`bash -c "$(curl -fsSL https://claude.ai/install.sh)"`, into `~/.local/bin`, no sudo): the script is downloaded whole before bash runs it. It says so when it sees the snap `claude-code` or VS Code's own copy of Claude Code (`~/.vscode-server/extensions`): neither is a standalone binary at a fixed path, so neither can be mounted into the sandbox. For Codex it names the audited versions and installs nothing | +| A Claude login (none yet, or the chosen one no longer gives a token) | `claude` (the binary setup found, also outside `PATH`; with `CLAUDE_CONFIG_DIR` set when the runner reads another config directory), to sign in and `/exit`. When the runner has a stored setup-token, or a config directory on macOS (where Claude Code keeps its login in the Keychain), it offers `autocraft harness claude` instead, to paste a new token from `claude setup-token` | +| A harness login for the runner | `autocraft harness claude --config-dir` (Linux) or `--keychain` (macOS) when that login exists (on macOS setup checks that the Keychain item exists without reading it); `autocraft harness codex` for Codex. A setup-token is not offered: choose it yourself | +| A dashboard login, or a login to another dashboard than the URL setup was given | `autocraft login `, when setup was given the URL; it replaces the other login, and the offer says so | + +To remove the AppArmor profile setup installed, unload it, then delete the file (newer Ubuntu releases ship this file in the `apparmor` package; leave theirs in place): + +```sh +sudo apparmor_parser -R /etc/apparmor.d/bwrap-userns-restrict +sudo rm /etc/apparmor.d/bwrap-userns-restrict +``` + +`--yes` runs every command without asking, the `sudo` and installer ones included. Without a terminal and without `--yes`, `setup` only lists the commands. When `~/.local/bin` is not on `PATH`, setup looks there too and, at the end, says how to add it to the shell profile (`export PATH="$HOME/.local/bin:$PATH"`). ### Moving a 1.2.0 runner @@ -257,7 +283,8 @@ The move (`autocraft migrate`, also run at the first start of 1.3.0, before the |---|---| | `login [--label X] [--no-wait] [--answer] [--no-agent]`, `login --wait`, `login --stdin` | Makes a credential and waits for its approval on the Connect page, or stores one read from stdin (see [Task Runner credentials](#task-runner-credentials)). `--answer` also asks to answer decisions and approve merges; `--no-agent` asks for no Agent access. | | `harness claude\|codex ...` | Chooses the harness login (see [Setting up a Task Runner](#setting-up-a-task-runner)). | -| `doctor` | Checks Node, platform, sandbox (on macOS with the canary), `git` and `tar`, the harness binary, version and login, a harness start inside the sandbox, the server and the tiers. Exit code 1 when a check fails. | +| `setup [] [--yes]` | Installs what the machine lacks, asking first (see [setup](#setup)), then runs `doctor` and returns its exit code. | +| `doctor` | Checks Node, platform, sandbox (on macOS with the canary), `git` and `tar`, the harness binary, version and login, a harness start inside the sandbox, the server and the tiers. Exit code 1 when a check fails; it then names `autocraft setup`. | | `update` | Downloads the server's current Task Runner over this file (checked with `node --check` first); restart `work` or the service afterwards. A version refusal names this command. | | `service install [--parallel N]` | Writes and starts a systemd user unit (Linux, `~/.config/systemd/user/autocraft.service`) or a launchd agent (macOS, `~/Library/LaunchAgents/autocraft.plist`) that runs `work` with these arguments and restarts it whenever it ends (systemd `Restart=always`, launchd `KeepAlive`). It keeps `PATH`, `XDG_CONFIG_HOME`, `XDG_CACHE_HOME` and `CLAUDE_CONFIG_DIR` from the shell it ran in. The log: `journalctl --user -u autocraft -f` (Linux), `$XDG_CACHE_HOME/autocraft-runner/service.log` (macOS). On Linux, when lingering is off, the command prints a line that the service stops at logout and names `loginctl enable-linger`; `doctor` warns the same while a unit is installed. No root. | | `service uninstall` / `service status` | Stops and removes the service; prints its state and where its log is. | @@ -280,7 +307,7 @@ The move (`autocraft migrate`, also run at the first start of 1.3.0, before the | `inbox show ` | `get_inbox_item` | One decision in full. | | `inbox feedback --pick --note "..."` | `send_feedback` | Your pick of one option (`option`) and/or a note (`text`); an operator answers. | | `queue [--repo R] [--limit N] [--cursor C]` | `list_merge_queue` | The merge queue as on the Queue page. | -| `queue add [--weight N]` | `queue_pr` | Pre-approves a PR's merge and fast-tracks it (operators with answering). | +| `queue add [--weight N]` | `queue_pr` | Pre-approves a PR's merge and fast-tracks it (operators, and maintainers who answer decisions, with answering; only an operator's `--weight` counts). | | `queue weight `, `queue weight --remove` | `set_weight` | Sets an item's fast-track weight, or takes it off the list (operators). | | `queue remove ` | `cancel_queued` | Withdraws a PR's pre-approved merge (operators with answering). | | `calls` | `list_model_calls` | The waiting model calls as on the Queue page's Model calls view (`user-local` mode). | diff --git a/docs/pipeline.md b/docs/pipeline.md index 4ad001df..ab6c9686 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -763,6 +763,8 @@ 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 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/github/commands.ts b/src/github/commands.ts index db51d94e..cf9c9bc8 100644 --- a/src/github/commands.ts +++ b/src/github/commands.ts @@ -378,7 +378,7 @@ async function carryOutRepin(db: DatabaseSync, r: Row, ref: PrRef | null, deps: 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, role, canWrite: perm === "ok", repo: r.repo, number: r.number, pr: r.pr === 1, ref, at: new Date(r.created_at) }); + 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))}`); diff --git a/src/repin/due.ts b/src/repin/due.ts index f12399a1..4b9431ca 100644 --- a/src/repin/due.ts +++ b/src/repin/due.ts @@ -4,28 +4,30 @@ 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; requested_at: string; + 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; ended: the comment that tells the outcome is still to post. +// 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'))) + 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 => new Date(now.getTime() - RETRY_MS).toISOString(); +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[]; + 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)); + 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 index 21a01713..a0288ed3 100644 --- a/src/repin/index.ts +++ b/src/repin/index.ts @@ -11,27 +11,32 @@ // - 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. +// 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 { getAccess } from "../access.ts"; import { absolute } from "../build/artifacts.ts"; -import { createTask } from "../build/tasks.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 { isQuiet } from "../security/quiet.ts"; import { settleRefusal } from "../settlers.ts"; import { fetchScript } from "../worker/rust.ts"; -import { repinsDue, type RepinRow } from "./due.ts"; -import { lockRefusal, repinManifest, type PrRef } from "./manifest.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; @@ -39,6 +44,8 @@ export const MAX_TRIES = 5; 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 @@ -75,40 +82,48 @@ const itemOf = (db: DatabaseSync, repo: string, number: number): Item | undefine // ---- the command --------------------------------------------------------------- +/** 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 with the reason when refused. + * 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; role: string; canWrite: boolean; repo: string; number: number; pr: boolean; ref: PrRef | null; /** When the command was given (the comment's time): a command never undoes a later one. */ at?: Date }): Promise { - if (!o.pr) throw new Error("autorepin is for pull requests"); +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 new Error(refusal); + 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 new Error("this pull request is not open"); + if (me?.kind !== "pr" || me.state !== "OPEN") throw refused("this pull request is not open"); if (!o.ref) { - // The row takes this command's time, so an older `autorepin` command still to be carried out (a retry) does not set it again. + // 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 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; - if (!n) throw new Error("no autorepin is waiting on this pull request"); - audit(db, o.login, "autorepin-off", refOf(o), {}); - return "Autorepin is off for this pull request"; + 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 new Error(`${o.ref.owner ? `${o.ref.owner}/` : ""}${o.ref.name} is not a repository AutoCraft tracks`); + 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 new Error("the pull request to wait for must be in another repository"); + 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 new Error(`${depRef} is not a pull request AutoCraft has read`); - if (other.state === "CLOSED") throw new Error(`${depRef} was closed without merging`); + 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 new Error(g.refused); + if ("refused" in g) throw refused(g.refused); // 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, requested_at, state) VALUES (?, ?, ?, ?, ?, ?, 'waiting') - ON CONFLICT (repo, number, ref_repo) DO UPDATE SET ref_number = excluded.ref_number, login = excluded.login, requested_at = excluded.requested_at, state = 'waiting', + 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, at).changes; - if (!set) throw new Error(`a later autorepin command for ${slugOf(dep)} on this pull request stands`); + .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` @@ -123,7 +138,7 @@ export type RepinDeps = { exec?: Exec; /** Directory holding one bare cache repository per repo (default: the fix-ups'). */ root?: string; - /** Reads the asker's live permission (default: the conversation cards' read, src/conversations/act.ts). */ + /** 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; @@ -145,7 +160,10 @@ class Ended extends Error { 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]; @@ -159,6 +177,14 @@ function finish(db: DatabaseSync, r: RepinRow, e: Ended, at: Date): void { 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); @@ -168,14 +194,14 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise // 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 Error(`GitHub returned no ${depRef}`); + 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 Error(`${depRef} is not merged on GitHub yet`); + if (merged.state !== "MERGED") throw new Retry(`${depRef} is not merged on GitHub yet`); const main = m.repository?.defaultBranchRef?.name; - if (!main) throw new Error(`GitHub returned no default branch for ${dep}`); + 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 Error(`GitHub returned no merge commit for ${depRef}`); + 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 }); @@ -185,14 +211,19 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise 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 found on ${dep}'s ${main}: ${oneLine(on.stderr)}`); + 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, and the repo must still approve pushes. - const access = getAccess(db, r.login); - if (!access) throw failed(`${r.login} no longer has an AutoCraft login`); - const permission = d.permission ?? (await import("../conversations/act.ts")).liveWrite; + // 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 Error(`GitHub could not tell ${r.login}'s access to ${slugOf(r.repo)}`); + 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); @@ -200,40 +231,53 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise 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 Error(`GitHub returned no ${refOf(r)}`); + 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 Error("the head moved while the lockfile was written"); + 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 Error("the author's permission could not be read yet"); + 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 Error(`the fetched head ${short(fetched)} is not the head GitHub reports`); + 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) throw new Error(`${path}: ${f.reason}`); + 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) throw failed(`${path}: ${out.reason}`); + 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) throw new Ended("pushed", `${dep} is already pinned to ${short(sha)}, the merge of ${depRef}; nothing to change`); + 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 { @@ -241,21 +285,24 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise const changed = files.map((f) => f.path); if (paths.includes(LOCK)) { const lock = await git.file(head, LOCK); - if (!lock.ok) throw failed(lock.reason); + if (!lock.ok) { + d.log?.(`autorepin ${refOf(r)}: ${LOCK}: ${oneLine(lock.reason)}`); + throw failed(`${LOCK} could not be read`); + } if (r.state !== "locking") { 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 = ?, task_id = ? WHERE ${KEY}`).run(sha, head, id, ...keyOf(r)); + 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 Error(`the lockfile task ${t ? t.state : "is gone"}`); + 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 Error("the lockfile task returned no Cargo.lock"); + 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); @@ -274,7 +321,7 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise 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 Error("the branch moved before the push"); + 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}`); } @@ -291,8 +338,13 @@ export function noticeText(r: Pick { +/** 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}`); @@ -325,11 +377,12 @@ export async function drainRepins(db: DatabaseSync, deps: RepinDeps): Promise= MAX_TRIES) finish(db, r, failed(why), clock()); - else { db.prepare(`UPDATE main.autorepins SET state = 'waiting', head = NULL, to_head = NULL, task_id = NULL, tries = tries + 1, tried_at = ? WHERE ${KEY}`).run(clock().toISOString(), ...keyOf(r)); continue; } + // 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 { 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++; diff --git a/src/repin/manifest.ts b/src/repin/manifest.ts index d0a69daa..6e874674 100644 --- a/src/repin/manifest.ts +++ b/src/repin/manifest.ts @@ -47,7 +47,8 @@ function sourcesOn(data: TomlTable, slug: string): TomlTable[] { 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 } - | { ok: false; reason: string }; + /** `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 @@ -56,7 +57,7 @@ export type Repinned = 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: ${before.error}` }; + 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; @@ -93,30 +94,38 @@ function lockedPackages(text: string): Locked[] | null { 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. - * It may add packages from crates.io and from `slug` at `sha`, and drop packages. It may not name another new source, - * keep a package of `slug` at another commit, or change the checksum of a package it keeps. + * 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 package from crates.io whose name `before` does not have from crates.io: 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 key = (p: Locked): string => `${p.name}@${p.version}@${p.source ?? ""}`; - const known = new Map(was.map((p) => [key(p), p])); + const pair = (p: Locked): string => `${p.name}\0${p.source ?? ""}`; + const exact = (p: Locked): string => `${pair(p)}\0${p.version}\0${p.checksum ?? ""}`; + const pairs = new Set(was.map(pair)), kept = new Set(was.map(exact)); 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}`)) return `the new lockfile has ${p.name} from ${slug} at another commit`; - continue; + 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`; } - const old = known.get(key(p)); - if (!old) { - if (p.source === null) return `the new lockfile adds the local package ${p.name}`; - if (!CRATES_IO.has(p.source)) return `the new lockfile adds ${p.name} from a source outside crates.io and ${slug}`; - } else if (old.checksum !== p.checksum) return `the new lockfile changes the checksum of ${p.name} ${p.version}`; + if (kept.has(exact(p))) continue; + if (pairs.has(pair(p))) return `the new lockfile changes the version or checksum of ${name}`; + if (p.source === null) return `the new lockfile adds the local package ${name}`; + if (!CRATES_IO.has(p.source)) return `the new lockfile adds ${name} from a source outside crates.io and ${slug}`; } return null; } diff --git a/src/schema.sql b/src/schema.sql index 1f619c92..6c0bbb56 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -596,6 +596,7 @@ CREATE TABLE IF NOT EXISTS autorepins ( 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 @@ -609,6 +610,14 @@ CREATE TABLE IF NOT EXISTS autorepins ( 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..1b9638f1 100644 --- a/src/stages/registry.ts +++ b/src/stages/registry.ts @@ -312,6 +312,8 @@ 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 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 index aa337c89..31922e52 100644 --- a/test/autorepin.test.ts +++ b/test/autorepin.test.ts @@ -105,6 +105,10 @@ describe("lockRefusal", () => { 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`))); @@ -173,7 +177,7 @@ function setup(o: { lock?: boolean; off?: Parameters[0] } = {}): return s; } -const set = (s: Setup) => requestRepin(s.w.db, { login: OPERATOR, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: { owner: "storytold", name: "libs", number: 12 } }); +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; @@ -187,15 +191,24 @@ function locked(s: Setup, lock: string | null, state = "done"): void { 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(); - 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: `@${SLUG} autorepin storytold/libs#12`, 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, permission: async () => "ok" }); + 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"); @@ -338,7 +351,7 @@ describe("autorepin", () => { 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, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: { owner: null, name: "libs", number: 12 }, ...o }); + 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/); @@ -349,12 +362,12 @@ describe("autorepin", () => { 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, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref, at: new Date(at) }); + 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 command/); + 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"); @@ -363,10 +376,29 @@ describe("autorepin", () => { test("off drops a waiting autorepin", async () => { const s = setup(); await set(s); - await requestRepin(s.w.db, { login: OPERATOR, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: null }); + 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"); + }); }); From 4e71f328138eb461765b2c35b5399b77475d7aab Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:33:09 +0000 Subject: [PATCH 4/4] Autorepin: refused or failed with a reason where no build worker would take the lockfile task, drained apart from the webhook pass, waiting state registered as a wait, a crates.io package with a name the old lockfile has must be kept exactly, and a lockfile task no longer wanted is cancelled --- docs/operations.md | 8 ++++---- docs/pipeline.md | 1 + src/repin/index.ts | 29 ++++++++++++++++++++++++++++- src/repin/manifest.ts | 15 ++++++++------- src/runner/runner.ts | 17 +++++++++++------ src/stages/registry.ts | 1 + test/autorepin.test.ts | 7 +++++++ 7 files changed, 60 insertions(+), 18 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 83f16f93..9e88e0f7 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -55,12 +55,12 @@ The runner drains `sync_requests` every 5 seconds while rows exist (`webhookTick **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, and where **Pushes** are not approved for the repo. 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. -- 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. +- 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 does not have from crates.io. Packages may be dropped. Without a lockfile there is no task. +- 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. diff --git a/docs/pipeline.md b/docs/pipeline.md index ab6c9686..6ea4a132 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -763,6 +763,7 @@ 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` | diff --git a/src/repin/index.ts b/src/repin/index.ts index a0288ed3..489d2187 100644 --- a/src/repin/index.ts +++ b/src/repin/index.ts @@ -32,6 +32,8 @@ 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"; @@ -82,6 +84,20 @@ const itemOf = (db: DatabaseSync, repo: string, number: number): Item | undefine // ---- 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); @@ -102,7 +118,9 @@ export async function requestRepin(db: DatabaseSync, o: { login: string; githubI // 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"; } @@ -117,6 +135,8 @@ export async function requestRepin(db: DatabaseSync, o: { login: string; githubI 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', @@ -169,6 +189,7 @@ 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 } : {}) }); } @@ -290,6 +311,8 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise 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] }], @@ -382,7 +405,11 @@ export async function drainRepins(db: DatabaseSync, deps: RepinDeps): Promise= MAX_TRIES) finish(db, r, failed(e instanceof Retry ? raw : UNEXPECTED), clock()); - else { db.prepare(`UPDATE main.autorepins SET state = 'waiting', task_id = NULL, tries = tries + 1, tried_at = ? WHERE ${KEY}`).run(clock().toISOString(), ...keyOf(r)); continue; } + 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++; diff --git a/src/repin/manifest.ts b/src/repin/manifest.ts index 6e874674..e2cbee7c 100644 --- a/src/repin/manifest.ts +++ b/src/repin/manifest.ts @@ -102,16 +102,17 @@ export const safePath = (s: string, what: string): string => (/^[A-Za-z0-9._/-]{ /** * 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 package from crates.io whose name `before` does not have from crates.io: Cargo may add those - * for the dependency's new requirements. Packages may be dropped. + * 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 pair = (p: Locked): string => `${p.name}\0${p.source ?? ""}`; - const exact = (p: Locked): string => `${pair(p)}\0${p.version}\0${p.checksum ?? ""}`; - const pairs = new Set(was.map(pair)), kept = new Set(was.map(exact)); + 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); @@ -123,9 +124,9 @@ export function lockRefusal(before: string, after: string, slug: string, sha: st return `the new lockfile has ${name} from ${slug} at another commit`; } if (kept.has(exact(p))) continue; - if (pairs.has(pair(p))) return `the new lockfile changes the version or checksum of ${name}`; - if (p.source === null) return `the new lockfile adds the local package ${name}`; + 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 9f63841c..e086ded4 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -104,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; @@ -193,7 +195,7 @@ export class Runner { this.webhookAt = Date.now(); const commands = !!this.db.prepare(`SELECT 1 FROM main.github_commands WHERE ${COMMAND_WORK_SQL} LIMIT 1`).get(); // Autorepins whose pull request was merged or closed, or whose lockfile task ended (src/repin). - const repins = anyRepinDue(this.db); + 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"); @@ -207,11 +209,14 @@ export class Runner { const k = await drainCommands(this.db, { querier: c, log: this.o.log }); if (k) this.o.log(`webhooks: carried out ${k} commands from comments`); } - // After the commands: an autorepin set on a pull request that is already merged starts in this pass. - if (repins || commands) { - 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`); + // 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/stages/registry.ts b/src/stages/registry.ts index 1b9638f1..c5180bed 100644 --- a/src/stages/registry.ts +++ b/src/stages/registry.ts @@ -312,6 +312,7 @@ 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" }, ], diff --git a/test/autorepin.test.ts b/test/autorepin.test.ts index 31922e52..e91b4494 100644 --- a/test/autorepin.test.ts +++ b/test/autorepin.test.ts @@ -360,6 +360,13 @@ describe("autorepin", () => { 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) });