diff --git a/src/discord/alerts.ts b/src/discord/alerts.ts index 37b831589..ac437ddd9 100644 --- a/src/discord/alerts.ts +++ b/src/discord/alerts.ts @@ -15,7 +15,10 @@ import type { Req, Role, User } from "../dash/types.ts"; import { BACKLOG, HANDLED, WITHDRAWN_OPTION, getDecision, itemsOf, optionsOf, reposOf, snoozedExpr, type DecisionRow, type Kind } from "../decisions.ts"; import { readSeqs } from "../live.ts"; import { trackedNames } from "../repos.ts"; -import { allAppIdentity, maintainerWritesOn } from "../settlers.ts"; +import { allAppIdentity, maintainerWritesFor } from "../settlers.ts"; +import { t } from "../i18n/index.ts"; +import { blockerLabel, recommendationLine } from "../workflow/status.ts"; +import { workflowOf } from "../workflow/store.ts"; import type { ActDeps } from "../conversations/act.ts"; import type { DiscordKeys } from "./keys.ts"; import { loginOf } from "./links.ts"; @@ -25,6 +28,7 @@ import { ghPermission, type PermissionReader } from "../fixup/author-permission. import { everySeq, exclusive, filterSeq, someSeq } from "../async-seq.ts"; import type { Db } from "../db/index.ts"; import * as kx from "../db/kx.ts"; +import type { ItemWorkflow } from "../workflow/types.ts"; /** What the alerts need from Discord beyond messages: the direct-message channel of a user. */ export type DmRest = DiscordRest & { createDm(userId: string): Promise<{ id: string }> }; @@ -33,7 +37,7 @@ export const PER_HOUR = 20; const HOUR_MS = 3_600_000; const POLL_MS = 2000; /** The topics a decision alert depends on: the decisions, their prepared choices, snoozes, who may settle, and item activity that wakes a snooze. */ -const TOPICS = ["decisions", "decision-choices", "decision-snooze"]; +const TOPICS = ["decisions", "decision-choices", "decision-snooze", "workflows"]; /** Who may settle and the activity that wakes a snooze change often and matter less: looked at this rarely. */ const SLOW_TOPICS = ["access", "items"]; const SLOW_MS = 60_000; @@ -73,7 +77,7 @@ const permKey = (login: string, repo: string): string => `${login.toLowerCase()} */ export async function mayReceive(db: Db, login: string, role: Role, repos: string[], now: number = Date.now(), kept: ReadonlySet = new Set()): Promise { if (role === "operator") return true; - if (role !== "maintainer" || !await maintainerWritesOn(db) || !await allAppIdentity(db, repos)) return false; + if (role !== "maintainer" || !await maintainerWritesFor(db, repos) || !await allAppIdentity(db, repos)) return false; const since = new Date(now - RECEIVE_PERMISSION_TTL_MS).toISOString(); return await everySeq(repos, async (r) => !!await db.get(db.k.selectFrom("main.repo_permissions").select((eb) => eb.lit(1).as("one")) .where("login", "=", login).where("repo", "=", r).where("permission", "in", ["write", "maintain", "admin"]) @@ -83,7 +87,7 @@ export async function mayReceive(db: Db, login: string, role: Role, repos: strin export async function mayAlert(db: Db, login: string): Promise { const role = await roleOf(db, login); if (role === "operator") return true; - if (role !== "maintainer" || !await maintainerWritesOn(db)) return false; + if (role !== "maintainer") return false; // Turning alerts on takes a write permission of any age: the alert pass reads a stale one again before it sends. return await someSeq((await trackedNames(db)), async (r) => await mayReceive(db, login, role, [r], Date.now(), new Set([permKey(login, r)]))); } @@ -148,6 +152,24 @@ export async function buildMessage(db: Db, d: DecisionRow, baseUrl: string | nul return { content, components: rows, choicesId: sig }; } +/** How long a workflow alert is remembered: a recommendation older than this is not sent. */ +const WORKFLOW_ALERT_DAYS = 7; +const DAY_MS = 86_400_000; +/** The message row of a workflow alert: one per workflow and recommendation, so a new recommendation is a new alert. */ +const workflowAlertId = (id: number, recAt: string): string => `wf:${id}:${recAt}`; + +/** The text alert for a workflow that stopped at a blocker or came back with a recommendation: no buttons, an answer is a command. */ +export async function buildWorkflowMessage(db: Db, w: ItemWorkflow, baseUrl: string | null): Promise { + const ref = `${soft(w.repo, 60)}#${w.number}`; + const lines = [`**${ref}** ${soft(await itemTitle(db, w.repo, w.number), 120)}`]; + lines.push(w.state === "blocked" && w.blocker ? t("Stopped at a blocker: {blocker}.", { blocker: blockerLabel(w.blocker) }) : t("Waiting for an answer.")); + const rec = recommendationLine(w.rec); + if (rec) lines.push(soft(rec, 600)); + lines.push(t("Answer with /autocraft do, for example: yes {ref}", { ref })); + if (baseUrl) lines.push(`${baseUrl.replace(/\/+$/, "")}/items/${encodeURIComponent(w.repo)}/${w.number}`); + return lines.join("\n").slice(0, 1990); +} + export type AlertDeps = { db: Db; keys: DiscordKeys; rest: DmRest; log: (line: string) => void; baseUrl: string | null; @@ -272,6 +294,40 @@ export class DecisionAlerts { } if (overflow.length) await this.#summary(p, overflow, now); } + await this.#workflowAlerts(people, now); + } + + /** + * Workflows on the maintainer workflow that stopped at a blocker or came back with a recommendation since the person turned alerts on, + * in repos where they may act: one text message per recommendation, within the same hourly limit as decision alerts. + */ + async #workflowAlerts(people: Alerter[], now: number): Promise { + const { db, rest, log } = this.#d; + const after = new Date(now - WORKFLOW_ALERT_DAYS * DAY_MS).toISOString(); + const rows = (await db.all(db.k.selectFrom("main.item_workflows as w").innerJoin("main.tracked_repos as r", "r.name", "w.repo").selectAll("w") + .where("r.workflow", "=", "new").where("w.state", "in", ["blocked", "recommending"]).where("w.rec_at", "is not", null).where("w.rec_at", ">", after).orderBy("w.rec_at"))).map(workflowOf); + if (!rows.length) return; + for (const p of people) { + const created = (await db.get(db.k.selectFrom("discord_alerts").select("created_at").where("user_hash", "=", p.userHash)))?.created_at ?? ""; + const have = new Set((await db.all(db.k.selectFrom("discord_alert_msgs").select("decision_id").where("user_hash", "=", p.userHash) + .where((eb) => kx.like(db, "decision_id", eb.val("wf:%"))))).map((r) => r.decision_id)); + const fresh = await filterSeq(rows, async (w) => w.recAt! >= created && !have.has(workflowAlertId(w.id, w.recAt!)) && await mayReceive(db, p.login, p.role, [w.repo], now, this.#kept)); + let room = (this.#d.perHour ?? PER_HOUR) - (await db.get(db.k.selectFrom("discord_alert_msgs").select((eb) => eb.fn.countAll().as("n")) + .where("user_hash", "=", p.userHash).where("sent_at", ">", new Date(now - HOUR_MS).toISOString())))!.n; + for (const w of fresh) { + if (room <= 0) break; + const id = workflowAlertId(w.id, w.recAt!); + try { + await rest.createMessage(p.channelId, { content: await buildWorkflowMessage(db, w, this.#d.baseUrl), allowed_mentions: { parse: [] } }); + await db.run(db.k.insertInto("discord_alert_msgs").values({ decision_id: id, user_hash: p.userHash, sealed: null, choices_id: null, sent_at: new Date(now).toISOString() }).onConflict((oc) => oc.doNothing())); + room--; + } catch (e) { + log(`discord: workflow alert not sent: ${(e as Error).message}`); + if (e instanceof RestError && e.status === 403) await db.run(db.k.insertInto("discord_alert_msgs").values({ decision_id: id, user_hash: p.userHash, sealed: null, choices_id: null, sent_at: new Date(now).toISOString() }).onConflict((oc) => oc.doNothing())); + else break; + } + } + } } async #summary(p: Alerter, ds: DecisionRow[], now: number): Promise { @@ -303,9 +359,12 @@ export class DecisionAlerts { async #refreshPermissions(people: Alerter[], now: number): Promise { const { db, log } = this.#d; const maintainers = people.filter((p) => p.role === "maintainer"); - if (!maintainers.length || !await maintainerWritesOn(db)) return; + if (!maintainers.length) return; const repos = new Set(); for (const d of await db.all(db.k.selectFrom("decisions").select(kx.cols("decisions")).$narrowType<{ kind: Kind }>().where("answer", "is", null).orderBy(kx.rowid("decisions")))) for (const r of reposOf(d)) repos.add(r); + // Workflows waiting for an answer: their repo's maintainers receive the alert. + for (const w of await db.all(db.k.selectFrom("main.item_workflows").select("repo").where("state", "in", ["blocked", "recommending"]).distinct())) repos.add(w.repo); + for (const r of [...repos]) if (!await maintainerWritesFor(db, [r])) repos.delete(r); if (!repos.size) return; const since = new Date(now - RECEIVE_PERMISSION_TTL_MS).toISOString(); const read = this.#d.readPermission ?? ghPermission; @@ -333,6 +392,8 @@ export class DecisionAlerts { await db.run(db.k.deleteFrom("discord_alert_msgs").where("decision_id", "=", m.decision_id).where("user_hash", "=", m.user_hash)); }; if (m.decision_id.startsWith("summary:")) return Date.parse(m.sent_at) < (this.#d.now ?? Date.now)() - 2 * HOUR_MS ? await forget() : undefined; + // A workflow alert is text only: nothing to edit, and it is kept as long as its recommendation could still be sent. + if (m.decision_id.startsWith("wf:")) return Date.parse(m.sent_at) < (this.#d.now ?? Date.now)() - (WORKFLOW_ALERT_DAYS + 1) * DAY_MS ? await forget() : undefined; const d = await getDecision(db, m.decision_id); const open = d && d.answer === null; if (open && m.sealed === null) return; diff --git a/src/settlers.ts b/src/settlers.ts index 99c822b91..e0cd00fb2 100644 --- a/src/settlers.ts +++ b/src/settlers.ts @@ -32,6 +32,9 @@ const newRepos = async (db: Db): Promise> => */ const writesFor = (on: boolean, fresh: ReadonlySet, repos: readonly string[]): boolean => on || (repos.length > 0 && repos.every((r) => fresh.has(r))); +/** `maintainer_writes` is on, or every one of `repos` (at least one) runs the maintainer workflow. */ +export const maintainerWritesFor = async (db: Db, repos: readonly string[]): Promise => writesFor(await maintainerWritesOn(db), await newRepos(db), repos); + /** `maintainersSettle` for one repo: also true in a repo on the maintainer workflow. */ export const maintainersSettleOn = async (db: Db, repo: string): Promise => await githubIdentity(db) === "app" && writesFor(await maintainerWritesOn(db), await newRepos(db), [repo]); diff --git a/src/workflow/effects.ts b/src/workflow/effects.ts index cf32153f8..c75653cdb 100644 --- a/src/workflow/effects.ts +++ b/src/workflow/effects.ts @@ -6,6 +6,7 @@ // Every start also writes the legacy rows (fast_track, preapprovals, operator_fixups), so `workflow flip --legacy` // leaves the old planner with everything it needs. import { audit } from "../dash/audit.ts"; +import { t } from "../i18n/index.ts"; import { backlogItem } from "../dash/api/decisions.ts"; import { applyAnswer } from "../dash/api/decisions.ts"; import { queueIssue } from "../dash/api/queue-page.ts"; @@ -29,9 +30,44 @@ import { requestRepin } from "../repin/index.ts"; import { markReviewsStale } from "../review/discussion.ts"; import type { ItemKind, ItemWorkflow, PlanPart, Surface } from "./types.ts"; -/** A legacy step refused the command; its message says why. */ +/** A legacy step refused the command; its message says why, translated (`effectText`). */ export class EffectError extends Error {} +/** + * The refusals of the legacy steps a command runs on, as translated text. The steps write English for logs and the classic pages; a + * refusal this table does not know stays as written. + */ +const LEGACY_TEXT: [RegExp, (m: RegExpExecArray) => string][] = [ + [/^(\S+#\d+) is not a pull request$/, (m) => t("{ref} is not a pull request.", { ref: m[1]! })], + [/^(\S+#\d+) is not open$/, (m) => t("{ref} is not open.", { ref: m[1]! })], + [/^(\S+#\d+) is outside the pipeline's scope/, (m) => t("{ref} is outside the pipeline's scope.", { ref: m[1]! })], + [/^(\S+#\d+) cannot be reviewed yet: it is a draft$/, (m) => t("{ref} is a draft, so it cannot be reviewed yet.", { ref: m[1]! })], + [/^(\S+#\d+) cannot be reviewed yet: it is in the backlog$/, (m) => t("{ref} is in the backlog, so it cannot be reviewed yet.", { ref: m[1]! })], + [/^(\S+#\d+) cannot be reviewed yet: it is held as a duplicate$/, (m) => t("{ref} is held as a duplicate, so it cannot be reviewed yet.", { ref: m[1]! })], + [/^(\S+#\d+) cannot be reviewed yet: (.+)$/, (m) => t("{ref} cannot be reviewed yet: {why}", { ref: m[1]!, why: m[2]! })], + [/^(\S+#\d+) has no head commit in the mirror yet$/, (m) => t("AutoCraft has not read the head commit of {ref} yet.", { ref: m[1]! })], + [/^the PR changed after your comment; comment again$/, () => t("The pull request changed after the command was written. Send it again.")], + [/^merging is not approved for (\S+)$/, (m) => t("Merging is not approved for {repo}.", { repo: m[1]! })], + [/^pushing is not approved for (\S+)$/, (m) => t("Pushing is not approved for {repo}.", { repo: m[1]! })], + [/^(\S+#\d+) already has a pre-approved merge in progress$/, (m) => t("{ref} is already on its way to a merge.", { ref: m[1]! })], + [/^(\S+#\d+) conflicts with its base branch/, (m) => t("{ref} conflicts with its base branch: the conflict merge comes first.", { ref: m[1]! })], + [/^can't push to the contributor's branch$/, () => t("AutoCraft can't push to the contributor's branch.")], + [/^the fix-up tries for this PR are used up$/, () => t("The fix-up tries for this pull request are used up.")], + [/^a fix-up of (\S+#\d+) is already queued$/, (m) => t("A fix-up of {ref} is already queued.", { ref: m[1]! })], + [/^the instructions are over (\d+) characters$/, (m) => t("The fix-up instructions are over {n} characters.", { n: m[1]! })], + [/^the author's permission on the repository could not be read yet/, () => t("The author's permission on the repository could not be read yet. Try again.")], + [/^(\S+#\d+) has no pre-approved merge in progress$/, (m) => t("{ref} is not on its way to a merge.", { ref: m[1]! })], +]; + +/** A legacy step's refusal as translated text; unknown text stays as written. */ +export function effectText(message: string): string { + for (const [re, text] of LEGACY_TEXT) { + const m = re.exec(message); + if (m) return text(m); + } + return message; +} + export type Target = { repo: string; number: number; kind: ItemKind; head: string | null }; export type Ctx = { db: Db; by: string; via: Surface; at: string; item: Target; exec?: Exec }; @@ -43,7 +79,7 @@ async function step(fn: () => Promise): Promise { try { return await fn(); } catch (e) { - throw e instanceof EffectError ? e : new EffectError((e as Error).message); + throw e instanceof EffectError ? e : new EffectError(effectText((e as Error).message)); } } @@ -72,10 +108,10 @@ async function mergeLeg(c: Ctx): Promise { try { await preapproveMerge(c.db, { repo: c.item.repo, number: c.item.number, by: c.by, via: c.via, ...(c.item.head ? { head: c.item.head } : {}) }); } catch (e) { - if (!(e instanceof PreapprovalRefused && e.active)) throw new EffectError((e as Error).message); + if (!(e instanceof PreapprovalRefused && e.active)) throw new EffectError(effectText((e as Error).message)); } const id = await activePreapproval(c.db, c.item); - if (id === null) throw new EffectError(`${ref(c.item)} has no pre-approved merge in progress`); + if (id === null) throw new EffectError(t("{ref} is not on its way to a merge.", { ref: ref(c.item) })); return id; } @@ -143,7 +179,7 @@ export async function stopAll(c: Ctx): Promise { const why = `stopped by ${by}`; const failed: string[] = []; const attempt = async (fn: () => Promise) => { - try { await fn(); } catch (e) { failed.push((e as Error).message); } + try { await fn(); } catch (e) { failed.push(effectText((e as Error).message)); } }; if (item.kind === "pr") { if (await activePreapproval(db, item) !== null) await attempt(() => cancelPreapproval(db, by, item.repo, item.number, c.exec, c.via)); @@ -195,7 +231,7 @@ export async function close(c: Ctx): Promise { let id: string; let question: Record; if (item.kind === "pr") { - if (!item.head) throw new EffectError(`${ref(item)} has no head commit in the mirror yet`); + if (!item.head) throw new EffectError(t("AutoCraft has not read the head commit of {ref} yet.", { ref: ref(item) })); id = closeDecisionId(item.repo, item.number, item.head); question = { id, kind: "close", repo: item.repo, number: item.number, question: "Close this PR?", context: `${by} asked to close it.`, facts: [`${HEAD_FACT}${item.head}`], options: Object.values(CLOSE_OPTIONS).map((o) => ({ ...o })), asked_by: by, asked_at: at }; @@ -205,8 +241,8 @@ export async function close(c: Ctx): Promise { facts: [], options: [{ ...SCOPE_OPTIONS.close }, { ...SCOPE_OPTIONS.take }], recommended: null, asked_by: by, asked_at: at }; } const had = await getDecision(db, id); - if (had?.answer === "close") throw new EffectError(`${ref(item)} is already being closed on ${had.answered_by}'s answer`); - if (had?.answer) throw new EffectError(`the close question at this head was already answered ${had.answer} by ${had.answered_by}`); + if (had?.answer === "close") throw new EffectError(t("{ref} is already being closed on the answer of {login}.", { ref: ref(item), login: had.answered_by ?? "" })); + if (had?.answer) throw new EffectError(t("The close question at this head was already answered {answer} by {login}.", { answer: had.answer, login: had.answered_by ?? "" })); if (!had) await ask(db, [question]); await step(async () => applyAnswer(db, (await getDecision(db, id))!, by, { answer: "close" }, "workflow", c.via)); return failed; @@ -217,11 +253,11 @@ export async function close(c: Ctx): Promise { /** The existing autorepin command, unchanged: ` [via ]` or `off`. The caller has applied the act rule. */ export async function autorepin(c: Ctx, args: string, githubId: number | null): Promise { const m = /^(\S+)(?:\s+via\s+(\S+))?$/i.exec(args.trim()); - if (!m) throw new EffectError("autorepin needs a pull request, or off"); + if (!m) throw new EffectError(t("autorepin needs a pull request, or off.")); const off = m[1]!.toLowerCase() === "off"; const prRef = off ? null : parsePrRef(m[1]!); - if (!off && !prRef) throw new EffectError(`${m[1]} is not a pull request`); - if (githubId === null) throw new EffectError(`${c.by} has no GitHub id on record yet; sign in to the dashboard once`); + if (!off && !prRef) throw new EffectError(t("{ref} is not a pull request.", { ref: m[1]! })); + if (githubId === null) throw new EffectError(t("AutoCraft has no GitHub id for {login} yet. Sign in to the dashboard once.", { login: c.by })); return await step(() => requestRepin(c.db, { login: c.by, githubId, role: "", canWrite: true, authorized: true, repo: c.item.repo, number: c.item.number, pr: c.item.kind === "pr", ref: prRef, branch: m[2] ? parseBranch(m[2]) : null, at: new Date(c.at), diff --git a/src/workflow/flip.ts b/src/workflow/flip.ts index 7a1fcc203..13431363d 100644 --- a/src/workflow/flip.ts +++ b/src/workflow/flip.ts @@ -29,7 +29,7 @@ const WITHDRAWN_KINDS = ["merge", "hold", "scope"]; * Whether the planner works item_workflows. Until it does, a flip to `new` would only withdraw questions the legacy planner * asks again, so a real flip is refused; a dry run still reports what it would do. */ -export const WORKFLOW_ENGINE_READY = false; +export const WORKFLOW_ENGINE_READY = true; const ENGINE_NOT_READY = "the planner does not work maintainer workflows yet: a flip now would only withdraw questions the legacy planner asks again"; export class FlipRefused extends Error {}