From 897694dd4af7115bb2feac034ae00e7af047e660 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:19:08 +0000 Subject: [PATCH] Conversation cards hold a command, a comment or a label (card model and reply parse); the retired decision cards move into the choices code --- src/conversations/cards.ts | 864 +++++++++++++------------------- src/conversations/queue.ts | 38 +- src/data/conversations/cards.ts | 2 +- src/data/conversations/types.ts | 2 +- src/data/mirror/comments.ts | 12 + src/decide/choices-convert.ts | 4 +- src/decide/choices-parse.ts | 619 ++++++++++++++++++++++- src/decide/choices.ts | 2 +- src/decide/prepare.ts | 4 +- src/preapproval/index.ts | 3 +- 10 files changed, 1006 insertions(+), 544 deletions(-) diff --git a/src/conversations/cards.ts b/src/conversations/cards.ts index 88d9c2fc8..faf93aa5e 100644 --- a/src/conversations/cards.ts +++ b/src/conversations/cards.ts @@ -1,217 +1,155 @@ -// Action cards: what Opus may propose, checked by our code, and the one-line description of each that the operator reads. -// Descriptions are built here from the parameters; the model never writes them. +// Action cards: what Opus may propose, checked by our code, and the plain lines a person reads. A card is a registered command +// (src/workflow/vocab.ts) that a press runs as the presser, a comment, or a label. Opus writes resolutions of steps; each step becomes +// the card that carries it out. Descriptions are built here from the parameters; the model never writes them. import { ownerOf, splitSlug } from "../owners.ts"; import { REFERENCE_LEAK } from "../review/opus-parse.ts"; -import { writeEffect } from "../act/index.ts"; -import { cleanReason } from "../act/templates.ts"; -import { optionsOf, getDecision, type DecisionRow, type Kind } from "../decisions.ts"; -import { KEEP_IN_CORE } from "../core/rules.ts"; -import { backlogHeldExpr, notOwnIntegrationExpr } from "../dupes/held.ts"; import { ALL_LABELS, isTypeLabel, sameLabel } from "../labels/set.ts"; -import { inScopeExpr } from "../data/workflow/fragments.ts"; -import { loadQuiet } from "../data/security/index.ts"; import { LOGIN } from "../access.ts"; -import { CLOSE_REASONS, COMMENT_MAX, INSTRUCTIONS_MAX, ISSUE_TITLE_MAX, RESOLVE_MAX, type CloseReason } from "./types.ts"; -import { findSeq, someSeq } from "../async-seq.ts"; +import { loadAuthoredIn, loadItems } from "../data/mirror/index.ts"; +import { loadPermissions, permKey } from "../data/access/index.ts"; +import { loadTrackedRepos } from "../data/control/index.ts"; +import { loadQuiet } from "../data/security/index.ts"; +import type { NewCard as StoredCard } from "../data/conversations/index.ts"; +import { COMMENT_MAX, ISSUE_TITLE_MAX } from "./types.ts"; import type { Db } from "../db/index.ts"; -import * as kx from "../db/kx.ts"; -import type { Expression, SqlBool } from "kysely"; -/** - * One step of a resolution. The comment step's text is the card's `text`. Every kind but `review` and `fixup` is one GitHub write - * through src/github/write.ts; `review` and `fixup` queue pipeline work. At most one step of each kind per card, except `label` - * and `unlabel`. `close`, `duplicate` and `transfer` end the item here and come last. - */ -export type Step = - | { kind: "comment" } - | { kind: "label"; label: string } - | { kind: "unlabel"; label: string } - | { kind: "close"; reason: CloseReason; pr: boolean } - | { kind: "duplicate"; of: number } - | { kind: "reopen" } - /** Opens a new issue in `repo` (this repo or another tracked one); title and body are the card's editable `issue` draft. */ - | { kind: "open_issue"; repo: string; title: string; body: string } - /** Issues only: moves the issue to another tracked repo of the same owner. */ - | { kind: "transfer"; to: string } - | { kind: "assign"; login: string } - /** PRs only. */ - | { kind: "request_reviewers"; logins: string[] } - /** PRs only: a fresh Opus review of the current head. */ - | { kind: "review" } - /** PRs only: a fix-up run with the operator-editable instructions; `merge` makes it a pre-approved merge (see Preapproval in web/src/api/types.ts). */ - | { kind: "fixup"; instructions: string; merge: boolean }; +/** An issue a merging command opens once the PR merged (src/conversations/held.ts). */ +export type FollowUp = { repo: string; title: string; body: string }; -/** How a resolution ends the item's open decision. `stamp` identifies the decision state it was written for. */ -export type Settle = - /** `reason`: the public reason a closing option's comment gives (see settleOf); it replaces the decision's own text when the card runs. */ - | { kind: "answer"; decision: string; option: string; stamp: string; reason?: string } - /** `fromClose`: derived from the close or duplicate step, so its summary is false when that step is skipped. */ - | { kind: "handled"; decision: string; summary: string; stamp: string; fromClose?: true } - | { kind: "backlog"; decision: string; stamp: string }; +/** A command of the registry: a press runs its text (commandText) through the workflow's runCommand as the presser. */ +export type RegistryCommand = + | { word: "review" } + | { word: "fix-up"; merge: boolean; followups?: FollowUp[] } + | { word: "merge"; followups?: FollowUp[] } + | { word: "backlog" } + /** `duplicateOf`: the item it duplicates, shown on the card. */ + | { word: "close"; pr: boolean; duplicateOf?: number }; -/** The legacy kinds (everything below `resolution`) stay runnable for cards stored before resolutions; new Opus output only produces `resolution`. */ -export type CardParams = - | { kind: "resolution"; steps: Step[]; settle: Settle | null } - | { kind: "comment"; text: string } - | { kind: "answer"; option: string; decision: string; stamp?: string } - | { kind: "label"; label: string } - | { kind: "backlog"; decision: string; stamp?: string } - | { kind: "duplicate"; of: number } - | { kind: "resolve"; decision: string; summary: string; stamp?: string } - | { kind: "close"; reason: CloseReason; pr: boolean }; +/** Actions with no registered command: the card shows them and a press refuses (actionRefusal). */ +export type OtherAction = + | { word: "reopen" } + | { word: "open_issue"; repo: string; title: string; body: string } + | { word: "transfer"; to: string } + | { word: "assign"; login: string } + | { word: "request_reviewers"; logins: string[] }; + +export type Command = RegistryCommand | OtherAction; + +/** The comment card's text is the card's `text`. */ +export type CardParams = { kind: "command"; command: Command } | { kind: "comment" } | { kind: "label"; label: string; remove: boolean }; export type NewCard = { params: CardParams; text: string | null; description: string }; -const ref = (repo: string, n: number) => `${repo}#${n}`; +const REGISTRY = new Set(["review", "fix-up", "merge", "backlog", "close"]); +export const isRegistry = (c: Command): c is RegistryCommand => REGISTRY.has(c.word); -/** The item's open decision: the newest unanswered one that is about this item alone and is not a duplicate-group decision. */ -export async function openDecision(db: Db, repo: string, n: number): Promise { - return await db.get(db.k.selectFrom("decisions").select(kx.cols("decisions")).$narrowType<{ kind: Kind }>().where("repo", "=", repo).where("number", "=", n) - .where("answer", "is", null).where((eb) => eb.not(kx.like(db, "id", eb.val("%:dupegroup:%")))).orderBy("asked_at", "desc").orderBy("id", "desc").limit(1)); +/** The text a press runs: registry words, read by src/workflow/parse.ts. */ +export function commandText(c: RegistryCommand): string { + return c.word === "fix-up" && c.merge ? "fix-up and merge" : c.word; } -/** Identifies the state of a decision a card was written for: its ask time and how often it was answered, undone or reopened. A re-ask or Reopen keeps the id, so the id alone cannot tell. */ -export async function decisionStamp(db: Db, d: DecisionRow): Promise { - const n = (await db.get(db.k.selectFrom("audit").select((eb) => eb.fn.countAll().as("n")).where("target", "=", d.id).where("action", "in", ["answer", "undo", "reopen"])))!.n; - return `${d.asked_at}|${n}`; -} - -const closeEffect = (p: { reason: CloseReason; pr: boolean }): string => p.pr ? "closes the PR on GitHub" : `closes the issue as ${p.reason === "completed" ? "completed" : "not planned"} on GitHub`; -const decisionWrite = async (db: Db, decision: string, option: string): Promise => { - const d = await getDecision(db, decision); - return d ? writeEffect(d.kind as Kind, option) : null; +/** Why a press of an action without a registered command runs nothing. */ +export const actionRefusal = (c: OtherAction): string => + `AutoCraft has no command to ${actionVerb[c.word]}; do it on GitHub`; +const actionVerb: Record = { + reopen: "reopen an item", open_issue: "open an issue", transfer: "move an issue", assign: "assign someone", request_reviewers: "request reviewers", }; -/** The GitHub write that answering with this card's option causes later (the Act step does it), or null when it writes nothing. For a resolution: every closing write it makes, joined. */ -export async function cardEffect(db: Db, p: CardParams): Promise { - if (p.kind === "resolution") { - const parts: string[] = []; - for (const st of p.steps) { - if (st.kind === "close") parts.push(closeEffect(st)); - else if (st.kind === "duplicate") parts.push("closes it as a duplicate on GitHub"); - else if (st.kind === "transfer") parts.push(`moves the issue to ${st.to} on GitHub`); - else if (st.kind === "fixup" && st.merge) parts.push("merges the PR on GitHub once the fix-up, the review and CI pass"); - } - if (p.settle?.kind === "answer") { - const w = await decisionWrite(db, p.settle.decision, p.settle.option); - if (w) parts.push(w); - } - return parts.length ? parts.join("; ") : null; - } - if (p.kind === "close") return closeEffect(p); - if (p.kind !== "answer" || !p.decision) return null; - return await decisionWrite(db, p.decision, p.option); +/** The stored form of a card. */ +export const storedCard = (c: NewCard): StoredCard => ({ kind: c.params.kind, params: JSON.stringify(c.params), text: c.text, description: c.description }); + +/** The card's parameters, or null for a card stored by the retired decision system (or unreadable). */ +export function readParams(kind: string, params: string): CardParams | null { + if (kind !== "command" && kind !== "comment" && kind !== "label") return null; + try { + const p = JSON.parse(params) as CardParams; + return p && typeof p === "object" && p.kind === kind ? p : null; + } catch { return null; } } -/** The word for a decision in the card lines: "scope", "close", "merge" ... ; "open" for kinds without a name of their own. */ -const questionWord = (d: DecisionRow | undefined): string => (d && d.kind !== "other" ? d.kind : "open"); -const optionLabel = (d: DecisionRow | undefined, key: string): string => (d ? optionsOf(d).find((x) => x.key === key)?.label : undefined) ?? key; +const followupsOf = (p: CardParams): FollowUp[] => + p.kind === "command" && (p.command.word === "merge" || p.command.word === "fix-up") ? p.command.followups ?? [] : []; -/** - * Whether the card holds its open_issue step until the PR merges: it answers Merge, or its fix-up merges. The issue is filed after the merge - * (src/conversations/held.ts), so a PR that never merges leaves none behind. - */ -export const holdsIssues = (p: CardParams): boolean => - p.kind === "resolution" && ((p.settle?.kind === "answer" && p.settle.option === "merge") || p.steps.some((x) => x.kind === "fixup" && x.merge)); +/** Whether the press holds issues until the merge: a merging command with follow-ups. */ +export const holdsIssues = (p: CardParams): boolean => followupsOf(p).length > 0; -/** One plain line for a step. `held`: the card holds its issue until the merge (holdsIssues). */ -export function stepLine(st: Step, held = false): string { - switch (st.kind) { - case "comment": return "Post the comment below"; - case "label": return `Add the label "${st.label}"`; - case "close": return st.pr ? "Close the PR" : `Close the issue as ${st.reason === "completed" ? "completed" : "not planned"}`; - case "duplicate": return `Close as a duplicate of #${st.of}`; - case "unlabel": return `Remove the label "${st.label}"`; - case "reopen": return "Reopen it"; - case "open_issue": return `${held ? "After the merge: open" : "Open"} an issue in ${st.repo}: "${st.title}"`; - case "transfer": return `Move the issue to ${st.to}`; - case "assign": return `Assign ${st.login}`; - case "request_reviewers": return `Ask ${st.logins.join(", ")} for a review`; +/** One plain line for a command. */ +export function commandLine(c: Command): string { + switch (c.word) { case "review": return "Review the PR again"; - case "fixup": return st.merge ? "Fix up the PR as described below, then merge it if the review and CI pass" : "Fix up the PR as described below"; + case "fix-up": return c.merge ? "Fix up the PR, then merge it if the review and CI pass" : "Fix up the PR"; + case "merge": return "Approve the merge"; + case "backlog": return "Move the item to the Backlog"; + case "close": return c.duplicateOf !== undefined ? `Close as a duplicate of #${c.duplicateOf}` : c.pr ? "Close the PR" : "Close the issue"; + case "reopen": return "Reopen it"; + case "open_issue": return `Open an issue in ${c.repo}: "${c.title}"`; + case "transfer": return `Move the issue to ${c.to}`; + case "assign": return `Assign ${c.login}`; + case "request_reviewers": return `Ask ${c.logins.join(", ")} for a review`; } } -/** One plain line for how a card ends the open decision. */ -export async function settleLine(db: Db, s: Settle): Promise { - const d = await getDecision(db, s.decision); - switch (s.kind) { - case "answer": return `Answers the ${questionWord(d)} question with "${optionLabel(d, s.option)}"${s.reason ? `, giving the reason: ${s.reason}` : ""}`; - case "handled": return `Closes the ${questionWord(d)} question as handled: "${s.summary}"`; - case "backlog": return "Moves the item to the Backlog"; - } +/** What runs, one plain line each. */ +export function cardLines(p: CardParams): string[] { + if (p.kind === "comment") return ["Post the comment below"]; + if (p.kind === "label") return [p.remove ? `Remove the label "${p.label}"` : `Add the label "${p.label}"`]; + return [commandLine(p.command), ...followupsOf(p).map((f) => `After the merge: open an issue in ${f.repo}: "${f.title}"`)]; } -/** The steps and settlement lines of any card, resolution or legacy (`description` is the legacy card's one line). */ -export async function cardLines(db: Db, p: CardParams, description: string): Promise<{ steps: string[]; settles?: string }> { - if (p.kind === "resolution") return { steps: p.steps.map((x) => stepLine(x, holdsIssues(p))), ...(p.settle && { settles: await settleLine(db, p.settle) }) }; - const steps = [description]; - switch (p.kind) { - case "answer": return { steps: [], settles: await settleLine(db, { kind: "answer", decision: p.decision, option: p.option, stamp: p.stamp ?? "" }) }; - case "backlog": return { steps: [], settles: "Moves the item to the Backlog" }; - case "resolve": return { steps: [], settles: await settleLine(db, { kind: "handled", decision: p.decision, summary: p.summary, stamp: p.stamp ?? "" }) }; - case "close": case "duplicate": return { steps, settles: "Closes the open questions as handled" }; - default: return { steps }; - } -} - -/** The primary button's label: the action in a few words, from the parameters and the item. Server-written. */ -export async function buttonLabel(db: Db, p: CardParams): Promise { - switch (p.kind) { - case "resolution": { - const close = p.steps.find((x) => x.kind === "close"); - if (close) return close.pr ? "Close PR" : "Close issue"; - if (p.steps.some((x) => x.kind === "duplicate")) return "Close as duplicate"; - if (p.steps.some((x) => x.kind === "transfer")) return "Move issue"; - const fix = p.steps.find((x) => x.kind === "fixup"); - if (fix) return fix.merge ? "Fix up and merge" : "Fix up"; - if (p.steps.some((x) => x.kind === "review")) return "Review again"; - if (p.settle?.kind === "answer") return `Answer "${optionLabel(await getDecision(db, p.settle.decision), p.settle.option)}"`; - if (p.settle?.kind === "backlog") return "Move to Backlog"; - if (p.steps.some((x) => x.kind === "open_issue")) return "Open issue"; - if (p.settle) return "Close question"; - if (p.steps.some((x) => x.kind === "comment")) return "Post comment"; - for (const [kind, label] of [["reopen", "Reopen"], ["request_reviewers", "Ask for review"], ["assign", "Assign"], ["unlabel", "Remove label"]] as const) if (p.steps.some((x) => x.kind === kind)) return label; - return "Add label"; - } - case "comment": return "Post comment"; - case "answer": { - const d = await getDecision(db, p.decision); - return `Answer "${optionLabel(d, p.option)}"`; - } - case "label": return "Add label"; +/** The primary button's label. */ +export function buttonLabel(p: CardParams): string { + if (p.kind === "comment") return "Post comment"; + if (p.kind === "label") return p.remove ? "Remove label" : "Add label"; + const c = p.command; + switch (c.word) { + case "review": return "Review again"; + case "fix-up": return c.merge ? "Fix up and merge" : "Fix up"; + case "merge": return "Merge"; case "backlog": return "Move to Backlog"; - case "resolve": return "Close decision"; - case "duplicate": return "Close as duplicate"; - case "close": return p.pr ? "Close PR" : "Close issue"; + case "close": return c.duplicateOf !== undefined ? "Close as duplicate" : c.pr ? "Close PR" : "Close issue"; + case "reopen": return "Reopen"; + case "open_issue": return "Open issue"; + case "transfer": return "Move issue"; + case "assign": return "Assign"; + case "request_reviewers": return "Ask for review"; } } -/** The card's first line: the button's action plus its key parameter ("Close issue as completed", "Close as duplicate of #12", "Move issue to "). Server-written. */ -export async function headline(db: Db, p: CardParams): Promise { - const closeOf = (pr: boolean, reason: CloseReason) => (pr ? "Close PR" : `Close issue as ${reason === "completed" ? "completed" : "not planned"}`); - switch (p.kind) { - case "resolution": { - const close = p.steps.find((x) => x.kind === "close"); - if (close?.kind === "close") return closeOf(close.pr, close.reason); - const dup = p.steps.find((x) => x.kind === "duplicate"); - if (dup?.kind === "duplicate") return `Close as duplicate of #${dup.of}`; - const move = p.steps.find((x) => x.kind === "transfer"); - if (move?.kind === "transfer") return `Move issue to ${move.to}`; - const open = p.steps.find((x) => x.kind === "open_issue"); - if (open?.kind === "open_issue" && await buttonLabel(db, p) === "Open issue") return `Open issue in ${open.repo}`; - return await buttonLabel(db, p); - } - case "duplicate": return `Close as duplicate of #${p.of}`; - case "close": return closeOf(p.pr, p.reason); - default: return await buttonLabel(db, p); - } +/** The card's first line: the button's action with its key parameter. */ +export function headline(p: CardParams): string { + if (p.kind !== "command") return buttonLabel(p); + const c = p.command; + if (c.word === "close" && c.duplicateOf !== undefined) return `Close as duplicate of #${c.duplicateOf}`; + if (c.word === "transfer") return `Move issue to ${c.to}`; + if (c.word === "open_issue") return `Open issue in ${c.repo}`; + return buttonLabel(p); } -/** The one-line description stored with a resolution: its steps and settlement. */ -export async function describe(db: Db, repo: string, n: number, p: CardParams & { kind: "resolution" }): Promise { - const lines = await cardLines(db, p, ""); - return `On ${ref(repo, n)}: ${[...lines.steps, ...(lines.settles ? [lines.settles] : [])].join("; ")}`; +/** The GitHub write the command leads to after the press, or null. */ +export function cardEffect(p: CardParams): string | null { + if (p.kind !== "command") return null; + const c = p.command; + if (c.word === "close") return c.pr ? "closes the PR on GitHub" : "closes the issue on GitHub"; + if (c.word === "merge" || (c.word === "fix-up" && c.merge)) return "merges the PR on GitHub once the review and CI pass"; + if (c.word === "transfer") return `moves the issue to ${c.to} on GitHub`; + return null; +} + +/** The one-line description stored with a card. */ +export const describe = (repo: string, n: number, p: CardParams): string => `On ${repo}#${n}: ${cardLines(p).join("; ")}`; + +/** Whether the card posts text drafted from the item as it was: refused after a push until Opus writes it again. */ +export const dependsOnCode = (p: CardParams): boolean => + p.kind === "comment" || holdsIssues(p) || (p.kind === "command" && p.command.word === "open_issue"); + +/** Whether the card puts model-written text on GitHub: refused on a quiet pull request until its fix is published. */ +export const postsText = (p: CardParams): boolean => + p.kind === "comment" || holdsIssues(p) || (p.kind === "command" && (p.command.word === "open_issue" || p.command.word === "transfer")); + +/** The repos a card writes to: its item's, and where it moves the item or opens an issue. */ +export function cardRepos(repo: string, p: CardParams | null): string[] { + const more = !p || p.kind !== "command" ? [] : p.command.word === "transfer" ? [p.command.to] : p.command.word === "open_issue" ? [p.command.repo] : followupsOf(p).map((f) => f.repo); + return [...new Set([repo, ...more])]; } const ENTITIES: Record = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", commat: "@", num: "#", lpar: "(", rpar: ")", lsqb: "[", rsqb: "]", lbrack: "[", rbrack: "]", colon: ":", sol: "/", period: ".", excl: "!", bsol: "\\" }; @@ -234,7 +172,7 @@ export function decodeEntities(s: string): string { /** * Model text for a public comment, cleaned like the Act step's comments: entities decoded first (so `@user` cannot notify), * then raw HTML, images, links (Markdown, autolinks and bare URLs, keeping a Markdown link's text), cross-repo references and every - * @ removed. An operator who edits a card may add links back. + * @ removed. A person who edits a card may add links back. */ export function cleanComment(s: string): string { let t = s; @@ -247,36 +185,58 @@ export function cleanComment(s: string): string { .replace(/<\/?[a-z!][^>]*>/gi, "") .replace(/]*>?/gi, "") .replace(/\b[\w.-]+\/[\w.-]+#\d+/g, "") - .replace(/[@\uFF20\uFE6B]/g, ""); + .replace(/[@@﹫]/g, ""); if (next === t) break; t = next; } return t.replace(/[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim(); } -/** Why Act would not close this item (an integration PR of ours, held by Backlog, outside the pilot), or null. */ -export async function closeRefusal(db: Db, repo: string, n: number): Promise { - const has = async (cond?: (eb: kx.AnyEb) => Expression) => !!await db.get(db.k.selectFrom("items as i").select((eb) => eb.lit(1).as("one")) - .where("i.repo", "=", repo).where("i.number", "=", n).$if(!!cond, (q) => q.where((eb) => cond!(eb)))); - if (!await has()) return `${ref(repo, n)} is not in the mirror`; - if (!await has((eb) => notOwnIntegrationExpr(db, eb, "i"))) return `${ref(repo, n)} is an integration PR the pipeline opened`; - if (!await has((eb) => inScopeExpr(db, eb, "i.repo", "i.number"))) return `${ref(repo, n)} is outside the pilot`; - if (await has((eb) => backlogHeldExpr(db, eb, "i"))) return `${ref(repo, n)} is held by a Backlog answer`; - return null; -} +// ---- checking what Opus proposed ------------------------------------------------------------------------------------ -/** The type label the item has besides `label` (type labels are exclusive), or null. */ -export async function otherTypeLabel(db: Db, repo: string, n: number, label: string, removing: readonly string[] = []): Promise { - if (!isTypeLabel(label)) return null; - const row = await db.get(db.k.selectFrom("items").select("labels").where("repo", "=", repo).where("number", "=", n)); - let have: unknown[] = []; - try { have = JSON.parse(row?.labels ?? "[]") as unknown[]; } catch { /* unreadable labels count as none */ } - return have.map(String).find((l) => isTypeLabel(l) && !sameLabel(l, label) && !removing.some((r) => sameLabel(r, l))) ?? null; +/** What the checks read about the item and the names a reply mentions, loaded once per reply (loadCardFacts). */ +export type CardFacts = { + repo: string; + n: number; + item: { kind: string; state: string; author: string | null; labels: string[] } | null; + quiet: boolean; + tracked: ReadonlySet; + /** Numbers of the repo's items the mirror has, among those asked for. */ + known: ReadonlySet; + /** Logins (lower case), among those asked for, known to write to the repo: a cached write permission, or an owner, member or collaborator association there. */ + writers: ReadonlySet; +}; + +const labelsOf = (raw: string | null): string[] => { + try { const l = JSON.parse(raw ?? "[]") as unknown; return Array.isArray(l) ? l.map(String) : []; } catch { return []; } +}; + +const WRITE = new Set(["write", "maintain", "admin"]); + +/** The facts the checks of one item read, in one wave. `numbers` and `logins`: the other items and the people a reply names. */ +export async function loadCardFacts(db: Db, repo: string, n: number, want: { numbers?: number[]; logins?: string[] } = {}): Promise { + const ref = `${repo}#${n}`; + const numbers = [...new Set((want.numbers ?? []).filter((x) => Number.isInteger(x) && x > 0 && x !== n))]; + const logins = [...new Set((want.logins ?? []).filter((l) => LOGIN.test(l)).map((l) => l.toLowerCase()))]; + const [items, quiet, tracked, perms, authored] = await db.together(() => Promise.all([ + loadItems(db, [{ repo, number: n }, ...numbers.map((number) => ({ repo, number }))], "card"), + loadQuiet(db, [ref]), + loadTrackedRepos(db), + loadPermissions(db, logins.map((login) => ({ login, repo }))), + loadAuthoredIn(db, repo, logins, ["OWNER", "MEMBER", "COLLABORATOR"]), + ])); + const it = items.get(ref); + return { + repo, n, quiet: quiet.size > 0, tracked: new Set(tracked.keys()), + item: it ? { kind: it.kind, state: it.state, author: it.author, labels: labelsOf(it.labels) } : null, + known: new Set(numbers.filter((x) => items.has(`${repo}#${x}`))), + writers: new Set(logins.filter((l) => WRITE.has(perms.get(permKey(l, repo))?.permission ?? "") || authored.has(l))), + }; } export type Checked = { value: T } | { note: string }; -/** Model text for a comment step, cleaned and checked. */ +/** Model text for a comment, cleaned and checked. */ export function commentText(raw: unknown, drop: ReadonlySet): Checked { const text = typeof raw === "string" ? cleanComment(raw) : ""; if (!text) return { note: "dropped a resolution whose comment step has no text" }; @@ -285,265 +245,157 @@ export function commentText(raw: unknown, drop: ReadonlySet): Checked> { - const l = typeof raw === "string" ? ALL_LABELS.find((x) => sameLabel(x.name, raw)) : undefined; - if (!l) return { note: `dropped a resolution: "${String(raw).slice(0, 40)}" is not a label the pipeline manages` }; - const other = await otherTypeLabel(db, repo, n, l.name, removing); - if (other) return { note: `dropped a resolution: the item already has the type label "${other}" and an item has one type label` }; - return { value: { kind: "label", label: l.name } }; -} - -export async function closeStep(db: Db, repo: string, n: number, reason: unknown): Promise> { - if (!CLOSE_REASONS.includes(reason as CloseReason)) return { note: "dropped a resolution whose close step has no reason of completed or not_planned" }; - const why = await closeRefusal(db, repo, n); - if (why) return { note: `dropped a resolution: ${why}` }; - const row = (await db.get(db.k.selectFrom("items").select(["kind", "state"]).where("repo", "=", repo).where("number", "=", n)))!; - if (row.state !== "OPEN") return { note: `dropped a resolution: ${ref(repo, n)} is not open` }; - return { value: { kind: "close", reason: reason as CloseReason, pr: row.kind === "pr" } }; -} - -export async function duplicateStep(db: Db, repo: string, n: number, of: unknown): Promise> { - if (!Number.isInteger(of) || of === n) return { note: "dropped a resolution whose duplicate step names no other item number" }; - if (!await db.get(db.k.selectFrom("items").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", of as number))) return { note: `dropped a resolution: ${ref(repo, of as number)} is not in the mirror` }; - const why = await closeRefusal(db, repo, n); - if (why) return { note: `dropped a resolution: ${why}` }; - return { value: { kind: "duplicate", of: of as number } }; -} - -type ItemFacts = { kind: string; state: string; author: string | null }; -const itemFacts = async (db: Db, repo: string, n: number): Promise => - await db.get(db.k.selectFrom("items").select(["kind", "state", "author"]).where("repo", "=", repo).where("number", "=", n)); -/** A repository name as the model wrote it, without a leading `owner/`. An owner that is not the repo's own leaves the value as written, which is no tracked repo. */ -const bareRepo = (v: unknown): unknown => { - if (typeof v !== "string" || !v.includes("/")) return v; - const { owner, name } = splitSlug(v); - return owner.toLowerCase() === ownerOf(name).toLowerCase() ? name : v; -}; -const isTracked = async (db: Db, repo: string): Promise => !!(await db.get(db.k.selectFrom("tracked_repos").select((eb) => eb.lit(1).as("one")).where("name", "=", repo))); -const sameLogin = (a: string | null, b: string): boolean => a !== null && a.toLowerCase() === b.toLowerCase(); - -/** - * Whether the mirror says `login` can write to `repo`: a cached permission of write or higher, or an association of owner, - * member or collaborator on an item or comment in the repo. The association is a hint only; Act reads the live permission before it writes. - */ -export async function mayWrite(db: Db, repo: string, login: string): Promise { - if (await db.get(db.k.selectFrom("repo_permissions").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("login", "=", login).where("permission", "in", ["write", "maintain", "admin"]))) return true; - return !!await db.get(db.k.selectFrom("items").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where((eb) => kx.ciEq(db, "author", eb.val(login))) - .where("author_association", "in", ["OWNER", "MEMBER", "COLLABORATOR"]) - .unionAll(db.k.selectFrom("comments").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where((eb) => kx.ciEq(db, "author", eb.val(login))) - .where("author_association", "in", ["OWNER", "MEMBER", "COLLABORATOR"])) - .limit(1)); -} - -const pr = (f: ItemFacts | undefined): boolean => f?.kind === "pr"; - -/** Model text for an issue title: cleaned like a comment, on one line. */ -function issueText(raw: unknown, max: number, what: string, drop: ReadonlySet, oneLineOnly: boolean): Checked { - const t = typeof raw === "string" ? (oneLineOnly ? cleanComment(raw).replace(/\s+/g, " ") : cleanComment(raw)) : ""; +/** Model text for an issue title (one line) or body, cleaned like a comment. */ +function issueText(raw: unknown, max: number, what: string, drop: ReadonlySet, oneLine: boolean): Checked { + const t = typeof raw === "string" ? (oneLine ? cleanComment(raw).replace(/\s+/g, " ") : cleanComment(raw)) : ""; if (!t) return { note: `dropped a resolution whose open_issue step has no ${what}` }; if (REFERENCE_LEAK.test(t) || drop.has(t)) return { note: `dropped a resolution whose issue ${what} mentions the reference folder or its documentation` }; if (t.length > max) return { note: `dropped a resolution whose issue ${what} is longer than ${max} characters` }; return { value: t }; } -export async function openIssueStep(db: Db, st: Record, drop: ReadonlySet): Promise> { - const repo = bareRepo(st.repo); - if (typeof repo !== "string" || !await isTracked(db, repo)) return { note: `dropped a resolution: "${String(st.repo).slice(0, 40)}" is not a tracked repository` }; - const title = issueText(st.title, ISSUE_TITLE_MAX, "title", drop, true); - if ("note" in title) return title; - const body = issueText(st.body, COMMENT_MAX, "body", drop, false); - if ("note" in body) return body; - return { value: { kind: "open_issue", repo, title: title.value, body: body.value } }; -} +/** A repository name as the model wrote it, without a leading `owner/` of the repo's own owner. */ +const bareRepo = (v: unknown): unknown => { + if (typeof v !== "string" || !v.includes("/")) return v; + const { owner, name } = splitSlug(v); + return owner.toLowerCase() === ownerOf(name).toLowerCase() ? name : v; +}; -export async function transferStep(db: Db, repo: string, n: number, toRaw: unknown): Promise> { - const to = bareRepo(toRaw); - const f = await itemFacts(db, repo, n); - if (pr(f)) return { note: "dropped a resolution: only an issue can be moved to another repository" }; - if (typeof to !== "string" || !await isTracked(db, to) || to === repo) return { note: `dropped a resolution: "${String(to).slice(0, 40)}" is not another tracked repository` }; - if (ownerOf(to).toLowerCase() !== ownerOf(repo).toLowerCase()) return { note: "dropped a resolution: an issue moves only between repositories of one owner" }; - const why = await closeRefusal(db, repo, n); - if (why) return { note: `dropped a resolution: ${why}` }; - if (f?.state !== "OPEN") return { note: `dropped a resolution: ${ref(repo, n)} is not open` }; - return { value: { kind: "transfer", to } }; -} +const isPr = (f: CardFacts): boolean => f.item?.kind === "pr"; +const isOpen = (f: CardFacts): boolean => f.item?.state === "OPEN"; +const sameLogin = (a: string | null | undefined, b: string): boolean => !!a && a.toLowerCase() === b.toLowerCase(); -export async function assignStep(db: Db, repo: string, n: number, login: unknown): Promise> { - if (typeof login !== "string" || !LOGIN.test(login)) return { note: "dropped a resolution whose assign step has no GitHub login" }; - if (!sameLogin((await itemFacts(db, repo, n))?.author ?? null, login) && !await mayWrite(db, repo, login)) return { note: `dropped a resolution: ${login} is neither the author nor known to have write access to ${repo}` }; - return { value: { kind: "assign", login } }; -} - -export async function reviewersStep(db: Db, repo: string, n: number, raw: unknown): Promise> { - const f = await itemFacts(db, repo, n); - if (!pr(f)) return { note: "dropped a resolution: reviewers can be requested on a PR only" }; - if (!Array.isArray(raw) || raw.length < 1 || raw.length > 3 || raw.some((x) => typeof x !== "string" || !LOGIN.test(x))) return { note: "dropped a resolution whose request_reviewers step does not list one to three GitHub logins" }; - const logins = raw as string[]; - if (new Set(logins.map((x) => x.toLowerCase())).size !== logins.length) return { note: "dropped a resolution that requests the same reviewer twice" }; - const bad = await findSeq(logins, async (x) => sameLogin(f!.author, x) || !await mayWrite(db, repo, x)); - if (bad) return { note: `dropped a resolution: ${bad} is the PR's author or not known to have write access to ${repo}` }; - return { value: { kind: "request_reviewers", logins } }; -} - -export async function unlabelStep(db: Db, repo: string, n: number, raw: unknown): Promise> { +/** The managed label the model named, or a note. */ +function labelOf(raw: unknown): Checked { const l = typeof raw === "string" ? ALL_LABELS.find((x) => sameLabel(x.name, raw)) : undefined; - if (!l) return { note: `dropped a resolution: "${String(raw).slice(0, 40)}" is not a label the pipeline manages` }; - const row = await db.get(db.k.selectFrom("items").select("labels").where("repo", "=", repo).where("number", "=", n)); - let have: unknown[] = []; - try { have = JSON.parse(row?.labels ?? "[]") as unknown[]; } catch { /* unreadable labels count as none */ } - if (!have.some((x) => sameLabel(String(x), l.name))) return { note: `dropped a resolution: the item does not have the label "${l.name}"` }; - return { value: { kind: "unlabel", label: l.name } }; + return l ? { value: l.name } : { note: `dropped a resolution: "${String(raw).slice(0, 40)}" is not a label the pipeline manages` }; } -async function reopenStep(db: Db, repo: string, n: number): Promise> { - const f = await itemFacts(db, repo, n); - if (f?.state !== "CLOSED") return { note: `dropped a resolution: ${ref(repo, n)} is not closed` }; - const why = await closeRefusal(db, repo, n); - return why ? { note: `dropped a resolution: ${why}` } : { value: { kind: "reopen" } }; +/** The type label the item has besides `label` (type labels are exclusive), or null. */ +export function otherTypeLabel(have: readonly string[], label: string, removing: readonly string[] = []): string | null { + if (!isTypeLabel(label)) return null; + return have.find((l) => isTypeLabel(l) && !sameLabel(l, label) && !removing.some((r) => sameLabel(r, l))) ?? null; } -export async function pipelineStep(db: Db, repo: string, n: number, st: Record): Promise> { - const f = await itemFacts(db, repo, n); - if (!pr(f) || f?.state !== "OPEN") return { note: `dropped a resolution: a ${String(st.kind)} step needs an open PR` }; - if (st.kind === "review") return { value: { kind: "review" } }; - const instructions = typeof st.instructions === "string" ? st.instructions.trim() : ""; - if (!instructions) return { note: "dropped a resolution whose fixup step has no instructions" }; - if (instructions.length > INSTRUCTIONS_MAX) return { note: `dropped a resolution whose fixup instructions are longer than ${INSTRUCTIONS_MAX} characters` }; - if (st.merge !== undefined && typeof st.merge !== "boolean") return { note: "dropped a resolution whose fixup merge is not true or false" }; - return { value: { kind: "fixup", instructions, merge: st.merge === true } }; +/** The step kinds that can pass the checks for the item as it is now (the item block's `steps`); "fixup with merge" is listed apart. */ +export function applicableSteps(f: CardFacts): string[] { + if (!f.item || !isOpen(f)) return []; + const out = ["comment", "label"]; + if (f.item.labels.some((l) => ALL_LABELS.some((x) => sameLabel(x.name, l)))) out.push("unlabel"); + out.push("close", "duplicate"); + if (isPr(f)) out.push("review", "fixup", "fixup with merge", "open_issue"); + return f.quiet ? out.filter((k) => k !== "comment" && k !== "open_issue") : out; } const MAX_STEPS = 8; -/** Steps that post model-written text on GitHub: not offered on a quiet pull request, whose fix must not be described in public before the advisory is published. */ -/** - * Whether a card's effect rests on the PR's code at the head it was written for: it posts a drafted comment or issue, or pushes a fix-up. - * Other cards (answer, backlog, hold, label, close, review, reviewers) still run after a push; these are refused until the choices are written again. - */ -export function dependsOnCode(params: CardParams, text: string | null): boolean { - switch (params.kind) { - case "comment": return true; - case "close": return text !== null && text.trim() !== ""; - case "resolution": return params.steps.some((x) => x.kind === "comment" || x.kind === "open_issue" || x.kind === "fixup") || (params.settle?.kind === "answer" && !!params.settle.reason?.trim()); - default: return false; - } -} - -export const PUBLIC_TEXT_STEPS: ReadonlySet = new Set(["comment", "open_issue", "transfer"]); - -/** The step kinds that can validate for the item as it is now, from the same facts and refusals as validateResolution; "fixup with merge" is listed apart. */ -export async function applicableSteps(db: Db, repo: string, n: number): Promise { - const f = await itemFacts(db, repo, n); - if (!f) return []; - const open = f.state === "OPEN", isPr = pr(f), out: string[] = ["open_issue"]; - const quiet = (await loadQuiet(db, [`${repo}#${n}`])).size > 0; - if (open) { - out.push("comment", "label", "assign"); - if (await someSeq(ALL_LABELS, async (l) => !("note" in await unlabelStep(db, repo, n, l.name)))) out.push("unlabel"); - if (!await closeRefusal(db, repo, n)) out.push("close", "duplicate"); - if (isPr) { - out.push("request_reviewers", "review", "fixup"); - const d = await openDecision(db, repo, n); - if (d && (d.kind === "merge" || d.kind === "scope" || d.kind === "hold")) out.push("fixup with merge"); - } else if (!await closeRefusal(db, repo, n)) out.push("transfer"); - } else if (f.state === "CLOSED" && !("note" in await reopenStep(db, repo, n))) out.push("reopen"); - return quiet ? out.filter((k) => !PUBLIC_TEXT_STEPS.has(k)) : out; -} - -/** The settlement the model asked for, checked against the item's open decision `d`. */ -async function settleOf(db: Db, d: DecisionRow, raw: unknown): Promise> { - if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { note: "dropped a resolution whose settle is not an object" }; - const s = raw as Record; - const stamp = await decisionStamp(db, d); - switch (s.kind) { - case "answer": - if (typeof s.option !== "string" || !optionsOf(d).some((o) => o.key === s.option)) return { note: `dropped a resolution: "${String(s.option).slice(0, 40)}" is not an option of the open decision` }; - if (s.reason === undefined || s.reason === null || s.reason === "") return { value: { kind: "answer", decision: d.id, option: s.option, stamp } }; - if (typeof s.reason !== "string") return { note: "dropped a resolution whose settle reason is not text" }; - // Only an option that closes with a comment takes a reason; for any other the field is ignored. - if (!/\bcloses\b/.test(writeEffect(d.kind as Kind, s.option) ?? "")) return { value: { kind: "answer", decision: d.id, option: s.option, stamp } }; - // The reason goes into the closing comment, which a quiet pull request never gets. - if (d.repo && d.number !== null && (await loadQuiet(db, [`${d.repo}#${d.number}`])).size > 0) return { note: "dropped a resolution: a quiet pull request's closing comment takes no reason" }; - const reason = cleanReason(cleanComment(s.reason)); - if (!reason) return { value: { kind: "answer", decision: d.id, option: s.option, stamp } }; - if (REFERENCE_LEAK.test(reason)) return { note: "dropped a resolution whose settle reason mentions the reference folder or its documentation" }; - return { value: { kind: "answer", decision: d.id, option: s.option, stamp, reason } }; - case "backlog": - return { value: { kind: "backlog", decision: d.id, stamp } }; - case "handled": { - const summary = typeof s.summary === "string" ? cleanComment(s.summary).replace(/\s+/g, " ") : ""; - if (!summary) return { note: "dropped a resolution that settles as handled without a summary" }; - if (REFERENCE_LEAK.test(summary)) return { note: "dropped a resolution whose summary mentions the reference folder or its documentation" }; - if (summary.length > RESOLVE_MAX) return { note: `dropped a resolution with a summary longer than ${RESOLVE_MAX} characters` }; - return { value: { kind: "handled", decision: d.id, summary, stamp } }; +/** One step as the model wrote it, checked; `merging`: an open_issue step becomes a follow-up of the merge. */ +function checkStep(f: CardFacts, st: Record, removing: readonly string[], drop: ReadonlySet): Checked { + const open = isOpen(f), ref = `${f.repo}#${f.n}`; + switch (st.kind) { + case "comment": return { value: { kind: "comment" } }; + case "label": case "unlabel": { + const l = labelOf(st.label); + if ("note" in l) return l; + if (!open) return { note: `dropped a resolution: ${ref} is not open` }; + const remove = st.kind === "unlabel"; + const have = f.item?.labels ?? []; + if (remove && !have.some((x) => sameLabel(x, l.value))) return { note: `dropped a resolution: the item does not have the label "${l.value}"` }; + const other = remove ? null : otherTypeLabel(have, l.value, removing); + if (other) return { note: `dropped a resolution: the item already has the type label "${other}" and an item has one type label` }; + return { value: { kind: "label", label: l.value, remove } }; + } + case "close": + if (!open) return { note: `dropped a resolution: ${ref} is not open` }; + return { value: { word: "close", pr: isPr(f) } }; + case "duplicate": { + const of = st.of; + if (!Number.isInteger(of) || of === f.n) return { note: "dropped a resolution whose duplicate step names no other item number" }; + if (!f.known.has(of as number)) return { note: `dropped a resolution: ${f.repo}#${of as number} is not in the mirror` }; + if (!open) return { note: `dropped a resolution: ${ref} is not open` }; + return { value: { word: "close", pr: isPr(f), duplicateOf: of as number } }; + } + case "review": case "fixup": + if (!isPr(f) || !open) return { note: `dropped a resolution: a ${String(st.kind)} step needs an open PR` }; + if (st.kind === "review") return { value: { word: "review" } }; + if (st.merge !== undefined && typeof st.merge !== "boolean") return { note: "dropped a resolution whose fixup merge is not true or false" }; + return { value: { word: "fix-up", merge: st.merge === true } }; + case "reopen": + if (f.item?.state !== "CLOSED") return { note: `dropped a resolution: ${ref} is not closed` }; + return { value: { word: "reopen" } }; + case "open_issue": { + const repo = bareRepo(st.repo); + if (typeof repo !== "string" || !f.tracked.has(repo)) return { note: `dropped a resolution: "${String(st.repo).slice(0, 40)}" is not a tracked repository` }; + const title = issueText(st.title, ISSUE_TITLE_MAX, "title", drop, true); + if ("note" in title) return title; + const body = issueText(st.body, COMMENT_MAX, "body", drop, false); + if ("note" in body) return body; + return { value: { repo, title: title.value, body: body.value } }; + } + case "transfer": { + const to = bareRepo(st.to); + if (isPr(f)) return { note: "dropped a resolution: only an issue can be moved to another repository" }; + if (typeof to !== "string" || !f.tracked.has(to) || to === f.repo) return { note: `dropped a resolution: "${String(to).slice(0, 40)}" is not another tracked repository` }; + if (ownerOf(to).toLowerCase() !== ownerOf(f.repo).toLowerCase()) return { note: "dropped a resolution: an issue moves only between repositories of one owner" }; + if (!open) return { note: `dropped a resolution: ${ref} is not open` }; + return { value: { word: "transfer", to } }; + } + case "assign": { + const login = st.login; + if (typeof login !== "string" || !LOGIN.test(login)) return { note: "dropped a resolution whose assign step has no GitHub login" }; + if (!sameLogin(f.item?.author, login) && !f.writers.has(login.toLowerCase())) return { note: `dropped a resolution: ${login} is neither the author nor known to have write access to ${f.repo}` }; + return { value: { word: "assign", login } }; + } + case "request_reviewers": { + if (!isPr(f)) return { note: "dropped a resolution: reviewers can be requested on a PR only" }; + const raw = st.logins; + if (!Array.isArray(raw) || raw.length < 1 || raw.length > 3 || raw.some((x) => typeof x !== "string" || !LOGIN.test(x))) return { note: "dropped a resolution whose request_reviewers step does not list one to three GitHub logins" }; + const logins = raw as string[]; + if (new Set(logins.map((x) => x.toLowerCase())).size !== logins.length) return { note: "dropped a resolution that requests the same reviewer twice" }; + const bad = logins.find((x) => sameLogin(f.item?.author, x) || !f.writers.has(x.toLowerCase())); + if (bad) return { note: `dropped a resolution: ${bad} is the PR's author or not known to have write access to ${f.repo}` }; + return { value: { word: "request_reviewers", logins } }; } default: - return { note: `dropped a resolution with unknown settle "${String(s.kind).slice(0, 40)}"` }; + return { note: `dropped a resolution with unknown step "${String(st.kind).slice(0, 40)}"` }; } } -/** The steps that settle an open decision as handled when the model named no settlement: they end the item here or hand the PR to a pipeline step. */ -type Settling = Extract; -export const isSettling = (x: Step): x is Settling => x.kind === "close" || x.kind === "duplicate" || x.kind === "transfer" || x.kind === "review" || x.kind === "fixup"; - -async function closeSettle(db: Db, repo: string, d: DecisionRow, st: Settling): Promise { - const summary = st.kind === "duplicate" ? `Closed as a duplicate of ${ref(repo, st.of)} in the conversation` - : st.kind === "transfer" ? `Moved to ${st.to} in the conversation` - : st.kind === "review" ? "Reviewed again" - : st.kind === "fixup" ? (st.merge ? "Fixed up and queued to merge" : "Fixed up") - : st.pr ? "Closed in the conversation" : `Closed as ${st.reason === "completed" ? "completed" : "not planned"} in the conversation`; - return { kind: "handled", decision: d.id, summary, stamp: await decisionStamp(db, d), fromClose: true }; -} +const isFollowUp = (v: object): v is FollowUp => "title" in v && "body" in v && !("word" in v); +const isCommand = (v: object): v is Command => "word" in v; /** - * One resolution as the model wrote it, checked against the item, or why it is dropped. Rules: at most one comment step and one - * close or duplicate step, which comes last; with an open decision the card settles it (a lone comment step may leave it open: the - * "ask" card); a close, duplicate, transfer, review or fixup step settles it as handled; an answer whose option already writes to GitHub - * takes no close, duplicate, transfer, reopen, reviewer, review or fixup step, and a comment only when the answer merges (an issue, label or assignee step is fine); - * the one exception is a scope answer that keeps the PR in core (take, small-extra) with a fixup step: the answer is recorded before the fix-up runs, so the review and the merge see the PR in core; - * without an open decision there is no settlement. At most one step of each kind except label and unlabel; close, duplicate and - * transfer end the item (at most one, last); reopen comes first and only on a closed item; a fixup that merges needs an open merge or scope decision on a PR. + * One resolution as the model wrote it, checked against the item, as the cards that carry out its steps (comments and labels first, + * then the commands), or why it is dropped. Rules: at most one step of each kind except label and unlabel; close, duplicate and transfer + * end the item (at most one, last); reopen comes first and not with an ending step; no review or fixup with an ending step. An open_issue + * step of a resolution that merges (a fixup that merges, or a merge settlement) is held until the merge. A settlement of `merge` or `backlog` + * becomes that command; any other settlement is dropped with a note. */ -async function validateResolution(db: Db, repo: string, n: number, c: Record, drop: ReadonlySet): Promise<{ card: NewCard } | { note: string }> { +export function validateResolution(f: CardFacts, c: Record, drop: ReadonlySet, notes: string[]): Checked { if (!Array.isArray(c.steps) || c.steps.length > MAX_STEPS) return { note: "dropped a resolution without a list of steps" }; - const steps: Step[] = []; - const removing = c.steps.flatMap((x) => (x && (x as { kind?: unknown }).kind === "unlabel" && typeof (x as { label?: unknown }).label === "string" ? [(x as { label: string }).label] : [])); - for (const raw of c.steps) { - const st = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record : {}; - let r: Checked; - switch (st.kind) { - case "comment": r = { value: { kind: "comment" } }; break; - case "label": r = await labelStep(db, repo, n, st.label, removing); break; - case "close": r = await closeStep(db, repo, n, st.reason); break; - case "duplicate": r = await duplicateStep(db, repo, n, st.of); break; - case "unlabel": r = await unlabelStep(db, repo, n, st.label); break; - case "reopen": r = await reopenStep(db, repo, n); break; - case "open_issue": r = await openIssueStep(db, st, drop); break; - case "transfer": r = await transferStep(db, repo, n, st.to); break; - case "assign": r = await assignStep(db, repo, n, st.login); break; - case "request_reviewers": r = await reviewersStep(db, repo, n, st.logins); break; - case "review": case "fixup": r = await pipelineStep(db, repo, n, st); break; - default: r = { note: `dropped a resolution with unknown step "${String(st.kind).slice(0, 40)}"` }; - } + const raws = c.steps.map((x) => (x && typeof x === "object" && !Array.isArray(x) ? x as Record : {})); + const removing = raws.flatMap((x) => (x.kind === "unlabel" && typeof x.label === "string" ? [x.label] : [])); + const kinds = raws.map((x) => String(x.kind)); + const checked: (Command | FollowUp | { kind: "comment" } | { kind: "label"; label: string; remove: boolean })[] = []; + for (const st of raws) { + const r = checkStep(f, st, removing, drop); if ("note" in r) return r; - steps.push(r.value); + checked.push(r.value); } - if (steps.some((x) => PUBLIC_TEXT_STEPS.has(x.kind)) && (await loadQuiet(db, [`${repo}#${n}`])).size > 0) return { note: "dropped a resolution that posts text on a quiet pull request" }; - const labels = steps.flatMap((x) => (x.kind === "label" ? [x.label] : [])); - if (new Set(labels).size !== labels.length) return { note: "dropped a resolution that adds the same label twice" }; - if (labels.filter(isTypeLabel).length > 1) return { note: "dropped a resolution that adds more than one type label" }; - const unlabels = steps.flatMap((x) => (x.kind === "unlabel" ? [x.label] : [])); - if (new Set(unlabels).size !== unlabels.length) return { note: "dropped a resolution that removes the same label twice" }; - if (unlabels.some((l) => labels.includes(l))) return { note: "dropped a resolution that adds and removes the same label" }; - const count = (k: Step["kind"]) => steps.filter((x) => x.kind === k).length; - for (const k of ["comment", "reopen", "open_issue", "assign", "request_reviewers", "review", "fixup"] as const) if (count(k) > 1) return { note: `dropped a resolution with more than one ${k} step` }; + const count = (k: string) => kinds.filter((x) => x === k).length; + for (const k of ["comment", "reopen", "open_issue", "assign", "request_reviewers", "review", "fixup"]) if (count(k) > 1) return { note: `dropped a resolution with more than one ${k} step` }; if (count("review") + count("fixup") > 1) return { note: "dropped a resolution with both a review and a fixup step" }; - if ((count("review") || count("fixup")) && (count("close") || count("duplicate"))) return { note: "dropped a resolution that closes the PR and also reviews or fixes it up" }; - const closing = steps.filter((x): x is Extract => x.kind === "close" || x.kind === "duplicate" || x.kind === "transfer"); - if (closing.length > 1) return { note: "dropped a resolution that ends the item twice (close, duplicate or transfer)" }; - if (closing.length === 1 && steps[steps.length - 1] !== closing[0]) return { note: "dropped a resolution whose close, duplicate or transfer step is not last" }; - if (count("reopen") === 1 && steps[0]!.kind !== "reopen") return { note: "dropped a resolution whose reopen step is not first" }; - if (count("reopen") === 1 && closing.length === 1) return { note: "dropped a resolution that reopens and ends the item" }; + const ending = kinds.filter((k) => k === "close" || k === "duplicate" || k === "transfer").length; + if (ending > 1) return { note: "dropped a resolution that ends the item twice (close, duplicate or transfer)" }; + if (ending === 1 && !["close", "duplicate", "transfer"].includes(kinds[kinds.length - 1]!)) return { note: "dropped a resolution whose close, duplicate or transfer step is not last" }; + if (ending === 1 && (count("review") || count("fixup"))) return { note: "dropped a resolution that closes the PR and also reviews or fixes it up" }; + if (count("reopen") === 1 && (kinds[0] !== "reopen" || ending === 1)) return { note: "dropped a resolution whose reopen step is not first or that also ends the item" }; + const labels = checked.flatMap((x) => ("kind" in x && x.kind === "label" ? [x] : [])); + const added = labels.filter((x) => !x.remove).map((x) => x.label), removed = labels.filter((x) => x.remove).map((x) => x.label); + if (new Set(added).size !== added.length || new Set(removed).size !== removed.length) return { note: "dropped a resolution that adds or removes the same label twice" }; + if (added.filter(isTypeLabel).length > 1) return { note: "dropped a resolution that adds more than one type label" }; + if (added.some((l) => removed.includes(l))) return { note: "dropped a resolution that adds and removes the same label" }; + if (f.quiet && kinds.some((k) => k === "comment" || k === "open_issue" || k === "transfer")) return { note: "dropped a resolution that posts text on a quiet pull request" }; let text: string | null = null; if (count("comment") === 1) { const t = commentText(c.text, drop); @@ -551,67 +403,49 @@ async function validateResolution(db: Db, repo: string, n: number, c: Record x.kind === "fixup"); - if (fix?.kind === "fixup" && fix.merge && (!d || (d.kind !== "merge" && d.kind !== "scope" && d.kind !== "hold"))) return { note: "dropped a resolution: a fixup that merges needs an open merge, scope or hold decision on the PR" }; - const settling = steps.find(isSettling); - if (settling) { - const keeps = settling.kind === "fixup" && d?.kind === "scope" && settle?.kind === "answer" && KEEP_IN_CORE.includes(settle.option); - if (settle && settle.kind !== "handled" && !keeps) return { note: `dropped a resolution that has a ${settling.kind} step and settles the question another way than handled` }; - if (d && !settle) settle = await closeSettle(db, repo, d, settling); - } - if (settle?.kind === "answer") { - const effect = await decisionWrite(db, settle.decision, settle.option); - // Merging takes a comment too (posted before the answer); closing options use their reason as the comment. - const merges = /\bmerges\b/.test(effect ?? ""); - if (effect && steps.some((x) => ["close", "duplicate", "transfer", "reopen", "request_reviewers", "review", "fixup", ...(merges ? [] : ["comment"])].includes(x.kind))) { - return { note: `dropped a resolution: the answer already writes to GitHub, so it takes only ${merges ? "comment, " : ""}label, assign and open_issue steps` }; - } - } - if (d && !settle && !(steps.length === 1 && steps[0]!.kind === "comment")) return { note: "dropped a resolution that leaves the open decision unsettled" }; - if (!settle && steps.length === 0) return { note: "dropped a resolution without steps or settlement" }; - const params: CardParams = { kind: "resolution", steps, settle }; - return { card: { params, text, description: await describe(db, repo, n, params) } }; + const commands = checked.filter((x): x is Command => isCommand(x)); + const issues = checked.filter((x): x is FollowUp => isFollowUp(x)); + const s = c.settle && typeof c.settle === "object" && !Array.isArray(c.settle) ? c.settle as Record : null; + const fix = commands.find((x): x is Extract => x.word === "fix-up"); + if (s?.kind === "answer" && s.option === "merge" && !fix) { + if (!isPr(f) || !isOpen(f) || ending) return { note: "dropped a resolution: a merge needs an open PR" }; + commands.push({ word: "merge" }); + } else if (s?.kind === "answer" && s.option === "merge" && fix) fix.merge = true; + else if (s?.kind === "backlog") commands.push({ word: "backlog" }); + else if (s) notes.push("dropped a settlement: questions are answered with commands now"); + const merging = commands.find((x): x is Extract => x.word === "merge" || (x.word === "fix-up" && x.merge)); + if (issues.length && merging) merging.followups = issues; + else commands.push(...issues.map((i): Command => ({ word: "open_issue", ...i }))); + const params: CardParams[] = [ + ...(text !== null ? [{ kind: "comment" } as const] : []), + ...labels.map((l): CardParams => ({ kind: "label", label: l.label, remove: l.remove })), + ...commands.map((command): CardParams => ({ kind: "command", command })), + ]; + if (!params.length) return { note: "dropped a resolution without steps" }; + return { value: params.map((p) => ({ params: p, text: p.kind === "comment" ? text : null, description: describe(f.repo, f.n, p) })) }; } -/** One card as the model wrote it, checked against the item, or why it is dropped. Only resolutions are accepted. */ -export async function validateCard(db: Db, repo: string, n: number, raw: unknown, drop: ReadonlySet = new Set()): Promise<{ card: NewCard } | { note: string }> { - if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { note: "dropped a card that is not an object" }; - const c = raw as Record; - if (c.kind !== "resolution") return { note: `dropped a card with unknown action "${String(c.kind).slice(0, 40)}"` }; - return await validateResolution(db, repo, n, c, drop); -} - -/** The "ask and keep the question open" card: a lone comment step on an item with an open decision. */ -const isAsk = (c: NewCard): boolean => c.params.kind === "resolution" && !c.params.settle; - export type Parsed = { text: string; cards: NewCard[]; notes: string[] }; -/** Resolutions per reply beyond one per option of the decision: outcomes no option covers (handled, a close, a step-only action). */ -const MAX_EXTRA = 2; +/** Cards per reply. */ +const MAX_CARDS = 8; const FENCE = /```actions[ \t]*\r?\n([\s\S]*?)```[ \t]*$/; -/** The cleaned text of each public text of a reply (a comment, an issue's body), with its field (`cards[i].text`, `cards[i].steps[j].body`, i the position in the actions block), for the reference checks. */ -export function commentTexts(reply: string): { field: string; text: string }[] { +const listOf = (reply: string): { m: RegExpExecArray | null; list: unknown } => { const m = FENCE.exec(reply.trimEnd()); - if (!m) return []; - let list: unknown; - try { list = JSON.parse(m[1]!); } catch { return []; } + if (!m) return { m, list: undefined }; + try { return { m, list: JSON.parse(m[1]!) }; } catch { return { m, list: null }; } +}; + +/** The cleaned text of each public text of a reply (a comment, an issue's title and body), with its field, for the reference checks. */ +export function commentTexts(reply: string): { field: string; text: string }[] { + const { list } = listOf(reply); if (!Array.isArray(list)) return []; - return list.slice(0, 20).flatMap((c: { kind?: unknown; text?: unknown; steps?: unknown; settle?: { reason?: unknown } | null }, i) => { + return list.slice(0, 20).flatMap((c: { kind?: unknown; text?: unknown; steps?: unknown }, i) => { if (!c || c.kind !== "resolution") return []; const out: { field: string; text: string }[] = []; const text = typeof c.text === "string" ? cleanComment(c.text) : ""; if (text) out.push({ field: `cards[${i}].text`, text }); - const reason = typeof c.settle?.reason === "string" ? cleanComment(c.settle.reason) : ""; - if (reason) out.push({ field: `cards[${i}].settle.reason`, text: reason }); if (Array.isArray(c.steps)) c.steps.forEach((st: { kind?: unknown; body?: unknown; title?: unknown }, j) => { if (!st || st.kind !== "open_issue") return; const body = typeof st.body === "string" ? cleanComment(st.body) : "", title = typeof st.title === "string" ? cleanComment(st.title).replace(/\s+/g, " ") : ""; @@ -622,39 +456,53 @@ export function commentTexts(reply: string): { field: string; text: string }[] { }); } -/** The reply's text and its valid cards. A reply with no text gets null. `drop`: cleaned comment texts the reply lint still flagged after the fix turn; their cards are dropped. */ -export async function parseReply(db: Db, repo: string, n: number, reply: string, drop: ReadonlySet = new Set()): Promise { - const m = FENCE.exec(reply.trimEnd()); +/** The item numbers and logins the reply's steps name, so one load reads them all. */ +function namesOf(list: unknown[]): { numbers: number[]; logins: string[] } { + const numbers: number[] = [], logins: string[] = []; + for (const c of list) { + const steps = (c as { steps?: unknown } | null)?.steps; + if (!Array.isArray(steps)) continue; + for (const st of steps as Record[]) { + if (!st || typeof st !== "object") continue; + if (st.kind === "duplicate" && typeof st.of === "number") numbers.push(st.of); + if (st.kind === "assign" && typeof st.login === "string") logins.push(st.login); + if (st.kind === "request_reviewers" && Array.isArray(st.logins)) logins.push(...st.logins.filter((x): x is string => typeof x === "string")); + } + } + return { numbers, logins }; +} + +/** The reply's text and its cards, checked against `f`. A reply with no text gets null. `drop`: cleaned texts the reply lint still flagged; their resolutions are dropped. */ +export function parseReplyWith(f: CardFacts, reply: string, drop: ReadonlySet = new Set()): Parsed | null { + const { m, list } = listOf(reply); const text = (m ? reply.trimEnd().slice(0, m.index) : reply).trim(); if (!text) return null; const notes: string[] = []; const cards: NewCard[] = []; - if (m) { - let list: unknown; - try { list = JSON.parse(m[1]!); } catch { list = null; } - if (!Array.isArray(list)) notes.push("dropped the actions block: it is not a JSON list"); - else { - const hasDecision = !!await openDecision(db, repo, n); - let asks = 0, extras = 0; - const options = new Set(); - for (const raw of list.slice(0, 20)) { - const v = await validateCard(db, repo, n, raw, drop); - if (!("card" in v)) { notes.push(v.note); continue; } - if (hasDecision && isAsk(v.card)) { - if (asks++ >= 1) notes.push("dropped a second card that only asks and keeps the question open"); - else cards.push(v.card); - } else { - const s = v.card.params.kind === "resolution" ? v.card.params.settle : null; - const option = s?.kind === "answer" ? s.option : s?.kind === "backlog" ? "backlog" : null; - if (option !== null) { - if (options.has(option)) notes.push("dropped a second resolution for the same option"); - else { options.add(option); cards.push(v.card); } - } else if (extras++ >= MAX_EXTRA) notes.push(`dropped a resolution beyond the ${MAX_EXTRA} extra outcomes allowed per reply`); - else cards.push(v.card); - } + if (m && !Array.isArray(list)) notes.push("dropped the actions block: it is not a JSON list"); + else if (Array.isArray(list)) { + const seen = new Set(); + for (const raw of list.slice(0, 20)) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { notes.push("dropped a card that is not an object"); continue; } + const c = raw as Record; + if (c.kind !== "resolution") { notes.push(`dropped a card with unknown action "${String(c.kind).slice(0, 40)}"`); continue; } + const v = validateResolution(f, c, drop, notes); + if ("note" in v) { notes.push(v.note); continue; } + for (const card of v.value) { + const key = card.params.kind === "command" ? `command:${card.params.command.word}` : card.params.kind === "label" ? `label:${card.params.label.toLowerCase()}` : `comment:${card.text}`; + if (seen.has(key)) { notes.push(`dropped a second card that does the same: ${card.description}`); continue; } + if (cards.length >= MAX_CARDS) { notes.push(`dropped the cards beyond the ${MAX_CARDS}th`); break; } + seen.add(key); + cards.push(card); } - if (list.length > 20) notes.push("dropped the cards beyond the twentieth"); } + if (list.length > 20) notes.push("dropped the cards beyond the twentieth"); } return { text, cards, notes }; } + +/** parseReplyWith over the facts of the item and of the names the reply mentions, loaded in one wave. */ +export async function parseReply(db: Db, repo: string, n: number, reply: string, drop: ReadonlySet = new Set()): Promise { + const { list } = listOf(reply); + return parseReplyWith(await loadCardFacts(db, repo, n, Array.isArray(list) ? namesOf(list) : {}), reply, drop); +} diff --git a/src/conversations/queue.ts b/src/conversations/queue.ts index 5811bb19c..d4a530bbe 100644 --- a/src/conversations/queue.ts +++ b/src/conversations/queue.ts @@ -3,38 +3,25 @@ // queued cards in order (item priority level, then the time of the press) once room returns, which is 00:00 UTC or an operator's // raise of the limit. Waiting for room is the registered "Daily limit" wait (src/stages/registry.ts); no timer runs. // Card writes and Act's closes share one count (src/conversations/usage.ts), held to the Act limit. -import { holdsIssues, type CardParams } from "./cards.ts"; +import { readParams, type CardParams } from "./cards.ts"; import { loadActRoom, loadQueue, type ActRoom } from "../data/conversations/index.ts"; import type { Db } from "../db/index.ts"; /** What a queued card needs to run later as the press would have run: the presser's choices at the time. */ -export type QueueArgs = { skip?: number[]; note?: string; noteStaysOut?: boolean; role?: string }; - -const WRITE_STEPS_ONE = new Set(["comment", "label", "close", "unlabel", "reopen", "open_issue", "transfer", "assign", "request_reviewers"]); +export type QueueArgs = { note?: string; noteStaysOut?: boolean; role?: string }; /** - * The GitHub writes a card makes when pressed: one per write step, two for a close that comes with a comment and for a duplicate close. Review and - * fix-up steps start pipeline work and write nothing here; an issue the card holds until the merge is counted when it is filed (src/conversations/held.ts). + * The GitHub writes a card makes when pressed: one for a comment or a label. A command writes nothing here: it runs through the + * workflow, whose steps and person actions keep their own counts; an issue a merging command holds is counted when it is filed + * (src/conversations/held.ts). */ -export function cardWriteCount(params: CardParams, text: string | null): number { - switch (params.kind) { - case "comment": case "label": return 1; - case "close": return text ? 2 : 1; - case "duplicate": return 2; - case "resolution": { - const held = holdsIssues(params); - return params.steps.reduce((n, s) => n + (s.kind === "duplicate" ? 2 : s.kind === "open_issue" && held ? 0 : WRITE_STEPS_ONE.has(s.kind) ? 1 : 0), 0); - } - default: return 0; - } +export function cardWriteCount(params: CardParams | null): number { + return params?.kind === "comment" || params?.kind === "label" ? 1 : 0; } -/** Writes the queued card still makes: the card's writes minus the steps the presser removed. */ -export function needOf(c: { params: string; text: string | null; queue_args?: string | null }): number { - const params = JSON.parse(c.params) as CardParams; - const args = JSON.parse(c.queue_args ?? "{}") as QueueArgs; - const left = params.kind === "resolution" && args.skip?.length ? { ...params, steps: params.steps.filter((_, k) => !args.skip!.includes(k)) } : params; - return cardWriteCount(left, c.text); +/** Writes the queued card still makes. */ +export function needOf(c: { kind: string; params: string }): number { + return cardWriteCount(readParams(c.kind, c.params)); } /** @@ -74,9 +61,8 @@ export const queuePlace = async (db: Db, cardId: number): Promise /** The shown reason of a queued press. The place is read when shown, never stored. */ export const queueReason = (place: number | null): string => (place === null ? "daily GitHub write limit" : `daily GitHub write limit, #${place} in line`); -/** Whether any card other than `except` waits in the queue. */ -export const queuedAhead = async (db: Db, except?: number): Promise => - (await queuedCards(db)).some((r) => r.id !== except); +/** Whether any card other than `except` waits in the loaded queue. */ +export const queuedAhead = (queue: { rows: { id: number }[] }, except?: number): boolean => queue.rows.some((r) => r.id !== except); /** The first queued card and what it needs, for the planner: it proposes the drain only when the head fits. */ export async function queueHead(db: Db): Promise<{ repo: string; fits: boolean } | null> { diff --git a/src/data/conversations/cards.ts b/src/data/conversations/cards.ts index dc3f7e4c6..d897e73af 100644 --- a/src/data/conversations/cards.ts +++ b/src/data/conversations/cards.ts @@ -57,7 +57,7 @@ export async function loadActRoom(db: Db, now: Date): Promise { control.loadActUsage(db, reset && reset > day ? reset : day), running.length ? control.countCardWrites(db, running.map((r) => ({ id: r.id, since: r.acted_at ?? undefined }))) : Promise.resolve(new Map()), ])); - return { limit, used, running: running.map((r): RunningCard => ({ id: r.id, params: r.params, text: r.text, queue_args: r.queue_args, written: written.get(r.id) ?? 0 })) }; + return { limit, used, running: running.map((r): RunningCard => ({ id: r.id, kind: r.kind, params: r.params, text: r.text, queue_args: r.queue_args, written: written.get(r.id) ?? 0 })) }; } /** Compare-and-set on `state IN from`; true when the card moved. Keys of `set` that are undefined are left alone. */ diff --git a/src/data/conversations/types.ts b/src/data/conversations/types.ts index 5ca8929eb..c4633a173 100644 --- a/src/data/conversations/types.ts +++ b/src/data/conversations/types.ts @@ -35,7 +35,7 @@ export type CardPatch = Partial }; /** The pure rule `used + reserve + need <= limit` is feature code: it derives the reserve from `running` with the card write counts. */ -export type RunningCard = { id: number; params: string; text: string | null; queue_args: string | null; written: number }; +export type RunningCard = { id: number; kind: string; params: string; text: string | null; queue_args: string | null; written: number }; export type ActRoom = { limit: number | null; used: number; running: RunningCard[] }; export type NewHeld = { card_id: number; workflow_id: number | null; approved_at: string | null; repo: string; number: number; issue_repo: string; title: string; body: string; by: string; at: string }; diff --git a/src/data/mirror/comments.ts b/src/data/mirror/comments.ts index fe0422b71..e6a2cc1cd 100644 --- a/src/data/mirror/comments.ts +++ b/src/data/mirror/comments.ts @@ -94,6 +94,18 @@ export async function loadActivityByLogins(db: Db, repo: string, logins: string[ return new Set(logins.filter((l) => found.has(l.toLowerCase()))); } +/** Logins (lower case) with an item or a comment in the repo written under one of `associations` (GitHub's author association); the match ignores case. */ +export async function loadAuthoredIn(db: Db, repo: string, logins: string[], associations: string[]): Promise> { + if (!logins.length || !associations.length) return new Set(); + const q = queryDb(db); + const lower = [...new Set(logins.map((l) => l.toLowerCase()))]; + const rows = await q.all(q.k.selectFrom("items").select((eb) => eb.fn("lower", ["author"]).as("login")).where("repo", "=", repo).where((eb) => kx.inList(db, eb.fn("lower", ["author"]), lower)) + .where((eb) => kx.inList(db, "author_association", associations)) + .union(q.k.selectFrom("comments").select((eb) => eb.fn("lower", ["author"]).as("login")).where("repo", "=", repo).where((eb) => kx.inList(db, eb.fn("lower", ["author"]), lower)) + .where((eb) => kx.inList(db, "author_association", associations))), { label: "mirror.loadAuthoredIn" }); + return new Set(rows.map((r) => r.login)); +} + const MARKS: SnippetMarks = { open: "\u0002", close: "\u0003", words: 24 }; /** Full-text comment search, best first (lower score); `limit` defaults to 20. */ diff --git a/src/decide/choices-convert.ts b/src/decide/choices-convert.ts index 88bb50661..37ce5beb9 100644 --- a/src/decide/choices-convert.ts +++ b/src/decide/choices-convert.ts @@ -1,7 +1,7 @@ // Converts the resolution cards Opus proposed before the choices format into decision_choices drafts, without a model call. // `cardsToDrafts` is the pure mapping (also used for settling cards in a conversation turn); `convertOpenDecisions` applies it to the open decisions. -import type { CardParams, Step } from "../conversations/cards.ts"; -import { decisionStamp, openDecision } from "../conversations/cards.ts"; +import type { CardParams, Step } from "./choices-parse.ts"; +import { decisionStamp, openDecision } from "./choices-parse.ts"; import type { DecisionRow } from "../decisions.ts"; import { applyDrafts, coresFor, MAX_ADDED_CORES, withIds, writeChoices } from "./choices.ts"; import { coreKey, type ChoicesBlockExtra, type ChoicesRow, type CoreKey, type StoredDraft } from "./choices-types.ts"; diff --git a/src/decide/choices-parse.ts b/src/decide/choices-parse.ts index 429b4c056..ec1d32d69 100644 --- a/src/decide/choices-parse.ts +++ b/src/decide/choices-parse.ts @@ -1,6 +1,20 @@ // Reading the model's fenced `choices` block: every extra is checked with the step checkers, every core with its extras through // compose and validateCard. What fails is dropped with a note; what survives is what `writeChoices` and `mergeChoices` store. -import { applicableSteps, cleanComment, decisionStamp, openDecision, parseReply, type Parsed, commentText, labelStep, assignStep, reviewersStep, unlabelStep, openIssueStep, validateCard, type NewCard, type Step } from "../conversations/cards.ts"; +import { ownerOf, splitSlug } from "../owners.ts"; +import { REFERENCE_LEAK } from "../review/opus-parse.ts"; +import { writeEffect } from "../act/index.ts"; +import { cleanReason } from "../act/templates.ts"; +import { KEEP_IN_CORE } from "../core/rules.ts"; +import { backlogHeldExpr, notOwnIntegrationExpr } from "../dupes/held.ts"; +import { ALL_LABELS, isTypeLabel, sameLabel } from "../labels/set.ts"; +import { inScopeExpr } from "../data/workflow/fragments.ts"; +import { loadQuiet } from "../data/security/index.ts"; +import { LOGIN } from "../access.ts"; +import { cleanComment } from "../conversations/cards.ts"; +import { CLOSE_REASONS, COMMENT_MAX, INSTRUCTIONS_MAX, ISSUE_TITLE_MAX, RESOLVE_MAX, type CloseReason } from "../conversations/types.ts"; +import { findSeq, someSeq } from "../async-seq.ts"; +import type { Expression, SqlBool } from "kysely"; +import { getDecision, type Kind } from "../decisions.ts"; import { optionsOf, type DecisionRow } from "../decisions.ts"; import { addedCore, compose, coresFor, currentChoices, extraId, mergeChoices, MAX_ADDED_CORES, withIds, writeChoices, type Core, @@ -360,3 +374,606 @@ export function choicesJson(p: ParsedChoices): string { ...(p.drop.length && { drop: p.drop }), }); } + +// ---- the legacy card model: resolutions of steps that settle a decision (only the retired decision files use it) ---- +/** + * One step of a resolution. The comment step's text is the card's `text`. Every kind but `review` and `fixup` is one GitHub write + * through src/github/write.ts; `review` and `fixup` queue pipeline work. At most one step of each kind per card, except `label` + * and `unlabel`. `close`, `duplicate` and `transfer` end the item here and come last. + */ +export type Step = + | { kind: "comment" } + | { kind: "label"; label: string } + | { kind: "unlabel"; label: string } + | { kind: "close"; reason: CloseReason; pr: boolean } + | { kind: "duplicate"; of: number } + | { kind: "reopen" } + /** Opens a new issue in `repo` (this repo or another tracked one); title and body are the card's editable `issue` draft. */ + | { kind: "open_issue"; repo: string; title: string; body: string } + /** Issues only: moves the issue to another tracked repo of the same owner. */ + | { kind: "transfer"; to: string } + | { kind: "assign"; login: string } + /** PRs only. */ + | { kind: "request_reviewers"; logins: string[] } + /** PRs only: a fresh Opus review of the current head. */ + | { kind: "review" } + /** PRs only: a fix-up run with the operator-editable instructions; `merge` makes it a pre-approved merge (see Preapproval in web/src/api/types.ts). */ + | { kind: "fixup"; instructions: string; merge: boolean }; + +/** How a resolution ends the item's open decision. `stamp` identifies the decision state it was written for. */ +export type Settle = + /** `reason`: the public reason a closing option's comment gives (see settleOf); it replaces the decision's own text when the card runs. */ + | { kind: "answer"; decision: string; option: string; stamp: string; reason?: string } + /** `fromClose`: derived from the close or duplicate step, so its summary is false when that step is skipped. */ + | { kind: "handled"; decision: string; summary: string; stamp: string; fromClose?: true } + | { kind: "backlog"; decision: string; stamp: string }; + +/** The legacy kinds (everything below `resolution`) stay runnable for cards stored before resolutions; new Opus output only produces `resolution`. */ +export type CardParams = + | { kind: "resolution"; steps: Step[]; settle: Settle | null } + | { kind: "comment"; text: string } + | { kind: "answer"; option: string; decision: string; stamp?: string } + | { kind: "label"; label: string } + | { kind: "backlog"; decision: string; stamp?: string } + | { kind: "duplicate"; of: number } + | { kind: "resolve"; decision: string; summary: string; stamp?: string } + | { kind: "close"; reason: CloseReason; pr: boolean }; + +export type NewCard = { params: CardParams; text: string | null; description: string }; + +const legacyRef = (repo: string, n: number) => `${repo}#${n}`; + +/** The item's open decision: the newest unanswered one that is about this item alone and is not a duplicate-group decision. */ +export async function openDecision(db: Db, repo: string, n: number): Promise { + return await db.get(db.k.selectFrom("decisions").select(kx.cols("decisions")).$narrowType<{ kind: Kind }>().where("repo", "=", repo).where("number", "=", n) + .where("answer", "is", null).where((eb) => eb.not(kx.like(db, "id", eb.val("%:dupegroup:%")))).orderBy("asked_at", "desc").orderBy("id", "desc").limit(1)); +} + +/** Identifies the state of a decision a card was written for: its ask time and how often it was answered, undone or reopened. A re-ask or Reopen keeps the id, so the id alone cannot tell. */ +export async function decisionStamp(db: Db, d: DecisionRow): Promise { + const n = (await db.get(db.k.selectFrom("audit").select((eb) => eb.fn.countAll().as("n")).where("target", "=", d.id).where("action", "in", ["answer", "undo", "reopen"])))!.n; + return `${d.asked_at}|${n}`; +} + +const closeEffect = (p: { reason: CloseReason; pr: boolean }): string => p.pr ? "closes the PR on GitHub" : `closes the issue as ${p.reason === "completed" ? "completed" : "not planned"} on GitHub`; +const decisionWrite = async (db: Db, decision: string, option: string): Promise => { + const d = await getDecision(db, decision); + return d ? writeEffect(d.kind as Kind, option) : null; +}; + +/** The GitHub write that answering with this card's option causes later (the Act step does it), or null when it writes nothing. For a resolution: every closing write it makes, joined. */ +export async function cardEffect(db: Db, p: CardParams): Promise { + if (p.kind === "resolution") { + const parts: string[] = []; + for (const st of p.steps) { + if (st.kind === "close") parts.push(closeEffect(st)); + else if (st.kind === "duplicate") parts.push("closes it as a duplicate on GitHub"); + else if (st.kind === "transfer") parts.push(`moves the issue to ${st.to} on GitHub`); + else if (st.kind === "fixup" && st.merge) parts.push("merges the PR on GitHub once the fix-up, the review and CI pass"); + } + if (p.settle?.kind === "answer") { + const w = await decisionWrite(db, p.settle.decision, p.settle.option); + if (w) parts.push(w); + } + return parts.length ? parts.join("; ") : null; + } + if (p.kind === "close") return closeEffect(p); + if (p.kind !== "answer" || !p.decision) return null; + return await decisionWrite(db, p.decision, p.option); +} + +/** The word for a decision in the card lines: "scope", "close", "merge" ... ; "open" for kinds without a name of their own. */ +const questionWord = (d: DecisionRow | undefined): string => (d && d.kind !== "other" ? d.kind : "open"); +const optionLabel = (d: DecisionRow | undefined, key: string): string => (d ? optionsOf(d).find((x) => x.key === key)?.label : undefined) ?? key; + +/** + * Whether the card holds its open_issue step until the PR merges: it answers Merge, or its fix-up merges. The issue is filed after the merge + * (src/conversations/held.ts), so a PR that never merges leaves none behind. + */ +export const holdsIssues = (p: CardParams): boolean => + p.kind === "resolution" && ((p.settle?.kind === "answer" && p.settle.option === "merge") || p.steps.some((x) => x.kind === "fixup" && x.merge)); + +/** One plain line for a step. `held`: the card holds its issue until the merge (holdsIssues). */ +export function stepLine(st: Step, held = false): string { + switch (st.kind) { + case "comment": return "Post the comment below"; + case "label": return `Add the label "${st.label}"`; + case "close": return st.pr ? "Close the PR" : `Close the issue as ${st.reason === "completed" ? "completed" : "not planned"}`; + case "duplicate": return `Close as a duplicate of #${st.of}`; + case "unlabel": return `Remove the label "${st.label}"`; + case "reopen": return "Reopen it"; + case "open_issue": return `${held ? "After the merge: open" : "Open"} an issue in ${st.repo}: "${st.title}"`; + case "transfer": return `Move the issue to ${st.to}`; + case "assign": return `Assign ${st.login}`; + case "request_reviewers": return `Ask ${st.logins.join(", ")} for a review`; + case "review": return "Review the PR again"; + case "fixup": return st.merge ? "Fix up the PR as described below, then merge it if the review and CI pass" : "Fix up the PR as described below"; + } +} + +/** One plain line for how a card ends the open decision. */ +export async function settleLine(db: Db, s: Settle): Promise { + const d = await getDecision(db, s.decision); + switch (s.kind) { + case "answer": return `Answers the ${questionWord(d)} question with "${optionLabel(d, s.option)}"${s.reason ? `, giving the reason: ${s.reason}` : ""}`; + case "handled": return `Closes the ${questionWord(d)} question as handled: "${s.summary}"`; + case "backlog": return "Moves the item to the Backlog"; + } +} + +/** The steps and settlement lines of any card, resolution or legacy (`description` is the legacy card's one line). */ +export async function cardLines(db: Db, p: CardParams, description: string): Promise<{ steps: string[]; settles?: string }> { + if (p.kind === "resolution") return { steps: p.steps.map((x) => stepLine(x, holdsIssues(p))), ...(p.settle && { settles: await settleLine(db, p.settle) }) }; + const steps = [description]; + switch (p.kind) { + case "answer": return { steps: [], settles: await settleLine(db, { kind: "answer", decision: p.decision, option: p.option, stamp: p.stamp ?? "" }) }; + case "backlog": return { steps: [], settles: "Moves the item to the Backlog" }; + case "resolve": return { steps: [], settles: await settleLine(db, { kind: "handled", decision: p.decision, summary: p.summary, stamp: p.stamp ?? "" }) }; + case "close": case "duplicate": return { steps, settles: "Closes the open questions as handled" }; + default: return { steps }; + } +} + +/** The primary button's label: the action in a few words, from the parameters and the item. Server-written. */ +export async function buttonLabel(db: Db, p: CardParams): Promise { + switch (p.kind) { + case "resolution": { + const close = p.steps.find((x) => x.kind === "close"); + if (close) return close.pr ? "Close PR" : "Close issue"; + if (p.steps.some((x) => x.kind === "duplicate")) return "Close as duplicate"; + if (p.steps.some((x) => x.kind === "transfer")) return "Move issue"; + const fix = p.steps.find((x) => x.kind === "fixup"); + if (fix) return fix.merge ? "Fix up and merge" : "Fix up"; + if (p.steps.some((x) => x.kind === "review")) return "Review again"; + if (p.settle?.kind === "answer") return `Answer "${optionLabel(await getDecision(db, p.settle.decision), p.settle.option)}"`; + if (p.settle?.kind === "backlog") return "Move to Backlog"; + if (p.steps.some((x) => x.kind === "open_issue")) return "Open issue"; + if (p.settle) return "Close question"; + if (p.steps.some((x) => x.kind === "comment")) return "Post comment"; + for (const [kind, label] of [["reopen", "Reopen"], ["request_reviewers", "Ask for review"], ["assign", "Assign"], ["unlabel", "Remove label"]] as const) if (p.steps.some((x) => x.kind === kind)) return label; + return "Add label"; + } + case "comment": return "Post comment"; + case "answer": { + const d = await getDecision(db, p.decision); + return `Answer "${optionLabel(d, p.option)}"`; + } + case "label": return "Add label"; + case "backlog": return "Move to Backlog"; + case "resolve": return "Close decision"; + case "duplicate": return "Close as duplicate"; + case "close": return p.pr ? "Close PR" : "Close issue"; + } +} + +/** The card's first line: the button's action plus its key parameter ("Close issue as completed", "Close as duplicate of #12", "Move issue to "). Server-written. */ +export async function headline(db: Db, p: CardParams): Promise { + const closeOf = (pr: boolean, reason: CloseReason) => (pr ? "Close PR" : `Close issue as ${reason === "completed" ? "completed" : "not planned"}`); + switch (p.kind) { + case "resolution": { + const close = p.steps.find((x) => x.kind === "close"); + if (close?.kind === "close") return closeOf(close.pr, close.reason); + const dup = p.steps.find((x) => x.kind === "duplicate"); + if (dup?.kind === "duplicate") return `Close as duplicate of #${dup.of}`; + const move = p.steps.find((x) => x.kind === "transfer"); + if (move?.kind === "transfer") return `Move issue to ${move.to}`; + const open = p.steps.find((x) => x.kind === "open_issue"); + if (open?.kind === "open_issue" && await buttonLabel(db, p) === "Open issue") return `Open issue in ${open.repo}`; + return await buttonLabel(db, p); + } + case "duplicate": return `Close as duplicate of #${p.of}`; + case "close": return closeOf(p.pr, p.reason); + default: return await buttonLabel(db, p); + } +} + +/** The one-line description stored with a resolution: its steps and settlement. */ +export async function describe(db: Db, repo: string, n: number, p: CardParams & { kind: "resolution" }): Promise { + const lines = await cardLines(db, p, ""); + return `On ${legacyRef(repo, n)}: ${[...lines.steps, ...(lines.settles ? [lines.settles] : [])].join("; ")}`; +} + +/** Why Act would not close this item (an integration PR of ours, held by Backlog, outside the pilot), or null. */ +export async function closeRefusal(db: Db, repo: string, n: number): Promise { + const has = async (cond?: (eb: kx.AnyEb) => Expression) => !!await db.get(db.k.selectFrom("items as i").select((eb) => eb.lit(1).as("one")) + .where("i.repo", "=", repo).where("i.number", "=", n).$if(!!cond, (q) => q.where((eb) => cond!(eb)))); + if (!await has()) return `${legacyRef(repo, n)} is not in the mirror`; + if (!await has((eb) => notOwnIntegrationExpr(db, eb, "i"))) return `${legacyRef(repo, n)} is an integration PR the pipeline opened`; + if (!await has((eb) => inScopeExpr(db, eb, "i.repo", "i.number"))) return `${legacyRef(repo, n)} is outside the pilot`; + if (await has((eb) => backlogHeldExpr(db, eb, "i"))) return `${legacyRef(repo, n)} is held by a Backlog answer`; + return null; +} + +/** The type label the item has besides `label` (type labels are exclusive), or null. */ +export async function otherTypeLabel(db: Db, repo: string, n: number, label: string, removing: readonly string[] = []): Promise { + if (!isTypeLabel(label)) return null; + const row = await db.get(db.k.selectFrom("items").select("labels").where("repo", "=", repo).where("number", "=", n)); + let have: unknown[] = []; + try { have = JSON.parse(row?.labels ?? "[]") as unknown[]; } catch { /* unreadable labels count as none */ } + return have.map(String).find((l) => isTypeLabel(l) && !sameLabel(l, label) && !removing.some((r) => sameLabel(r, l))) ?? null; +} + +export type Checked = { value: T } | { note: string }; + +/** Model text for a comment step, cleaned and checked. */ +export function commentText(raw: unknown, drop: ReadonlySet): Checked { + const text = typeof raw === "string" ? cleanComment(raw) : ""; + if (!text) return { note: "dropped a resolution whose comment step has no text" }; + if (REFERENCE_LEAK.test(text) || drop.has(text)) return { note: "dropped a resolution whose comment mentions the reference folder or its documentation" }; + if (text.length > COMMENT_MAX) return { note: `dropped a resolution whose comment is longer than ${COMMENT_MAX} characters` }; + return { value: text }; +} + +export async function labelStep(db: Db, repo: string, n: number, raw: unknown, removing: readonly string[]): Promise> { + const l = typeof raw === "string" ? ALL_LABELS.find((x) => sameLabel(x.name, raw)) : undefined; + if (!l) return { note: `dropped a resolution: "${String(raw).slice(0, 40)}" is not a label the pipeline manages` }; + const other = await otherTypeLabel(db, repo, n, l.name, removing); + if (other) return { note: `dropped a resolution: the item already has the type label "${other}" and an item has one type label` }; + return { value: { kind: "label", label: l.name } }; +} + +export async function closeStep(db: Db, repo: string, n: number, reason: unknown): Promise> { + if (!CLOSE_REASONS.includes(reason as CloseReason)) return { note: "dropped a resolution whose close step has no reason of completed or not_planned" }; + const why = await closeRefusal(db, repo, n); + if (why) return { note: `dropped a resolution: ${why}` }; + const row = (await db.get(db.k.selectFrom("items").select(["kind", "state"]).where("repo", "=", repo).where("number", "=", n)))!; + if (row.state !== "OPEN") return { note: `dropped a resolution: ${legacyRef(repo, n)} is not open` }; + return { value: { kind: "close", reason: reason as CloseReason, pr: row.kind === "pr" } }; +} + +export async function duplicateStep(db: Db, repo: string, n: number, of: unknown): Promise> { + if (!Number.isInteger(of) || of === n) return { note: "dropped a resolution whose duplicate step names no other item number" }; + if (!await db.get(db.k.selectFrom("items").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", of as number))) return { note: `dropped a resolution: ${legacyRef(repo, of as number)} is not in the mirror` }; + const why = await closeRefusal(db, repo, n); + if (why) return { note: `dropped a resolution: ${why}` }; + return { value: { kind: "duplicate", of: of as number } }; +} + +type ItemFacts = { kind: string; state: string; author: string | null }; +const itemFacts = async (db: Db, repo: string, n: number): Promise => + await db.get(db.k.selectFrom("items").select(["kind", "state", "author"]).where("repo", "=", repo).where("number", "=", n)); +/** A repository name as the model wrote it, without a leading `owner/`. An owner that is not the repo's own leaves the value as written, which is no tracked repo. */ +const bareRepo = (v: unknown): unknown => { + if (typeof v !== "string" || !v.includes("/")) return v; + const { owner, name } = splitSlug(v); + return owner.toLowerCase() === ownerOf(name).toLowerCase() ? name : v; +}; +const isTracked = async (db: Db, repo: string): Promise => !!(await db.get(db.k.selectFrom("tracked_repos").select((eb) => eb.lit(1).as("one")).where("name", "=", repo))); +const sameLogin = (a: string | null, b: string): boolean => a !== null && a.toLowerCase() === b.toLowerCase(); + +/** + * Whether the mirror says `login` can write to `repo`: a cached permission of write or higher, or an association of owner, + * member or collaborator on an item or comment in the repo. The association is a hint only; Act reads the live permission before it writes. + */ +export async function mayWrite(db: Db, repo: string, login: string): Promise { + if (await db.get(db.k.selectFrom("repo_permissions").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("login", "=", login).where("permission", "in", ["write", "maintain", "admin"]))) return true; + return !!await db.get(db.k.selectFrom("items").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where((eb) => kx.ciEq(db, "author", eb.val(login))) + .where("author_association", "in", ["OWNER", "MEMBER", "COLLABORATOR"]) + .unionAll(db.k.selectFrom("comments").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where((eb) => kx.ciEq(db, "author", eb.val(login))) + .where("author_association", "in", ["OWNER", "MEMBER", "COLLABORATOR"])) + .limit(1)); +} + +const pr = (f: ItemFacts | undefined): boolean => f?.kind === "pr"; + +/** Model text for an issue title: cleaned like a comment, on one line. */ +function issueText(raw: unknown, max: number, what: string, drop: ReadonlySet, oneLineOnly: boolean): Checked { + const t = typeof raw === "string" ? (oneLineOnly ? cleanComment(raw).replace(/\s+/g, " ") : cleanComment(raw)) : ""; + if (!t) return { note: `dropped a resolution whose open_issue step has no ${what}` }; + if (REFERENCE_LEAK.test(t) || drop.has(t)) return { note: `dropped a resolution whose issue ${what} mentions the reference folder or its documentation` }; + if (t.length > max) return { note: `dropped a resolution whose issue ${what} is longer than ${max} characters` }; + return { value: t }; +} + +export async function openIssueStep(db: Db, st: Record, drop: ReadonlySet): Promise> { + const repo = bareRepo(st.repo); + if (typeof repo !== "string" || !await isTracked(db, repo)) return { note: `dropped a resolution: "${String(st.repo).slice(0, 40)}" is not a tracked repository` }; + const title = issueText(st.title, ISSUE_TITLE_MAX, "title", drop, true); + if ("note" in title) return title; + const body = issueText(st.body, COMMENT_MAX, "body", drop, false); + if ("note" in body) return body; + return { value: { kind: "open_issue", repo, title: title.value, body: body.value } }; +} + +export async function transferStep(db: Db, repo: string, n: number, toRaw: unknown): Promise> { + const to = bareRepo(toRaw); + const f = await itemFacts(db, repo, n); + if (pr(f)) return { note: "dropped a resolution: only an issue can be moved to another repository" }; + if (typeof to !== "string" || !await isTracked(db, to) || to === repo) return { note: `dropped a resolution: "${String(to).slice(0, 40)}" is not another tracked repository` }; + if (ownerOf(to).toLowerCase() !== ownerOf(repo).toLowerCase()) return { note: "dropped a resolution: an issue moves only between repositories of one owner" }; + const why = await closeRefusal(db, repo, n); + if (why) return { note: `dropped a resolution: ${why}` }; + if (f?.state !== "OPEN") return { note: `dropped a resolution: ${legacyRef(repo, n)} is not open` }; + return { value: { kind: "transfer", to } }; +} + +export async function assignStep(db: Db, repo: string, n: number, login: unknown): Promise> { + if (typeof login !== "string" || !LOGIN.test(login)) return { note: "dropped a resolution whose assign step has no GitHub login" }; + if (!sameLogin((await itemFacts(db, repo, n))?.author ?? null, login) && !await mayWrite(db, repo, login)) return { note: `dropped a resolution: ${login} is neither the author nor known to have write access to ${repo}` }; + return { value: { kind: "assign", login } }; +} + +export async function reviewersStep(db: Db, repo: string, n: number, raw: unknown): Promise> { + const f = await itemFacts(db, repo, n); + if (!pr(f)) return { note: "dropped a resolution: reviewers can be requested on a PR only" }; + if (!Array.isArray(raw) || raw.length < 1 || raw.length > 3 || raw.some((x) => typeof x !== "string" || !LOGIN.test(x))) return { note: "dropped a resolution whose request_reviewers step does not list one to three GitHub logins" }; + const logins = raw as string[]; + if (new Set(logins.map((x) => x.toLowerCase())).size !== logins.length) return { note: "dropped a resolution that requests the same reviewer twice" }; + const bad = await findSeq(logins, async (x) => sameLogin(f!.author, x) || !await mayWrite(db, repo, x)); + if (bad) return { note: `dropped a resolution: ${bad} is the PR's author or not known to have write access to ${repo}` }; + return { value: { kind: "request_reviewers", logins } }; +} + +export async function unlabelStep(db: Db, repo: string, n: number, raw: unknown): Promise> { + const l = typeof raw === "string" ? ALL_LABELS.find((x) => sameLabel(x.name, raw)) : undefined; + if (!l) return { note: `dropped a resolution: "${String(raw).slice(0, 40)}" is not a label the pipeline manages` }; + const row = await db.get(db.k.selectFrom("items").select("labels").where("repo", "=", repo).where("number", "=", n)); + let have: unknown[] = []; + try { have = JSON.parse(row?.labels ?? "[]") as unknown[]; } catch { /* unreadable labels count as none */ } + if (!have.some((x) => sameLabel(String(x), l.name))) return { note: `dropped a resolution: the item does not have the label "${l.name}"` }; + return { value: { kind: "unlabel", label: l.name } }; +} + +async function reopenStep(db: Db, repo: string, n: number): Promise> { + const f = await itemFacts(db, repo, n); + if (f?.state !== "CLOSED") return { note: `dropped a resolution: ${legacyRef(repo, n)} is not closed` }; + const why = await closeRefusal(db, repo, n); + return why ? { note: `dropped a resolution: ${why}` } : { value: { kind: "reopen" } }; +} + +export async function pipelineStep(db: Db, repo: string, n: number, st: Record): Promise> { + const f = await itemFacts(db, repo, n); + if (!pr(f) || f?.state !== "OPEN") return { note: `dropped a resolution: a ${String(st.kind)} step needs an open PR` }; + if (st.kind === "review") return { value: { kind: "review" } }; + const instructions = typeof st.instructions === "string" ? st.instructions.trim() : ""; + if (!instructions) return { note: "dropped a resolution whose fixup step has no instructions" }; + if (instructions.length > INSTRUCTIONS_MAX) return { note: `dropped a resolution whose fixup instructions are longer than ${INSTRUCTIONS_MAX} characters` }; + if (st.merge !== undefined && typeof st.merge !== "boolean") return { note: "dropped a resolution whose fixup merge is not true or false" }; + return { value: { kind: "fixup", instructions, merge: st.merge === true } }; +} + +const MAX_STEPS = 8; + +/** Steps that post model-written text on GitHub: not offered on a quiet pull request, whose fix must not be described in public before the advisory is published. */ +/** + * Whether a card's effect rests on the PR's code at the head it was written for: it posts a drafted comment or issue, or pushes a fix-up. + * Other cards (answer, backlog, hold, label, close, review, reviewers) still run after a push; these are refused until the choices are written again. + */ +export function dependsOnCode(params: CardParams, text: string | null): boolean { + switch (params.kind) { + case "comment": return true; + case "close": return text !== null && text.trim() !== ""; + case "resolution": return params.steps.some((x) => x.kind === "comment" || x.kind === "open_issue" || x.kind === "fixup") || (params.settle?.kind === "answer" && !!params.settle.reason?.trim()); + default: return false; + } +} + +export const PUBLIC_TEXT_STEPS: ReadonlySet = new Set(["comment", "open_issue", "transfer"]); + +/** The step kinds that can validate for the item as it is now, from the same facts and refusals as validateResolution; "fixup with merge" is listed apart. */ +export async function applicableSteps(db: Db, repo: string, n: number): Promise { + const f = await itemFacts(db, repo, n); + if (!f) return []; + const open = f.state === "OPEN", isPr = pr(f), out: string[] = ["open_issue"]; + const quiet = (await loadQuiet(db, [`${repo}#${n}`])).size > 0; + if (open) { + out.push("comment", "label", "assign"); + if (await someSeq(ALL_LABELS, async (l) => !("note" in await unlabelStep(db, repo, n, l.name)))) out.push("unlabel"); + if (!await closeRefusal(db, repo, n)) out.push("close", "duplicate"); + if (isPr) { + out.push("request_reviewers", "review", "fixup"); + const d = await openDecision(db, repo, n); + if (d && (d.kind === "merge" || d.kind === "scope" || d.kind === "hold")) out.push("fixup with merge"); + } else if (!await closeRefusal(db, repo, n)) out.push("transfer"); + } else if (f.state === "CLOSED" && !("note" in await reopenStep(db, repo, n))) out.push("reopen"); + return quiet ? out.filter((k) => !PUBLIC_TEXT_STEPS.has(k)) : out; +} + +/** The settlement the model asked for, checked against the item's open decision `d`. */ +async function settleOf(db: Db, d: DecisionRow, raw: unknown): Promise> { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { note: "dropped a resolution whose settle is not an object" }; + const s = raw as Record; + const stamp = await decisionStamp(db, d); + switch (s.kind) { + case "answer": + if (typeof s.option !== "string" || !optionsOf(d).some((o) => o.key === s.option)) return { note: `dropped a resolution: "${String(s.option).slice(0, 40)}" is not an option of the open decision` }; + if (s.reason === undefined || s.reason === null || s.reason === "") return { value: { kind: "answer", decision: d.id, option: s.option, stamp } }; + if (typeof s.reason !== "string") return { note: "dropped a resolution whose settle reason is not text" }; + // Only an option that closes with a comment takes a reason; for any other the field is ignored. + if (!/\bcloses\b/.test(writeEffect(d.kind as Kind, s.option) ?? "")) return { value: { kind: "answer", decision: d.id, option: s.option, stamp } }; + // The reason goes into the closing comment, which a quiet pull request never gets. + if (d.repo && d.number !== null && (await loadQuiet(db, [`${d.repo}#${d.number}`])).size > 0) return { note: "dropped a resolution: a quiet pull request's closing comment takes no reason" }; + const reason = cleanReason(cleanComment(s.reason)); + if (!reason) return { value: { kind: "answer", decision: d.id, option: s.option, stamp } }; + if (REFERENCE_LEAK.test(reason)) return { note: "dropped a resolution whose settle reason mentions the reference folder or its documentation" }; + return { value: { kind: "answer", decision: d.id, option: s.option, stamp, reason } }; + case "backlog": + return { value: { kind: "backlog", decision: d.id, stamp } }; + case "handled": { + const summary = typeof s.summary === "string" ? cleanComment(s.summary).replace(/\s+/g, " ") : ""; + if (!summary) return { note: "dropped a resolution that settles as handled without a summary" }; + if (REFERENCE_LEAK.test(summary)) return { note: "dropped a resolution whose summary mentions the reference folder or its documentation" }; + if (summary.length > RESOLVE_MAX) return { note: `dropped a resolution with a summary longer than ${RESOLVE_MAX} characters` }; + return { value: { kind: "handled", decision: d.id, summary, stamp } }; + } + default: + return { note: `dropped a resolution with unknown settle "${String(s.kind).slice(0, 40)}"` }; + } +} + +/** The steps that settle an open decision as handled when the model named no settlement: they end the item here or hand the PR to a pipeline step. */ +type Settling = Extract; +export const isSettling = (x: Step): x is Settling => x.kind === "close" || x.kind === "duplicate" || x.kind === "transfer" || x.kind === "review" || x.kind === "fixup"; + +async function closeSettle(db: Db, repo: string, d: DecisionRow, st: Settling): Promise { + const summary = st.kind === "duplicate" ? `Closed as a duplicate of ${legacyRef(repo, st.of)} in the conversation` + : st.kind === "transfer" ? `Moved to ${st.to} in the conversation` + : st.kind === "review" ? "Reviewed again" + : st.kind === "fixup" ? (st.merge ? "Fixed up and queued to merge" : "Fixed up") + : st.pr ? "Closed in the conversation" : `Closed as ${st.reason === "completed" ? "completed" : "not planned"} in the conversation`; + return { kind: "handled", decision: d.id, summary, stamp: await decisionStamp(db, d), fromClose: true }; +} + +/** + * One resolution as the model wrote it, checked against the item, or why it is dropped. Rules: at most one comment step and one + * close or duplicate step, which comes last; with an open decision the card settles it (a lone comment step may leave it open: the + * "ask" card); a close, duplicate, transfer, review or fixup step settles it as handled; an answer whose option already writes to GitHub + * takes no close, duplicate, transfer, reopen, reviewer, review or fixup step, and a comment only when the answer merges (an issue, label or assignee step is fine); + * the one exception is a scope answer that keeps the PR in core (take, small-extra) with a fixup step: the answer is recorded before the fix-up runs, so the review and the merge see the PR in core; + * without an open decision there is no settlement. At most one step of each kind except label and unlabel; close, duplicate and + * transfer end the item (at most one, last); reopen comes first and only on a closed item; a fixup that merges needs an open merge or scope decision on a PR. + */ +async function validateResolution(db: Db, repo: string, n: number, c: Record, drop: ReadonlySet): Promise<{ card: NewCard } | { note: string }> { + if (!Array.isArray(c.steps) || c.steps.length > MAX_STEPS) return { note: "dropped a resolution without a list of steps" }; + const steps: Step[] = []; + const removing = c.steps.flatMap((x) => (x && (x as { kind?: unknown }).kind === "unlabel" && typeof (x as { label?: unknown }).label === "string" ? [(x as { label: string }).label] : [])); + for (const raw of c.steps) { + const st = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record : {}; + let r: Checked; + switch (st.kind) { + case "comment": r = { value: { kind: "comment" } }; break; + case "label": r = await labelStep(db, repo, n, st.label, removing); break; + case "close": r = await closeStep(db, repo, n, st.reason); break; + case "duplicate": r = await duplicateStep(db, repo, n, st.of); break; + case "unlabel": r = await unlabelStep(db, repo, n, st.label); break; + case "reopen": r = await reopenStep(db, repo, n); break; + case "open_issue": r = await openIssueStep(db, st, drop); break; + case "transfer": r = await transferStep(db, repo, n, st.to); break; + case "assign": r = await assignStep(db, repo, n, st.login); break; + case "request_reviewers": r = await reviewersStep(db, repo, n, st.logins); break; + case "review": case "fixup": r = await pipelineStep(db, repo, n, st); break; + default: r = { note: `dropped a resolution with unknown step "${String(st.kind).slice(0, 40)}"` }; + } + if ("note" in r) return r; + steps.push(r.value); + } + if (steps.some((x) => PUBLIC_TEXT_STEPS.has(x.kind)) && (await loadQuiet(db, [`${repo}#${n}`])).size > 0) return { note: "dropped a resolution that posts text on a quiet pull request" }; + const labels = steps.flatMap((x) => (x.kind === "label" ? [x.label] : [])); + if (new Set(labels).size !== labels.length) return { note: "dropped a resolution that adds the same label twice" }; + if (labels.filter(isTypeLabel).length > 1) return { note: "dropped a resolution that adds more than one type label" }; + const unlabels = steps.flatMap((x) => (x.kind === "unlabel" ? [x.label] : [])); + if (new Set(unlabels).size !== unlabels.length) return { note: "dropped a resolution that removes the same label twice" }; + if (unlabels.some((l) => labels.includes(l))) return { note: "dropped a resolution that adds and removes the same label" }; + const count = (k: Step["kind"]) => steps.filter((x) => x.kind === k).length; + for (const k of ["comment", "reopen", "open_issue", "assign", "request_reviewers", "review", "fixup"] as const) if (count(k) > 1) return { note: `dropped a resolution with more than one ${k} step` }; + if (count("review") + count("fixup") > 1) return { note: "dropped a resolution with both a review and a fixup step" }; + if ((count("review") || count("fixup")) && (count("close") || count("duplicate"))) return { note: "dropped a resolution that closes the PR and also reviews or fixes it up" }; + const closing = steps.filter((x): x is Extract => x.kind === "close" || x.kind === "duplicate" || x.kind === "transfer"); + if (closing.length > 1) return { note: "dropped a resolution that ends the item twice (close, duplicate or transfer)" }; + if (closing.length === 1 && steps[steps.length - 1] !== closing[0]) return { note: "dropped a resolution whose close, duplicate or transfer step is not last" }; + if (count("reopen") === 1 && steps[0]!.kind !== "reopen") return { note: "dropped a resolution whose reopen step is not first" }; + if (count("reopen") === 1 && closing.length === 1) return { note: "dropped a resolution that reopens and ends the item" }; + let text: string | null = null; + if (count("comment") === 1) { + const t = commentText(c.text, drop); + if ("note" in t) return t; + text = t.value; + } else if (c.text !== undefined && c.text !== null && c.text !== "") return { note: "dropped a resolution with a comment text but no comment step" }; + + const d = await openDecision(db, repo, n); + let settle: Settle | null = null; + if (c.settle !== undefined && c.settle !== null) { + if (!d) return { note: "dropped a resolution: the item has no open decision to settle" }; + const s = await settleOf(db, d, c.settle); + if ("note" in s) return s; + settle = s.value; + } + const fix = steps.find((x) => x.kind === "fixup"); + if (fix?.kind === "fixup" && fix.merge && (!d || (d.kind !== "merge" && d.kind !== "scope" && d.kind !== "hold"))) return { note: "dropped a resolution: a fixup that merges needs an open merge, scope or hold decision on the PR" }; + const settling = steps.find(isSettling); + if (settling) { + const keeps = settling.kind === "fixup" && d?.kind === "scope" && settle?.kind === "answer" && KEEP_IN_CORE.includes(settle.option); + if (settle && settle.kind !== "handled" && !keeps) return { note: `dropped a resolution that has a ${settling.kind} step and settles the question another way than handled` }; + if (d && !settle) settle = await closeSettle(db, repo, d, settling); + } + if (settle?.kind === "answer") { + const effect = await decisionWrite(db, settle.decision, settle.option); + // Merging takes a comment too (posted before the answer); closing options use their reason as the comment. + const merges = /\bmerges\b/.test(effect ?? ""); + if (effect && steps.some((x) => ["close", "duplicate", "transfer", "reopen", "request_reviewers", "review", "fixup", ...(merges ? [] : ["comment"])].includes(x.kind))) { + return { note: `dropped a resolution: the answer already writes to GitHub, so it takes only ${merges ? "comment, " : ""}label, assign and open_issue steps` }; + } + } + if (d && !settle && !(steps.length === 1 && steps[0]!.kind === "comment")) return { note: "dropped a resolution that leaves the open decision unsettled" }; + if (!settle && steps.length === 0) return { note: "dropped a resolution without steps or settlement" }; + const params: CardParams = { kind: "resolution", steps, settle }; + return { card: { params, text, description: await describe(db, repo, n, params) } }; +} + +/** One card as the model wrote it, checked against the item, or why it is dropped. Only resolutions are accepted. */ +export async function validateCard(db: Db, repo: string, n: number, raw: unknown, drop: ReadonlySet = new Set()): Promise<{ card: NewCard } | { note: string }> { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { note: "dropped a card that is not an object" }; + const c = raw as Record; + if (c.kind !== "resolution") return { note: `dropped a card with unknown action "${String(c.kind).slice(0, 40)}"` }; + return await validateResolution(db, repo, n, c, drop); +} + +/** The "ask and keep the question open" card: a lone comment step on an item with an open decision. */ +const isLegacyAsk = (c: NewCard): boolean => c.params.kind === "resolution" && !c.params.settle; + +export type Parsed = { text: string; cards: NewCard[]; notes: string[] }; + +/** Resolutions per reply beyond one per option of the decision: outcomes no option covers (handled, a close, a step-only action). */ +const MAX_EXTRA = 2; +const LEGACY_FENCE = /```actions[ \t]*\r?\n([\s\S]*?)```[ \t]*$/; + +/** The cleaned text of each public text of a reply (a comment, an issue's body), with its field (`cards[i].text`, `cards[i].steps[j].body`, i the position in the actions block), for the reference checks. */ +export function commentTexts(reply: string): { field: string; text: string }[] { + const m = LEGACY_FENCE.exec(reply.trimEnd()); + if (!m) return []; + let list: unknown; + try { list = JSON.parse(m[1]!); } catch { return []; } + if (!Array.isArray(list)) return []; + return list.slice(0, 20).flatMap((c: { kind?: unknown; text?: unknown; steps?: unknown; settle?: { reason?: unknown } | null }, i) => { + if (!c || c.kind !== "resolution") return []; + const out: { field: string; text: string }[] = []; + const text = typeof c.text === "string" ? cleanComment(c.text) : ""; + if (text) out.push({ field: `cards[${i}].text`, text }); + const reason = typeof c.settle?.reason === "string" ? cleanComment(c.settle.reason) : ""; + if (reason) out.push({ field: `cards[${i}].settle.reason`, text: reason }); + if (Array.isArray(c.steps)) c.steps.forEach((st: { kind?: unknown; body?: unknown; title?: unknown }, j) => { + if (!st || st.kind !== "open_issue") return; + const body = typeof st.body === "string" ? cleanComment(st.body) : "", title = typeof st.title === "string" ? cleanComment(st.title).replace(/\s+/g, " ") : ""; + if (body) out.push({ field: `cards[${i}].steps[${j}].body`, text: body }); + if (title) out.push({ field: `cards[${i}].steps[${j}].title`, text: title }); + }); + return out; + }); +} + +/** The reply's text and its valid cards. A reply with no text gets null. `drop`: cleaned comment texts the reply lint still flagged after the fix turn; their cards are dropped. */ +export async function parseReply(db: Db, repo: string, n: number, reply: string, drop: ReadonlySet = new Set()): Promise { + const m = LEGACY_FENCE.exec(reply.trimEnd()); + const text = (m ? reply.trimEnd().slice(0, m.index) : reply).trim(); + if (!text) return null; + const notes: string[] = []; + const cards: NewCard[] = []; + if (m) { + let list: unknown; + try { list = JSON.parse(m[1]!); } catch { list = null; } + if (!Array.isArray(list)) notes.push("dropped the actions block: it is not a JSON list"); + else { + const hasDecision = !!await openDecision(db, repo, n); + let asks = 0, extras = 0; + const options = new Set(); + for (const raw of list.slice(0, 20)) { + const v = await validateCard(db, repo, n, raw, drop); + if (!("card" in v)) { notes.push(v.note); continue; } + if (hasDecision && isLegacyAsk(v.card)) { + if (asks++ >= 1) notes.push("dropped a second card that only asks and keeps the question open"); + else cards.push(v.card); + } else { + const s = v.card.params.kind === "resolution" ? v.card.params.settle : null; + const option = s?.kind === "answer" ? s.option : s?.kind === "backlog" ? "backlog" : null; + if (option !== null) { + if (options.has(option)) notes.push("dropped a second resolution for the same option"); + else { options.add(option); cards.push(v.card); } + } else if (extras++ >= MAX_EXTRA) notes.push(`dropped a resolution beyond the ${MAX_EXTRA} extra outcomes allowed per reply`); + else cards.push(v.card); + } + } + if (list.length > 20) notes.push("dropped the cards beyond the twentieth"); + } + } + return { text, cards, notes }; +} diff --git a/src/decide/choices.ts b/src/decide/choices.ts index 2c24dc765..f4bbd5f87 100644 --- a/src/decide/choices.ts +++ b/src/decide/choices.ts @@ -3,7 +3,7 @@ // Only Opus's drafts and pick are stored; the offered cores are computed whenever they are read. import { randomUUID } from "node:crypto"; import { writeEffect } from "../act/index.ts"; -import { applicableSteps } from "../conversations/cards.ts"; +import { applicableSteps } from "./choices-parse.ts"; import { getDecision, optionsOf, type DecisionRow, type Kind } from "../decisions.ts"; import { coreKey, MAX_ADDED_CORES, parseCoreKey, diff --git a/src/decide/prepare.ts b/src/decide/prepare.ts index a0d572e2a..057c61aa5 100644 --- a/src/decide/prepare.ts +++ b/src/decide/prepare.ts @@ -12,7 +12,7 @@ import { referenceDir } from "../reference.ts"; import { SUMMARY_MIN, summaryInput } from "../classify/parse.ts"; import { pool } from "../classify/run.ts"; import { itemsOf, optionsOf, factsOf, type DecisionRow, type Kind } from "../decisions.ts"; -import { openDecision, type NewCard } from "../conversations/cards.ts"; +import { openDecision, type NewCard } from "./choices-parse.ts"; import { choicesTexts, parseChoices, type ParsedChoices } from "./choices-parse.ts"; import { coreSummaries } from "./choices.ts"; import { parseCoreKey, type CoreKey } from "./choices-types.ts"; @@ -20,7 +20,7 @@ import { ensureConversation, insertTurn, opusBlock, refreshItem, turnsOf, type D import { CLAUDE_PROMPTS } from "../prompts/index.ts"; import { codeDiff } from "../review/diff.ts"; import { REPO_PATH } from "../sandbox/command.ts"; -import { applicableSteps } from "../conversations/cards.ts"; +import { applicableSteps } from "./choices-parse.ts"; import { inScopeExpr } from "../data/workflow/fragments.ts"; import { notOwnIntegrationExpr } from "../dupes/held.ts"; import { judgementModel } from "./judgement.ts"; diff --git a/src/preapproval/index.ts b/src/preapproval/index.ts index 24f3f9f59..5e5f99e6a 100644 --- a/src/preapproval/index.ts +++ b/src/preapproval/index.ts @@ -14,7 +14,6 @@ // advancePreapprovals on each runner tick: no timer and no wait of its own; the one time comparison (the start of the mirror's last sync against the push) is made when the tick runs anyway. Merging itself is never called from here. import { settleMemo, settlesNow } from "../settlers.ts"; import type { Preapproval } from "../../web/src/api/types.ts"; -import type { Step } from "../conversations/cards.ts"; import { systemBlock } from "../conversations/store.ts"; import { cifixBucket, decidePr, fixupOf, ownImplementation, reviseOf } from "../core/decide.ts"; import { loadPrFact, loadPrFacts } from "../core/facts.ts"; @@ -45,7 +44,7 @@ import { import type { Db } from "../db/index.ts"; import { INPUT_TOPICS } from "../runner/autopilot.ts"; -export type PipelineStep = Extract; +export type PipelineStep = { kind: "review" } | { kind: "fixup"; instructions: string; merge: boolean }; const ACTOR = "pipeline"; export const INSTRUCTIONS_MAX = 1500;