From fc311280417c94ef048474bcc02ced553d19698b Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 01:44:51 +0000 Subject: [PATCH] Conversation cards: validate and run unlabel, reopen, open_issue, transfer, assign, request_reviewers, review and fixup steps --- src/agents/steps.ts | 2 +- src/conversations/act.ts | 198 ++++++++++++++++++++++++++++++---- src/conversations/cards.ts | 176 ++++++++++++++++++++++++++---- src/conversations/types.ts | 4 + src/dash/api/admin.ts | 2 +- src/dash/api/conversations.ts | 26 ++++- src/github/actions.ts | 4 + src/github/write.ts | 34 ++++++ src/prompts/index.ts | 16 ++- test/conversations.test.ts | 36 +++++++ 10 files changed, 450 insertions(+), 48 deletions(-) diff --git a/src/agents/steps.ts b/src/agents/steps.ts index 065f6a877..6d76539c4 100644 --- a/src/agents/steps.ts +++ b/src/agents/steps.ts @@ -195,7 +195,7 @@ export type ConversationCtx = ReferenceCtx & { db: DatabaseSync; repo: string; n export const CONVERSATION: ClaudeStep = { provider: "claude", id: "conversation.turn", toPrompt: (x) => [x], size: () => 1, - lint: { fields: ["cards[].text"], make: (_x, c) => async (text, stage) => (parseReply(c.db, c.repo, c.n, text) ? referenceProblems(commentTexts(text), c.dir, c.semantic, { stage }) : null) }, + lint: { fields: ["cards[].text", "cards[].steps[].body"], make: (_x, c) => async (text, stage) => (parseReply(c.db, c.repo, c.n, text) ? referenceProblems(commentTexts(text), c.dir, c.semantic, { stage }) : null) }, parse: (text, _x, ctx, c) => { const r = parseReply(c.db, c.repo, c.n, text, dropTexts(ctx.problems)); return r === null ? null : { value: r }; }, }; diff --git a/src/conversations/act.ts b/src/conversations/act.ts index 604685232..5870d1c20 100644 --- a/src/conversations/act.ts +++ b/src/conversations/act.ts @@ -6,13 +6,17 @@ import { readLive } from "../act/index.ts"; import { duplicateComment } from "../act/templates.ts"; import { audit } from "../dash/audit.ts"; import { optionsOf, BACKLOG, HANDLED, getDecision, reposOf, replaceProposedCards } from "../decisions.ts"; -import { addLabels, closeItem, commentOn, type Note, type Writer } from "../github/write.ts"; +import { GITHUB_ACTIONS } from "../github/actions.ts"; +import { addLabels, closeItem, commentOn, createIssue, IssueError, assignTo, removeLabel, reopenItem, requestReviewers, transferIssue, type Note, type Writer } from "../github/write.ts"; +import { exec as defaultExec, type Exec } from "../fixup/git.ts"; +import { runPipelineStep } from "../preapproval/index.ts"; +import type { CardEdit } from "../../web/src/api/types.ts"; import { repoLabels } from "../labels/github.ts"; import { Client, type Querier } from "../mirror.ts"; import { CLAUDE_PROMPTS } from "../prompts/index.ts"; -import { closeRefusal, decisionStamp, openDecision, otherTypeLabel, stepLine, type CardParams, type Settle } from "./cards.ts"; +import { closeRefusal, decisionStamp, isSettling, openDecision, otherTypeLabel, stepLine, type CardParams, type Settle, type Step } from "./cards.ts"; import { ConversationError, insertTurn, staleOf, systemBlock, type StoreDeps } from "./store.ts"; -import { COMMENT_MAX, NOTE_MAX, type CloseReason } from "./types.ts"; +import { COMMENT_MAX, INSTRUCTIONS_MAX, ISSUE_TITLE_MAX, NOTE_MAX, type CloseReason } from "./types.ts"; export type CardRow = { seen: string | null; @@ -21,7 +25,7 @@ export type CardRow = { }; /** `canWrite` is the signed-in operator's write access to a repo; the shell has none to check. */ -export type ActDeps = StoreDeps & { querier?: Querier; canWrite?: (repo: string) => Promise; /** Indexes into a resolution's steps the operator removed. */ skip?: number[]; /** The operator's note with the choice. */ note?: string }; +export type ActDeps = StoreDeps & { querier?: Querier; /** Runs `gh` for the open_issue step. */ exec?: Exec; canWrite?: (repo: string) => Promise; /** Indexes into a resolution's steps the operator removed. */ skip?: number[]; /** The operator's note with the choice. */ note?: string }; export const cardOf = (db: DatabaseSync, id: number): CardRow | undefined => db.prepare("SELECT * FROM conversation_cards WHERE id = ?").get(id) as CardRow | undefined; @@ -38,15 +42,42 @@ const CARD_NOTE: Note = { by: "operator", model: CLAUDE_PROMPTS["conversation.tu const oneLine = (s: string): string => s.replace(/\s+/g, " ").trim().slice(0, 300); const ref = (repo: string, n: number) => `${repo}#${n}`; -/** Replaces the text of a comment card that has not run. */ -export function editCard(db: DatabaseSync, id: number, by: string, text: string, deps?: StoreDeps): CardRow { +/** Replaces the drafts of a card that has not run: the comment text, the open_issue step's title and body, the fixup step's instructions. A field left out stays. */ +export function editCard(db: DatabaseSync, id: number, by: string, edit: CardEdit, deps?: StoreDeps): CardRow { const c = need(db, id); - if (c.kind !== "comment" && !((c.kind === "close" || c.kind === "resolution") && c.text !== null)) throw new ConversationError(400, "only a comment card, or a card with a comment, has text to edit"); - const t = text.trim(); - if (!t) throw new ConversationError(400, "the comment is empty"); - if (t.length > COMMENT_MAX) throw new ConversationError(400, `the comment is longer than ${COMMENT_MAX} characters`); + if (edit.text === undefined && edit.issue === undefined && edit.instructions === undefined) throw new ConversationError(400, "nothing to edit"); + let text: string | null = c.text; + if (edit.text !== undefined) { + if (c.kind !== "comment" && !((c.kind === "close" || c.kind === "resolution") && c.text !== null)) throw new ConversationError(400, "only a comment card, or a card with a comment, has text to edit"); + const t = edit.text.trim(); + if (!t) throw new ConversationError(400, "the comment is empty"); + if (t.length > COMMENT_MAX) throw new ConversationError(400, `the comment is longer than ${COMMENT_MAX} characters`); + text = t; + } + let params = c.params; + if (edit.issue !== undefined || edit.instructions !== undefined) { + const p = JSON.parse(c.params) as CardParams; + if (p.kind !== "resolution") throw new ConversationError(400, "only a resolution has an issue or instructions to edit"); + let steps: Step[] = p.steps; + if (edit.issue !== undefined) { + const title = String(edit.issue.title ?? "").replace(/\s+/g, " ").trim(), body = String(edit.issue.body ?? "").trim(); + if (!steps.some((x) => x.kind === "open_issue")) throw new ConversationError(400, "the card has no open_issue step"); + if (!title || !body) throw new ConversationError(400, "the issue needs a title and a body"); + if (title.length > ISSUE_TITLE_MAX) throw new ConversationError(400, `the issue title is longer than ${ISSUE_TITLE_MAX} characters`); + if (body.length > COMMENT_MAX) throw new ConversationError(400, `the issue body is longer than ${COMMENT_MAX} characters`); + steps = steps.map((x) => (x.kind === "open_issue" ? { ...x, title, body } : x)); + } + if (edit.instructions !== undefined) { + const instructions = edit.instructions.trim(); + if (!steps.some((x) => x.kind === "fixup")) throw new ConversationError(400, "the card has no fixup step"); + if (!instructions) throw new ConversationError(400, "the instructions are empty"); + if (instructions.length > INSTRUCTIONS_MAX) throw new ConversationError(400, `the instructions are longer than ${INSTRUCTIONS_MAX} characters`); + steps = steps.map((x) => (x.kind === "fixup" ? { ...x, instructions } : x)); + } + params = JSON.stringify({ ...p, steps }); + } const at = (deps?.now?.() ?? new Date()).toISOString(); - const r = db.prepare("UPDATE conversation_cards SET text = ?, edited_by = ?, edited_at = ? WHERE id = ? AND state = 'proposed'").run(t, by, at, id); + const r = db.prepare("UPDATE conversation_cards SET text = ?, params = ?, edited_by = ?, edited_at = ? WHERE id = ? AND state = 'proposed'").run(text, params, by, at, id); if (r.changes !== 1) throw new ConversationError(409, `the card is already ${c.state}`); audit(db, by, "conversation-card-edit", ref(c.repo, c.number), { card: id }); return need(db, id); @@ -125,6 +156,7 @@ class StepError extends Error { } type Ctx = { + exec: Exec; /** The operator's note: kept on the decision it settles, never posted to GitHub. */ note?: string; db: DatabaseSync; c: CardRow; by: string; q: Querier; at: string; w: Writer; source: { source: string; card: number } }; @@ -166,12 +198,12 @@ async function closeThe({ db, c, by, q, at, w, source }: Ctx, p: { reason: Close return { how, url }; } -/** The item is closed: its open decisions (but `except`) are settled now, not at the next sync's withdrawal. */ +/** The item is closed or moved: its open decisions (but `except`) are settled now, not at the next sync's withdrawal. `what` is the phrase after "Closed" or the whole summary when it starts with "Moved". */ function settleOthers(db: DatabaseSync, c: CardRow, how: string, by: string, at: string, except?: string): void { const open = db.prepare("SELECT id FROM decisions WHERE repo = ? AND number = ? AND answer IS NULL AND id NOT LIKE '%:dupegroup:%'").all(c.repo, c.number) as { id: string }[]; for (const d of open) { if (d.id === except) continue; - try { resolveDecision(db, c, d.id, undefined, `Closed${how} in the conversation`, by, at); } catch { /* answered meanwhile; the next sync withdraws what is left */ } + try { resolveDecision(db, c, d.id, undefined, how.startsWith("Moved") ? `${how} in the conversation` : `Closed${how} in the conversation`, by, at); } catch { /* answered meanwhile; the next sync withdraws what is left */ } } } @@ -195,6 +227,118 @@ async function closeDuplicate({ db, c, by, q, at, w, source }: Ctx, of: number): return { url }; } +/** The Act step's daily limit also covers the GitHub writes of conversation cards: they and the Act jobs' items today, against the limit row. */ +function actRoom(db: DatabaseSync): void { + const row = db.prepare("SELECT per_day FROM stage_limits WHERE step = 'act'").get() as { per_day: number | null } | undefined; + if (!row || row.per_day === null) return; + const day = `${new Date().toISOString().slice(0, 10)}T00:00:00.000Z`; + const actions = Object.keys(GITHUB_ACTIONS); + const cards = (db.prepare(`SELECT COUNT(*) AS n FROM audit WHERE at >= ? AND details LIKE '%"source":"conversation"%' AND action IN (${actions.map(() => "?").join(",")})`).get(day, ...actions) as { n: number }).n; + const jobs = (db.prepare("SELECT COALESCE(SUM(items), 0) AS n FROM jobs WHERE step = 'act' AND started_at >= ?").get(day) as { n: number }).n; + if (cards + jobs >= row.per_day) throw new Error(`the daily limit of ${row.per_day} Act writes is reached`); +} + +/** The Act approval of `repo` for the operator's write, and room under the daily limit. */ +function actGrant(db: DatabaseSync, repo: string, by: string, need: "comment" | "labels" = "comment") { + const g = guardRepo(db, repo, need, { operator: by }); + if ("refused" in g) throw new Error(g.refused); + actRoom(db); + return g; +} + +const ORG = "storytold"; +const USER_ID = `query($login: String!) { user(login: $login) { id login } }`; +const COLLABORATORS = `query($owner: String!, $name: String!, $login: String!) { repository(owner: $owner, name: $name) { collaborators(query: $login, first: 10) { edges { permission node { login } } } } }`; +const REPO_ID = `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { id } }`; + +async function userOf(q: Querier, login: string): Promise<{ id: string; login: string }> { + const d = await q.query(USER_ID, { login }) as { user?: { id: string; login: string } | null }; + if (!d.user) throw new Error(`GitHub has no user ${login}`); + return d.user; +} + +/** Reads the live permission: `login` must hold write, maintain or admin on the repo. Throws when GitHub cannot tell. */ +async function needLiveWrite(q: Querier, repo: string, login: string): Promise { + const d = await q.query(COLLABORATORS, { owner: ORG, name: repo, login }) as { repository?: { collaborators?: { edges?: { permission: string; node: { login: string } }[] } | null } | null }; + const e = d.repository?.collaborators?.edges?.find((x) => x.node.login.toLowerCase() === login.toLowerCase()); + if (!e || !["WRITE", "MAINTAIN", "ADMIN"].includes(e.permission)) throw new Error(`${login} does not have write access to ${repo}`); +} + +async function unlabel(ctx: Ctx, label: string): Promise { + const { db, c, by, q, w, source } = ctx; + const g = actGrant(db, c.repo, by, "labels"); + const live = await liveOpen(q, c.repo, c.number); + const id = (await repoLabels(q, c.repo)).labels.get(label.toLowerCase()); + if (!id) throw new Error(`the label "${label}" does not exist on ${c.repo}`); + await removeLabel(w, g, q, { repo: c.repo, number: c.number, id: live.id }, { id, name: label }, source); + return { result: `Label "${label}" removed`, url: null }; +} + +async function reopen(ctx: Ctx): Promise { + const { db, c, by, q, w, source } = ctx; + const g = actGrant(db, c.repo, by); + const refusal = closeRefusal(db, c.repo, c.number); + if (refusal) throw new Error(refusal); + const live = await readLive(q, c.repo, c.number); + if (!live) throw new Error("GitHub returned no such item"); + if (live.state === "OPEN") throw new Error("already open on GitHub"); + if (live.state !== "CLOSED") throw new Error(`${live.state.toLowerCase()} on GitHub: it cannot be reopened`); + await reopenItem(w, g, q, { repo: c.repo, number: c.number, id: live.id, pr: live.type === "PullRequest" }, source); + return { result: "Reopened", url: null }; +} + +async function openIssue(ctx: Ctx, st: Extract): Promise { + const { db, c, by, w, source, exec } = ctx; + const g = actGrant(db, st.repo, by); + try { + const made = await createIssue(w, g, exec, { repo: st.repo, target: ref(c.repo, c.number), title: st.title, body: st.body }, CARD_NOTE, source); + return { result: `Opened ${ref(st.repo, made.number)}`, url: made.url }; + } catch (e) { + if (e instanceof IssueError && !e.clear) throw new Error(`${e.message}; the issue may exist in ${st.repo}, check before running again`); + throw e; + } +} + +async function transfer(ctx: Ctx, st: Extract): Promise { + const { db, c, by, q, w, source } = ctx; + const g = actGrant(db, c.repo, by); + const gTo = actGrant(db, st.to, by); + const refusal = closeRefusal(db, c.repo, c.number); + if (refusal) throw new Error(refusal); + const live = await liveOpen(q, c.repo, c.number); + if (live.type !== "Issue") throw new Error("only an issue can be moved to another repository"); + const t = await q.query(REPO_ID, { owner: ORG, name: st.to }) as { repository?: { id: string } | null }; + if (!t.repository) throw new Error(`GitHub has no repository ${st.to}`); + const url = await transferIssue(w, g, gTo, q, { repo: c.repo, number: c.number, id: live.id }, { repo: st.to, id: t.repository.id }, source); + return { result: `Moved to ${st.to}`, url: url || null }; +} + +async function assign(ctx: Ctx, login: string): Promise { + const { db, c, by, q, w, source } = ctx; + const g = actGrant(db, c.repo, by); + const live = await liveOpen(q, c.repo, c.number); + const author = (db.prepare("SELECT author FROM items WHERE repo = ? AND number = ?").get(c.repo, c.number) as { author: string | null } | undefined)?.author ?? null; + if (author?.toLowerCase() !== login.toLowerCase()) await needLiveWrite(q, c.repo, login); + await assignTo(w, g, q, { repo: c.repo, number: c.number, id: live.id }, await userOf(q, login), source); + return { result: `Assigned ${login}`, url: null }; +} + +async function askReviewers(ctx: Ctx, logins: string[]): Promise { + const { db, c, by, q, w, source } = ctx; + const g = actGrant(db, c.repo, by); + const live = await liveOpen(q, c.repo, c.number); + if (live.type !== "PullRequest") throw new Error("reviewers can be requested on a PR only"); + const author = (db.prepare("SELECT author FROM items WHERE repo = ? AND number = ?").get(c.repo, c.number) as { author: string | null } | undefined)?.author ?? null; + const users: { id: string; login: string }[] = []; + for (const l of logins) { + if (author?.toLowerCase() === l.toLowerCase()) throw new Error(`${l} is the PR's author`); + await needLiveWrite(q, c.repo, l); + users.push(await userOf(q, l)); + } + await requestReviewers(w, g, q, { repo: c.repo, number: c.number, id: live.id }, users, source); + return { result: `Asked ${logins.join(", ")} for a review`, url: null }; +} + /** Fails before any step runs when the decision a resolution settles has changed. */ async function checkSettle(db: DatabaseSync, c: CardRow, s: Settle, canWrite?: ActDeps["canWrite"]): Promise { const d = getDecision(db, s.decision); @@ -235,6 +379,24 @@ async function runResolution(ctx: Ctx, p: CardParams & { kind: "resolution" }, c results.push(`Closed as a duplicate of ${ref(c.repo, st.of)}`); break; } + case "unlabel": results.push((await unlabel(ctx, st.label)).result); break; + case "reopen": results.push((await reopen(ctx)).result); break; + case "open_issue": { + const o = await openIssue(ctx, st); + url ??= o.url; + results.push(o.result); + break; + } + case "transfer": { + const o = await transfer(ctx, st); + url ??= o.url; + closedHow = `Moved to ${st.to}`; + results.push(o.result); + break; + } + case "assign": results.push((await assign(ctx, st.login)).result); break; + case "request_reviewers": results.push((await askReviewers(ctx, st.logins)).result); break; + case "review": case "fixup": results.push((await runPipelineStep(db, { repo: c.repo, number: c.number, step: st, by })).label); break; } done.push(stepLine(st)); } @@ -252,8 +414,8 @@ async function runResolution(ctx: Ctx, p: CardParams & { kind: "resolution" }, c return { result: results.join("; "), url }; } -async function run(db: DatabaseSync, c: CardRow, p: CardParams, by: string, q: Querier, at: string, canWrite?: ActDeps["canWrite"], note?: string): Promise { - const ctx: Ctx = { note, db, c, by, q, at, w: { db, login: by }, source: { source: "conversation", card: c.id } }; +async function run(db: DatabaseSync, c: CardRow, p: CardParams, by: string, q: Querier, at: string, canWrite?: ActDeps["canWrite"], note?: string, exec: Exec = defaultExec): Promise { + const ctx: Ctx = { exec, note, db, c, by, q, at, w: { db, login: by }, source: { source: "conversation", card: c.id } }; switch (p.kind) { case "resolution": return runResolution(ctx, p, canWrite); case "answer": return answerDecision(db, c, p.decision, p.stamp, p.option, by, at, canWrite, note); @@ -295,8 +457,8 @@ export async function doCard(db: DatabaseSync, id: number, by: string, deps: Act skipped.push(...all.filter((_, k) => deps.skip!.includes(k)).map(stepLine)); params = { ...params, steps }; // The settlement derived from a close step says the item was closed; without that step only the operator's own words are true. - if (params.settle?.kind === "handled" && params.settle.fromClose && all.some((x, k) => deps.skip!.includes(k) && (x.kind === "close" || x.kind === "duplicate"))) { - if (!note) throw new ConversationError(400, "skipping the close step needs a note saying how the question was handled"); + if (params.settle?.kind === "handled" && params.settle.fromClose && all.some((x, k) => deps.skip!.includes(k) && isSettling(x))) { + if (!note) throw new ConversationError(400, "skipping the step that settles the question needs a note saying how it was handled"); params = { ...params, settle: { kind: "handled", decision: params.settle.decision, summary: note, stamp: params.settle.stamp } }; noteIsSummary = true; } @@ -306,7 +468,7 @@ export async function doCard(db: DatabaseSync, id: number, by: string, deps: Act if (claim.changes !== 1) return { card: c, ran: false }; let out: Outcome | null = null, error: string | null = null, posted = false; try { - out = await run(db, c, params, by, deps.querier ?? new Client(1000), at, deps.canWrite, noteIsSummary ? undefined : note); + out = await run(db, c, params, by, deps.querier ?? new Client(1000), at, deps.canWrite, noteIsSummary ? undefined : note, deps.exec); } catch (e) { error = oneLine(String((e as Error).message ?? e)); posted = e instanceof StepError && e.posted; diff --git a/src/conversations/cards.ts b/src/conversations/cards.ts index fae3a7817..cd4dd3877 100644 --- a/src/conversations/cards.ts +++ b/src/conversations/cards.ts @@ -7,7 +7,8 @@ import { optionsOf, getDecision, type DecisionRow, type Kind } from "../decision import { backlogHeldSql, notOwnIntegrationSql } from "../dupes/held.ts"; import { ALL_LABELS, isTypeLabel, sameLabel } from "../labels/set.ts"; import { pilotSql } from "../pilot.ts"; -import { CLOSE_REASONS, COMMENT_MAX, RESOLVE_MAX, type CardKind, type CloseReason } from "./types.ts"; +import { LOGIN } from "../access.ts"; +import { CLOSE_REASONS, COMMENT_MAX, INSTRUCTIONS_MAX, ISSUE_TITLE_MAX, RESOLVE_MAX, type CardKind, type CloseReason } from "./types.ts"; /** * 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 @@ -80,6 +81,8 @@ export function cardEffect(db: DatabaseSync, p: CardParams): string | null { 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 = decisionWrite(db, p.settle.decision, p.settle.option); @@ -144,10 +147,17 @@ export function buttonLabel(db: DatabaseSync, p: CardParams): string { 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(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"; - return p.steps.some((x) => x.kind === "comment") ? "Post comment" : "Add label"; + 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": { @@ -263,7 +273,98 @@ function duplicateStep(db: DatabaseSync, repo: string, n: number, of: unknown): return { value: { kind: "duplicate", of: of as number } }; } -const MAX_STEPS = 6; +type ItemFacts = { kind: string; state: string; author: string | null }; +const itemFacts = (db: DatabaseSync, repo: string, n: number): ItemFacts | undefined => + db.prepare("SELECT kind, state, author FROM items WHERE repo = ? AND number = ?").get(repo, n) as ItemFacts | undefined; +const isTracked = (db: DatabaseSync, repo: unknown): repo is string => typeof repo === "string" && !!db.prepare("SELECT 1 FROM tracked_repos WHERE name = ?").get(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 function mayWrite(db: DatabaseSync, repo: string, login: string): boolean { + if (db.prepare("SELECT 1 FROM repo_permissions WHERE repo = ? AND login = ? AND permission IN ('write', 'maintain', 'admin')").get(repo, login)) return true; + return !!db.prepare(`SELECT 1 FROM items WHERE repo = ? AND author = ? COLLATE NOCASE AND author_association IN ('OWNER', 'MEMBER', 'COLLABORATOR') + UNION ALL SELECT 1 FROM comments WHERE repo = ? AND author = ? COLLATE NOCASE AND author_association IN ('OWNER', 'MEMBER', 'COLLABORATOR') LIMIT 1`).get(repo, login, repo, login); +} + +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 }; +} + +function openIssueStep(db: DatabaseSync, st: Record, drop: ReadonlySet): Checked { + if (!isTracked(db, st.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: st.repo, title: title.value, body: body.value } }; +} + +function transferStep(db: DatabaseSync, repo: string, n: number, to: unknown): Checked { + const f = itemFacts(db, repo, n); + if (pr(f)) return { note: "dropped a resolution: only an issue can be moved to another repository" }; + if (!isTracked(db, to) || to === repo) return { note: `dropped a resolution: "${String(to).slice(0, 40)}" is not another tracked repository` }; + const why = 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 } }; +} + +function assignStep(db: DatabaseSync, repo: string, n: number, login: unknown): Checked { + if (typeof login !== "string" || !LOGIN.test(login)) return { note: "dropped a resolution whose assign step has no GitHub login" }; + if (!sameLogin(itemFacts(db, repo, n)?.author ?? null, login) && !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 } }; +} + +function reviewersStep(db: DatabaseSync, repo: string, n: number, raw: unknown): Checked { + const f = 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 = logins.find((x) => sameLogin(f!.author, x) || !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 } }; +} + +function unlabelStep(db: DatabaseSync, repo: string, n: number, 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 = db.prepare("SELECT labels FROM items WHERE repo = ? AND number = ?").get(repo, n) as { labels: string | null } | undefined; + 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 } }; +} + +function reopenStep(db: DatabaseSync, repo: string, n: number): Checked { + const f = itemFacts(db, repo, n); + if (f?.state !== "CLOSED") return { note: `dropped a resolution: ${ref(repo, n)} is not closed` }; + const why = closeRefusal(db, repo, n); + return why ? { note: `dropped a resolution: ${why}` } : { value: { kind: "reopen" } }; +} + +function pipelineStep(db: DatabaseSync, repo: string, n: number, st: Record): Checked { + const f = 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; /** The settlement the model asked for, checked against the item's open decision `d`. */ function settleOf(db: DatabaseSync, d: DecisionRow, raw: unknown): Checked { @@ -288,18 +389,26 @@ function settleOf(db: DatabaseSync, d: DecisionRow, raw: unknown): Checked): Settle { - const summary = closing.kind === "duplicate" ? `Closed as a duplicate of ${ref(repo, closing.of)} in the conversation` - : closing.pr ? "Closed in the conversation" : `Closed as ${closing.reason === "completed" ? "completed" : "not planned"} in the conversation`; +/** 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"; + +function closeSettle(db: DatabaseSync, repo: string, d: DecisionRow, st: Settling): Settle { + 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: 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 or duplicate step settles it as handled; an answer whose option already writes to GitHub takes no comment, - * close or duplicate step; without an open decision there is no settlement. + * "ask" card); a close, duplicate, transfer, review or fixup step settles it as handled; an answer whose option already writes to GitHub + * takes no comment, close, duplicate, transfer, reopen, reviewer, review or fixup step (an issue, label or assignee step is fine); + * 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. */ function validateResolution(db: DatabaseSync, repo: string, n: number, c: Record, drop: ReadonlySet): { card: NewCard } | { note: string } { if (!Array.isArray(c.steps) || c.steps.length > MAX_STEPS) return { note: "dropped a resolution without a list of steps" }; @@ -312,6 +421,13 @@ function validateResolution(db: DatabaseSync, repo: string, n: number, c: Record case "label": r = labelStep(db, repo, n, st.label); break; case "close": r = closeStep(db, repo, n, st.reason); break; case "duplicate": r = duplicateStep(db, repo, n, st.of); break; + case "unlabel": r = unlabelStep(db, repo, n, st.label); break; + case "reopen": r = reopenStep(db, repo, n); break; + case "open_issue": r = openIssueStep(db, st, drop); break; + case "transfer": r = transferStep(db, repo, n, st.to); break; + case "assign": r = assignStep(db, repo, n, st.login); break; + case "request_reviewers": r = reviewersStep(db, repo, n, st.logins); break; + case "review": case "fixup": r = 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; @@ -320,11 +436,17 @@ function validateResolution(db: DatabaseSync, repo: string, n: number, c: Record 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; - const closing = steps.filter((x): x is Extract => x.kind === "close" || x.kind === "duplicate"); - if (count("comment") > 1) return { note: "dropped a resolution with more than one comment step" }; - if (closing.length > 1) return { note: "dropped a resolution that closes the item twice" }; - if (closing.length === 1 && steps[steps.length - 1] !== closing[0]) return { note: "dropped a resolution whose close step is not last" }; + 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" }; + 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); @@ -340,12 +462,15 @@ function validateResolution(db: DatabaseSync, repo: string, n: number, c: Record if ("note" in s) return s; settle = s.value; } - if (closing[0]) { - if (settle && settle.kind !== "handled") return { note: "dropped a resolution that closes the item and settles the question another way than handled" }; - if (d && !settle) settle = closeSettle(db, repo, d, closing[0]); + const fix = steps.find((x) => x.kind === "fixup"); + if (fix?.kind === "fixup" && fix.merge && (!d || (d.kind !== "merge" && d.kind !== "scope"))) return { note: "dropped a resolution: a fixup that merges needs an open merge or scope decision on the PR" }; + const settling = steps.find(isSettling); + if (settling) { + if (settle && settle.kind !== "handled") return { note: `dropped a resolution that has a ${settling.kind} step and settles the question another way than handled` }; + if (d && !settle) settle = closeSettle(db, repo, d, settling); } - if (settle?.kind === "answer" && steps.some((x) => x.kind === "comment" || x.kind === "close" || x.kind === "duplicate") && decisionWrite(db, settle.decision, settle.option)) { - return { note: "dropped a resolution: the answer already writes to GitHub, so it takes no comment or close step" }; + if (settle?.kind === "answer" && steps.some((x) => ["comment", "close", "duplicate", "transfer", "reopen", "request_reviewers", "review", "fixup"].includes(x.kind)) && decisionWrite(db, settle.decision, settle.option)) { + return { note: "dropped a resolution: the answer already writes to GitHub, so it takes only 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" }; @@ -370,16 +495,23 @@ export type Parsed = { text: string; cards: NewCard[]; notes: string[] }; const MAX_EXTRA = 2; const FENCE = /```actions[ \t]*\r?\n([\s\S]*?)```[ \t]*$/; -/** The cleaned text of each comment of a reply, with its field (`cards[i].text`, i the position in the actions block), for the reference checks. */ +/** 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 = 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 }, i) => { - const text = c && c.kind === "resolution" && typeof c.text === "string" ? cleanComment(c.text) : ""; - return text ? [{ field: `cards[${i}].text`, text }] : []; + 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 }); + if (Array.isArray(c.steps)) c.steps.forEach((st: { kind?: unknown; body?: unknown }, j) => { + const body = st && st.kind === "open_issue" && typeof st.body === "string" ? cleanComment(st.body) : ""; + if (body) out.push({ field: `cards[${i}].steps[${j}].body`, text: body }); + }); + return out; }); } diff --git a/src/conversations/types.ts b/src/conversations/types.ts index f25ac398d..e5a2de456 100644 --- a/src/conversations/types.ts +++ b/src/conversations/types.ts @@ -25,6 +25,10 @@ export const COMMENT_MAX = 1500; export const NOTE_MAX = 500; /** Longest summary of a resolve card. */ export const RESOLVE_MAX = 200; +/** Longest title of an issue the open_issue step creates. */ +export const ISSUE_TITLE_MAX = 120; +/** Longest instructions text of a fixup step. */ +export const INSTRUCTIONS_MAX = 1500; export const MESSAGE_MAX = 4000; export const OPENING_MAX = 1500; export const ITEM_BODY_LIMIT = 8000; diff --git a/src/dash/api/admin.ts b/src/dash/api/admin.ts index ec7ad6a39..4530384f9 100644 --- a/src/dash/api/admin.ts +++ b/src/dash/api/admin.ts @@ -37,7 +37,7 @@ const AUDIT_PAGE = 50; export const operatorOnly = (a: string) => a.startsWith("access-") || a.startsWith("account-") || ["session-revoke", "sign-in", "sign-in-refused"].includes(a); export const AUDIT_ACTIONS = [ "answer", "undo", "adopt", "opinion", "opinion-retract", "comment", "override", "rule", "access-add", "access-remove", "access-role", - "session-revoke", "sign-in", "sign-in-refused", "account-add", "account-change", "account-login-start", "account-login-code", "account-login-cancel", "account-sign-out", "account-refresh", "repo-track", "repo-untrack", "reference-import", "labels-approve", "labels-revoke", "labels-apply", "merge-approve", "merge-revoke", "comment-approve", "comment-revoke", "act-comment", "act-close", "act-skip", "push-approve", "push-revoke", "fixup-push", "fixup-comment", "fixup-comment-edit", "fixissue-approve", "fixissue-revoke", "mainfix-approve", "mainfix-revoke", "optional-check-add", "optional-check-remove", "fixissue-push", "fixissue-pr", "fixissue-comment", + "session-revoke", "sign-in", "sign-in-refused", "account-add", "account-change", "account-login-start", "account-login-code", "account-login-cancel", "account-sign-out", "account-refresh", "repo-track", "repo-untrack", "reference-import", "labels-approve", "labels-revoke", "labels-apply", "merge-approve", "merge-revoke", "comment-approve", "comment-revoke", "act-comment", "act-close", "act-reopen", "act-unlabel", "act-transfer", "act-request-reviewers", "act-skip", "push-approve", "push-revoke", "fixup-push", "fixup-comment", "fixup-comment-edit", "fixissue-approve", "fixissue-revoke", "mainfix-approve", "mainfix-revoke", "optional-check-add", "optional-check-remove", "fixissue-push", "fixissue-pr", "fixissue-comment", "job-request", "job-cancel", "pipeline-switch", "stage-limit", "limit-reset", "pilot-set", "pilot-clear", "repo-pipeline", "review-post", "review-edit", "batch-again", "reopen", "backlog-bulk", "withdraw", "single-merge-max", "label-create", "batch-pr-close", "fork-create", "assign", "unassign", "merge", "batch-push", "batch-pr", "shared-repos", "fasttrack-add", "fasttrack-remove", "merge-hold", "merge-release", "batch-remove", "batch-stop", "areas-edit", "areas-accept", "ci-approve", "ci-revoke", "ci-run-approve", "ci-rerun", "cifix-push", "cifix-comment", "cifix-check", "postmerge-file", "postmerge-file-one", "postmerge-review", "postmerge-backfill", diff --git a/src/dash/api/conversations.ts b/src/dash/api/conversations.ts index b9347d7eb..baff06418 100644 --- a/src/dash/api/conversations.ts +++ b/src/dash/api/conversations.ts @@ -1,6 +1,6 @@ // Opus conversations on items. Everyone who may see the repo reads them; only operators write, edit, run and dismiss. import type { DatabaseSync } from "node:sqlite"; -import type { Conversation, ConversationCard, ConversationTurn } from "../../../web/src/api/types.ts"; +import type { CardEdit, Conversation, ConversationCard, ConversationTurn } from "../../../web/src/api/types.ts"; import { buttonLabel, cardEffect, cardLines, type CardParams } from "../../conversations/cards.ts"; import { cardOf, dismissCard, doCard, editCard, sweepRunningCards, type ActDeps, type CardRow } from "../../conversations/act.ts"; import { ConversationError, addOperatorMessage, conversationOf, includesOf, pendingTurn, setInclude, staleOf, turnsOf, type IncludeRow, type StoreDeps } from "../../conversations/store.ts"; @@ -33,10 +33,16 @@ export function cardView(db: DatabaseSync, c: CardRow): ConversationCard { const effect = c.kind === "answer" || c.kind === "close" || c.kind === "resolution" ? cardEffect(db, params) : null; const lines = cardLines(db, params, c.description); const commentStep = params.kind === "resolution" ? params.steps.findIndex((x) => x.kind === "comment") : params.kind === "comment" || (params.kind === "close" && c.text !== null) ? 0 : -1; + const issueAt = params.kind === "resolution" ? params.steps.findIndex((x) => x.kind === "open_issue") : -1; + const fixupAt = params.kind === "resolution" ? params.steps.findIndex((x) => x.kind === "fixup") : -1; + const issueStep = params.kind === "resolution" ? params.steps[issueAt] : undefined; + const fixupStep = params.kind === "resolution" ? params.steps[fixupAt] : undefined; const stale = c.state === "proposed" ? staleOf(db, c.repo, c.number, c.seen) : undefined; return { steps: lines.steps, ...(commentStep >= 0 && { commentStep }), + ...(issueStep?.kind === "open_issue" && { issue: { step: issueAt, repo: issueStep.repo, title: issueStep.title, body: issueStep.body } }), + ...(fixupStep?.kind === "fixup" && { fixup: { step: fixupAt, instructions: fixupStep.instructions, merge: fixupStep.merge } }), ...(params.kind === "resolution" && params.settle?.kind === "answer" && { option: params.settle.option }), ...(stale && { stale }), ...(lines.settles && { settles: lines.settles }), @@ -80,6 +86,22 @@ function itemOf(req: Req): { repo: string; n: number } { return { repo: req.params.repo!, n }; } +/** The edit a card-edit request carries: any of text, issue ({title, body}) and instructions. */ +function cardEdit(req: Req): CardEdit { + const b = req.json as Record | null; + if (!b || typeof b !== "object" || Array.isArray(b)) throw new HttpError(400, "the body must be an object"); + const edit: CardEdit = {}; + if (b.text !== undefined) { if (typeof b.text !== "string") throw new HttpError(400, "text must be a string"); edit.text = b.text; } + if (b.instructions !== undefined) { if (typeof b.instructions !== "string") throw new HttpError(400, "instructions must be a string"); edit.instructions = b.instructions; } + if (b.issue !== undefined) { + const i = b.issue as Record | null; + if (!i || typeof i !== "object" || typeof i.title !== "string" || typeof i.body !== "string") throw new HttpError(400, "issue must be an object with a title and a body"); + edit.issue = { title: i.title, body: i.body }; + } + if (Object.keys(edit).length === 0) throw new HttpError(400, "the body must have a text, an issue or instructions"); + return edit; +} + function text(req: Req): string { const b = req.json; if (!b || typeof b !== "object" || Array.isArray(b) || typeof (b as { text?: unknown }).text !== "string") throw new HttpError(400, "the body must be an object with a text"); @@ -134,7 +156,7 @@ async function needCard(db: DatabaseSync, req: Req): Promise { export async function editCardText(db: DatabaseSync, req: Req): Promise { const c = await needCard(db, req); - return cardView(db, guard(() => editCard(db, c.id, req.user.login, text(req)))); + return cardView(db, guard(() => editCard(db, c.id, req.user.login, cardEdit(req)))); } export async function dismiss(db: DatabaseSync, req: Req): Promise { diff --git a/src/github/actions.ts b/src/github/actions.ts index 592e8706e..2fb6887da 100644 --- a/src/github/actions.ts +++ b/src/github/actions.ts @@ -8,6 +8,10 @@ export const GITHUB_ACTIONS: Record = { "fixup-comment-edit": "Edited comment", "fixissue-comment": "Commented", "act-close": "Closed", + "act-reopen": "Reopened", + "act-unlabel": "Removed label", + "act-transfer": "Moved issue", + "act-request-reviewers": "Requested review", "batch-pr-close": "Closed PR", "merge": "Merged", "assign": "Assigned", diff --git a/src/github/write.ts b/src/github/write.ts index 1d7a19524..a4281780e 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -79,6 +79,13 @@ const ASSIGN = `mutation($id: ID!, $user: ID!) { const UNASSIGN = `mutation($id: ID!, $user: ID!) { removeAssigneesFromAssignable(input: { assignableId: $id, assigneeIds: [$user] }) { clientMutationId } }`; +const REOPEN_ISSUE = `mutation($id: ID!) { reopenIssue(input: { issueId: $id }) { clientMutationId } }`; +const REOPEN_PR = `mutation($id: ID!) { reopenPullRequest(input: { pullRequestId: $id }) { clientMutationId } }`; +const REMOVE_LABEL = `mutation($id: ID!, $label: ID!) { removeLabelsFromLabelable(input: { labelableId: $id, labelIds: [$label] }) { clientMutationId } }`; +const TRANSFER_ISSUE = `mutation($id: ID!, $repo: ID!) { transferIssue(input: { issueId: $id, repositoryId: $repo }) { issue { url number } } }`; +const REQUEST_REVIEWS = `mutation($id: ID!, $users: [ID!]!) { + requestReviews(input: { pullRequestId: $id, userIds: $users, union: true }) { clientMutationId } +}`; const ADD_REVIEW = `mutation($pr: ID!, $oid: GitObjectID!, $body: String!) { addPullRequestReview(input: { pullRequestId: $pr, commitOID: $oid, body: $body, event: COMMENT }) { pullRequestReview { id } } }`; @@ -124,6 +131,33 @@ export async function unassignFrom(w: Writer, g: Grant, q: Querier, item: ItemRe await recorded(w, "unassign", refOf(item.repo, item.number), { ...details, assignee: user.login }, () => q.query(UNASSIGN, { id: item.id, user: user.id })); } +export async function reopenItem(w: Writer, g: Grant, q: Querier, item: ItemRef & { pr: boolean }, details: Details = {}): Promise { + covers(g, item.repo, item.number); + await recorded(w, "act-reopen", refOf(item.repo, item.number), details, () => q.query(item.pr ? REOPEN_PR : REOPEN_ISSUE, { id: item.id })); +} + +export async function removeLabel(w: Writer, g: Grant, q: Querier, item: ItemRef, label: { id: string; name: string }, details: Details = {}): Promise { + covers(g, item.repo, item.number); + await recorded(w, "act-unlabel", refOf(item.repo, item.number), { ...details, label: label.name }, () => q.query(REMOVE_LABEL, { id: item.id, label: label.id })); +} + +/** Moves an issue to another repository of the organisation (`to.id` is its node id). The grant `gTo` must cover the target repo; returns the issue's new URL. */ +export async function transferIssue(w: Writer, g: Grant, gTo: Grant, q: Querier, item: ItemRef, to: { repo: string; id: string }, details: Details = {}): Promise { + covers(g, item.repo, item.number); + covers(gTo, to.repo); + const r = await recorded(w, "act-transfer", refOf(item.repo, item.number), { ...details, to: to.repo }, + () => q.query(TRANSFER_ISSUE, { id: item.id, repo: to.id }) as Promise<{ transferIssue?: { issue?: { url?: string } } }>, + (x) => ({ url: x.transferIssue?.issue?.url ?? undefined })); + return r.transferIssue?.issue?.url ?? ""; +} + +/** Requests reviews from users (added to the reviewers already requested). */ +export async function requestReviewers(w: Writer, g: Grant, q: Querier, item: ItemRef, users: { id: string; login: string }[], details: Details = {}): Promise { + covers(g, item.repo, item.number); + await recorded(w, "act-request-reviewers", refOf(item.repo, item.number), { ...details, reviewers: users.map((u) => u.login) }, + () => q.query(REQUEST_REVIEWS, { id: item.id, users: users.map((u) => u.id) })); +} + /** Posts a review as a plain comment review on the commit; returns the review id (null when GitHub returned none). */ export async function postReview(w: Writer, q: Querier, g: Guarded<"post-review">, nodeId: string, note: Note, text: string, details: Details = {}): Promise { const body = withNote(note, text); diff --git a/src/prompts/index.ts b/src/prompts/index.ts index ce001fd61..ac97e8734 100644 --- a/src/prompts/index.ts +++ b/src/prompts/index.ts @@ -26,7 +26,7 @@ import { SUMMARY_MAX_WORDS, WHY_MAX_WORDS } from "../prose.ts"; import { GROUP_BODY_LIMIT, GROUP_DIFF_CHARS, GROUP_MAX, GROUP_MAX_POINTS, GROUP_REASON_WORDS, type CompareIssues, type ComparePrs } from "../dupes/group.ts"; import { JEV_ACCEPT, JEV_REJECT, PAIR_BODY_LIMIT, VERDICTS as PAIR_VERDICTS, pairView, type DupePair } from "../dupes/pair.ts"; import { CHECK_MAX_PROBLEMS, CHECK_REASON_WORDS, SAMPLE_FIXISSUE_CHECK, SAMPLE_FIXUP_CHECK, type FixIssueCheckInput, type FixupCheckInput } from "../patchcheck/types.ts"; -import { COMMENT_MAX, RESOLVE_MAX, OPENING_MAX, SAMPLE_CONVERSATION, type ConversationInput } from "../conversations/types.ts"; +import { COMMENT_MAX, INSTRUCTIONS_MAX, ISSUE_TITLE_MAX, RESOLVE_MAX, OPENING_MAX, SAMPLE_CONVERSATION, type ConversationInput } from "../conversations/types.ts"; import { RECOMMEND_BODY_LIMIT, RECOMMEND_REASON_MAX, SAMPLE_RECOMMEND, type RecommendInput } from "../decide/recommend-types.ts"; import { SAMPLE_COMPARE_ISSUES, SAMPLE_COMPARE_PRS, SAMPLE_CONFLICT_PRS, SAMPLE_DUPE_PAIRS, SAMPLE_FIXUP_PRS, SAMPLE_ITEMS, SAMPLE_OPUS_PRS, SAMPLE_PREMERGE_PRS } from "./samples.ts"; import { QUOTE_WORDS, REFERENCE_JEV_ACCEPT, REFERENCE_JEV_REJECT, SAMPLE_REFERENCE_LINT, type ReferenceLintInput } from "../replylint.ts"; @@ -933,11 +933,19 @@ Steps, in this order, each at most once except labels: - {"kind": "comment"}: post "text" on the item, at most ${COMMENT_MAX} characters. Write one or two short factual lines for the contributor: no offers, no maintainer tone, no mention of AI or of this conversation, no @mentions, no URLs unless needed. - {"kind": "label", "label": ""}: add one of the labels the pipeline manages: bugfix, performance, missing feature, small extra, plugin candidate, infra, security, needs decision. - {"kind": "close", "reason": "completed" | "not_planned"} or {"kind": "duplicate", "of": }: the last step, and at most one of the two. A close closes the item on GitHub (a pull request is closed without a reason). Use "completed" when the work is already on the default branch (cite the pull request or commit in the comment); use "not_planned" when the project clearly does not want it. A duplicate comments "Duplicate of #." and closes the item. +- {"kind": "unlabel", "label": ""}: remove one of the managed labels the item has. Repeatable like label. +- {"kind": "reopen"}: first step only, on a closed item (not a merged PR). +- {"kind": "open_issue", "repo": "", "title": "", "body": ""}: open a new issue in this repository or another tracked one. Write it like a comment: short, factual, no @mentions, no URLs unless needed. Use it for "Merge #n now and open a follow-up issue for ..." (settle with the merge option) or to file work that belongs elsewhere. +- {"kind": "assign", "login": ""}: assign the item's author or a person with write access to the repository. +- {"kind": "request_reviewers", "logins": ["", ...]}: pull requests only; one to three people with write access, never the PR's author. +- {"kind": "review"}: pull requests only; a fresh review of the current head, after which the pipeline decides again. Use it when the operator wants a second look or the diff changed. Settles as handled. +- {"kind": "fixup", "instructions": "", "merge": true | false}: open pull requests only; the fix-up step pushes the described change to the PR branch. The instructions are for the fix-up model and are never posted. With "merge": true it is a pre-approved merge: after the push the PR is reviewed and checked again and merges only when both pass; otherwise a new question comes back. Use merge true only on a card for a merge or scope decision, for "Fix up ... then merge". Settles as handled; give no answer settle with it. +- {"kind": "transfer", "to": ""}: issues only; moves the issue to that repository, e.g. "Move to storytold/". It ends the item here: the last step, and at most one of close, duplicate and transfer. Settles as handled. Settle, when the item block has a decision (its options are listed there): -- {"kind": "answer", "option": ""}: answer the decision. Answering can close the item or start later steps, so an option that closes the item or merges takes no comment, close or duplicate step (label steps are fine); propose it only when the operator asked for it or it clearly follows. When an option closes the item with the right meaning, use that option instead of a close step. +- {"kind": "answer", "option": ""}: answer the decision. Answering can close the item or start later steps, so an option that closes the item or merges takes no comment, close, duplicate, transfer, reopen, reviewer, review or fixup step (label, unlabel, assign and open_issue steps are fine); propose it only when the operator asked for it or it clearly follows. When an option closes the item with the right meaning, use that option instead of a close step. - {"kind": "handled", "summary": ""}: close the decision as handled in the conversation; nothing more is written to GitHub. Use it when no option fits and the steps settle the matter. - {"kind": "backlog"}: hold the item undecided; nothing is written to GitHub. -Rules. When the item has a decision, every card settles it, except one extra card whose only step is a comment and whose settle is null: ask the author something and keep the question open (at most one per reply). A card with a close or duplicate step settles as handled unless you give a settle of that kind. When the item has no decision, settle is null. Each resolution is a draft for one option of the decision (settle answer or backlog, with the steps that go with it) or an extra outcome that no option covers (settle handled, a close or duplicate step, or steps only). Give at most one resolution per option and at most two extra outcomes; the first card is your pick. Add only the options worth drafting. The optional ask card comes last. Our code checks every card and drops invalid ones. Propose nothing the operator did not need. Do not repeat a card that was already proposed or run unless the operator asks.`; +Rules. When the item has a decision, every card settles it, except one extra card whose only step is a comment and whose settle is null: ask the author something and keep the question open (at most one per reply). A card with a close, duplicate, transfer, review or fixup step settles as handled; give no settle of another kind with it. When the item has no decision, settle is null. Each resolution is a draft for one option of the decision (settle answer or backlog, with the steps that go with it) or an extra outcome that no option covers (settle handled, a close or duplicate step, or steps only). Give at most one resolution per option and at most two extra outcomes; the first card is your pick. Add only the options worth drafting. The optional ask card comes last. Our code checks every card and drops invalid ones. Propose nothing the operator did not need. Do not repeat a card that was already proposed or run unless the operator asks.`; const CONVERSATION: ClaudePrompt = { id: "conversation.turn", @@ -976,7 +984,7 @@ The conversation so far, oldest first. The last turn is the message to answer. {{turns}}`, output: "Plain text followed by an optional fenced actions block holding a JSON array of cards.", - validation: `${CLAUDE_RESULT} The text before the last fenced actions block is the reply; it must not be empty. The block is parsed as JSON; each card must be a resolution and is checked by our code (steps in the allowed order with at most one comment step and one close or duplicate step, last; comment text at most ${COMMENT_MAX} characters; labels of the managed set; a duplicate target that is another item of the repository; a close reason of completed or not_planned on an open item that Act could close; a settle that is an answer with an option of the item's open decision, handled with a summary of at most ${RESOLVE_MAX} characters, or backlog). With an open decision every card must settle it, except at most one card with a single comment step and no settle; a close or duplicate step settles as handled; an answer whose option writes to GitHub takes no comment, close or duplicate step; without an open decision settle must be null. At most one resolution per option and two extra outcomes are kept besides the ask card; the order is kept. An invalid card is dropped with a note shown under the reply. ${FIX_TURN} Lint problems: a mention of the reference folder or a page file in a resolution's comment text; for a repo with reference documentation, also a run of ${QUOTE_WORDS} or more consecutive words that appears in the reference pages, and a text that refers to documentation, a manual, a user guide or help pages of another product or names a commercial application or vendor (lint.reference.jev, lint.reference.haiku, as for review.opus). Fallback: the card is dropped with a note. A reply with no text is not linted and is repeated once; after that the operator's message is marked failed and can be sent again. The cards' titles, step lines, settlement lines and button labels are written by our code from their parameters, not by the model.`, + validation: `${CLAUDE_RESULT} The text before the last fenced actions block is the reply; it must not be empty. The block is parsed as JSON; each card must be a resolution and is checked by our code (steps with at most one of each kind except label and unlabel; close, duplicate and transfer end the item and come last, at most one of them; reopen first and only on a closed item; comment text at most ${COMMENT_MAX} characters; labels of the managed set, and an unlabel of one the item has; a duplicate target that is another item of the repository; a close reason of completed or not_planned on an open item that Act could close; an open_issue in a tracked repository with a title of at most ${ISSUE_TITLE_MAX} and a body of at most ${COMMENT_MAX} characters, cleaned like a comment; a transfer of an issue to another tracked repository; an assign of the item's author or a person with write access; one to three request_reviewers with write access on a PR, never its author; review and fixup on an open PR only, at most one of the two, with fixup instructions of 1 to ${INSTRUCTIONS_MAX} characters, and a fixup that merges only with an open merge or scope decision; a settle that is an answer with an option of the item's open decision, handled with a summary of at most ${RESOLVE_MAX} characters, or backlog). With an open decision every card must settle it, except at most one card with a single comment step and no settle; a close, duplicate, transfer, review or fixup step settles as handled; an answer whose option writes to GitHub takes only label, unlabel, assign and open_issue steps; without an open decision settle must be null. At most one resolution per option and two extra outcomes are kept besides the ask card; the order is kept. An invalid card is dropped with a note shown under the reply. ${FIX_TURN} Lint problems: a mention of the reference folder or a page file in a resolution's comment text or an issue body; for a repo with reference documentation, also a run of ${QUOTE_WORDS} or more consecutive words that appears in the reference pages, and a text that refers to documentation, a manual, a user guide or help pages of another product or names a commercial application or vendor (lint.reference.jev, lint.reference.haiku, as for review.opus). Fallback: the card is dropped with a note. A reply with no text is not linted and is repeated once; after that the operator's message is marked failed and can be sent again. The cards' titles, step lines, settlement lines and button labels are written by our code from their parameters, not by the model.`, limits: { perCall: 1, attempts: 2, timeoutSeconds: 1800 }, extra: [ { label: "Prompt order", value: "The fixed text above, then the stored item block, then the earlier turns as stored, then the new message last, so that each turn reuses the cached start of the one before. Nothing that changes (times, counts, live state) comes before the newest turn; a changed pull request head or item text is added as a system turn." }, diff --git a/test/conversations.test.ts b/test/conversations.test.ts index e212ac2e1..c4bd91963 100644 --- a/test/conversations.test.ts +++ b/test/conversations.test.ts @@ -113,6 +113,42 @@ describe("cards", () => { }); }); +describe("new step kinds", () => { + const R = (steps: unknown[], settle: unknown = null, extra: Record = {}) => ({ kind: "resolution", steps, settle, ...extra }); + const issue = { kind: "open_issue", repo: "lib", title: "Follow up", body: "Check the edge case." }; + const run = (db: DatabaseSync, n: number, cards: unknown[]) => parseReply(db, "app", n, `Text.\n\`\`\`actions\n${JSON.stringify(cards)}\n\`\`\``)!; + + test("transfer is for issues and last, an answer that writes takes open_issue but not a comment, fixup that merges needs a merge or scope decision", () => { + const db = fresh(); + db.prepare("INSERT INTO tracked_repos (name, added_by, added_at, pipeline) VALUES ('lib', 'op', ?, 1)").run(T0); + ask(db, [{ id: "app#2:merge", kind: "merge", repo: "app", number: 2, question: "Merge?", options: [{ key: "merge", label: "Merge" }, { key: "hold", label: "Hold" }] }]); + const p1 = run(db, 3, [ + R([{ kind: "transfer", to: "lib" }]), + R([{ kind: "transfer", to: "lib" }, { kind: "comment" }], null, { text: "Moved." }), + R([{ kind: "transfer", to: "app" }]), + R([{ kind: "comment" }, { kind: "transfer", to: "lib" }], null, { text: "Moving it." }), + R([{ kind: "open_issue", repo: "nowhere", title: "x", body: "y" }]), + R([{ kind: "review" }]), + ]); + assert.deepEqual(p1.cards.map((c) => c.params.kind === "resolution" ? c.params.steps.map((x) => x.kind).join("+") : ""), ["transfer", "comment+transfer"]); + assert.equal(p1.notes.length, 4); + // Issue 1 has the scope decision "close", which writes to GitHub. + const p2 = run(db, 1, [ + R([issue], { kind: "answer", option: "close" }), + R([{ kind: "comment" }, issue], { kind: "answer", option: "close" }, { text: "Closing." }), + ]); + assert.equal(p2.cards.length, 1); + assert.equal(p2.cards[0]!.description.includes('Open an issue in lib: "Follow up"'), true); + const fix = (merge: boolean) => ({ kind: "fixup", instructions: "Rename the helper.", merge }); + const p3 = run(db, 2, [R([fix(true)]), R([fix(false)], { kind: "answer", option: "hold" })]); + assert.equal(p3.cards.length, 1, "the answer settle is refused with a fixup"); + assert.equal(p3.cards[0]!.params.kind === "resolution" && p3.cards[0]!.params.settle?.kind, "handled"); + assert.equal(run(db, 3, [R([fix(true)])]).cards.length, 0, "an issue has no fix-up"); + const none = run(db, 2, [R([{ kind: "fixup", instructions: "x", merge: true }, { kind: "request_reviewers", logins: ["someone"] }])]); + assert.equal(none.cards.length, 0); + }); +}); + describe("Do it", () => { test("a close card comments, closes with the state reason and answers the item's open decision as handled", async () => { const db = fresh();