From df653e52be9c0dc28fe660aea77248a52ca515d9 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 06:25:21 +0000 Subject: [PATCH] Guard PR writes: gates and guard, Guarded argument on merge, push, review, ask comment and CI run writes, merge pinned to the reviewed head --- src/cifix/index.ts | 21 ++++++-- src/core/facts.ts | 3 +- src/core/gates.ts | 45 ++++++++++++++++ src/core/guard.ts | 99 ++++++++++++++++++++++++++++++++++++ src/core/plan.ts | 2 + src/fixissue/index.ts | 4 +- src/fixup/conflict.ts | 14 +++-- src/fixup/index.ts | 16 ++++-- src/github/write.ts | 78 +++++++++++++++++----------- src/mainfix/index.ts | 4 +- src/mainfix/pr.ts | 4 +- src/merge/batch.ts | 17 +++++-- src/merge/ci-approval.ts | 10 +++- src/merge/index.ts | 13 ++++- src/merge/safe-merge.ts | 19 ++++--- src/merge/single.ts | 5 +- src/review/post.ts | 10 ++-- src/runner/steps.ts | 17 ++++--- test/cifix.test.ts | 2 +- test/fixup-conflict.test.ts | 2 +- test/fixup.test.ts | 4 +- test/github-activity.test.ts | 13 ++--- test/github-note.test.ts | 5 +- test/github-writes.test.ts | 60 ---------------------- test/guard.test.ts | 99 ++++++++++++++++++++++++++++++++++++ test/guarded.ts | 5 ++ test/merge.test.ts | 8 +-- test/world.ts | 2 +- 28 files changed, 431 insertions(+), 150 deletions(-) create mode 100644 src/core/gates.ts create mode 100644 src/core/guard.ts delete mode 100644 test/github-writes.test.ts create mode 100644 test/guard.test.ts create mode 100644 test/guarded.ts diff --git a/src/cifix/index.ts b/src/cifix/index.ts index 604c9d8a4..9e9187199 100644 --- a/src/cifix/index.ts +++ b/src/cifix/index.ts @@ -25,7 +25,9 @@ import { editable, validatePatch } from "../fixup/patch.ts"; import { readGate } from "../merge/changes-requested.ts"; import { longLivedOf, pushable, BASE_ORG } from "../fixup/pushable.ts"; import { HOLD_CANNOT_PUSH } from "../fixup/template.ts"; -import { ghComment, ghRerunFailed, pushBranch, type Note, type Writer } from "../github/write.ts"; +import { CLI_BY, type By } from "../core/gates.ts"; +import { guard, liveOf } from "../core/guard.ts"; +import { ghAskComment, ghComment, ghRerunFailed, pushBranch, type Note, type Writer } from "../github/write.ts"; import { Client, type Querier } from "../mirror.ts"; import { ghExec, type Gh } from "../merge/safe-merge.ts"; import { checkLine, parseCheck, recordCheck } from "../patchcheck/index.ts"; @@ -107,7 +109,7 @@ export function defaultDeps(): CifixDeps { }; } -export type CifixParams = { repo: string; limit?: number; /** Default true. */ dryRun?: boolean; onHandled?: (n: number) => void }; +export type CifixParams = { repo: string; limit?: number; /** Default true. */ dryRun?: boolean; onHandled?: (n: number) => void; /** Who asked; default: an operator at the command line. */ by?: By }; export type CifixSummary = { runId: string; repo: string; dryRun: boolean; pushed: string[]; asked: string[]; queued: string[]; infra: string[]; skipped: string[]; @@ -387,8 +389,15 @@ export async function runCifix(db: DatabaseSync, params: CifixParams, log: (line log(` ${ref}: skipped: ${reason}`); return; } + const g = await guard(db, { repo, number: c.number }, { kind: "cifix", bucket: kind === "format" ? "collect" : "work", head: c.head }, params.by ?? CLI_BY, liveOf(db, d.querier)); + if ("refused" in g) { + // Nothing is recorded: the head is tried again once the refusal's reason is gone. + summary.skipped.push(ref); + log(` ${ref}: skipped: ${g.refused}`); + return; + } if (!canPush) { - const cm = await ghComment(gw, d.exec, "cifix-comment", { repo, number: c.number, pr: true }, codeNote, askText(checkName, v.patch), { run: runId, head: c.head }); + const cm = await ghAskComment(gw, d.exec, "cifix-comment", g, codeNote, askText(checkName, v.patch), { run: runId, head: c.head }); if (cm.code !== 0) { const reason = `the comment failed: ${scrubReason(oneLine(cm.stderr), d.root)}`; rec.set(c, kind, "comment-failed", reason, { files: v.files }); @@ -412,7 +421,7 @@ export async function runCifix(db: DatabaseSync, params: CifixParams, log: (line const outside = outsideShown(shown, await git.diffText(head, commit)); if (outside) { fail("refused", outside); return; } rec.pushing(c, kind, commit, v.files); - const push = await pushBranch(gw, git, "cifix-push", { repo, number: c.number, remote: pr.headRepository!.nameWithOwner, branch: pr.headRefName, sha: commit, expected: head }, { run: runId, from: head, to: commit, files: v.files, changed: v.changed, kind }); + const push = await pushBranch(gw, git, "cifix-push", g, { remote: pr.headRepository!.nameWithOwner, branch: pr.headRefName, sha: commit }, { run: runId, from: head, to: commit, files: v.files, changed: v.changed, kind }); if (push.code !== 0) { const err = oneLine(push.stderr); if (/stale info|rejected|fetch first/i.test(err)) fail("refused", "the branch moved since the checks ran"); @@ -588,13 +597,15 @@ export async function runRerun(db: DatabaseSync, params: CifixParams, log: (line const pr = r.repository?.pullRequest; noteLive(db, repo, c.number, pr, d.now().toISOString()); if (!pr || pr.state !== "OPEN" || pr.isDraft || pr.headRefOid !== c.head) { log(` ${ref}: skipped: closed, a draft or at another head`); out.skipped.push(ref); continue; } + const g = await guard(db, { repo, number: c.number }, { kind: "cifix", bucket: "rerun", head: c.head }, params.by ?? CLI_BY); + if ("refused" in g) { log(` ${ref}: skipped: ${g.refused}`); out.skipped.push(ref); continue; } params.onHandled?.(++n); // Recorded before the calls: one rerun per head, even if this process dies in the middle of them. db.prepare("INSERT INTO ci_fixes (repo, number, head, kind, state, reason, files, attempt, runs, created_at) VALUES (?, ?, ?, 'infra', 'rerunning', NULL, '[]', 0, ?, ?)") .run(repo, c.number, c.head, JSON.stringify(runs), d.now().toISOString()); const errors: string[] = []; for (const run of runs) { - const res = await ghRerunFailed(w, d.exec, { repo, number: c.number, runId: run }, { head: c.head }); + const res = await ghRerunFailed(w, d.exec, g, run, { head: c.head }); if (res.code !== 0) errors.push(oneLine(res.stderr || res.stdout)); } // One rerun per head, whether or not GitHub took every run. diff --git a/src/core/facts.ts b/src/core/facts.ts index bdc86d3db..2dca69463 100644 --- a/src/core/facts.ts +++ b/src/core/facts.ts @@ -96,6 +96,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const own = ownFixPrs(db, opts.repo); const mainRed = redMainRepos(db); const answers = new Map(actionable(db).filter((a) => a.kind === "merge").map((a) => [a.id, a.answer])); + const pipelineOn = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_enabled'").get() as { value: string } | undefined)?.value === "1"; const pipelineLogin = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value ?? null; const posts = new Map((db.prepare("SELECT repo, number, review_id, head_oid, posted_at, opus_at FROM review_posts").all() as { repo: string; number: number; review_id: string; head_oid: string | null; posted_at: string | null; opus_at: string | null }[]) .map((p) => [`${p.repo}#${p.number}`, p])); @@ -167,7 +168,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const integration = !r.not_integration; const lines = (r.additions ?? 0) + (r.deletions ?? 0); const base: PrFacts = { - repo: r.repo, number: r.number, now, ghState: r.state, head, draft: fresh ? r.c_state !== "OPEN" || !!r.c_draft : !!r.is_draft, + repo: r.repo, number: r.number, now, pipelineOn, ghState: r.state, head, draft: fresh ? r.c_state !== "OPEN" || !!r.c_draft : !!r.is_draft, author: r.author, authorIsPipeline: r.author !== null && r.author === pipelineLogin, tier: "not", lines, size: sizeOf(lines), label: null, needsDecisionFlag: false, scopeAnswer: scope.get(ref) ?? null, inScope, integration, batchPr: !!r.batch_pr, heldBacklog: !!r.held_backlog, heldDuplicate: !r.held_backlog && !!r.held_dup, mergeHeld: holds.has(ref), diff --git a/src/core/gates.ts b/src/core/gates.ts new file mode 100644 index 000000000..34a451fb0 --- /dev/null +++ b/src/core/gates.ts @@ -0,0 +1,45 @@ +// The gates on writes: the repo approvals each action needs and the global pipeline switch. Pure. The planner and the +// guard (guard.ts) both use it; decide() does not (it shows what would run, approved or not). +import type { ActionKind, PrFacts } from "./plan.ts"; + +/** Who asks for a write: the pipeline itself (the autopilot), or an operator (a job they requested, or a command they ran). */ +export type By = "pipeline" | { operator: string }; + +/** An action as the gates and the guard see it: its kind, and the bucket where the kind has several (fix-up: fix | ask, ...). */ +export type Want = { kind: ActionKind; bucket?: string }; + +type Approval = "merge" | "push" | "comment" | "ci"; + +const WHAT: Record = { merge: "merging", push: "pushing", comment: "commenting", ci: "approving CI runs" }; + +/** The approval an action's GitHub write needs, or null for an action that writes nothing there. */ +export function approvalOf(f: Pick, a: Want): Approval | null { + switch (a.kind) { + case "merge": return "merge"; + case "post-review": return "comment"; + case "approve-ci": return "ci"; + case "fixup": + case "conflict": + return a.bucket === "fix" || a.bucket === "merge" ? "push" : a.bucket === "ask" ? "comment" : null; + case "cifix": + if (a.bucket === "rerun") return "ci"; + // A closed branch gets the patch as a comment instead of a push. + return a.bucket === "work" || a.bucket === "collect" ? (f.pushable ? "push" : "comment") : null; + default: return null; + } +} + +/** Why the write is refused, or null. */ +export function gates(f: PrFacts, a: Want, by: By): string | null { + if (by === "pipeline" && !f.pipelineOn) return "the pipeline is off"; + const need = approvalOf(f, a); + if (!need) return null; + const ok = { merge: f.repoFacts.mergeApproved, push: f.repoFacts.pushApproved, comment: f.repoFacts.commentApproved, ci: f.repoFacts.ciApproved }[need]; + return ok ? null : `${WHAT[need]} in ${f.repo} is not approved`; +} + +/** Writes from the command line are an operator's. */ +export const CLI_BY: By = { operator: "cli" }; + +/** The writer behind a job: the autopilot's own jobs are the pipeline's, every other requester is an operator. */ +export const byOfJob = (requestedBy: string): By => (requestedBy === "pipeline" ? "pipeline" : { operator: requestedBy }); diff --git a/src/core/guard.ts b/src/core/guard.ts new file mode 100644 index 000000000..3d53b938a --- /dev/null +++ b/src/core/guard.ts @@ -0,0 +1,99 @@ +// The guard: the only way to get a `Guarded` value, which every PR write in github/write.ts requires. +// Right before a write it reloads the facts (with a live read of head, state and mergeable for merges and pushes), +// runs decide() again, applies the gates, and passes only when the Plan still holds the same action at the same head. +import type { DatabaseSync } from "node:sqlite"; +import type { Querier } from "../mirror.ts"; +import { refreshChecks } from "../review/checks.ts"; +import { decidePr } from "./decide.ts"; +import { loadPrFact } from "./facts.ts"; +import { gates, type By, type Want } from "./gates.ts"; +import type { PrFacts } from "./plan.ts"; + +declare const guarded: unique symbol; + +/** What the guard let through: the action, the reviewed head it holds at, and the PR. Only `guard` makes one. */ +export type Guarded = { readonly [guarded]: true; readonly action: Want; readonly head: string; readonly repo: string; readonly number: number }; +export type Refused = { refused: string }; +/** The action to guard: `head` is the head the caller reviewed or worked on. `batch`: a member of a merge batch, which is in its batch state, not ready. */ +export type Ask = Want & { head: string; batch?: boolean }; +export type Ref = { repo: string; number: number }; + +export type LiveRead = { state: "OPEN" | "MERGED" | "CLOSED"; head: string; draft: boolean; mergeable: string }; +export type Live = (repo: string, number: number) => Promise; + +/** The live read of the merge step: fetches the PR's checks (and stores them), which carry head, state, draft and mergeable. */ +export function liveOf(db: DatabaseSync, q: Querier): Live { + return async (repo, number) => { + const [c] = await refreshChecks(db, q, repo, [number]); + return c ? { state: c.state as LiveRead["state"], head: c.head_oid, draft: c.is_draft, mergeable: c.mergeable ?? "UNKNOWN" } : null; + }; +} + +const short = (s: string | null): string => (s ?? "none").slice(0, 7); +const BATCH_STATES: readonly string[] = ["batch-checking", "in-batch"]; + +/** Merges and pushes read GitHub first: the head must not have moved. */ +const needsLive = (a: Want): boolean => + a.kind === "merge" || (a.kind === "fixup" && a.bucket === "fix") || (a.kind === "conflict" && a.bucket === "merge") + || (a.kind === "cifix" && (a.bucket === "work" || a.bucket === "collect")); + +const make = (ref: Ref, a: Want, head: string): Guarded => ({ action: a, head, repo: ref.repo, number: ref.number }) as Guarded; + +async function check(db: DatabaseSync, ref: Ref, a: Ask, by: By, live?: Live): Promise<{ f: PrFacts } | Refused> { + const name = `${ref.repo}#${ref.number}`; + let read: LiveRead | null = null; + if (needsLive(a)) { + if (!live) return { refused: `${name}: no live read of the PR before the write` }; + try { + read = await live(ref.repo, ref.number); + } catch (e) { + return { refused: `${name}: live read failed: ${String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 200)}` }; + } + if (!read) return { refused: `${name}: GitHub returned no such PR` }; + if (read.state !== "OPEN") return { refused: `${name}: no longer open on GitHub (${read.state.toLowerCase()})` }; + if (read.head !== a.head) return { refused: `${name}: head moved from ${short(a.head)} to ${short(read.head)} since the review` }; + } + let f = loadPrFact(db, ref.repo, ref.number); + if (!f) return { refused: `${name}: not an open PR the pipeline tracks` }; + if (read) f = { ...f, ghState: read.state, head: read.head, draft: read.draft, mergeable: read.mergeable }; + const why = gates(f, a, by); + if (why) return { refused: `${name}: ${why}` }; + if (a.batch && f.mergeHeld) return { refused: `${name}: merge held by an operator` }; + const plan = decidePr(f); + const holds = plan.head === a.head && (plan.actions.some((x) => x.kind === a.kind && x.head === a.head && (a.bucket === undefined || x.params?.bucket === a.bucket)) + || (a.batch === true && a.kind === "merge" && BATCH_STATES.includes(plan.state) && plan.path !== null)); + if (!holds) { + const now = plan.actions.map((x) => x.kind + (typeof x.params?.bucket === "string" ? `:${x.params.bucket}` : "")).join(", ") || "none"; + return { refused: `${name}: the plan no longer has ${a.kind}${a.bucket ? `:${a.bucket}` : ""} at ${short(a.head)} (state ${plan.state}, head ${short(plan.head)}, actions: ${now}${plan.wait ? `, waiting for ${plan.wait}` : ""})` }; + } + return { f }; +} + +/** Lets one PR write through, or says why not. Call it right before the write. */ +export async function guard(db: DatabaseSync, ref: Ref, action: Ask, by: By, live?: Live): Promise { + const r = await check(db, ref, action, by, live); + if ("refused" in r) return r; + return make(ref, action, action.head); +} + +/** + * Lets the merge of a batch PR through: every member must pass the guard at its batched head, and the batch PR must + * still be open at the batch tip. The returned value is for the batch PR. + */ +export async function guardBatchMerge(db: DatabaseSync, batch: Ref & { head: string }, members: { number: number; head: string }[], by: By, live: Live): Promise { + for (const m of members) { + const r = await guard(db, { repo: batch.repo, number: m.number }, { kind: "merge", head: m.head, batch: true }, by, live); + if ("refused" in r) return r; + } + const name = `${batch.repo}#${batch.number}`; + let read: LiveRead | null; + try { + read = await live(batch.repo, batch.number); + } catch (e) { + return { refused: `${name}: live read failed: ${String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 200)}` }; + } + if (!read) return { refused: `${name}: GitHub returned no such PR` }; + if (read.state !== "OPEN") return { refused: `${name}: no longer open on GitHub (${read.state.toLowerCase()})` }; + if (read.head !== batch.head) return { refused: `${name}: the batch branch moved from ${short(batch.head)} to ${short(read.head)}` }; + return make(batch, { kind: "merge" }, batch.head); +} diff --git a/src/core/plan.ts b/src/core/plan.ts index a77ddef4f..238aad54e 100644 --- a/src/core/plan.ts +++ b/src/core/plan.ts @@ -79,6 +79,8 @@ export type PrFacts = { repo: string; number: number; /** Time of the decision, ms. */ now: number; + /** The global pipeline switch. decide() ignores it; gates() applies it to the pipeline's own writes. */ + pipelineOn: boolean; /** GitHub state as mirrored. */ ghState: "OPEN" | "MERGED" | "CLOSED"; /** The PR's current head commit (checks fetched after the mirror's last update win over the mirror). */ diff --git a/src/fixissue/index.ts b/src/fixissue/index.ts index fdfa27f6e..a07cb0137 100644 --- a/src/fixissue/index.ts +++ b/src/fixissue/index.ts @@ -44,7 +44,7 @@ import { fixIssueApprovalOf } from "./approval.ts"; import { hasOpenPr, notRustKey, selectIssues, type IssueCandidate } from "./candidates.ts"; import { parseTriage, sourcePaths, validateFixPatch } from "./parse.ts"; import { branchName, claimCommentText, commentText, commitMessage, prBody, prTitle } from "./template.ts"; -import { ghComment, ghFork, ghOpenPr, pushBranch, type Writer } from "../github/write.ts"; +import { ghComment, ghFork, ghOpenPr, pushOwnBranch, type Writer } from "../github/write.ts"; import { COMMENTS_SHOWN, COMMENT_CHARS, FILE_CAP, ISSUE_BODY_LIMIT, MAX_PATHS, MAX_ROUNDS, TOTAL_CAP, type IssueText, type PatchInput, type TriageInput } from "./types.ts"; import { inPilot, pilotSqlFor } from "../pilot.ts"; import { backlogHeld, backlogHeldSql } from "../dupes/held.ts"; @@ -610,7 +610,7 @@ export async function openPr(x: Ctx, r: AttemptRow): Promise { } if (!permitted()) return false; const fork = await forkOf({ db, login: ACTOR }, d.exec, who.login, r.repo, { run: x.runId }); - const push = await pushBranch({ db, login: ACTOR }, git, "fixissue-push", { repo: r.repo, number: r.number, remote: fork, branch, sha: commit }, { run: x.runId, fork }); + const push = await pushOwnBranch({ db, login: ACTOR }, git, "fixissue-push", { repo: r.repo, number: r.number, remote: fork, branch, sha: commit }, { run: x.runId, fork }); if (push.code !== 0) { log(` ${ref}: push failed: ${oneLine(push.stderr)}`); tried(); return false; } if (await closedLive(x, r)) { fail(db, d, r, "the issue is closed"); return false; } const body = prBody(r.number, files, testPath); diff --git a/src/fixup/conflict.ts b/src/fixup/conflict.ts index c83b85af6..d59a0a1e6 100644 --- a/src/fixup/conflict.ts +++ b/src/fixup/conflict.ts @@ -7,7 +7,9 @@ import { join } from "node:path"; import type { DatabaseSync } from "node:sqlite"; import { REPO_PATH } from "../sandbox/command.ts"; import { audit } from "../dash/audit.ts"; -import { ghComment, pushBranch, type Writer } from "../github/write.ts"; +import type { By } from "../core/gates.ts"; +import { guard, liveOf } from "../core/guard.ts"; +import { ghAskComment, ghComment, pushBranch, type Writer } from "../github/write.ts"; import { cachedDiff } from "../review/diff.ts"; import { checkLine, parseCheck, recordCheck } from "../patchcheck/index.ts"; import { CHECK_DIFF_CAP, CHECK_PATCH_CAP, type FixupCheckInput } from "../patchcheck/types.ts"; @@ -43,6 +45,8 @@ export type ConflictRun = { prQuery: string; scrub: (raw: string) => string; who: () => Promise; git: () => Git; /** Called once per PR handled. */ onHandled?: (n: number) => void; handled: { n: number }; + /** Who asked: gates the writes. */ + by: By; /** Assigns the PR to the pipeline's account when nobody is assigned; takes our assignment back when the stage gives up. */ claim: (c: ConflictCandidate, pr: PrNode) => Promise; release: (c: ConflictCandidate) => Promise; @@ -92,7 +96,9 @@ export async function askConflict(db: DatabaseSync, x: ConflictRun, c: ConflictC if (!pr) return; if (pr.mergeable !== "CONFLICTING") { x.log(` ${ref}: skipped: GitHub no longer reports a conflict`); return; } if (!BASE_NAME.test(c.base)) { x.log(` ${ref}: skipped: unusable base branch name`); return; } - const cm = await ghComment(x.gw, x.d.exec, "conflict-comment", { repo: x.repo, number: c.number, pr: true }, { by: "fixed" }, conflictAskText(c.base), { run: x.runId, head: c.head }); + const g = await guard(db, { repo: x.repo, number: c.number }, { kind: "conflict", bucket: "ask", head: c.head }, x.by); + if ("refused" in g) { x.log(` ${ref}: skipped: ${g.refused}`); return; } + const cm = await ghAskComment(x.gw, x.d.exec, "conflict-comment", g, { by: "fixed" }, conflictAskText(c.base), { run: x.runId, head: c.head }); if (cm.code !== 0) { x.log(` ${ref}: comment failed: ${oneLine(cm.stderr)}`); return; } record(db, x.at(), c, "asked", null, [], null); x.summary.asked.push(ref); @@ -213,8 +219,10 @@ export async function mergeConflict(db: DatabaseSync, x: ConflictRun, c: Conflic if (!again) return; } const commit = await git.commitMerge(tree, [head, baseSha], mergeMessage(c.base, pr.headRefName), { name: who.login, email: who.email }); + const g = await guard(db, { repo: x.repo, number: c.number }, { kind: "conflict", bucket: "merge", head: c.head }, x.by, liveOf(db, x.d.querier)); + if ("refused" in g) { x.log(` ${ref}: skipped: ${g.refused}`); return; } recordPushing(db, x.at(), c, files, baseSha, commit); - const push = await pushBranch(x.gw, git, "conflict-push", { repo: x.repo, number: c.number, remote: pr.headRepository.nameWithOwner, branch: pr.headRefName, sha: commit, expected: head }, { run: x.runId, from: head, to: commit, base: c.base, files }); + const push = await pushBranch(x.gw, git, "conflict-push", g, { remote: pr.headRepository.nameWithOwner, branch: pr.headRefName, sha: commit }, { run: x.runId, from: head, to: commit, base: c.base, files }); if (push.code !== 0) { const err = oneLine(push.stderr); if (/denied|403|permission|not allowed|protected branch|declined|GH013/i.test(err)) { held("push-denied", "the branch cannot be pushed to"); return; } diff --git a/src/fixup/index.ts b/src/fixup/index.ts index b28cd3263..df409fea0 100644 --- a/src/fixup/index.ts +++ b/src/fixup/index.ts @@ -18,7 +18,9 @@ import { REPO_PATH } from "../sandbox/command.ts"; import { checkoutForPr } from "../sandbox/index.ts"; import { audit } from "../dash/audit.ts"; import { withNote } from "../github/note.ts"; -import { ghComment, ghEditComment, pushBranch, type Note, type Writer } from "../github/write.ts"; +import { CLI_BY, type By } from "../core/gates.ts"; +import { guard, liveOf } from "../core/guard.ts"; +import { ghAskComment, ghComment, ghEditComment, pushBranch, type Note, type Writer } from "../github/write.ts"; import { claimItem, releaseItem, type Assignable } from "../github/claim.ts"; import { connect } from "../db.ts"; import { Client, type Querier } from "../mirror.ts"; @@ -85,6 +87,8 @@ export type FixupParams = { /** Default true. */ dryRun?: boolean; onHandled?: (n: number) => void; + /** Who asked; default: an operator at the command line. */ + by?: By; }; export type FixupSummary = { runId: string; repo: string; dryRun: boolean; @@ -240,7 +244,9 @@ export async function runFixup(db: DatabaseSync, params: FixupParams, log: (line return; } const body = c.carry ? c.carry.suggestion! : askText(c.fixes); - const cm = await ghComment(gw, d.exec, "fixup-comment", { repo, number: c.number, pr: true }, c.carry ? (c.model ? { by: "operator", model: c.model } : { by: "fixed-operator" }) : { by: "model", kind: "comment", model: c.model }, body, { run: runId, head: c.head }); + const g = await guard(db, { repo, number: c.number }, { kind: "fixup", bucket: "ask", head: c.head }, params.by ?? CLI_BY); + if ("refused" in g) { log(` ${ref}: not asked: ${g.refused}`); return; } + const cm = await ghAskComment(gw, d.exec, "fixup-comment", g, c.carry ? (c.model ? { by: "operator", model: c.model } : { by: "fixed-operator" }) : { by: "model", kind: "comment", model: c.model }, body, { run: runId, head: c.head }); if (cm.code !== 0) { log(` ${ref}: comment failed: ${oneLine(cm.stderr)}`); return; } rec.fixup(c, "asked", null, [...new Set(c.fixes.map((f) => f.file))]); if (count) params.onHandled?.(++handled.n); @@ -271,7 +277,7 @@ export async function runFixup(db: DatabaseSync, params: FixupParams, log: (line }; const conflictRun: ConflictRun = { repo, runId, log, d, gw, at, summary, prQuery: PR_QUERY, scrub: (raw) => scrubReason(raw, d.root), git: () => git, - who: () => (whoP ??= whoAmI(d.exec)), onHandled: params.onHandled, handled, claim, release, + who: () => (whoP ??= whoAmI(d.exec)), onHandled: params.onHandled, handled, claim, release, by: params.by ?? CLI_BY, }; for (const c of cAsks) await askConflict(db, conflictRun, c); if (!picks.length && !cMerges.length) return summary; @@ -384,8 +390,10 @@ export async function runFixup(db: DatabaseSync, params: FixupParams, log: (line if (!now || now.state !== "OPEN" || now.isDraft) { log(` ${ref}: skipped: no longer an open, non-draft PR after the model calls`); continue; } if (now.headRefOid !== c.head) { log(` ${ref}: skipped: head moved to ${short(now.headRefOid)} during the model calls`); continue; } + const g = await guard(db, { repo, number: c.number }, { kind: "fixup", bucket: "fix", head: c.head }, params.by ?? CLI_BY, liveOf(db, d.querier)); + if ("refused" in g) { log(` ${ref}: skipped: ${g.refused}`); continue; } rec.pushing(c, commit, v.files); - const push = await pushBranch(gw, git, "fixup-push", { repo, number: c.number, remote: pr.headRepository.nameWithOwner, branch: pr.headRefName, sha: commit, expected: head }, { run: runId, from: head, to: commit, files: v.files, changed: v.changed }); + const push = await pushBranch(gw, git, "fixup-push", g, { remote: pr.headRepository.nameWithOwner, branch: pr.headRefName, sha: commit }, { run: runId, from: head, to: commit, files: v.files, changed: v.changed }); if (push.code !== 0) { const err = oneLine(push.stderr); if (/stale info|rejected|fetch first/i.test(err)) fail("refused", "the branch moved since the review"); diff --git a/src/github/write.ts b/src/github/write.ts index f4853ea05..621b39338 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -1,12 +1,13 @@ // The only module that writes to GitHub. Every function performs the write // and records it in the audit table itself, failed attempts included, so a -// caller cannot write without leaving a record. test/github-writes.test.ts -// fails when any other file in src/ sends a mutation, pushes, merges or -// otherwise writes. Transports (querier, exec, git, merge command) stay +// caller cannot write without leaving a record. Writes to a pull request take a +// `Guarded` value that only core/guard.ts makes, so the compiler enforces that the +// guard ran right before. Transports (querier, exec, git, merge command) stay // injected so tests fake them and assert the rows. import type { DatabaseSync } from "node:sqlite"; import { ORG } from "../act/templates.ts"; import { connect } from "../db.ts"; +import type { Guarded } from "../core/guard.ts"; import type { Exec, ExecResult, Git } from "../fixup/git.ts"; import type { Querier } from "../mirror.ts"; import { type Note, withNote } from "./note.ts"; @@ -106,18 +107,18 @@ export async function unassignFrom(w: Writer, q: Querier, item: ItemRef, user: { } /** Posts a review as a plain comment review on the commit; returns the review id (null when GitHub returned none). */ -export async function postReview(w: Writer, q: Querier, item: ItemRef, head: string, note: Note, text: string, details: Details = {}): Promise { +export async function postReview(w: Writer, q: Querier, g: Guarded, nodeId: string, note: Note, text: string, details: Details = {}): Promise { const body = withNote(note, text); - const r = await recorded(w, "review-post", refOf(item.repo, item.number), { ...details, head }, - () => q.query(ADD_REVIEW, { pr: item.id, oid: head, body }) as Promise<{ addPullRequestReview?: { pullRequestReview?: { id?: string } | null } | null }>, + const r = await recorded(w, "review-post", refOf(g.repo, g.number), { ...details, head: g.head }, + () => q.query(ADD_REVIEW, { pr: nodeId, oid: g.head, body }) as Promise<{ addPullRequestReview?: { pullRequestReview?: { id?: string } | null } | null }>, (x) => ({ review: x.addPullRequestReview?.pullRequestReview?.id ?? undefined }), (x) => (x.addPullRequestReview?.pullRequestReview?.id ? null : "GitHub returned no review")); return r.addPullRequestReview?.pullRequestReview?.id ?? null; } -export async function editReview(w: Writer, q: Querier, repo: string, number: number, reviewId: string, head: string, note: Note, text: string, details: Details = {}): Promise { +export async function editReview(w: Writer, q: Querier, g: Guarded, reviewId: string, note: Note, text: string, details: Details = {}): Promise { const body = withNote(note, text); - await recorded(w, "review-edit", refOf(repo, number), { ...details, head, review: reviewId }, () => q.query(EDIT_REVIEW, { id: reviewId, body })); + await recorded(w, "review-edit", refOf(g.repo, g.number), { ...details, head: g.head, review: reviewId }, () => q.query(EDIT_REVIEW, { id: reviewId, body })); } export async function createLabel(w: Writer, q: Querier, repo: string, repoId: string, label: { name: string; color: string; description: string }, retry: Retry = direct, details: Details = {}): Promise { @@ -160,7 +161,12 @@ async function viaGh(w: Writer, exec: Exec, action: string, target: string, deta (r) => (r.code === 0 ? null : oneLine(r.stderr || r.stdout) || `exit code ${r.code}`)); } -/** `action` is the audit action of the caller's stage (act, fixup or fixissue comment). */ +/** Asks a contributor on their PR (fix-up, conflict or CI fix where the branch is closed to us); `action` is the audit action of the caller's stage. */ +export function ghAskComment(w: Writer, exec: Exec, action: string, g: Guarded, note: Note, text: string, details: Details = {}): Promise { + return ghComment(w, exec, action, { repo: g.repo, number: g.number, pr: true }, note, text, details); +} + +/** `action` is the audit action of the caller's stage (act, fixup or fixissue comment). Not for asks: those use ghAskComment. */ export function ghComment(w: Writer, exec: Exec, action: string, o: { repo: string; number: number; pr: boolean }, note: Note, text: string, details: Details = {}): Promise { const body = withNote(note, text); return viaGh(w, exec, action, refOf(o.repo, o.number), { ...details, text: body }, @@ -221,28 +227,36 @@ export async function createIssue(w: Writer, exec: Exec, o: { repo: string; targ } /** Approves one Actions run that waits for a maintainer's approval (a run from an outside contributor's PR). */ -export function ghApproveRun(w: Writer, exec: Exec, o: { repo: string; number: number; runId: number }, details: Details = {}): Promise { - return viaGh(w, exec, "ci-run-approve", refOf(o.repo, o.number), { ...details, run: o.runId }, - ["api", "-X", "POST", `repos/${ORG}/${o.repo}/actions/runs/${o.runId}/approve`]); +export function ghApproveRun(w: Writer, exec: Exec, g: Guarded, runId: number, details: Details = {}): Promise { + return viaGh(w, exec, "ci-run-approve", refOf(g.repo, g.number), { ...details, run: runId }, + ["api", "-X", "POST", `repos/${ORG}/${g.repo}/actions/runs/${runId}/approve`]); } -/** Reruns the failed jobs of one Actions run (same head commit). */ -export function ghRerunFailed(w: Writer, exec: Exec, o: { repo: string; number: number; runId: number } | { repo: string; head: string; runId: number }, details: Details = {}): Promise { - // A run on a default-branch head belongs to no item: the audit target names the repo and the commit. - const target = "number" in o ? refOf(o.repo, o.number) : `${o.repo}:${o.head.slice(0, 8)}`; - return viaGh(w, exec, "ci-rerun", target, { ...details, run: o.runId }, +/** Reruns the failed jobs of one Actions run of a PR's head commit. */ +export function ghRerunFailed(w: Writer, exec: Exec, g: Guarded, runId: number, details: Details = {}): Promise { + return viaGh(w, exec, "ci-rerun", refOf(g.repo, g.number), { ...details, run: runId }, + ["run", "rerun", String(runId), "--failed", "--repo", `${ORG}/${g.repo}`]); +} + +/** Reruns the failed jobs of one Actions run on a default-branch head. It belongs to no item: the audit target names the repo and the commit. */ +export function ghRerunMainFailed(w: Writer, exec: Exec, o: { repo: string; head: string; runId: number }, details: Details = {}): Promise { + return viaGh(w, exec, "ci-rerun", `${o.repo}:${o.head.slice(0, 8)}`, { ...details, run: o.runId }, ["run", "rerun", String(o.runId), "--failed", "--repo", `${ORG}/${o.repo}`]); } // ---- git pushes --------------------------------------------------------------- -/** - * Pushes `sha` to `branch` of `remote` (owner/name). With `expected` the push is refused when the branch moved - * (a contributor's branch); without it the branch is replaced (the pipeline's own fork). - */ -export function pushBranch(w: Writer, git: Pick, action: string, o: { repo: string; number?: number; remote: string; branch: string; sha: string; expected?: string }, details: Details = {}): Promise { - const lease = o.expected === undefined ? "--force" : `--force-with-lease=refs/heads/${o.branch}:${o.expected}`; - const target = o.number === undefined ? `${o.repo}:${o.branch}` : refOf(o.repo, o.number); +/** Pushes `sha` to a PR's branch `branch` of `remote` (owner/name); refused by git when the branch is no longer at the guarded head. */ +export function pushBranch(w: Writer, git: Pick, action: string, g: Guarded, o: { remote: string; branch: string; sha: string }, details: Details = {}): Promise { + return pushed(w, git, action, refOf(g.repo, g.number), o, `--force-with-lease=refs/heads/${o.branch}:${g.head}`, details); +} + +/** Pushes `sha` to `branch` of the pipeline's own fork, replacing the branch. */ +export function pushOwnBranch(w: Writer, git: Pick, action: string, o: { repo: string; number?: number; remote: string; branch: string; sha: string }, details: Details = {}): Promise { + return pushed(w, git, action, o.number === undefined ? `${o.repo}:${o.branch}` : refOf(o.repo, o.number), o, "--force", details); +} + +function pushed(w: Writer, git: Pick, action: string, target: string, o: { remote: string; branch: string; sha: string }, lease: string, details: Details): Promise { return recorded(w, action, target, { ...details, branch: o.branch, remote: o.remote, commit: o.sha }, () => git.git(["push", "--quiet", lease, `https://github.com/${o.remote}.git`, `${o.sha}:refs/heads/${o.branch}`]), undefined, @@ -256,13 +270,17 @@ export type CommandResult = { code: number; stdout: string; stderr: string }; /** Set on the child that `mergeViaCommand` starts, so the child does not record the same merge again. */ export const MERGE_RECORDED_ENV = "AUTOCRAFT_MERGE_RECORDED"; -/** Runs the merge command (`args` = OWNER/REPO PR --squash|--merge ...) and records the merge or the refusal. */ -export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string[]) => Promise, cmd: string, args: string[], details: Details = {}, landed?: () => Promise): Promise { - const [slug = "", pr = ""] = args; - const repo = repoName(slug); - const method = args.find((a) => a === "--squash" || a === "--merge")?.slice(2); +/** + * Runs the merge command for the guarded PR and records the merge or the refusal. The command gets + * `OWNER/REPO PR --squash|--merge [--head ]`; with `pin` (the built-in safe-merge) it refuses when GitHub's head + * differs from the head the guard checked. An external command does not understand `--head` and pins its own read. + */ +export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string[]) => Promise, cmd: string, g: Guarded, o: { method: "squash" | "merge"; extra?: string[]; pin: boolean }, details: Details = {}, landed?: () => Promise): Promise { + const args = [`${ORG}/${g.repo}`, String(g.number), `--${o.method}`, ...(o.extra ?? []), ...(o.pin ? ["--head", g.head] : [])]; + const repo = g.repo; + const method: string = o.method; const base = { ...details, method }; - const target = refOf(repo, Number(pr)); + const target = refOf(repo, g.number); const id = begin(w, "merge", target, base); let r: CommandResult; try { diff --git a/src/mainfix/index.ts b/src/mainfix/index.ts index 836139bd4..ef1aaefb4 100644 --- a/src/mainfix/index.ts +++ b/src/mainfix/index.ts @@ -14,7 +14,7 @@ import { ORG } from "../act/templates.ts"; import { actionable, ask, getDecision } from "../decisions.ts"; import { connect } from "../db.ts"; import { exec, fixupDir, type Exec } from "../fixup/git.ts"; -import { createIssue, ghRerunFailed, IssueError, type Writer } from "../github/write.ts"; +import { createIssue, ghRerunMainFailed, IssueError, type Writer } from "../github/write.ts"; import { askClaude, saveUsage, type Usage } from "../classify/run.ts"; import { checkoutForCommit } from "../sandbox/index.ts"; import { readFailure } from "../cifix/logs.ts"; @@ -216,7 +216,7 @@ async function classifyHead(db: DatabaseSync, repo: string, cur: Current, deps: } const w: Writer = { db, login: ACTOR }; for (const [runId, rows] of rerunRuns) { - const res = await ghRerunFailed(w, deps.exec, { repo, head: cur.headSha, runId }, { checks: rows.map((r) => r.check) }); + const res = await ghRerunMainFailed(w, deps.exec, { repo, head: cur.headSha, runId }, { checks: rows.map((r) => r.check) }); if (res.code !== 0) for (const r of rows) setState(db, r, "nothing-to-do", `GitHub refused the rerun: ${oneLine(res.stderr || res.stdout, 120)}`, deps.now().toISOString()); else { s.reran++; log(` ${repo}: reran the failed jobs of run ${runId}`); } } diff --git a/src/mainfix/pr.ts b/src/mainfix/pr.ts index cec9e85a5..60d444ec9 100644 --- a/src/mainfix/pr.ts +++ b/src/mainfix/pr.ts @@ -13,7 +13,7 @@ import { forkOf } from "../fixissue/index.ts"; import { outsideShown } from "../fixup/excerpt.ts"; import { Git, type Exec } from "../fixup/git.ts"; import { scrubReason, whoAmI } from "../fixup/index.ts"; -import { ghOpenPr, pushBranch } from "../github/write.ts"; +import { ghOpenPr, pushOwnBranch } from "../github/write.ts"; import { MAIN_FIX_BRANCH_PREFIX } from "../mainci/index.ts"; import type { Gh } from "../merge/safe-merge.ts"; import { cleanLine } from "../review/post-template.ts"; @@ -164,7 +164,7 @@ async function attempt(c: Ctx, rows: FixRow[], count: () => void): Promise ({ name: r.check, runUrl: r.run_url })), culprit: now.culprit, culpritPr: now.culpritPr, files: v.files, changed: v.changed }); const pr = await ghOpenPr({ db: c.db, login: PR_ACTOR }, c.exec, "main-fix-pr", { repo: c.repo, target: ref, base: now.branch, head: `${owner}:${branch}`, title, body }, diff --git a/src/merge/batch.ts b/src/merge/batch.ts index bb99615ce..ac0d9ac18 100644 --- a/src/merge/batch.ts +++ b/src/merge/batch.ts @@ -16,7 +16,9 @@ import { closeMergedQuestions } from "./withdraw.ts"; import { mkdirSync } from "node:fs"; import type { DatabaseSync } from "node:sqlite"; import { audit } from "../dash/audit.ts"; -import { assignTo, ghClosePr, ghOpenPr, mergeViaCommand, pushBranch, unassignFrom, type Writer } from "../github/write.ts"; +import { CLI_BY, type By } from "../core/gates.ts"; +import { guard, guardBatchMerge, liveOf } from "../core/guard.ts"; +import { assignTo, ghClosePr, ghOpenPr, mergeViaCommand, pushOwnBranch, unassignFrom, type Writer } from "../github/write.ts"; import { type Exec, exec, fixupDir } from "../fixup/git.ts"; import { whoAmI } from "../fixup/index.ts"; import { branchOf, forkOf } from "../fixissue/index.ts"; @@ -55,6 +57,8 @@ export type BatchParams = { limit?: number; /** Called with the running count of PRs merged. */ onMerged?: (merged: number) => void; + /** Who asked; default: an operator at the command line. */ + by?: By; }; export type BatchSummary = { runId: string; repo: string; started: string[]; published: string[]; merged: number[]; failed: number[]; split: string[]; superseded: string[]; waiting: string[] }; @@ -93,6 +97,8 @@ export async function runBatches(db: DatabaseSync, params: BatchParams, log: (li const left = () => (params.limit === undefined ? Infinity : params.limit - landed); const w: Writer = { db, login: ACTOR }; + const by = params.by ?? CLI_BY; + const liveRead = liveOf(db, d.querier); const refOf = (n: number) => `${repo}#${n}`; const branch = branchOf(db, repo); const closePr = async (b: BatchRow, why: string) => { @@ -150,6 +156,8 @@ export async function runBatches(db: DatabaseSync, params: BatchParams, log: (li if (chain.length && !admits(chain.map((x) => x.cand), c, max)) continue; const sha = await git.fetchPr(ORG, repo, c.number); if (sha !== c.head) { log(` ${refOf(c.number)}: head moved to ${short(sha)}; left out`); continue; } + const g = await guard(db, { repo, number: c.number }, { kind: "merge", head: c.head, batch: true }, by, liveRead); + if ("refused" in g) { log(` ${refOf(c.number)}: left out: ${g.refused}`); continue; } const tree = await git.mergeTree(cur, sha); if (!tree) { log(` ${refOf(c.number)}: conflicts with the batch so far; waits for the next one`); continue; } cur = await git.mergeCommit(tree, [cur, sha], `Merge pull request #${c.number}`, { name: who.login, email: who.email }); @@ -246,7 +254,7 @@ export async function runBatches(db: DatabaseSync, params: BatchParams, log: (li if (getBatch(db, b.id).state !== "checking") return; const who = await whoAmI(d.exec); const fork = await forkOf(w, d.exec, who.login, repo, { run: runId }); - const push = await pushBranch(w, git, "batch-push", { repo, remote: fork, branch: b.branch, sha: b.commit_sha }, { run: runId, fork }); + const push = await pushOwnBranch(w, git, "batch-push", { repo, remote: fork, branch: b.branch, sha: b.commit_sha }, { run: runId, fork }); if (push.code !== 0) return publishFailed(b, `push failed: ${oneLine(push.stderr)}`); updateBatch(db, b.id, at(), { fork }); const links = members.map((m) => `- [${repo}#${m.number}](https://github.com/${ORG}/${repo}/pull/${m.number})`).join("\n"); @@ -373,7 +381,10 @@ export async function runBatches(db: DatabaseSync, params: BatchParams, log: (li if (getBatch(db, b.id).state !== "open") { log(` ${b.branch}: ended meanwhile; not merged`); return; } if (members.some((m) => mergeHeld(db, repo, m.number))) { log(` ${b.branch}: a PR in the batch was held meanwhile; not merged`); s.waiting.push(b.branch); return; } let after: Awaited>[number] | undefined; - const r = await mergeViaCommand(w, d.run, d.mergeCommand, [`${ORG}/${repo}`, String(b.pr_number), "--merge", ...allowFailedArgs(db, repo, d.mergeCommand)], { run: runId, head: b.commit_sha, batch: b.branch }, async () => { + // Every member must still hold at its batched head, and the batch PR at the batch tip. + const g = await guardBatchMerge(db, { repo, number: b.pr_number!, head: b.commit_sha }, members.map((m) => ({ number: m.number, head: m.head_oid })), by, liveRead); + if ("refused" in g) { log(` ${b.branch}: not merged: ${g.refused}`); s.waiting.push(b.branch); return; } + const r = await mergeViaCommand(w, d.run, d.mergeCommand, g, { method: "merge", extra: allowFailedArgs(db, repo, d.mergeCommand), pin: d.mergeCommand === DEFAULT_MERGE_COMMAND }, { run: runId, head: b.commit_sha, batch: b.branch }, async () => { after = (await refreshChecks(db, d.querier, repo, [b.pr_number!]))[0]; return after?.state === "MERGED"; }); diff --git a/src/merge/ci-approval.ts b/src/merge/ci-approval.ts index d067a0635..7a9b75f2e 100644 --- a/src/merge/ci-approval.ts +++ b/src/merge/ci-approval.ts @@ -12,6 +12,8 @@ import { effectiveCi } from "../optional-checks.ts"; import { connect } from "../db.ts"; import { notHeldSql } from "../dupes/held.ts"; import type { Exec } from "../fixup/git.ts"; +import { guard } from "../core/guard.ts"; +import { CLI_BY, type By } from "../core/gates.ts"; import { ghApproveRun, type Writer } from "../github/write.ts"; import { mergeHeld } from "./holds.ts"; import { trackedNames } from "../repos.ts"; @@ -151,6 +153,8 @@ export type ApproveDeps = { /** Most PRs to approve runs for. */ limit: number; log?: (line: string) => void; + /** Who asked; a command-line run is an operator's. */ + by?: By; }; export type ApproveResult = { approved: string[]; skipped: string[]; failed: string[] }; @@ -190,14 +194,18 @@ export async function approveRuns(db: DatabaseSync, repo: string, d: ApproveDeps const todo = runs.filter((r) => r.event === "pull_request" && (c.failed[r.id] ?? 0) < MAX_FAILURES); const failed = { ...c.failed }; const done: number[] = []; + let stopped: string | null = null; for (const run of todo) { if (!ciApprovalOf(db, repo)) throw new Error(`approving CI runs in ${repo} is not approved`); - const r = await ghApproveRun(w, d.exec, { repo, number: c.number, runId: run.id }, { head: c.head, workflow: run.name }); + const g = await guard(db, { repo, number: c.number }, { kind: "approve-ci", head: c.head }, d.by ?? CLI_BY); + if ("refused" in g) { stopped = g.refused; break; } + const r = await ghApproveRun(w, d.exec, g, run.id, { head: c.head, workflow: run.name }); if (r.code === 0) done.push(run.id); else if (REPEATABLE.test(`${r.stderr} ${r.stdout}`)) failed[run.id] = (failed[run.id] ?? 0) + 1; else log(`${ref}: run ${run.id}: ${(r.stderr || r.stdout).trim().slice(0, 120)}; will retry`); } save(c, runs.filter((r) => !done.includes(r.id)), done, failed); + if (stopped !== null) { log(`${ref}: not approved: ${stopped}`); out.skipped.push(ref); continue; } const bad = todo.length - done.length; (bad ? out.failed : out.approved).push(ref); log(`${ref}: ${bad ? `${bad} of ${todo.length} runs not approved` : `approved ${todo.length} runs`}`); diff --git a/src/merge/index.ts b/src/merge/index.ts index 82beaf5e2..f44052f5f 100644 --- a/src/merge/index.ts +++ b/src/merge/index.ts @@ -18,6 +18,8 @@ import type { DatabaseSync } from "node:sqlite"; import { audit } from "../dash/audit.ts"; import { connect } from "../db.ts"; import { actionable, ask, factsOf, getDecision } from "../decisions.ts"; +import { CLI_BY, type By } from "../core/gates.ts"; +import { guard, liveOf } from "../core/guard.ts"; import { assignTo, mergeViaCommand, MERGE_RECORDED_ENV, type Writer } from "../github/write.ts"; import { Client, markMerged, type Querier } from "../mirror.ts"; import { refreshChecks } from "../review/checks.ts"; @@ -66,6 +68,8 @@ export type MergeParams = { stopOnRefusal?: boolean; /** Called with the running count of PRs merged, after each merge. */ onMerged?: (merged: number) => void; + /** Who asked; default: an operator at the command line. */ + by?: By; }; export type MergeSummary = { @@ -341,7 +345,14 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line const method = methodOf(info); // A hold may have been set during the calls above. if (mergeHeld(db, repo, e.number)) { log(` ${refOf(e)}: merge held meanwhile; skipped`); summary.attempted.pop(); continue; } - const r = await mergeViaCommand(w, d.run, d.mergeCommand, [`${ORG}/${repo}`, String(e.number), `--${method}`, ...allowFailedArgs(db, repo, d.mergeCommand)], { run: runId, head: e.head, path: e.path }); + const g = await guard(db, { repo, number: e.number }, { kind: "merge", head: e.head }, params.by ?? CLI_BY, liveOf(db, d.querier)); + if ("refused" in g) { + // Not recorded as a merge attempt: the PR is tried again once the reason is gone. + summary.refused.push({ ref: refOf(e), reason: g.refused }); + log(` ${refOf(e)}: not merged: ${g.refused}`); + continue; + } + const r = await mergeViaCommand(w, d.run, d.mergeCommand, g, { method, extra: allowFailedArgs(db, repo, d.mergeCommand), pin: d.mergeCommand === DEFAULT_MERGE_COMMAND }, { run: runId, head: e.head, path: e.path }); if (r.code !== 0) { const why = oneLine(r.stderr) || oneLine(r.stdout) || `exit code ${r.code}`; refuse(e, method, `${d.mergeCommand}: ${why}`); diff --git a/src/merge/safe-merge.ts b/src/merge/safe-merge.ts index d72984820..3c6af0722 100644 --- a/src/merge/safe-merge.ts +++ b/src/merge/safe-merge.ts @@ -3,7 +3,9 @@ // green (or skipped/neutral), and no maintainer's "changes requested" review // stands; the merge is pinned to the head that was checked. // -// autocraft safe-merge OWNER/REPO PR --squash|--merge [--allow-pending NAME]... [--allow-failed NAME]... +// autocraft safe-merge OWNER/REPO PR --squash|--merge [--allow-pending NAME]... [--allow-failed NAME]... [--head SHA] +// +// --head SHA is the head the caller reviewed: the merge refuses when GitHub's head is another one. // // --allow-failed NAME accepts a failed check of that exact name (an optional check), only while GitHub's merge // state of the PR is not BLOCKED (a failing required check blocks it); every other check must still be green. @@ -135,10 +137,13 @@ export async function safeMerge( gh: Gh = ghExec, sleep: (ms: number) => Promise = (ms) => new Promise((r) => setTimeout(r, ms)), /** Record the merge in the database (the command line; a calling pipeline stage records its own). */ recordMerge = false, + /** The head the caller reviewed; a different head on GitHub is refused. */ + expectHead?: string, ): Promise { const refuse = (why: string): SafeMergeResult => ({ merged: false, reason: `REFUSED ${repo}#${pr}: ${why}` }); const v = JSON.parse(await gh(["pr", "view", pr, "-R", repo, "--json", "state,isDraft,mergeable,mergeStateStatus,headRefOid,statusCheckRollup"])) as PrView; const head = v.headRefOid; + if (expectHead !== undefined && head !== expectHead) return refuse(`head is ${head.slice(0, 7)}, not the reviewed ${expectHead.slice(0, 7)}`); let why = refuseView(v, allow, allowFailed); if (why) return refuse(why); const runs = JSON.parse(await gh(["api", `repos/${repo}/actions/runs?head_sha=${head}&per_page=100`])) as { workflow_runs?: Run[] }; @@ -156,31 +161,33 @@ export async function safeMerge( return { merged: true, message: `${repo}#${pr} ${line} (head ${head.slice(0, 9)}, ${v.statusCheckRollup.length} checks green${accepted.length ? `; accepted failed optional checks: ${accepted.join(", ")}` : ""})` }; } -const USAGE = "usage: autocraft safe-merge OWNER/REPO PR --squash|--merge [--allow-pending NAME]... [--allow-failed NAME]..."; +const USAGE = "usage: autocraft safe-merge OWNER/REPO PR --squash|--merge [--allow-pending NAME]... [--allow-failed NAME]... [--head SHA]"; -export function parseSafeMergeArgs(args: string[]): { repo: string; pr: string; method: Method; allow: string[]; allowFailed: string[] } | null { +export function parseSafeMergeArgs(args: string[]): { repo: string; pr: string; method: Method; allow: string[]; allowFailed: string[]; head?: string } | null { if (args.length < 3) return null; const [repo, pr, method, ...rest] = args as [string, string, string, ...string[]]; if (method !== "--squash" && method !== "--merge") return null; const allow: string[] = [], allowFailed: string[] = []; + let head: string | undefined; for (let i = 0; i < rest.length; i += 2) { const name = rest[i + 1]; if (name === undefined) return null; if (rest[i] === "--allow-pending") allow.push(name); else if (rest[i] === "--allow-failed") allowFailed.push(name); + else if (rest[i] === "--head") head = name; else return null; } - return { repo, pr, method, allow, allowFailed }; + return { repo, pr, method, allow, allowFailed, ...(head ? { head } : {}) }; } export const commands = { "safe-merge": { - summary: "safe-merge OWNER/REPO PR --squash|--merge [--allow-pending NAME]... [--allow-failed NAME]...: merge one PR only when it is green and unchanged", + summary: "safe-merge OWNER/REPO PR --squash|--merge [--allow-pending NAME]... [--allow-failed NAME]... [--head SHA]: merge one PR only when it is green and unchanged", async run(args: string[]): Promise { const a = parseSafeMergeArgs(args); if (!a) { console.error(USAGE); process.exit(2); } try { - const r = await safeMerge(a.repo, a.pr, a.method, a.allow, a.allowFailed, ghExec, undefined, true); + const r = await safeMerge(a.repo, a.pr, a.method, a.allow, a.allowFailed, ghExec, undefined, true, a.head); if (r.merged) console.log(`safe-merge: ${r.message}`); else { console.error(`safe-merge: ${r.reason}`); process.exit(1); } } catch (e) { diff --git a/src/merge/single.ts b/src/merge/single.ts index 638a5297c..b73e6f3ba 100644 --- a/src/merge/single.ts +++ b/src/merge/single.ts @@ -5,6 +5,7 @@ import { audit } from "../dash/audit.ts"; import { cachedDiff, ghDiff, type DiffFetcher } from "../review/diff.ts"; import { mergeApprovalOf } from "./approval.ts"; import { activeBatches } from "./batch-store.ts"; +import type { By } from "../core/gates.ts"; import { runMerge, type MergeDeps, type MergeSummary } from "./index.ts"; import { buildQueue, eligible, refusedAsBefore } from "./queue.ts"; @@ -68,7 +69,7 @@ export async function planSingles(db: DatabaseSync, repo: string, fetchDiff: Dif * with green checks ends the round. */ export async function runSingles( - db: DatabaseSync, params: { repo: string; limit?: number; onMerged?: (n: number) => void }, + db: DatabaseSync, params: { repo: string; limit?: number; onMerged?: (n: number) => void; by?: By }, log: (line: string) => void = console.log, deps?: MergeDeps, fetchDiff?: DiffFetcher, ): Promise { if (!mergeApprovalOf(db, params.repo)) throw new Error(`merging in ${params.repo} is not approved`); @@ -76,7 +77,7 @@ export async function runSingles( const plan = await planSingles(db, params.repo, fetchDiff); if (!plan) return null; log(`merge ${params.repo}: ${plan.size} PRs ready, none sharing a file; merging them one at a time`); - return runMerge(db, { repo: params.repo, limit: params.limit, dryRun: false, only: (e) => plan.has(e.number), stopOnRefusal: true, onMerged: params.onMerged }, log, deps); + return runMerge(db, { repo: params.repo, limit: params.limit, dryRun: false, only: (e) => plan.has(e.number), stopOnRefusal: true, onMerged: params.onMerged, by: params.by }, log, deps); } export const commands = { diff --git a/src/review/post.ts b/src/review/post.ts index 6f9d77e9d..59f084b83 100644 --- a/src/review/post.ts +++ b/src/review/post.ts @@ -8,6 +8,8 @@ import type { DatabaseSync } from "node:sqlite"; import { commentApprovalOf } from "../act/approval.ts"; import { type Note, editReview, postReview, type Writer } from "../github/write.ts"; +import { guard } from "../core/guard.ts"; +import { CLI_BY, type By } from "../core/gates.ts"; import { backlogHeldSql, groupHeldSql, notOwnIntegrationSql } from "../dupes/held.ts"; import { Client, type Querier } from "../mirror.ts"; import { prInfo } from "../merge/index.ts"; @@ -33,7 +35,7 @@ export type PostCandidate = { opusAt: string; }; export type PostSummary = { repo: string; dryRun: boolean; candidates: number; posted: string[]; edited: string[]; skipped: { ref: string; reason: string }[]; failed: { ref: string; reason: string }[]; note: string | null }; -export type PostParams = { repo: string; limit?: number; dryRun?: boolean; onHandled?: (n: number) => void }; +export type PostParams = { repo: string; limit?: number; dryRun?: boolean; onHandled?: (n: number) => void; by?: By }; export type PostDeps = { querier: Querier; now: () => Date }; export const defaultPostDeps = (): PostDeps => ({ querier: new Client(1000), now: () => new Date() }); @@ -115,13 +117,15 @@ export async function runReviewPost(db: DatabaseSync, params: PostParams, log: ( if (!live) { skip("not found on GitHub"); continue; } if (live.state !== "OPEN") { skip(`now ${live.state}`); continue; } if (live.head !== c.head_oid) { skip(`head moved to ${live.head.slice(0, 7)}`); continue; } + const g = await guard(db, { repo, number: c.number }, { kind: "post-review", head: c.head_oid }, params.by ?? CLI_BY); + if ("refused" in g) { skip(g.refused); continue; } const at = d.now().toISOString(); if (c.editId) { - await editReview(w, d.querier, repo, c.number, c.editId, c.head_oid, REVIEW_NOTE(c), c.body); + await editReview(w, d.querier, g, c.editId, REVIEW_NOTE(c), c.body); db.prepare("UPDATE review_posts SET head_oid = ?, edited_at = ?, opus_at = ? WHERE repo = ? AND number = ?").run(c.head_oid, at, c.opusAt, repo, c.number); s.edited.push(refOf(c)); } else { - const id = await postReview(w, d.querier, { repo, number: c.number, id: live.id }, c.head_oid, REVIEW_NOTE(c), c.body); + const id = await postReview(w, d.querier, g, live.id, REVIEW_NOTE(c), c.body); if (!id) throw new Error("GitHub returned no review"); db.prepare("INSERT OR REPLACE INTO review_posts (repo, number, review_id, head_oid, posted_at, opus_at) VALUES (?, ?, ?, ?, ?, ?)").run(repo, c.number, id, c.head_oid, at, c.opusAt); s.posted.push(refOf(c)); diff --git a/src/runner/steps.ts b/src/runner/steps.ts index bef52cbd5..4987d1076 100644 --- a/src/runner/steps.ts +++ b/src/runner/steps.ts @@ -9,6 +9,7 @@ import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; import type { DatabaseSync } from "node:sqlite"; import { DECIDE_MODELS } from "../decide/index.ts"; +import { byOfJob } from "../core/gates.ts"; import { envVar } from "../env.ts"; import { stageOfStep } from "../stages/registry.ts"; @@ -290,16 +291,16 @@ export const STEPS: StepDef[] = [ const refused = await checkMergeApproved(ctx.db, ctx.params); if (refused) throw new Error(refused); const repo = String(ctx.params.repo), limit = Number(ctx.params.limit); - const singly = await runSingles(ctx.db, { repo, limit, onMerged: ctx.handled }, ctx.log); + const singly = await runSingles(ctx.db, { repo, limit, onMerged: ctx.handled, by: byOfJob(ctx.job.requestedBy) }, ctx.log); if (singly) { ctx.acted(singly.merged.length + singly.asked.length); return `${repo}: ${singly.merged.length} merged singly, ${singly.refused.length} refused, ${singly.asked.length} decisions asked`; } - const b = await runBatches(ctx.db, { repo, limit, onMerged: ctx.handled }, ctx.log); + const b = await runBatches(ctx.db, { repo, limit, onMerged: ctx.handled, by: byOfJob(ctx.job.requestedBy) }, ctx.log); ctx.usageRun(b.runId); let single = { merged: [] as string[], attempted: [] as string[], refused: [] as unknown[], asked: [] as string[] }; if (limit > b.merged.length) { - single = await runMerge(ctx.db, { repo, limit: limit - b.merged.length, dryRun: false, only: singleMergeOnly, onMerged: (n) => ctx.handled(b.merged.length + n) }, ctx.log); + single = await runMerge(ctx.db, { repo, limit: limit - b.merged.length, dryRun: false, only: singleMergeOnly, onMerged: (n) => ctx.handled(b.merged.length + n), by: byOfJob(ctx.job.requestedBy) }, ctx.log); } ctx.acted(b.started.length + b.published.length + b.split.length + b.superseded.length + b.failed.length + single.merged.length + single.asked.length + b.merged.length); return `${repo}: ${b.merged.length} merged in batches (${b.started.length} started, ${b.published.length} opened, ${b.split.length} split), ${single.merged.length} merged singly, ${single.asked.length} decisions asked`; @@ -360,7 +361,7 @@ export const STEPS: StepDef[] = [ const { runFixup } = await import("../fixup/index.ts"); const refused = await checkPushApproved(ctx.db, ctx.params); if (refused) throw new Error(refused); - const r = await runFixup(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false, onHandled: ctx.handled }, ctx.log); + const r = await runFixup(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false, onHandled: ctx.handled, by: byOfJob(ctx.job.requestedBy) }, ctx.log); ctx.acted(r.pushed.length + r.asked.length + r.failed.length + r.held.length); return `${r.repo}: pushed ${r.pushed.length}, ${r.asked.length} asked, ${r.failed.length} failed or refused, ${r.held.length} held`; }, @@ -546,7 +547,7 @@ export const STEPS: StepDef[] = [ const { runReviewPost } = await import("../review/post.ts"); const refused = await checkCommentApproved(ctx.db, ctx.params); if (refused) throw new Error(refused); - const r = await runReviewPost(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false, onHandled: ctx.handled }, ctx.log); + const r = await runReviewPost(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false, onHandled: ctx.handled, by: byOfJob(ctx.job.requestedBy) }, ctx.log); return `${r.repo}: ${r.posted.length} posted, ${r.edited.length} edited, ${r.skipped.length} skipped, ${r.failed.length} failed`; }, }, @@ -716,7 +717,7 @@ export const STEPS: StepDef[] = [ const refused = await checkCiApproved(ctx.db, ctx.params); if (refused) throw new Error(refused); const repo = String(ctx.params.repo); - const r = await approveRuns(ctx.db, repo, { gh: ghExec, exec, limit: Number(ctx.params.limit), log: ctx.log }); + const r = await approveRuns(ctx.db, repo, { gh: ghExec, exec, limit: Number(ctx.params.limit), log: ctx.log, by: byOfJob(ctx.job.requestedBy) }); ctx.handled(r.approved.length + r.failed.length); if (r.failed.length) throw new Error(`${repo}: runs not approved on ${r.failed.join(", ")}`); return `${repo}: runs approved on ${r.approved.length} PRs, ${r.skipped.length} skipped`; @@ -739,7 +740,7 @@ export const STEPS: StepDef[] = [ const { runCifix } = await import("../cifix/index.ts"); const refused = await checkPushApproved(ctx.db, ctx.params); if (refused) throw new Error(refused); - const r = await runCifix(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false, onHandled: ctx.handled }, ctx.log); + const r = await runCifix(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false, onHandled: ctx.handled, by: byOfJob(ctx.job.requestedBy) }, ctx.log); ctx.acted(r.pushed.length + r.asked.length + r.queued.length + r.failed.length + r.held.length + r.infra.length); return `${r.repo}: pushed ${r.pushed.length}, ${r.asked.length} commented, ${r.queued.length} formatter runs queued, ${r.infra.length} infrastructure failures, ${r.failed.length} failed or refused, ${r.held.length} held`; }, @@ -760,7 +761,7 @@ export const STEPS: StepDef[] = [ const { runRerun } = await import("../cifix/index.ts"); const refused = await checkCiApproved(ctx.db, ctx.params); if (refused) throw new Error(refused); - const r = await runRerun(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false, onHandled: ctx.handled }, ctx.log); + const r = await runRerun(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false, onHandled: ctx.handled, by: byOfJob(ctx.job.requestedBy) }, ctx.log); return `${r.repo}: reran ${r.reran.length} PRs, ${r.skipped.length} skipped`; }, }, diff --git a/test/cifix.test.ts b/test/cifix.test.ts index ccabaf7e3..f724f9425 100644 --- a/test/cifix.test.ts +++ b/test/cifix.test.ts @@ -247,7 +247,7 @@ function world(opts: { log?: string; reply?: string | null; check?: string | nul spent: 0, remaining: 5000, async query() { return { repository: { pullRequest: { - id: "PR7", state: opts.closedAfter !== undefined && ++reads > opts.closedAfter ? "CLOSED" : "OPEN", isDraft: false, headRefOid: head, headRefName: "fix", maintainerCanModify: opts.canModify !== false, mergeable: "MERGEABLE", + id: "PR7", number: 7, commits: { nodes: [{ commit: { statusCheckRollup: { contexts: { nodes: [{ __typename: "CheckRun", name: "gate / test", status: "COMPLETED", conclusion: "FAILURE" }] } } } }] }, state: opts.closedAfter !== undefined && ++reads > opts.closedAfter ? "CLOSED" : "OPEN", isDraft: false, headRefOid: head, headRefName: "fix", maintainerCanModify: opts.canModify !== false, mergeable: "MERGEABLE", headRepository: { nameWithOwner: "contrib/app" }, assignees: { nodes: [] }, reviewDecision: opts.decision ?? null, } } }; }, diff --git a/test/fixup-conflict.test.ts b/test/fixup-conflict.test.ts index 26bceed0c..63ea3e2d9 100644 --- a/test/fixup-conflict.test.ts +++ b/test/fixup-conflict.test.ts @@ -71,7 +71,7 @@ function world(o: { conflicting: boolean; big?: boolean; pad?: boolean; eol?: "c async query(q: string) { if (q.startsWith("mutation")) { log.push("assign"); return {}; } return { repository: { pullRequest: { - id: "PR7", state: "OPEN", isDraft: false, headRefOid: head, headRefName: "feat", maintainerCanModify: o.canModify !== false, mergeable: "CONFLICTING", + id: "PR7", number: 7, state: "OPEN", isDraft: false, headRefOid: head, headRefName: "feat", maintainerCanModify: o.canModify !== false, mergeable: "CONFLICTING", headRepository: { nameWithOwner: "org-x/app" }, assignees: { nodes: [] }, } } }; }, diff --git a/test/fixup.test.ts b/test/fixup.test.ts index 5136cb71a..24a0f8163 100644 --- a/test/fixup.test.ts +++ b/test/fixup.test.ts @@ -172,7 +172,7 @@ function world(opts: { check?: string | null; reply?: string | null; moveBranch? } log.push("pr-info"); return { repository: { pullRequest: { - id: "PR7", state: "OPEN", isDraft: false, headRefOid: head, headRefName: "fix", maintainerCanModify: opts.canModify !== false, mergeable: "MERGEABLE", + id: "PR7", number: 7, state: "OPEN", isDraft: false, headRefOid: head, headRefName: "fix", maintainerCanModify: opts.canModify !== false, mergeable: "MERGEABLE", headRepository: { nameWithOwner: "contrib/app" }, assignees: { nodes: w.assigned.map((login) => ({ login })) }, } } }; }, @@ -640,7 +640,7 @@ describe("review of a moved head", () => { describe("fixup repost", () => { test("edits the recorded ask comment to the full text once, records it, and does nothing when the text matches", async () => { - const w = world(); + const w = world({ canModify: false }); const db = fresh(w.head, { canModify: false }); setCommentApproval(db, "op", "app", true); const long = "y".repeat(400); diff --git a/test/github-activity.test.ts b/test/github-activity.test.ts index f514f65ab..7a705a1fa 100644 --- a/test/github-activity.test.ts +++ b/test/github-activity.test.ts @@ -1,4 +1,5 @@ // The write module records every GitHub write (failures too) and GET /api/github-activity lists them. +import { guarded } from "./guarded.ts"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync } from "node:fs"; import { join } from "node:path"; @@ -7,7 +8,7 @@ import { connect } from "../src/db.ts"; import { comment, openedToday } from "../src/fixissue/index.ts"; import { githubActivity } from "../src/dash/api/github-activity.ts"; import type { Note } from "../src/github/note.ts"; -import { addLabels, closeItem, commentOn, ghComment, mergeViaCommand, pushBranch, type Writer } from "../src/github/write.ts"; +import { addLabels, closeItem, commentOn, ghComment, mergeViaCommand, pushBranch, pushOwnBranch, type Writer } from "../src/github/write.ts"; import { readSeqs } from "../src/live.ts"; import type { Querier } from "../src/mirror.ts"; import type { Req } from "../src/dash/types.ts"; @@ -53,12 +54,12 @@ test("each wrapper function records its write; a failed write records the error const bad = fakeQuerier(true); await assert.rejects(closeItem(w, bad, { repo: "app", number: 8, id: "N8", pr: false }, { decision: "d2" }), /boom/); - const pushed = await pushBranch(w, { git: async () => ({ code: 0, stdout: "", stderr: "" }) }, "fixup-push", { repo: "app", number: 7, remote: "bot/app", branch: "fix", sha: "a".repeat(40), expected: "b".repeat(40) }, { run: "r1" }); + const pushed = await pushBranch(w, { git: async () => ({ code: 0, stdout: "", stderr: "" }) }, "fixup-push", guarded("app", 7, "b".repeat(40)), { remote: "bot/app", branch: "fix", sha: "a".repeat(40) }, { run: "r1" }); assert.equal(pushed.code, 0); - await pushBranch(w, { git: async () => ({ code: 1, stdout: "", stderr: "denied\n403" }) }, "batch-push", { repo: "app", remote: "bot/app", branch: "integration-1", sha: "c".repeat(40) }); + await pushOwnBranch(w, { git: async () => ({ code: 1, stdout: "", stderr: "denied\n403" }) }, "batch-push", { repo: "app", remote: "bot/app", branch: "integration-1", sha: "c".repeat(40) }); await ghComment(w, async () => ({ code: 0, stdout: "https://github.com/storytold/app/pull/7#issuecomment-2\n", stderr: "" }), "fixup-comment", { repo: "app", number: 7, pr: true }, FIXED, "Pushed fixes.", { run: "r1" }); - await mergeViaCommand(w, async () => ({ code: 0, stdout: `storytold/app#7 MERGED ${"d".repeat(40)} (head abc)`, stderr: "" }), "safe-merge", ["storytold/app", "7", "--squash"], { run: "r1" }); - await mergeViaCommand(w, async () => ({ code: 1, stdout: "", stderr: "REFUSED: checks not green" }), "safe-merge", ["storytold/app", "9", "--merge"]); + await mergeViaCommand(w, async () => ({ code: 0, stdout: `storytold/app#7 MERGED ${"d".repeat(40)} (head abc)`, stderr: "" }), "safe-merge", guarded("app", 7, "e".repeat(40)), { method: "squash", pin: true }, { run: "r1" }); + await mergeViaCommand(w, async () => ({ code: 1, stdout: "", stderr: "REFUSED: checks not green" }), "safe-merge", guarded("app", 9, "e".repeat(40)), { method: "merge", pin: true }); const p = await githubActivity(db, req()); assert.equal(p.total, 8); @@ -148,7 +149,7 @@ test("a viewer sees only rows of repos visible to them; an operator also sees un const q = fakeQuerier(); await commentOn(w, q, "act-comment", { repo: "app", number: 1, id: "N1" }, FIXED, "a"); await commentOn(w, q, "act-comment", { repo: "gone", number: 1, id: "G1" }, FIXED, "b"); - await pushBranch(w, { git: async () => ({ code: 0, stdout: "", stderr: "" }) }, "batch-push", { repo: "gone", remote: "bot/gone", branch: "b1", sha: "a".repeat(40) }); + await pushOwnBranch(w, { git: async () => ({ code: 0, stdout: "", stderr: "" }) }, "batch-push", { repo: "gone", remote: "bot/gone", branch: "b1", sha: "a".repeat(40) }); assert.deepEqual((await githubActivity(db, req("", "viewer"))).rows.map((r) => r.repo), ["app"]); assert.equal((await githubActivity(db, req("", "operator"))).total, 3); }); diff --git a/test/github-note.test.ts b/test/github-note.test.ts index 0341745bc..7b1359078 100644 --- a/test/github-note.test.ts +++ b/test/github-note.test.ts @@ -1,4 +1,5 @@ // Every text-posting wrapper in src/github/write.ts puts the note line first, then a blank line, then the text. +import { guarded } from "./guarded.ts"; import assert from "node:assert/strict"; import { mkdtempSync } from "node:fs"; import { join } from "node:path"; @@ -27,8 +28,8 @@ test("each posting wrapper sends the note as the first line and records the text const vars: Record[] = []; const q = { spent: 0, remaining: null, async query(_q: string, v: Record) { vars.push(v); return { addComment: {}, addPullRequestReview: { pullRequestReview: { id: "R1" } } }; } } as Querier; await commentOn(w, q, "act-comment", item, note, "The text."); - await postReview(w, q, item, "abc", note, "The text."); - await editReview(w, q, "app", 7, "R1", "abc", note, "The text."); + await postReview(w, q, guarded("app", 7, "abc"), "N7", note, "The text."); + await editReview(w, q, guarded("app", 7, "abc"), "R1", note, "The text."); assert.deepEqual(vars.map((v) => v.body), [want, want, want]); const calls: { args: string[]; input?: string }[] = []; diff --git a/test/github-writes.test.ts b/test/github-writes.test.ts deleted file mode 100644 index 59701b149..000000000 --- a/test/github-writes.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Every write to GitHub goes through src/github/write.ts, which records it. This scans the rest of src/ for -// the ways a write can be sent and fails on any hit, so a new write path cannot skip the activity record. -import assert from "node:assert/strict"; -import { readdirSync, readFileSync } from "node:fs"; -import { join, relative } from "node:path"; -import test from "node:test"; -import { GITHUB_ACTIONS } from "../src/github/write.ts"; - -const SRC = new URL("../src", import.meta.url).pathname; -const WRITER = "github/write.ts"; - -function files(dir: string): string[] { - return readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(join(dir, e.name)) : e.name.endsWith(".ts") ? [join(dir, e.name)] : [])); -} - -const RULES: { what: string; re: RegExp; window?: number }[] = [ - { what: "GraphQL mutation", re: /["'`]\s*mutation\b/ }, - { what: "git push", re: /["'`]push["'`]/ }, - { what: "gh pr/issue write", re: /["'`](pr|issue)["'`]\s*,\s*["'`](merge|create|close|comment|edit|ready|reopen|delete|lock|review|transfer|pin|unpin|unlock)["'`]/ }, - { what: "gh workflow/run/secret write", re: /["'`](workflow|run|secret|variable)["'`]\s*,\s*["'`](run|rerun|cancel|enable|disable|set|delete|remove)["'`]/ }, - { what: "gh repo/label/release write", re: /["'`](repo|label|release|gist)["'`]\s*,\s*["'`](fork|create|edit|delete|rename|archive|clone)["'`]/ }, - { what: "gh api write verb", re: /["'`]api["'`][^\n]*["'`](--method|-X|--field|-f|-F|--raw-field)["'`]/, window: 3 }, - { what: "HTTP write verb", re: /method:\s*["'`](POST|PATCH|PUT|DELETE)["'`]/ }, - { what: "merge command run", re: /\.run\(\s*\w+\.mergeCommand/ }, - { what: "safe-merge started", re: /["'`]safe-merge["'`]\s*,\s*\.\.\./ }, -]; - -// Files that match a rule without writing to GitHub. -const ALLOWED: Record = { - "dash/api/index.ts": ["HTTP write verb"], // this app's own routes - "dash/server/provider.ts": ["HTTP write verb"], // OAuth token exchange for sign-in - "merge/safe-merge.ts": ["gh api write verb"], // -f/-F only pass variables to a read-only GraphQL query - "merge/index.ts": ["safe-merge started"], // starts the built-in command; the write is recorded by mergeViaCommand - "stages/registry.ts": ["git push"], // stage descriptions, no code -}; - -test("only src/github/write.ts sends writes to GitHub", () => { - const hits: string[] = []; - for (const f of files(SRC)) { - const rel = relative(SRC, f); - if (rel === WRITER) continue; - const lines = readFileSync(f, "utf8").split("\n"); - lines.forEach((line, i) => { - if (/^\s*(\/\/|\*|\/\*)/.test(line)) return; - for (const r of RULES) { - // A rule with a window also matches a call written over a few lines. - const text = r.window ? lines.slice(i, i + r.window).join(" ") : line; - if (r.window && !/["'`]api["'`]/.test(line)) continue; - if (r.re.test(text) && !(ALLOWED[rel] ?? []).includes(r.what)) hits.push(`${rel}:${i + 1}: ${r.what}: ${line.trim().slice(0, 100)}`); - } - }); - } - assert.deepEqual(hits, [], "write through src/github/write.ts so the activity is recorded"); -}); - -test("the write module has a label for every action it records", () => { - const src = readFileSync(join(SRC, WRITER), "utf8"); - const used = new Set([...src.matchAll(/(?:"|')([a-z]+(?:-[a-z]+)*)(?:"|')/g)].map((m) => m[1]!).filter((a) => /^(labels-apply|label-create|act-|fixup-|fixissue-|batch-|review-|merge$|assign$|unassign$|fork-create)/.test(a))); - for (const a of used) assert.ok(a in GITHUB_ACTIONS, `${a} has no label in GITHUB_ACTIONS`); -}); diff --git a/test/guard.test.ts b/test/guard.test.ts new file mode 100644 index 000000000..f8989d019 --- /dev/null +++ b/test/guard.test.ts @@ -0,0 +1,99 @@ +// The guard: a write passes only when the Plan, reloaded right before it, still holds the same action at the same head. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { DatabaseSync } from "node:sqlite"; +import { setPushApproval } from "../src/fixup/approval.ts"; +import { gates } from "../src/core/gates.ts"; +import { guard, type Live, type LiveRead } from "../src/core/guard.ts"; +import { ORG } from "../src/act/templates.ts"; +import { mergeViaCommand } from "../src/github/write.ts"; +import { mergeDecisionId } from "../src/merge/queue.ts"; +import { parseSafeMergeArgs, safeMerge } from "../src/merge/safe-merge.ts"; +import { fresh } from "./batch-fixture.ts"; +import { prFacts } from "./world.ts"; + +const ref = { repo: "app", number: 1 }; +const open: LiveRead = { state: "OPEN", head: "sha1", draft: false, mergeable: "MERGEABLE" }; +const live = (r: Partial = {}): Live => async () => ({ ...open, ...r }); +const MERGE = { kind: "merge", head: "sha1" } as const; +const T = "2026-01-02T00:00:00Z"; +const OP = { operator: "op" }; + +const ok = (r: unknown): boolean => !(r as { refused?: string }).refused; +const why = (r: unknown): string => (r as { refused?: string }).refused ?? ""; + +/** PR 1 as a take-fix review with one fix, pushable, in a repo approved for pushes. */ +function takeFix(): DatabaseSync { + const db = fresh([{ n: 1 }]); + db.prepare("UPDATE opus_reviews SET verdict = 'take-fix', fixes = ?").run(JSON.stringify([{ file: "src/lib.rs", change: "rename a to b" }])); + setPushApproval(db, "op", "app", true); + return db; +} + +test("passes when the Plan still holds the merge at the reviewed head", async () => { + const g = await guard(fresh([{ n: 1 }]), ref, MERGE, OP, live()); + assert.ok(ok(g), why(g)); + assert.deepEqual([(g as { head: string }).head, (g as { repo: string }).repo, (g as { number: number }).number], ["sha1", "app", 1]); +}); + +test("refuses a merge without a live read, and when GitHub's head moved", async () => { + const db = fresh([{ n: 1 }]); + assert.match(why(await guard(db, ref, MERGE, OP)), /no live read/); + assert.match(why(await guard(db, ref, MERGE, OP, live({ head: "sha9" }))), /head moved from sha1 to sha9/); + assert.match(why(await guard(db, ref, MERGE, OP, live({ state: "CLOSED" }))), /no longer open/); +}); + +test("refuses when an operator's Hold answer arrived", async () => { + const db = fresh([{ n: 1 }]); + const id = mergeDecisionId("app", 1, "sha1"); + db.prepare("INSERT INTO decisions (id, kind, repo, number, items, question, options, facts, asked_at, answer, answered_by, answered_at) VALUES (?, 'merge', 'app', 1, '[]', 'q', '[]', ?, ?, 'hold', 'op', ?)") + .run(id, JSON.stringify(["head commit sha1"]), T, T); + db.prepare("INSERT INTO access (login, role) VALUES ('op', 'operator')").run(); + assert.match(why(await guard(db, ref, MERGE, OP, live())), /plan no longer has merge/); +}); + +test("refuses when a maintainer's changes-requested review blocks the PR", async () => { + const db = fresh([{ n: 1 }]); + db.prepare("INSERT INTO review_gates (repo, number, blocked, by_login, read_at) VALUES ('app', 1, 1, 'maint', ?)").run(T); + assert.match(why(await guard(db, ref, MERGE, OP, live())), /plan no longer has merge/); +}); + +test("a push needs the repo's push approval at the write", async () => { + const db = takeFix(); + const push = { kind: "fixup", bucket: "fix", head: "sha1" } as const; + assert.ok(ok(await guard(db, ref, push, OP, live())), "holds while approved"); + setPushApproval(db, "op", "app", false); + assert.match(why(await guard(db, ref, push, OP, live())), /pushing in app is not approved/); +}); + +test("the global pipeline switch gates the pipeline's writes, not an operator's", async () => { + const db = fresh([{ n: 1 }]); + assert.match(why(await guard(db, ref, MERGE, "pipeline", live())), /pipeline is off/); + assert.ok(ok(await guard(db, ref, MERGE, OP, live()))); + db.prepare("INSERT INTO main.settings (key, value) VALUES ('pipeline_enabled', '1')").run(); + assert.ok(ok(await guard(db, ref, MERGE, "pipeline", live()))); +}); + +test("gates: each action kind needs its approval", () => { + const off = (k: "mergeApproved" | "pushApproved" | "commentApproved" | "ciApproved") => prFacts({ repoFacts: { [k]: false } }); + assert.match(gates(off("mergeApproved"), { kind: "merge" }, OP) ?? "", /merging/); + assert.match(gates(off("pushApproved"), { kind: "conflict", bucket: "merge" }, OP) ?? "", /pushing/); + assert.match(gates(off("commentApproved"), { kind: "fixup", bucket: "ask" }, OP) ?? "", /commenting/); + assert.match(gates(off("commentApproved"), { kind: "post-review" }, OP) ?? "", /commenting/); + assert.match(gates(off("ciApproved"), { kind: "approve-ci" }, OP) ?? "", /CI runs/); + assert.match(gates(off("ciApproved"), { kind: "cifix", bucket: "rerun" }, OP) ?? "", /CI runs/); + assert.equal(gates(off("pushApproved"), { kind: "merge" }, OP), null); +}); + +test("the merge command gets the reviewed head, and the built-in command refuses another head", async () => { + const g = await guard(fresh([{ n: 1 }]), ref, MERGE, OP, live()); + assert.ok(ok(g)); + const seen: string[][] = []; + await mergeViaCommand({ db: fresh([{ n: 1 }]), login: "t" }, async (_c, args) => { seen.push(args); return { code: 0, stdout: "", stderr: "" }; }, "safe-merge", + g as Exclude, { method: "squash", pin: true }); + assert.deepEqual(seen[0], [`${ORG}/app`, "1", "--squash", "--head", "sha1"]); + assert.equal(parseSafeMergeArgs(seen[0]!)?.head, "sha1"); + const gh = async () => JSON.stringify({ state: "OPEN", isDraft: false, mergeable: "MERGEABLE", headRefOid: "other0000", statusCheckRollup: [] }); + const r = await safeMerge("o/r", "1", "--squash", [], [], gh, async () => {}, false, "sha1"); + assert.deepEqual(r, { merged: false, reason: "REFUSED o/r#1: head is other00, not the reviewed sha1" }); +}); diff --git a/test/guarded.ts b/test/guarded.ts new file mode 100644 index 000000000..b8c9d3031 --- /dev/null +++ b/test/guarded.ts @@ -0,0 +1,5 @@ +// A Guarded value without running the guard, for tests of the write functions themselves. +import type { Guarded } from "../src/core/guard.ts"; +import type { Want } from "../src/core/gates.ts"; + +export const guarded = (repo: string, number: number, head: string, action: Want = { kind: "merge" }): Guarded => ({ repo, number, head, action }) as unknown as Guarded; diff --git a/test/merge.test.ts b/test/merge.test.ts index e60f8a67f..28eb3d446 100644 --- a/test/merge.test.ts +++ b/test/merge.test.ts @@ -198,9 +198,9 @@ describe("merge queue", () => { const log: Log = []; const s = await runMerge(db, { repo: "app", dryRun: false }, quiet, fakes(log, { assignees: new Map([[11, ["someone"]]]) })); assert.deepEqual(s.merged, ["app#1", "app#11", "app#16"]); - assert.deepEqual(log.slice(0, 8), [ - "checks 1", "info 1", "viewer", "assign PR1", "safe-merge-test storytold/app 1 --squash", - "checks 11", "info 11", "safe-merge-test storytold/app 11 --squash", + assert.deepEqual(log.slice(0, 10), [ + "checks 1", "info 1", "viewer", "assign PR1", "checks 1", "safe-merge-test storytold/app 1 --squash", + "checks 11", "info 11", "checks 11", "safe-merge-test storytold/app 11 --squash", ]); assert.deepEqual(s.asked.sort(), [3, 4, 5].map((n) => mergeDecisionId("app", n, `sha${n}`))); const facts = JSON.parse((db.prepare("SELECT facts FROM decisions WHERE id = ?").get(mergeDecisionId("app", 3, "sha3")) as { facts: string }).facts) as string[]; @@ -403,7 +403,7 @@ describe("merging a few ready PRs one at a time", () => { assert.equal(singleMergeMax(db), 3); const { r, log } = await attempt(db, diffs()); assert.deepEqual(r?.merged, ["app#1", "app#11", "app#16"]); - assert.deepEqual(log.filter((l) => l.startsWith("checks")), ["checks 1", "checks 11", "checks 16"]); + assert.deepEqual(log.filter((l) => l.startsWith("checks")), ["checks 1", "checks 1", "checks 11", "checks 11", "checks 16", "checks 16"]); assert.equal(noBatch(db), 0); const moved = await attempt(fresh(), diffs(), { heads: new Map([[11, "newer"]]) }); diff --git a/test/world.ts b/test/world.ts index 54d1dd200..6ec65308b 100644 --- a/test/world.ts +++ b/test/world.ts @@ -8,7 +8,7 @@ export const REVIEW_AT = "2026-11-04T10:00:00.000Z"; type Override = { [K in keyof PrFacts]?: PrFacts[K] extends object | null ? Partial> | null : PrFacts[K] }; const base = (): PrFacts => ({ - repo: "app", number: 1, now: NOW, ghState: "OPEN", head: HEAD, draft: false, + repo: "app", number: 1, now: NOW, pipelineOn: true, ghState: "OPEN", head: HEAD, draft: false, author: "dev", authorIsPipeline: false, tier: "whitelisted", lines: 20, size: "S", label: "bugfix", needsDecisionFlag: false, scopeAnswer: null, inScope: true, integration: false, batchPr: false, heldBacklog: false, heldDuplicate: false, mergeHeld: false, fast: false, score: 100, repoFacts: { mergeApproved: true, pushApproved: true, commentApproved: true, ciApproved: true, noCi: false, mainRed: false },