From fca8e32effbdac79fccc4ff08dced40de848d1b3 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 05:47:11 +0000 Subject: [PATCH] PR stalls: ask a Hold question for every hold review; ask Merge? for failed verification, an idle CI fix, an unknown mergeable state and a stuck refusal; ask the contributor when red CI holds the review --- src/act/index.ts | 53 +++++++++++-- src/answers/hold.ts | 2 +- src/cifix/select.ts | 4 +- src/conversations/cards.ts | 2 +- src/core/decide.ts | 93 ++++++++++++++++++++--- src/core/facts.ts | 27 +++++-- src/core/issue-facts.ts | 2 +- src/core/plan.ts | 8 +- src/core/rules.ts | 20 ++++- src/db.ts | 2 +- src/decide/choices.ts | 3 + src/decide/prepare.ts | 2 +- src/decide/prepared.ts | 4 +- src/decisions-used.ts | 3 +- src/decisions.ts | 2 +- src/merge/index.ts | 8 +- src/merge/mergeable.ts | 58 ++++++++++++++ src/merge/queue.ts | 2 +- src/merge/withdraw.ts | 22 ++++-- src/review/checks.ts | 2 + src/review/index.ts | 2 + src/review/opus.ts | 4 +- src/review/summary.ts | 6 +- src/stages/registry.ts | 1 + test/decide-pr.test.ts | 10 +-- test/invariants.test.ts | 2 +- test/pr-stalls.test.ts | 108 +++++++++++++++++++++++++++ test/world.ts | 4 +- web/src/api/mock/conversationMock.ts | 19 ++++- web/src/api/mock/fixtures.ts | 20 +++++ web/src/api/types.ts | 2 +- web/src/lib/links.ts | 2 +- web/src/modules/decisions/parts.tsx | 2 + web/src/modules/decisions/state.ts | 1 + web/src/modules/home/views.tsx | 4 +- 35 files changed, 445 insertions(+), 61 deletions(-) create mode 100644 src/merge/mergeable.ts create mode 100644 test/pr-stalls.test.ts diff --git a/src/act/index.ts b/src/act/index.ts index 7a5ee2d7..5d600d1a 100644 --- a/src/act/index.ts +++ b/src/act/index.ts @@ -39,7 +39,9 @@ import { plannedItems } from "../core/select-items.ts"; import { jobItem } from "../runner/job-items.ts"; import { orderTargets } from "./order.ts"; import { actRoom } from "../conversations/queue.ts"; -import { setAsideSupersededQuestions } from "../merge/withdraw.ts"; +import { setAsideSupersededQuestions, withdrawHoldQuestion } from "../merge/withdraw.ts"; +import { holdDecisionId, HOLD_OPTIONS } from "../core/rules.ts"; +import { planned } from "../core/select.ts"; import { ownerOf } from "../owners.ts"; import { sweepStaleAnswers } from "../answers/sweep.ts"; import { authFailure, isWaiting, laneForDecision, markExecDone, noWriteReason, setExecState, SIGN_IN_REASON, type LaneDeps, type Lane } from "../github/user-lane.ts"; @@ -92,6 +94,7 @@ export const closeDecisionId = (repo: string, number: number, head: string): str const WRITES: Partial>> = { scope: { close: "closes it on GitHub" }, close: { close: "closes the PR on GitHub" }, + hold: { close: "closes the PR on GitHub" }, duplicate: { close: "closes it on GitHub", accept: "posts the comments shown and closes the duplicates on GitHub" }, merge: { merge: "merges on GitHub", close: "closes the PR on GitHub" }, }; @@ -133,6 +136,46 @@ export function closeQuestion(r: ReviewRow, why: string | null = null, quiet = f }; } +// ---- Hold: what next? ------------------------------------------------------------ + +/** The question for a PR whose latest review says hold, asked once per head. Review again and a fix-up first are cores of the prepared answer (src/decide/choices.ts). */ +export function holdQuestion(r: ReviewRow, quiet = false): Record & { id: string } { + const reason = cleanReason(r.reason); + return { + id: holdDecisionId(r.repo, r.number, r.head_oid), kind: "hold", repo: r.repo, number: r.number, + question: "The review put this PR on hold. What next?", + context: `The Opus review says hold${r.sure === 0 ? " (Opus was unsure)" : ""}: it neither takes the PR as it is nor closes it, and nothing happens until a person decides.`, + facts: [ + ...(quiet ? [] : [`${REASON_FACT}${r.reason.replace(/\s+/g, " ").trim().slice(0, 300)}`]), + `author: ${r.author ?? "unknown"}, size ${sizeOf(r.lines)}`, + `${HEAD_FACT}${r.head_oid}`, + ], + options: Object.values(HOLD_OPTIONS).map((o) => ({ ...o })), + ...(quiet ? {} : { public_text: reason }), + asked_by: ACTOR, + }; +} + +/** + * Asks the Hold questions the Plans call for and sets aside open ones whose head is no longer held. Writes decisions only. + * Returns the ids asked. + */ +export function askHoldDecisions(db: DatabaseSync, at: string, repo?: string): string[] { + const get = db.prepare(`SELECT r.repo, r.number, r.head_oid, r.reason, r.sure, COALESCE(i.additions, 0) + COALESCE(i.deletions, 0) AS lines, i.title, i.author + FROM final_reviews r JOIN items i ON i.repo = r.repo AND i.number = r.number WHERE r.repo = ? AND r.number = ? AND r.head_oid = ? AND r.verdict = 'hold'`); + const todo = planned(db, "ask-merge", repo ? { repo } : {}).filter((p) => p.action.params?.hold === true); + const qs: (Record & { id: string })[] = []; + for (const p of todo) { + if (p.action.params?.withdraw) { withdrawHoldQuestion(db, p.facts.repo, p.facts.number, String(p.action.params?.decisionHead ?? p.action.head ?? ""), at, "the review at that head no longer says hold"); continue; } + const r = get.get(p.facts.repo, p.facts.number, p.action.head) as ReviewRow | undefined; + if (r) qs.push(holdQuestion(r, isQuiet(db, r.repo, r.number))); + } + if (qs.length) { ask(db, qs.map((q) => ({ ...q, asked_at: at }))); setAsideSupersededQuestions(db, at, repo); } + else setAsideSupersededQuestions(db, at, repo); + fillReviewSummaries(db, at, repo); + return qs.map((q) => q.id); +} + export function askCloseDecisions(db: DatabaseSync, repo: string, at: string): string[] { const qs = closeRows(db, repo).map((r) => closeQuestion(r, reviewText(db, r.repo, r.number, r.head_oid)?.why ?? null, isQuiet(db, r.repo, r.number))); if (qs.length) { ask(db, qs.map((q) => ({ ...q, asked_at: at }))); setAsideSupersededQuestions(db, at, repo); } @@ -142,7 +185,7 @@ export function askCloseDecisions(db: DatabaseSync, repo: string, at: string): s // ---- what to act on ------------------------------------------------------------ -type Target = { decisionId: string; kind: "scope" | "close" | "duplicate" | "merge"; repo: string; number: number }; +type Target = { decisionId: string; kind: "scope" | "close" | "duplicate" | "merge" | "hold"; repo: string; number: number }; type ActionRow = { attempts: number; id: number; decision_id: string; repo: string; number: number; kind: string; state: string; comment_url: string | null; reason: string | null; created_at: string }; const rowOf = (db: DatabaseSync, t: Target): ActionRow | undefined => @@ -220,7 +263,7 @@ function commentFor(d: DecisionRow, t: Target, quiet = false): string { export function commentPreview(d: DecisionRow): string | null { // A group decision shows the stored texts of each option instead (src/dupes/texts.ts). if (d.kind === "duplicate" && d.id.includes(":dupegroup:")) return null; - if (d.kind === "scope" || d.kind === "close" || d.kind === "merge") return commentFor(d, { decisionId: d.id, kind: d.kind, repo: d.repo ?? "", number: d.number ?? 0 }); + if (d.kind === "scope" || d.kind === "close" || d.kind === "merge" || d.kind === "hold") return commentFor(d, { decisionId: d.id, kind: d.kind, repo: d.repo ?? "", number: d.number ?? 0 }); if (d.kind === "duplicate") { const orig = factValue(d, DUP_FACT); return orig && d.repo ? duplicateComment({ repo: d.repo, original: orig, closed: false }) : null; @@ -309,7 +352,7 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st const live = await readLive(q, t.repo, t.number); if (!live) { skip(t, "GitHub returned no such item"); continue; } if (live.state !== "OPEN") { skip(t, `already ${live.state.toLowerCase()} on GitHub`); continue; } - if (t.kind === "close" || t.kind === "merge") { + if (t.kind === "close" || t.kind === "merge" || t.kind === "hold") { const h = headFact(dec); if (live.type !== "PullRequest" || !h || live.head !== h) { skip(t, `head moved since the decision (${h ? short(h) : "no head recorded"} → ${live.head ? short(live.head) : "none"})`); continue; } } @@ -334,7 +377,7 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st if (!o) { skip(t, "GitHub returned no such original"); continue; } how = duplicateClose({ id: o.id, pr: o.type === "PullRequest" }, `${orig[1]}#${orig[2]}`); body = duplicateComment({ repo: t.repo, original: `${orig[1]}#${orig[2]}`, closed: o.state !== "OPEN" }); - } else body = commentFor(dec, t, t.kind === "close" && isQuiet(db, t.repo, t.number)); + } else body = commentFor(dec, t, (t.kind === "close" || t.kind === "hold") && isQuiet(db, t.repo, t.number)); url = await commentOn(w, g, q, "act-comment", { repo: t.repo, number: t.number, id: live.id }, decisionNote(dec), body, { decision: t.decisionId }); // Saved before the close so a retry after a failed close does not comment twice. save(t, "failed", "comment posted; close not done yet", url); diff --git a/src/answers/hold.ts b/src/answers/hold.ts index ae393854..0ab1dac9 100644 --- a/src/answers/hold.ts +++ b/src/answers/hold.ts @@ -119,7 +119,7 @@ export function clearDispute(db: DatabaseSync, id: string): void { */ export function heldOpenSql(login: string, operator: boolean): string { const me = `'${login.replace(/'/g, "''")}'`; - const writes = `((decisions.answer = 'close' AND decisions.kind IN ('scope', 'close', 'duplicate', 'merge')) OR (decisions.answer = 'merge' AND decisions.kind = 'merge') + const writes = `((decisions.answer = 'close' AND decisions.kind IN ('scope', 'close', 'duplicate', 'merge', 'hold')) OR (decisions.answer = 'merge' AND decisions.kind = 'merge') OR (decisions.kind = 'duplicate' AND (decisions.answer = 'accept' OR decisions.answer LIKE 'keep:%')))`; // An open decision whose queued press someone disputed: the presser and operators look at it. const queuedDispute = `(decisions.answer IS NULL AND decisions.exec_state = '${SETTLING}' AND EXISTS (SELECT 1 FROM main.conversation_cards hc WHERE hc.state = 'queued' AND hc.dispute_by IS NOT NULL diff --git a/src/cifix/select.ts b/src/cifix/select.ts index d1ae6c7c..ad42e09e 100644 --- a/src/cifix/select.ts +++ b/src/cifix/select.ts @@ -7,9 +7,9 @@ import type { CifixCandidate, CifixSelection } from "./candidates.ts"; export function selectCifix(db: DatabaseSync, repo: string, run?: string | null, plans?: PlanSet): CifixSelection { const out: CifixSelection = { work: [], collect: [], rerun: [], capped: [], ask: [], lint: [] }; for (const { facts: f, action } of planned(db, "cifix", { repo, ...(run !== undefined ? { run } : {}), ...(plans ? { plans } : {}) })) { - const x = f.cifix!, r = f.review!; + const x = f.cifix!, r = f.review; const c: CifixCandidate = { - repo, number: f.number, head: action.head!, verdict: r.verdict as "take" | "take-fix", reason: r.reason, attempt: x.tries + 1, + repo, number: f.number, head: action.head!, verdict: r?.verdict === "take-fix" ? "take-fix" : "take", reason: r?.reason ?? "", attempt: x.tries + 1, route: f.pushable ? "branch" : "comment", rerun: x.rerunAt !== null, rerunAt: x.rerunAt, }; const bucket = action.params?.bucket; diff --git a/src/conversations/cards.ts b/src/conversations/cards.ts index 0b2a131f..0e4bd25c 100644 --- a/src/conversations/cards.ts +++ b/src/conversations/cards.ts @@ -430,7 +430,7 @@ export function applicableSteps(db: DatabaseSync, repo: string, n: number): stri if (isPr) { out.push("request_reviewers", "review", "fixup"); const d = openDecision(db, repo, n); - if (d && (d.kind === "merge" || d.kind === "scope")) out.push("fixup with merge"); + if (d && (d.kind === "merge" || d.kind === "scope" || d.kind === "hold")) out.push("fixup with merge"); } else if (!closeRefusal(db, repo, n)) out.push("transfer"); } else if (f.state === "CLOSED" && !("note" in reopenStep(db, repo, n))) out.push("reopen"); return quiet ? out.filter((k) => !PUBLIC_TEXT_STEPS.has(k)) : out; diff --git a/src/core/decide.ts b/src/core/decide.ts index abc304df..8e86dccf 100644 --- a/src/core/decide.ts +++ b/src/core/decide.ts @@ -3,7 +3,7 @@ import { BATCHABLE, MAIN_RED_HELD, PREMERGE_DEFECT_REASON, PREMERGE_UNSURE_REASON, PREMERGE_FAILED_REASON, PREMERGE_MAX_TRIES, RETRY_AFTER_MS, REVIEW_LABELS, KEEP_IN_CORE, RULE_LABELS, RULE_SIZES, RULE_TIERS, UNSURE_REASON, VERIFY_UNAVAILABLE, ciAllows, conflictNote, verifyAllows, verifyOk, - FIXUP_MAX_ATTEMPTS, CIFIX_FINAL_STATES, CIFIX_MAX_PUSHES_PER_PR, CIFIX_MAX_TRIES, CIFIX_MAX_TRIES_PER_PR, + FIXUP_MAX_ATTEMPTS, CIFIX_FINAL_STATES, CIFIX_MAX_PUSHES_PER_PR, CIFIX_MAX_TRIES, CIFIX_MAX_TRIES_PER_PR, STATE_REFUSAL, UNKNOWN_GAP_MS, UNKNOWN_REREADS, } from "./rules.ts"; import { UNCHECKED_REASON } from "./sensitive.ts"; import { inFlightNow, unassignActions } from "./assignment.ts"; @@ -38,6 +38,14 @@ export function queueEntry(f: PrFacts, merged: boolean, open: boolean): Entry { for (const c of f.statementConflicts) reasons.push(`conflicts with ${c.where}: "${excerpt(c.text)}" (${c.reason})`); if (f.verification?.state === VERIFY_UNAVAILABLE) reasons.push(`not verified: ${f.verification.summary ?? "Verify cannot build this repo"}`); if (f.ci === "none" && f.repoFacts.noCi) reasons.push("the repo has no CI checks"); + if (open && (f.verification?.state === "failed" || f.verification?.state === "error")) reasons.push(`verification ${f.verification.state === "failed" ? "failed" : "errored"}: ${excerpt(f.verification.summary ?? f.verification.note ?? "no detail")}`); + // A merge refused for a reason other than the state of CI or mergeable waits for nothing that changes by itself: a person is asked. + if (open && refusalStuck(f)) reasons.push(`the merge was refused: ${excerpt(f.lastMerge!.reason!)}`); + const stuckUnknown = open ? unknownStuck(f) : null; + if (stuckUnknown) reasons.push(stuckUnknown); + // The CI fix has nothing to fix, but the queue reads CI as failing: a person decides. + const idle = open ? ciFixIdle(f) : null; + if (idle) reasons.push(idle); // Only a merge answer is set aside at an unsure head; a hold or close still counts. const given = f.decision.answer; const answer = given === "merge" && r.unsure && !f.decision.mergeAnswerAfterReview ? null : given; @@ -87,13 +95,13 @@ function stateOf(f: PrFacts, e: Entry, merged: boolean, held: "backlog" | "dupli if (!e.reasons.length) e.path = "rule"; else if (e.answer === "merge") e.path = "operator"; if (f.mergeable === "CONFLICTING") return "conflict"; - if (f.ci === "failure") return "ci-failed"; + if (f.ci === "failure") return !e.path && ciFixIdle(f) ? "needs-decision" : "ci-failed"; if ((f.runs?.waiting ?? 0) > 0) return "ci-approval"; // A Merge? question is asked only once the operator can see the verification result. - if (!e.path) return verifyState(f) ?? "needs-decision"; + if (!e.path) { const v = verifyState(f); return v === "verify-failed" || v === "verify-error" ? "needs-decision" : v ?? "needs-decision"; } if (!ciAllows(e.path, f.ci, e.noCi) || f.mergeable !== "MERGEABLE") return "waiting-ci"; const v = verifyState(f); - if (v) return v; + if (v && !(e.path === "operator" && (v === "verify-failed" || v === "verify-error"))) return v; if (e.path === "rule" && e.premerge) { if (e.premerge === "none" || e.premerge === "retry") return "waiting-premerge"; if (e.premerge === "fix") { @@ -132,11 +140,11 @@ const premergeRetryDue = (f: PrFacts): boolean => { const WAITS: Partial> = { "waiting-ci": "CI or GitHub's mergeable state", "waiting-premerge": "the pre-merge review", "waiting-verify": "verification", "needs-decision": "an operator's Merge? answer", "ci-approval": "approval of CI runs", "waiting-main-ci": "a green main", "in-batch": "its batch", - "batch-checking": "its batch", "batch-failed": "its batch", "changes-requested": "the maintainer's review", refused: "a change in CI or mergeable state", + "batch-checking": "its batch", "batch-failed": "its batch", "verify-failed": "a person: verification failed", "verify-error": "a person: verification errored", "changes-requested": "the maintainer's review", refused: "a change in CI or mergeable state", }; /** Queue states whose WAITS text waits on a person. */ -const PERSON_WAITS: ReadonlySet = new Set(["needs-decision", "ci-approval", "changes-requested"]); +const PERSON_WAITS: ReadonlySet = new Set(["needs-decision", "ci-approval", "changes-requested", "verify-failed", "verify-error"]); /** An operator's Hold or Close answer at the head: nothing is pushed or asked of the contributor, whatever the source. */ const declinedBy = (f: PrFacts): boolean => f.decision.answer !== null && f.decision.answer !== "merge"; @@ -167,13 +175,47 @@ export function fixupOf(f: PrFacts): { bucket: FixupBucket; done: boolean } | nu return { bucket: f.repoFacts.pushApproved ? "fix" : "unapproved", done: false }; } -export type CifixBucket = "work" | "unapproved" | "cannot-push" | "formatting" | "linting" | "collect" | "rerun" | "rerun-wait" | "failed" | "capped" | "done"; +/** The last merge try was refused for a reason that is not about CI, mergeable or the head, and nothing changed since: only a person can clear it. */ +export function refusalStuck(f: PrFacts): boolean { + const m = f.lastMerge; + if (m?.outcome !== "refused" || !m.reason || STATE_REFUSAL.test(m.reason) || f.runsApprovedAfterMerge) return false; + return m.ci === null || m.mergeable === null || (m.ci === f.ci && m.mergeable === f.mergeable); +} + +/** GitHub still reports the mergeable state as unknown after every re-read: the reason for a Merge? question, or null. */ +export function unknownStuck(f: PrFacts): string | null { + const u = f.unknown; + if (!u || f.mergeable === "MERGEABLE" || f.mergeable === "CONFLICTING" || u.rereads < UNKNOWN_REREADS || !u.lastAt || f.now - Date.parse(u.lastAt) < UNKNOWN_GAP_MS) return null; + return `GitHub still reports the merge state as unknown after ${u.rereads} re-reads since ${u.since.slice(0, 16).replace("T", " ")}`; +} + +/** The CI fix is done with nothing to fix while the queue reads CI as failing: the reason for a Merge? question, or null. */ +export function ciFixIdle(f: PrFacts): string | null { + const c = f.cifix; + if (f.ci !== "failure" || f.mergeable === "CONFLICTING" || !c || !c.states.includes("skipped") || c.states.some((s) => s !== "skipped" && CIFIX_FINAL_STATES.includes(s)) || cifixBucket(f) !== "done") return null; + return `CI fails, but the CI fix has nothing to fix${c.skipReason ? ` (${excerpt(c.skipReason)})` : ""}`; +} + +export type CifixBucket = "unreviewed" | "work" | "unapproved" | "cannot-push" | "formatting" | "linting" | "collect" | "rerun" | "rerun-wait" | "failed" | "capped" | "done"; + +/** CI is red at the head, the review gate waits on it, and no take review covers the head. */ +function unreviewedRed(f: PrFacts): boolean { + const r = f.review; + const covered = !!r && (r.verdict === "take" || r.verdict === "take-fix") && r.head === f.head && !r.stale; + return f.ghState === "OPEN" && f.ci === "failure" && f.reviewHold?.kind === "ci" && f.reviewHold.red === true && !covered && !declinedBy(f) && !f.draft && notHeld(f) + && f.mergeable !== "CONFLICTING" && !f.changesRequested && !f.mergeHeld && !f.brokeByUs && !f.gateRed; +} /** Where the CI fix step stands for a PR whose CI fails at the reviewed head, or null when it is no candidate. */ export function cifixBucket(f: PrFacts): CifixBucket | null { const r = f.review, c = f.cifix; // Our own push that turned the checks red is repaired against the pushed head, whose review is still the one of the head before. const broke = !!f.brokeByUs || !!f.gateRed; + // The next review waits for green CI at a head no take review covers, and the CI fix needs a take review: the contributor is asked once. + if (c && unreviewedRed(f)) { + if (CIFIX_FINAL_STATES.some((s) => c.states.includes(s))) return "done"; + return f.repoFacts.commentApproved && !f.quiet ? "unreviewed" : "cannot-push"; + } if (declinedBy(f) || !r || !c || (r.verdict !== "take" && r.verdict !== "take-fix") || (r.head !== f.head && !broke) || f.ghState !== "OPEN" || (f.ci !== "failure" && !broke) || f.draft || !notHeld(f)) return null; if (f.mergeable === "CONFLICTING" || (r.stale && !broke) || f.changesRequested || f.mergeHeld) return null; if (r.verdict === "take-fix") { @@ -198,6 +240,7 @@ export function cifixBucket(f: PrFacts): CifixBucket | null { function cifixOf(f: PrFacts): "work" | "collect" | "rerun" | "capped" | "ask" | "other" | null { const b = cifixBucket(f); if (b === null) return null; + if (b === "unreviewed") return "ask"; // A fix given up or capped at this head: the contributor is asked once. // Not for our own breakage, and not when the fix-up already asked at this head: one comment per head. if ((b === "failed" || b === "capped") && f.repoFacts.commentApproved && !f.brokeByUs && fixupOf(f)?.bucket !== "asked") return "ask"; @@ -221,6 +264,17 @@ const stuckWait = (f: PrFacts): Wait | null => { return cf === "cannot-push" ? approval : null; }; +/** What a PR waits on when the review waits for red CI and the CI fix could not start: the contributor was asked, or a person decides. Null when the ask is still due. */ +const unreviewedWait = (f: PrFacts): Wait | null => { + if (!f.cifix || !unreviewedRed(f)) return null; + const s = f.cifix.states; + if (s.includes("asked")) return contributor("the contributor to fix CI"); + if (!f.repoFacts.commentApproved) return person("comment approval for the repo"); + if (s.includes("comment-failed")) return person("a person: the comment to the contributor failed"); + if (s.includes("skipped")) return person(`a person: CI is red and the CI fix has nothing to fix${f.cifix.skipReason ? ` (${excerpt(f.cifix.skipReason)})` : ""}`); + return CIFIX_FINAL_STATES.some((x) => s.includes(x)) ? person("a person to look at the red CI") : null; +}; + /** Actions that work the PR towards merge (a push, a base merge, a review of a new head, a pre-merge review, the merge), as against comment-only asks. */ const worksOn = (a: Action): boolean => { const b = a.params?.bucket; @@ -380,6 +434,12 @@ export function decidePr(f: PrFacts): Plan { else actions.push(act("cifix", f.head, { bucket: cf })); } + // A hold review: a person is asked once per head what to do (src/merge/hold.ts). A question left open for a head that is no longer held is set aside by the same step. + const hq = f.decision.hold; + const holdState = state === "opus-hold" && !!r && !held && !f.heldBacklog; + if (holdState && !hq.asked && !hq.otherOpen) actions.push(act("ask-merge", r!.head, { hold: true })); + else if (!holdState && hq.open) actions.push(act("ask-merge", f.head, { hold: true, withdraw: true, decisionHead: r?.head ?? f.head })); + // Stored model patches whose lint task ended: the collect step folds the format changes and pushes, or sends the findings back to the model. for (const l of f.lint) { // A conflict resolution is collected while the PR still conflicts; every other patch needs it not to. @@ -409,9 +469,24 @@ export function decidePr(f: PrFacts): Plan { actions.push(...unassignOf(f, state, actions)); const main = actions.some((a) => ["review", "carry", "premerge", "ask-merge", "merge", "verify"].includes(a.kind)); - const queueWait = (st: QueueState): Wait | null => (WAITS[st] ? { text: WAITS[st]!, kind: PERSON_WAITS.has(st) ? "person" : "system" } : null); + const queueWait = (st: QueueState): Wait | null => { + if (st === "waiting-ci" && f.mergeable !== "MERGEABLE" && f.mergeable !== "CONFLICTING" && f.unknown) { + const stuck = unknownStuck(f); + return stuck ? person(`${stuck}; closing and reopening the PR on GitHub makes it compute the state`) + : system(`GitHub's merge state, unknown since ${f.unknown.since.slice(11, 16)} (read again ${f.unknown.rereads} of ${UNKNOWN_REREADS})`); + } + if (st === "refused" && refusalStuck(f)) return person(`a person: the merge was refused (${excerpt(f.lastMerge!.reason!)})`); + if (st === "ci-failed") { const idle = ciFixIdle(f); if (idle) return person(`a person: ${idle}; fix the check or mark it optional`); } + return WAITS[st] ? { text: WAITS[st]!, kind: PERSON_WAITS.has(st) ? "person" : "system" } : null; + }; + // The Hold question of a hold review: open, answered Wait, or answered and being carried out. + const holdWait: Wait | null = holdState && !hq.asked && hq.otherOpen ? person("an answer to the item's open question; the Hold question follows") + : !holdState || !hq.asked ? null + : hq.open ? person("an operator's Hold answer") + : hq.answer === "wait" ? contributor("the author (the Hold question was answered: wait)") + : system("the answer to the Hold question to be carried out"); const wait: Wait | null = main ? null : e ? (f.mergeHeld && e.state !== "merged" ? person("merge held by an operator") : stuckWait(f) ?? (e.state === "needs-fix-up" ? fixupWait(f, fx, actions) : queueWait(e.state))) : null; // A review hold names what the pre-approved merge itself waits for, so it comes before the generic pre-approval wait. - const finalWait: Wait | null = wait ?? (!main && reviewWait ? (f.reviewHold?.person ? person(reviewWait) : system(reviewWait)) : null) ?? (f.operator?.hold && !main ? system("its pre-approved merge") : null); + const finalWait: Wait | null = wait ?? (main ? null : holdWait ?? unreviewedWait(f)) ?? (!main && reviewWait ? (f.reviewHold?.person ? person(reviewWait) : system(reviewWait)) : null) ?? (f.operator?.hold && !main ? system("its pre-approved merge") : null); return plan(state, { ...(e ? { path: e.path, reasons: e.reasons, note: e.note, conflictNote: e.conflictNote, eligible: eligible(f, e) } : {}), actions, wait: finalWait?.text ?? null, waitKind: finalWait?.kind ?? null }); } diff --git a/src/core/facts.ts b/src/core/facts.ts index b1bc04f7..a463c48e 100644 --- a/src/core/facts.ts +++ b/src/core/facts.ts @@ -29,7 +29,8 @@ import { attemptsOf, parseFixes } from "../fixup/candidates.ts"; import { operatorTries, operatorTriesLeft, operatorWork, queuedOperatorFix } from "../preapproval/state.ts"; import { getTask, TERMINAL } from "../build/tasks.ts"; import { SINCE_KEY } from "../postmerge/select.ts"; -import { BASE_NAME, OPEN_GROUP_SQL, PIPELINE_LOGIN_KEY, OPEN_QUESTION_SQL, UNSURE_AT_SQL, mergeDecisionId } from "./rules.ts"; +import { unknownOf } from "../merge/mergeable.ts"; +import { BASE_NAME, OPEN_GROUP_SQL, PIPELINE_LOGIN_KEY, OPEN_QUESTION_SQL, UNSURE_AT_SQL, mergeDecisionId, holdDecisionId } from "./rules.ts"; import { getRule, STATS_SQL, tierOf, type Tier } from "../whitelist.ts"; import { findingsOf, premergeAt, premergeFixUsed } from "../premerge/store.ts"; import { headOf } from "../review/candidates.ts"; @@ -170,7 +171,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const taskEnded = (id: number | null): boolean => { const t = id != null ? getTask(db, id) : null; return !t || TERMINAL.includes(t.state); }; const lintCifix = db.prepare("SELECT lint_task FROM ci_fixes WHERE repo = ? AND number = ? AND head = ? AND state = 'linting' ORDER BY rowid"); const lintConflict = db.prepare("SELECT lint_task FROM conflict_merges WHERE repo = ? AND number = ? AND from_head = ? AND state = 'linting' ORDER BY rowid"); - const cifixRows = db.prepare("SELECT state, created_at, task_id, runs FROM ci_fixes WHERE repo = ? AND number = ? AND head = ? ORDER BY created_at, rowid"); + const cifixRows = db.prepare("SELECT state, created_at, task_id, runs, reason FROM ci_fixes WHERE repo = ? AND number = ? AND head = ? ORDER BY created_at, rowid"); const cifixTotals = db.prepare(`SELECT COALESCE(SUM(state IN (${CIFIX_PUSH_STATES.map(() => "?").join(",")})), 0) AS pushes, COALESCE(SUM(state IN (${CIFIX_TRY_STATES.map(() => "?").join(",")})), 0) AS tries FROM ci_fixes WHERE repo = ? AND number = ?`); const queued = rows.filter((r) => r.in_pilot && r.not_integration && (r.r_verdict === "take" || r.r_verdict === "take-fix") && r.author); const tiers = tiersOf(db, [...new Set(queued.map((r) => r.author!))]); @@ -195,6 +196,13 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const waiting = db.prepare("SELECT runs, approved, reread, failed, cross_repo, approved_at FROM ci_run_approvals WHERE repo = ? AND number = ? AND head_oid = ?"); const verifs = db.prepare("SELECT state, kind, summary, note FROM verifications WHERE repo = ? AND number = ? AND head_sha = ?"); const decision = db.prepare("SELECT id FROM decisions WHERE id = ?"); + const holdRow = db.prepare("SELECT answer FROM decisions WHERE id = ?"); + // An item has one open question at a time (src/merge/withdraw.ts): a Hold question would set another one aside, so it waits for that one. + const otherOpen = db.prepare("SELECT 1 FROM decisions WHERE repo = ? AND number = ? AND answer IS NULL AND id NOT LIKE '%~replaced-%' AND id NOT LIKE '%:dupegroup:%' AND kind IN ('scope', 'merge', 'close') LIMIT 1"); + const holdQuestionOf = (repo: string, number: number, id: string): PrFacts["decision"]["hold"] => { + const row = holdRow.get(id) as { answer: string | null } | undefined; + return { asked: !!row, open: !!row && row.answer === null, answer: row?.answer ?? null, otherOpen: !!otherOpen.get(repo, number) }; + }; const statement = db.prepare("SELECT id, repo, number, text FROM owner_statements WHERE id = ?"); const openQuestion = db.prepare(OPEN_QUESTION_SQL); const answeredAfter = db.prepare(`SELECT 1 FROM decisions WHERE id = ? AND kind = 'merge' AND answer = 'merge' AND answered_at > ? AND ${settledBySql("decisions")}`); @@ -245,9 +253,9 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] inScope, integration, batchPr: !!r.batch_pr, heldBacklog: !!r.held_backlog, heldDuplicate: !r.held_backlog && !!r.held_dup, quiet: own.quiet.has(ref), mergeHeld: holds.has(ref), fast: (r.score ?? 0) >= FAST_FLOOR, score: r.score, repoFacts: rf.f, review: null, post: { postable: false, posted: null }, - checksHere: false, checksOpen: false, ci: "unknown", mergeable: r.i_mergeable ?? "UNKNOWN", runs: null, + checksHere: false, checksOpen: false, ci: "unknown", mergeable: r.i_mergeable ?? "UNKNOWN", unknown: null, runs: null, lastMerge: null, runsApprovedAfterMerge: false, verification: null, verifyUnavailable: null, - decision: { asked: false, openQuestion: false, answer: null, mergeAnswerAfterReview: false, inOpenGroup: grouped.has(ref) }, + decision: { asked: false, openQuestion: false, answer: null, mergeAnswerAfterReview: false, inOpenGroup: grouped.has(ref), hold: { asked: false, open: false, answer: null, otherOpen: false } }, premerge: null, premergeFixUsed: false, sensitive: null, statementConflicts: [], pushable: false, pushChain: [], conflict: null, inActiveBatch: activeBatched.has(ref), fixup: null, carry: [], lint: [], cifix: null, postmerge: null, batch: null, mainFix: false, changesRequested: null, gateFailureNote: null, }; base.inFlight = r.state === "OPEN" && !integration && !!r.author && own.isOwn(r.repo, r.author) && own.prs.has(ref); @@ -303,6 +311,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] stale: stale.has(`${ref}@${r.r_head}`), staleActionable: staleActionable.has(`${ref}@${r.r_head}`), }; base.pushChain = chain; + base.decision.hold = holdQuestionOf(r.repo, r.number, holdDecisionId(r.repo, r.number, r.r_head)); if (r.state === "OPEN" && head && head !== r.r_head && (ourFixupHead.get(r.repo, r.number, head) || ourSameDiffMerge.get(r.repo, r.number, head)) && carriedReview(db, { repo: r.repo, number: r.number, head_oid: head }, stale)) base.carriable = true; if (r.state === "OPEN" && (chain.length > 1 || (!!head && !!pushedHere.get(r.repo, r.number, head)))) base.inFlight = true; base.sensitive = sensitiveAt(r.repo, r.number, r.r_head); @@ -336,7 +345,8 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const last = merges.get(r.repo, r.number, r.r_head) as { outcome: string; reason: string | null; ci: string | null; mergeable: string | null; at: string } | undefined; // An operator's Retry after a refusal asks for another try now, without waiting for CI or the mergeable state to change. - if (last && !(last.outcome === "refused" && retriedAfter.get(mergeDecisionId(r.repo, r.number, r.r_head), last.at))) { + // A fresh Merge answer after a refusal asks for another try, as a Retry does. + if (last && !(last.outcome === "refused" && (retriedAfter.get(mergeDecisionId(r.repo, r.number, r.r_head), last.at) || answeredAfter.get(mergeDecisionId(r.repo, r.number, r.r_head), last.at)))) { base.lastMerge = { outcome: last.outcome, reason: last.reason, ci: last.ci, mergeable: last.mergeable }; base.runsApprovedAfterMerge = !!wait?.approved_at && wait.approved_at > last.at; } @@ -344,11 +354,13 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] if (!base.verification || base.verification.state === "stale") { base.verifyUnavailable = !rf.pub ? PRIVATE_REASON : rf.f.noCi && cachedRust(r.repo, r.r_head) === false ? NOT_RUST_REASON : null; } + if (r.state === "OPEN" && base.mergeable !== "MERGEABLE" && base.mergeable !== "CONFLICTING") base.unknown = unknownOf(db, r.repo, r.number, r.r_head); const id = mergeDecisionId(r.repo, r.number, r.r_head); const given = answers.get(id) ?? null; base.decision = { asked: !!decision.get(id), openQuestion: r.state === "OPEN" && !!openQuestion.get(r.repo, r.number), answer: given, mergeAnswerAfterReview: given === "merge" && !!answeredAfter.get(id, r.r_at), inOpenGroup: grouped.has(ref), + hold: base.decision.hold, }; if (r.state !== "OPEN") { out.push(base); continue; } @@ -376,8 +388,8 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] if (base.lint.length && r.state === "OPEN") base.inFlight = true; } if (base.ci === "failure" || base.brokeByUs || base.gateRed) { - const cfHead = base.brokeByUs || base.gateRed ? head : r.r_head; - const prior = cifixRows.all(r.repo, r.number, cfHead) as { state: string; created_at: string; task_id: number | null; runs: string | null }[]; + const cfHead = base.brokeByUs || base.gateRed || (head && head !== r.r_head) ? head : r.r_head; + const prior = cifixRows.all(r.repo, r.number, cfHead) as { state: string; created_at: string; task_id: number | null; runs: string | null; reason: string | null }[]; const totals = cifixTotals.get(...CIFIX_PUSH_STATES, ...CIFIX_TRY_STATES, r.repo, r.number) as { pushes: number; tries: number }; const formatting = prior.find((x) => x.state === "formatting"); const task = formatting?.task_id != null ? getTask(db, formatting.task_id) : null; @@ -388,6 +400,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] infraRuns: infra ? (parseList(infra.runs ?? "[]") as number[]) : null, formattingTask: formatting?.task_id ?? null, formatterEnded: !task || TERMINAL.includes(task.state), totalPushes: totals.pushes, totalTries: totals.tries, checksAt: r.c_at, + skipReason: [...prior].reverse().find((x) => x.state === "skipped")?.reason ?? null, }; } base.batch = inBatch.get(`${ref}@${r.r_head}`) ?? null; diff --git a/src/core/issue-facts.ts b/src/core/issue-facts.ts index cef33e11..1cfc7a1c 100644 --- a/src/core/issue-facts.ts +++ b/src/core/issue-facts.ts @@ -145,7 +145,7 @@ export function loadItemFacts(db: DatabaseSync, opts: ItemLoadOptions = {}): Ite const waitingExec = new Set((db.prepare("SELECT id FROM main.decisions WHERE exec_state IN ('waiting-token', 'waiting-permission') AND applied_at IS NULL").all() as { id: string }[]).map((r) => r.id)); const answeredClose = new Map(); for (const a of actionable(db)) { - if (a.kind !== "scope" && a.kind !== "close" && a.kind !== "duplicate" && a.kind !== "merge") continue; + if (a.kind !== "scope" && a.kind !== "close" && a.kind !== "duplicate" && a.kind !== "merge" && a.kind !== "hold") continue; if (a.kind !== "scope" && a.number === null) continue; for (const it of a.items) { const ex = a.exceptions.find((e) => e.repo === it.repo && e.number === it.number); diff --git a/src/core/plan.ts b/src/core/plan.ts index 681c1528..63866d10 100644 --- a/src/core/plan.ts +++ b/src/core/plan.ts @@ -168,6 +168,8 @@ export type PrFacts = { /** CI at the reviewed head with optional checks applied; "pending" while approved runs have not finished; "unknown" when the checks are of another head. */ ci: string; mergeable: string; + /** The mergeable state has read as unknown since `since`, and was read again `rereads` times (src/merge/mergeable.ts); null when it is known. */ + unknown: { since: string; rereads: number; lastAt: string | null } | null; /** Workflow runs waiting for approval at the head the checks describe (for an integration PR: at the batch tip). */ runs: { waiting: number; reread: boolean; crossRepo: boolean; approvable: number; @@ -194,6 +196,8 @@ export type PrFacts = { mergeAnswerAfterReview: boolean; /** Member of an open duplicate group (asked after the group is answered). */ inOpenGroup: boolean; + /** The Hold question of a review that says hold, at the reviewed head: asked at all, still unanswered, and the answer given. */ + hold: { asked: boolean; open: boolean; answer: string | null; /** Another open question of the item (scope, Merge?, Close?) is asked first. */ otherOpen: boolean }; }; /** The pre-merge review row at the reviewed head. */ @@ -229,6 +233,8 @@ export type PrFacts = { states: string[]; tries: number; rerunAt: string | null; infraRuns: number[] | null; formattingTask: number | null; formatterEnded: boolean; totalPushes: number; totalTries: number; + /** The reason of the head's skipped CI fix (nothing to fix), or null. */ + skipReason: string | null; /** When the checks were fetched (ISO). */ checksAt: string | null; } | null; @@ -343,7 +349,7 @@ export type ItemFacts = { }; /** Operator answers "close" that the Act step applies to this item: one per decision, with the state of its action row (null: none yet; done and skipped are final). */ - answeredClose: { decisionId: string; kind: "scope" | "close" | "duplicate" | "merge"; security: boolean; action: string | null; /** A member of a duplicate group decision: the Act step closes it, and its close record (not an actions row) ends the target. */ group?: boolean; /** The decision waits for its operator's token or access: no act action until it is retried or answered again. */ waiting?: boolean }[]; + answeredClose: { decisionId: string; kind: "scope" | "close" | "duplicate" | "merge" | "hold"; security: boolean; action: string | null; /** A member of a duplicate group decision: the Act step closes it, and its close record (not an actions row) ends the target. */ group?: boolean; /** The decision waits for its operator's token or access: no act action until it is retried or answered again. */ waiting?: boolean }[]; /** The final Opus review at the PR's latest review head says close. `atHead`: that is the PR's current head. `asked`: the Close? decision at that head exists. */ closeReview: { head: string; atHead: boolean; asked: boolean } | null; diff --git a/src/core/rules.ts b/src/core/rules.ts index 20ea0c2a..06fe7276 100644 --- a/src/core/rules.ts +++ b/src/core/rules.ts @@ -19,8 +19,17 @@ export const VERIFY_OK = ["passed", "ci-enough"]; export const verifyOk = (state: string | null | undefined): boolean => !!state && VERIFY_OK.includes(state); /** A PR in a repo Verify cannot build is merged only on an operator's answer, which says "not verified". */ export const VERIFY_UNAVAILABLE = "unavailable"; +/** A failed or errored verification is asked about in the Merge? question; an operator's Merge answer to it stands. */ export const verifyAllows = (path: "rule" | "operator" | null, state: string | null | undefined): boolean => - verifyOk(state) || (path === "operator" && state === VERIFY_UNAVAILABLE); + verifyOk(state) || (path === "operator" && (state === VERIFY_UNAVAILABLE || state === "failed" || state === "error")); + +/** A PR whose mergeable state reads unknown is read again (src/merge/mergeable.ts): after UNKNOWN_AFTER_MS, UNKNOWN_REREADS times, UNKNOWN_GAP_MS apart; then a person is asked. */ +export const UNKNOWN_AFTER_MS = 30 * 60_000; +export const UNKNOWN_GAP_MS = 2 * 3600_000; +export const UNKNOWN_REREADS = 3; + +/** A merge refusal that only reports the state of CI, mergeable or the head: it clears when that state changes. Any other refusal is asked about. */ +export const STATE_REFUSAL = /^(not ready at merge time|head moved|no longer open|GitHub returned no such PR|the operator's merge answer is gone|verification at)/; export const ciAllows = (path: "rule" | "operator" | null, ci: string | null | undefined, noCi: boolean): boolean => ci === "success" || (path === "operator" && ci === "none" && noCi); @@ -107,6 +116,15 @@ export const MERGE_OPTIONS = { close: { key: "close", label: "Close", hint: "Not wanted as it is; post a short comment and close the PR." }, } as const; +/** Options of the "Hold" question asked for a PR whose Opus review says hold. Review again, and a fix-up first, are offered as cores (src/decide/choices.ts). */ +export const HOLD_OPTIONS = { + wait: { key: "wait", label: "Wait for the author", hint: "Keep it open and leave it to the author; asked again after a new commit or review." }, + close: { key: "close", label: "Close", hint: "Not wanted as it is; post a short comment and close the PR." }, +} as const; + +/** One Hold question per PR head. */ +export const holdDecisionId = (repo: string, number: number, head: string): string => `${repo}#${number}:hold@${head}`; + /** One open decision per PR head: a push gets a new one. */ export const mergeDecisionId = (repo: string, number: number, head: string): string => `${repo}#${number}:merge@${head}`; export const HEAD_FACT = "head commit "; diff --git a/src/db.ts b/src/db.ts index 1efb3d06..092ee490 100644 --- a/src/db.ts +++ b/src/db.ts @@ -323,7 +323,7 @@ function migrateValues(db: DatabaseSync): void { db.exec("BEGIN IMMEDIATE"); db.exec(`UPDATE main.decisions SET prepared_at = NULL, prepared_head = NULL WHERE answer IS NULL AND number IS NOT NULL AND id NOT LIKE '%:dupegroup:%' AND prepared_at IS NOT NULL - AND NOT (kind IN ('merge', 'close') AND instr(id, '@') > 0 + AND NOT (kind IN ('merge', 'close', 'hold') AND instr(id, '@') > 0 AND substr(id, instr(id, '@') + 1) IS NOT (SELECT i.head_oid FROM main.items i WHERE i.repo = decisions.repo AND i.number = decisions.number)) AND ((recommended IS NOT NULL AND NOT EXISTS (SELECT 1 FROM main.conversation_cards c WHERE c.repo = decisions.repo AND c.number = decisions.number AND c.state = 'proposed' AND (json_extract(c.params, '$.settle.option') = decisions.recommended OR json_extract(c.params, '$.option') = decisions.recommended))) diff --git a/src/decide/choices.ts b/src/decide/choices.ts index f47bd55a..cace2bd7 100644 --- a/src/decide/choices.ts +++ b/src/decide/choices.ts @@ -104,6 +104,7 @@ export function autocraftLine(p: ParsedCoreKey, kind: string, itemKind: string): case "take": case "small-extra": return itemKind === "pr" ? "keeps working: review, fix-up, merge" : "keeps working: may try a fix"; case "plugin": return "adds the plugin candidate label later"; case "need-info": return "keeps it out of later stages until asked again"; + case "wait": return "keeps it open and leaves it to the author; asks again after a new commit or review"; case "accept": return "closes the duplicates and keeps the original"; case "distinct": return "records that they differ and works on each"; } @@ -134,6 +135,8 @@ export function coresFor(db: DatabaseSync, d: DecisionRow): Core[] { if (!d.repo || !d.number || d.id.includes(":dupegroup:") || !itemOf(db, d.repo, d.number)) return []; const applicable = new Set(applicableSteps(db, d.repo, d.number)); const out: Core[] = []; + // A Hold question always offers a new review first: the other cores follow the options. + if (d.kind === "hold") { const c = addedCore(db, d, coreKey.review, applicable); if (c) out.push(c); } for (const o of optionsOf(d)) { if (o.key === "backlog") continue; const effect = writeEffect(d.kind, o.key); diff --git a/src/decide/prepare.ts b/src/decide/prepare.ts index 3b01fdec..5356e73b 100644 --- a/src/decide/prepare.ts +++ b/src/decide/prepare.ts @@ -265,7 +265,7 @@ export async function prepare(db: DatabaseSync, ids: string[], p: PrepareParams) const got = r.value; // The PR moved on while the call ran: the next pass prepares it for the new head. A group's kept item may be closed; prepareIds decides whether the group is still open. const after = itemOf.get(repo, n) as ItemRow | undefined; - if (!after || (!group && after.state !== "OPEN") || (isPr && d.kind === "merge" && after.head_oid !== head)) { + if (!after || (!group && after.state !== "OPEN") || (isPr && (d.kind === "merge" || d.kind === "hold") && after.head_oid !== head)) { // Counted as a try at the head it was asked for: a new head is prepared at once, anything else waits like a failure instead of repeating every pass. failed.run(head, now(), head, d.id); p.log(`decide: ${d.id}: head moved on during the call; prepared again next pass`); diff --git a/src/decide/prepared.ts b/src/decide/prepared.ts index dfb849f1..d55f70f7 100644 --- a/src/decide/prepared.ts +++ b/src/decide/prepared.ts @@ -71,7 +71,7 @@ export const utcDayStart = (nowMs: number): string => `${new Date(nowMs).toISOSt /** A Merge? or Close? decision is made for one head commit: its id ends in `@`. */ const idHead = (d: PrepareColumns): string | null => { - const m = d.id === undefined || (d.kind !== "merge" && d.kind !== "close") ? null : /:(?:merge|close)@(.+)$/.exec(d.id); + const m = d.id === undefined || (d.kind !== "merge" && d.kind !== "close" && d.kind !== "hold") ? null : /:(?:merge|close|hold)@(.+)$/.exec(d.id); return m ? m[1]! : null; }; @@ -82,7 +82,7 @@ const idHead = (d: PrepareColumns): string | null => { */ export const isPrepared = (d: PrepareColumns, head: string | null): boolean => { if (d.prepared_at === null) return false; - if (d.kind === undefined || d.kind === "merge") return (d.prepared_head ?? null) === (head ?? null); + if (d.kind === undefined || d.kind === "merge" || d.kind === "hold") return (d.prepared_head ?? null) === (head ?? null); if (d.prepared_discussion != null && (d.discussion_key ?? "") !== d.prepared_discussion && ((d.prepares_today ?? 0) < DISCUSSION_PREPARES_PER_DAY || !!d.prepare_requested_at)) return false; if (choicesDependOnCode(d.stale_choices)) return false; return !(d.reviewed_at && d.reviewed_at > d.prepared_at); diff --git a/src/decisions-used.ts b/src/decisions-used.ts index 417a52bc..46c15604 100644 --- a/src/decisions-used.ts +++ b/src/decisions-used.ts @@ -25,11 +25,12 @@ export function applyUsedAnswers(db: DatabaseSync, at: string = new Date().toISO const attempted = db.prepare("SELECT 1 FROM fix_attempts WHERE repo = ? AND number = ?"); let n = 0; for (const a of actionable(db)) { - if (a.kind !== "scope" && a.kind !== "close") continue; + if (a.kind !== "scope" && a.kind !== "close" && a.kind !== "hold") continue; const d = getDecision(db, a.id)!; const perItem = a.items.map((it) => ({ it, answer: a.exceptions.find((e) => e.repo === it.repo && e.number === it.number)?.answer ?? a.answer })); if (!perItem.length || perItem.some((p) => p.answer === "close")) continue; const used = perItem.every(({ it, answer }) => { + if (a.kind === "hold") return answer === "wait"; if (a.kind === "close") return answer === "hold" || answer === "keep"; if (answer === "need-info") return true; const row = item.get(it.repo, it.number) as ItemRow | undefined; diff --git a/src/decisions.ts b/src/decisions.ts index 4a684105..962a283d 100644 --- a/src/decisions.ts +++ b/src/decisions.ts @@ -10,7 +10,7 @@ import { audit } from "./dash/audit.ts"; import { connect } from "./db.ts"; import { inPilot } from "./pilot.ts"; -export const KINDS = ["scope", "duplicate", "close", "merge", "split", "other"] as const; +export const KINDS = ["scope", "duplicate", "close", "merge", "hold", "split", "other"] as const; export type Kind = (typeof KINDS)[number]; export type Option = { key: string; label: string; hint?: string }; diff --git a/src/merge/index.ts b/src/merge/index.ts index ca046a3e..c1ef8342 100644 --- a/src/merge/index.ts +++ b/src/merge/index.ts @@ -38,6 +38,7 @@ import { envVar } from "../env.ts"; import { effectiveCi, optionalChecks } from "../optional-checks.ts"; import { jobItem } from "../runner/job-items.ts"; import { sweepStaleAnswers } from "../answers/sweep.ts"; +import { askHoldDecisions } from "../act/index.ts"; import { authFailure, isWaiting, laneForDecision, markExecDone, noWriteReason, setExecState, SIGN_IN_REASON, type Lane, type LaneDeps } from "../github/user-lane.ts"; import { ownerOf } from "../owners.ts"; @@ -228,12 +229,13 @@ function askDue(db: DatabaseSync, due: QueueEntry[], at: string, log: (line: str export function askMergeDecisions(db: DatabaseSync, opts: { repos?: string[]; run?: string | null; at?: string; log?: (line: string) => void } = {}): string[] { const repos = opts.repos && new Set(opts.repos); const queue = buildQueue(db, { merged: "exclude", ...(opts.run === undefined ? {} : { run: opts.run }) }); - const asks = new Set(planned(db, "ask-merge", { ...(opts.run === undefined ? {} : { run: opts.run }) }).filter((p) => !repos || repos.has(p.facts.repo)).map((p) => `${p.facts.repo}#${p.facts.number}`)); + const asks = new Set(planned(db, "ask-merge", { ...(opts.run === undefined ? {} : { run: opts.run }) }).filter((p) => !p.action.params?.hold && (!repos || repos.has(p.facts.repo))).map((p) => `${p.facts.repo}#${p.facts.number}`)); const due = queue.filter((e) => asks.has(`${e.repo}#${e.number}`)); const at = opts.at ?? new Date().toISOString(); withdrawBlockedQuestions(db, queue.filter((e) => !repos || repos.has(e.repo)), at); for (const r of repos ?? new Set(queue.map((e) => e.repo))) withdrawGroupedQuestions(db, at, r); const ids = askDue(db, due, at, opts.log); + for (const r of repos ?? new Set(planned(db, "ask-merge", {}).filter((p) => p.action.params?.hold).map((p) => p.facts.repo))) ids.push(...askHoldDecisions(db, at, r)); fillReviewSummaries(db, at); return ids; } @@ -276,7 +278,7 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line // An answered merge that waits for its operator's token or access takes no slot of the limit; it comes back when retried. picks = picks.filter((e) => !(e.path === "operator" && isWaiting(db, e.decisionId))); if (params.limit !== undefined) picks = picks.slice(0, params.limit); - const askDueNow = new Set(planned(db, "ask-merge", { repo }).map((p) => p.facts.number)); + const askDueNow = new Set(planned(db, "ask-merge", { repo }).filter((p) => !p.action.params?.hold).map((p) => p.facts.number)); const ask1 = open.filter((e) => askDueNow.has(e.number)); const summary: MergeSummary = { runId, repo, dryRun, states, attempted: [], merged: [], refused: [], asked: [] }; log(`merge ${repo}: ${queue.length} in the queue (${QUEUE_STATES.filter((s) => states[s]).map((s) => `${states[s]} ${s}`).join(", ") || "none"})`); @@ -301,6 +303,8 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line summary.asked = askDue(db, ask1, at(), log); log(` asked ${summary.asked.length} Merge? decision${summary.asked.length === 1 ? "" : "s"}`); } + const holds = askHoldDecisions(db, at(), repo); + if (holds.length) { summary.asked.push(...holds); log(` asked ${holds.length} Hold decision${holds.length === 1 ? "" : "s"}`); } fillReviewSummaries(db, at()); // What GitHub reported for the PR being tried, once known; a refusal records it so the autopilot retries only when it changes. diff --git a/src/merge/mergeable.ts b/src/merge/mergeable.ts new file mode 100644 index 00000000..794e5bb0 --- /dev/null +++ b/src/merge/mergeable.ts @@ -0,0 +1,58 @@ +// A PR whose mergeable state GitHub keeps reporting as unknown. The checks step reads every waiting PR each minute; when a read still +// shows UNKNOWN after UNKNOWN_AFTER_MS, the PR is read again (GitHub computes the merge state when a PR is requested), at most +// UNKNOWN_REREADS times with UNKNOWN_GAP_MS between tries. The merge queue then asks a person (src/core/decide.ts). +import type { DatabaseSync } from "node:sqlite"; +import type { Querier } from "../mirror.ts"; +import { refreshChecks, type PrChecks } from "../review/checks.ts"; + +import { UNKNOWN_AFTER_MS, UNKNOWN_GAP_MS, UNKNOWN_REREADS } from "../core/rules.ts"; + +export { UNKNOWN_AFTER_MS, UNKNOWN_GAP_MS, UNKNOWN_REREADS }; + +const PREFIX = "mergeable_unknown:"; +const keyOf = (repo: string, n: number) => `${PREFIX}${repo}#${n}`; + +export type UnknownState = { head: string; since: string; rereads: number; lastAt: string | null }; + +const parse = (v: string): UnknownState | null => { try { const x = JSON.parse(v) as UnknownState; return typeof x.since === "string" && typeof x.head === "string" ? x : null; } catch { return null; } }; + +/** Keeps the first time a head was seen with an unknown mergeable state; a known state forgets it. */ +export function noteMergeable(db: DatabaseSync, rows: PrChecks[], at: string): void { + const get = db.prepare("SELECT value FROM main.settings WHERE key = ?"); + const set = db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value"); + const del = db.prepare("DELETE FROM main.settings WHERE key = ?"); + for (const r of rows) { + const k = keyOf(r.repo, r.number); + const cur = get.get(k) as { value: string } | undefined; + if (r.mergeable === "MERGEABLE" || r.mergeable === "CONFLICTING" || r.state !== "OPEN") { if (cur) del.run(k); continue; } + const prev = cur ? parse(cur.value) : null; + if (!prev || prev.head !== r.head_oid) set.run(k, JSON.stringify({ head: r.head_oid, since: at, rereads: 0, lastAt: null } satisfies UnknownState)); + } +} + +/** What the planner needs for one PR at a head, or null when its state is not unknown (or not noted yet). */ +export function unknownOf(db: DatabaseSync, repo: string, n: number, head: string): UnknownState | null { + const row = db.prepare("SELECT value FROM main.settings WHERE key = ?").get(keyOf(repo, n)) as { value: string } | undefined; + const s = row ? parse(row.value) : null; + return s && s.head === head ? s : null; +} + +/** Reads the repo's long-unknown PRs again, one try each per UNKNOWN_GAP_MS. Returns the numbers read. */ +export async function rereadUnknown(db: DatabaseSync, client: Querier, repo: string, log: (line: string) => void = () => {}, nowMs: number = Date.now()): Promise { + const rows = db.prepare("SELECT key, value FROM main.settings WHERE key LIKE ?").all(`${PREFIX}${repo}#%`) as { key: string; value: string }[]; + const due: { n: number; s: UnknownState }[] = []; + for (const r of rows) { + const s = parse(r.value); + const n = Number(r.key.slice(r.key.lastIndexOf("#") + 1)); + if (!s || !Number.isInteger(n) || s.rereads >= UNKNOWN_REREADS) continue; + if (Date.parse(s.since) + UNKNOWN_AFTER_MS > nowMs || (s.lastAt !== null && Date.parse(s.lastAt) + UNKNOWN_GAP_MS > nowMs)) continue; + due.push({ n, s }); + } + if (!due.length) return []; + // The count is stored before the read: a failing read still uses up its try. + const set = db.prepare("UPDATE main.settings SET value = ? WHERE key = ?"); + for (const d of due) set.run(JSON.stringify({ ...d.s, rereads: d.s.rereads + 1, lastAt: new Date(nowMs).toISOString() } satisfies UnknownState), keyOf(repo, d.n)); + await refreshChecks(db, client, repo, due.map((d) => d.n), log); + log(`checks: ${repo}: read ${due.length} PR${due.length === 1 ? "" : "s"} with an unknown mergeable state again (${due.map((d) => `#${d.n}`).join(", ")})`); + return due.map((d) => d.n); +} diff --git a/src/merge/queue.ts b/src/merge/queue.ts index b4f37d9c..e61911dc 100644 --- a/src/merge/queue.ts +++ b/src/merge/queue.ts @@ -13,7 +13,7 @@ import type { Tier } from "../whitelist.ts"; export { QUEUE_STATES, type QueueState }; export { RULE_LABELS, RULE_SIZES, RULE_TIERS, UNSURE_REASON, PREMERGE_DEFECT_REASON, PREMERGE_UNSURE_REASON, PREMERGE_FAILED_REASON, VERIFY_OK, verifyOk, VERIFY_UNAVAILABLE, verifyAllows, ciAllows, - MERGE_OPTIONS, mergeDecisionId, HEAD_FACT, OPEN_GROUP_SQL, PIPELINE_LOGIN_KEY, + MERGE_OPTIONS, mergeDecisionId, holdDecisionId, HEAD_FACT, OPEN_GROUP_SQL, PIPELINE_LOGIN_KEY, } from "../core/rules.ts"; export { NO_CI_SAMPLE, repoHasNoCi } from "./no-ci.ts"; export { headWasUnsure, ownFixPrs } from "../core/facts.ts"; diff --git a/src/merge/withdraw.ts b/src/merge/withdraw.ts index 39e630e6..0d985deb 100644 --- a/src/merge/withdraw.ts +++ b/src/merge/withdraw.ts @@ -2,7 +2,7 @@ import type { DatabaseSync } from "node:sqlite"; import { audit } from "../dash/audit.ts"; import { clearAskedStage } from "../decisions.ts"; -import { mergeDecisionId, OPEN_GROUP_SQL, type QueueEntry } from "./queue.ts"; +import { holdDecisionId, mergeDecisionId, OPEN_GROUP_SQL, type QueueEntry } from "./queue.ts"; /** Answer value of a question the pipeline set aside; no operator wrote it, so no later step acts on it. */ export const WITHDRAWN = "withdrawn"; @@ -21,10 +21,18 @@ function renameDecision(db: DatabaseSync, id: string, to: string): void { * answered one that was not acted on yet is marked applied with a note. */ export function withdrawMergeQuestion(db: DatabaseSync, repo: string, number: number, head: string, at: string, why = "superseded by a new review"): boolean { - const id = mergeDecisionId(repo, number, head); + return setAside(db, mergeDecisionId(repo, number, head), repo, number, head, at, why, (a) => a !== "merge"); +} + +/** Sets the head's Hold question aside the same way. A close answer waiting for Act still stands. */ +export function withdrawHoldQuestion(db: DatabaseSync, repo: string, number: number, head: string, at: string, why = "superseded by a new review"): boolean { + return setAside(db, holdDecisionId(repo, number, head), repo, number, head, at, why, (a) => a === "close"); +} + +function setAside(db: DatabaseSync, id: string, repo: string, number: number, head: string, at: string, why: string, stands: (answer: string) => boolean): boolean { const row = db.prepare("SELECT answer, applied_at FROM decisions WHERE id = ?").get(id) as { answer: string | null; applied_at: string | null } | undefined; - // An answer other than merge (close, hold) waiting for Act still stands: the new review doesn't change it. - if (!row || (row.answer !== null && row.answer !== "merge" && !row.applied_at)) return false; + // An answer that waits for Act and does not depend on the review still stands: the new review doesn't change it. + if (!row || (row.answer !== null && stands(row.answer) && !row.applied_at)) return false; const old = `${id}~replaced-${at}`; db.exec("BEGIN IMMEDIATE"); try { @@ -134,7 +142,7 @@ const HEAD_MOVED_NOTE = "the pull request changed since"; */ function setAsideOldHeadQuestions(db: DatabaseSync, at: string, repo?: string): number { const rows = db.prepare(`SELECT d.id, d.kind, d.repo, d.number FROM decisions d JOIN items i ON i.repo = d.repo AND i.number = d.number - WHERE d.answer IS NULL AND d.kind IN ('merge', 'close') AND d.id NOT LIKE '%~replaced-%' AND i.kind = 'pr' AND i.head_oid IS NOT NULL + WHERE d.answer IS NULL AND d.kind IN ('merge', 'close', 'hold') AND d.id NOT LIKE '%~replaced-%' AND i.kind = 'pr' AND i.head_oid IS NOT NULL AND d.id <> d.repo || '#' || d.number || ':' || d.kind || '@' || i.head_oid AND d.id LIKE d.repo || '#' || d.number || ':' || d.kind || '@%' ${repo ? "AND d.repo = ?" : ""}`) .all(...(repo ? [repo] : [])) as { id: string; kind: string; repo: string; number: number }[]; if (!rows.length) return 0; @@ -164,7 +172,7 @@ function setAsideOldHeadQuestions(db: DatabaseSync, at: string, repo?: string): export function setAsideSupersededQuestions(db: DatabaseSync, at: string, repo?: string): number { const stale = setAsideOldHeadQuestions(db, at, repo); const rows = db.prepare(`SELECT id, kind, repo, number FROM decisions WHERE answer IS NULL AND number IS NOT NULL - AND kind IN ('scope', 'merge', 'close') AND id NOT LIKE '%:dupegroup:%' AND id NOT LIKE '%~replaced-%' ${repo ? "AND repo = ?" : ""} + AND kind IN ('scope', 'merge', 'close', 'hold') AND id NOT LIKE '%:dupegroup:%' AND id NOT LIKE '%~replaced-%' ${repo ? "AND repo = ?" : ""} ORDER BY asked_at DESC, rowid DESC`).all(...(repo ? [repo] : [])) as { id: string; kind: string; repo: string; number: number }[]; const seen = new Set(); const aside: { r: (typeof rows)[number]; why: string }[] = []; @@ -205,7 +213,7 @@ const closedWhy = (r: OpenRow): string => r.state === "MERGED" ? "the pull reque export function withdrawClosedQuestions(db: DatabaseSync, at: string): number { const single = db.prepare(`SELECT d.id, d.kind, d.repo, d.number, i.state, i.kind AS itemKind FROM decisions d JOIN items i ON i.repo = d.repo AND i.number = d.number - WHERE d.answer IS NULL AND d.number IS NOT NULL AND d.kind IN ('scope', 'close', 'merge', 'duplicate') AND d.id NOT LIKE '%:dupegroup:%' AND d.id NOT LIKE '%~replaced-%' + WHERE d.answer IS NULL AND d.number IS NOT NULL AND d.kind IN ('scope', 'close', 'merge', 'hold', 'duplicate') AND d.id NOT LIKE '%:dupegroup:%' AND d.id NOT LIKE '%~replaced-%' AND i.state IN ('CLOSED', 'MERGED')`).all() as OpenRow[]; const groups = db.prepare(`SELECT d.id, d.kind, d.repo, d.number FROM decisions d WHERE d.answer IS NULL AND d.kind = 'duplicate' AND d.id LIKE '%:dupegroup:%' AND d.id NOT LIKE '%~replaced-%' diff --git a/src/review/checks.ts b/src/review/checks.ts index 5ac4b6de..e0efb142 100644 --- a/src/review/checks.ts +++ b/src/review/checks.ts @@ -5,6 +5,7 @@ import { KEEP_KNOWN_MERGEABLE, type Querier } from "../mirror.ts"; import { pilotSql } from "../pilot.ts"; import { resolvePushes } from "../push-outcomes.ts"; import { overallAt, recordRuns, type Suite } from "../merge/ci-approval.ts"; +import { noteMergeable } from "../merge/mergeable.ts"; /** PRs per query: 100 check contexts each keeps a query well under GitHub's node limit. */ export const CHECKS_PER_QUERY = 40; @@ -101,6 +102,7 @@ export function saveChecks(db: DatabaseSync, rows: PrChecks[], at = new Date().t ins.run(r.repo, r.number, r.head_oid, r.state, r.is_draft ? 1 : 0, r.overall, JSON.stringify(r.checks), r.mergeable, r.maintainer_can_modify ? 1 : 0, at); for (const r of rows) recordRuns(db, r, at); resolvePushes(db, rows, at); + noteMergeable(db, rows, at); } /** Fetches and stores the checks of the given PRs (all open PRs of the repo when none are given). */ diff --git a/src/review/index.ts b/src/review/index.ts index 91d2b7f2..b3f8d5a0 100644 --- a/src/review/index.ts +++ b/src/review/index.ts @@ -7,6 +7,7 @@ import type { DatabaseSync } from "node:sqlite"; import { connect } from "../db.ts"; import { Client, type Querier } from "../mirror.ts"; import { refreshChecks } from "./checks.ts"; +import { rereadUnknown } from "../merge/mergeable.ts"; import { markReviewsStale, withRetry } from "./discussion.ts"; export type ChecksParams = { repo: string }; @@ -14,6 +15,7 @@ export type ChecksParams = { repo: string }; /** For the runner: refreshes CI and merge state of every open PR of the repo. */ export async function runChecks(db: DatabaseSync, params: ChecksParams, log: (line: string) => void = console.log, querier: Querier = new Client(1000)): Promise<{ prs: number }> { const rows = await withRetry(() => refreshChecks(db, querier, params.repo, undefined, log)); + await rereadUnknown(db, querier, params.repo, log); return { prs: rows.length }; } diff --git a/src/review/opus.ts b/src/review/opus.ts index a9d64298..c146bf35 100644 --- a/src/review/opus.ts +++ b/src/review/opus.ts @@ -13,7 +13,7 @@ import { openBlockers } from "./blockers.ts"; import { isScopeQuestion, settledScope } from "./candidates.ts"; import { recordReviewFailure, reviewHolds } from "./gate.ts"; import { MAX_RERUNS_PER_DAY, countRerun, discussionOf, ensurePipelineLogin, liveDiscussion, markedStaleSince, staleReviews, withRetry, type Snapshot } from "./discussion.ts"; -import { withdrawMergeQuestion } from "../merge/withdraw.ts"; +import { withdrawHoldQuestion, withdrawMergeQuestion } from "../merge/withdraw.ts"; import { headWasUnsure, mergeDecisionId } from "../merge/queue.ts"; import { relatedOpen, latestReview } from "../postmerge/related.ts"; import { HISTORY_COPY_SQL } from "../db.ts"; @@ -88,6 +88,8 @@ export function saveOpus(db: DatabaseSync, runId: string | null, c: { repo: stri const worse = r.verdict === "take" || r.verdict === "take-fix" ? "the new review is unsure" : `the new review is a ${r.verdict}`; withdrawMergeQuestion(db, c.repo, c.number, c.head_oid, at, `superseded by a new review: ${worse}`); } + // The Hold question belongs to one review: a review made again at the head asks it anew if the verdict is still hold. + if (again) withdrawHoldQuestion(db, c.repo, c.number, c.head_oid, at, "superseded by a new review"); // The row about to be replaced may predate the history: copy it first. db.prepare(`${HISTORY_COPY_SQL} AND o.repo = ? AND o.number = ? AND o.head_oid = ?`).run(c.repo, c.number, c.head_oid); const risks = JSON.stringify(r.risks), fixes = r.fixes.length ? JSON.stringify(r.fixes) : null, pub = r.public ? JSON.stringify(r.public) : null, claims = r.claims.length ? JSON.stringify(r.claims) : null; diff --git a/src/review/summary.ts b/src/review/summary.ts index f582ddac..5fec9f89 100644 --- a/src/review/summary.ts +++ b/src/review/summary.ts @@ -49,7 +49,7 @@ export const reviewFact = (r: ReviewText): string => `review: ${r.verdict}: ${r. * Skips decisions the prepare step has written or that have choices (their summary and pick are the judgement model's). Writes only what differs, so a second run changes nothing. Returns how many decisions it changed. */ export function fillReviewSummaries(db: DatabaseSync, at: string, repo?: string): number { - const rows = db.prepare(`SELECT * FROM decisions WHERE kind IN ('merge', 'close') AND answer IS NULL AND number IS NOT NULL AND prepared_at IS NULL + const rows = db.prepare(`SELECT * FROM decisions WHERE kind IN ('merge', 'close', 'hold') AND answer IS NULL AND number IS NOT NULL AND prepared_at IS NULL AND NOT EXISTS (SELECT 1 FROM main.decision_choices c WHERE c.decision_id = decisions.id AND c.state = 'current') ${repo ? "AND repo = ?" : ""}`).all(...(repo ? [repo] : [])) as DecisionRow[]; const upd = db.prepare(`UPDATE main.decisions SET summary = ?, summary_by = ?, summary_at = ?, facts = ?, recommended = ?, recommended_reason = ?, recommended_by = NULL @@ -60,11 +60,11 @@ export function fillReviewSummaries(db: DatabaseSync, at: string, repo?: string) const head = factsOf(d).find((f) => f.startsWith(HEAD_FACT))?.slice(HEAD_FACT.length).trim(); const r = head ? reviewText(db, d.repo!, d.number!, head) : null; if (!r) continue; - const line = (f: string) => (d.kind === "merge" && f.startsWith("review: ") ? reviewFact(r) : d.kind === "close" && f.startsWith("review reason: ") ? `review reason: ${r.reason.slice(0, 300)}` : f); + const line = (f: string) => (d.kind === "merge" && f.startsWith("review: ") ? reviewFact(r) : (d.kind === "close" || d.kind === "hold") && f.startsWith("review reason: ") ? `review reason: ${r.reason.slice(0, 300)}` : f); const facts = JSON.stringify(factsOf(d).map(line)); // The same rule as the ask: Merge? recommends unless Opus was unsure or the pre-merge review blocked the rule (its facts say so), Close? always; both only with a reason. const preMerge = factsOf(d).some((f) => f.startsWith("pre-merge defect: ") || f.startsWith("pre-merge review failed: ")); - const recommended = r.why && (d.kind === "close" || (r.sure && !preMerge)) ? (d.kind === "close" ? "close" : "merge") : null; + const recommended = d.kind === "hold" ? null : r.why && (d.kind === "close" || (r.sure && !preMerge)) ? (d.kind === "close" ? "close" : "merge") : null; const same = d.summary === r.summary && (d.summary_by ?? "") === r.by && d.facts === facts && d.recommended === recommended && d.recommended_reason === (recommended ? r.why : null); if (same) continue; upd.run(r.summary, r.by || null, d.summary === r.summary ? (d.summary_at ?? at) : at, facts, recommended, recommended ? r.why : null, d.id); diff --git a/src/stages/registry.ts b/src/stages/registry.ts index d4fcf771..cd0f9fa4 100644 --- a/src/stages/registry.ts +++ b/src/stages/registry.ts @@ -380,6 +380,7 @@ export const STAGES: StageDef[] = [ waits: [ { name: "Pre-merge review", why: "A PR the rule would merge, or a pre-approved merge before its hand-over, waits for an adversarial Opus review of its head commit (one model call per head); while the step cannot run (pipeline off, usage pause) it waits", howLong: "Until the call ends; a failed call is tried again after 1 hour, at most 3 tries, then a person decides", showsAs: "Queue state `waiting-premerge`", kind: "external" }, { name: "Pre-merge review retry", why: "The model call for the head failed or returned no valid review", howLong: "1 hour between tries; after 3 failed tries the merge queue asks a person", showsAs: "Queue state `waiting-premerge` (tries left) or a Merge? question (\"pre-merge review failed\")", kind: "backoff" }, + { name: "Mergeable state unknown", why: "GitHub has not computed whether the PR merges; the checks job reads it again every minute, and a PR still unknown after 30 minutes is requested again", howLong: "Up to 3 re-reads, 2 hours apart; then the merge queue asks a person (Merge? with the reason)", showsAs: "Plan wait: GitHub's merge state, unknown since hh:mm (read again n of 3), then a Merge? question", kind: "backoff" }, { name: "Upstream CI of PRs and open batch PRs", why: "External", howLong: "Read again every minute per repo while any waits", showsAs: "\"waiting for CI on N PRs in repo\"", kind: "external" }, { name: "Runs waiting for approval", why: "GitHub holds the runs of an outside contributor's PR until a maintainer approves them; the pipeline approves them once the head has a final take or take-fix review and the repo's CI approval is on", howLong: "Until the step runs (read again with each checks job)", showsAs: "Queue state `ci-approval`", kind: "external" }, { name: "Batch PR runs awaiting approval", why: "The batch PR comes from the pipeline account's fork, so GitHub may hold its workflow runs (`action_required`) until a maintainer approves them; the ci-approve step approves them when the repo's CI approval is on and every member was reviewed at its batched head", howLong: "Until the runs are approved and finish (read again with each checks job)", showsAs: "Batch note \"batch PR runs wait for a maintainer's approval\"", kind: "external" }, diff --git a/test/decide-pr.test.ts b/test/decide-pr.test.ts index 7a8cab60..30b5a497 100644 --- a/test/decide-pr.test.ts +++ b/test/decide-pr.test.ts @@ -70,8 +70,8 @@ const rows: Row[] = [ { name: "checks of another head: CI unknown", facts: { ci: "unknown", checksHere: false }, expect: { state: "waiting-ci" } }, { name: "no verification yet", facts: { verification: null }, expect: { state: "waiting-verify", path: "rule", actions: ["verify:plan"] } }, { name: "stale verification is verified again", facts: { verification: { state: "stale" } }, expect: { state: "waiting-verify", actions: ["verify:plan"] } }, - { name: "failed verification", facts: { verification: { state: "failed" } }, expect: { state: "verify-failed", actions: [] } }, - { name: "verification error", facts: { verification: { state: "error" } }, expect: { state: "verify-error", actions: [] } }, + { name: "failed verification", facts: { verification: { state: "failed", summary: "tests fail" } }, expect: { state: "needs-decision", actions: ["ask-merge"] } }, + { name: "verification error", facts: { verification: { state: "error", summary: "no build" } }, expect: { state: "needs-decision", actions: ["ask-merge"] } }, { name: "CI is enough counts as verified", facts: { verification: { state: "ci-enough" } }, expect: { state: "ready", actions: ["merge"] } }, { name: "outside the rule, not verified yet: no question before the result", facts: { ...SIZE_L, verification: null }, expect: { state: "waiting-verify", actions: ["verify:plan"] } }, { name: "unavailable repo is Verify's second bucket", facts: { verification: null, verifyUnavailable: "the repo is private" }, expect: { state: "waiting-verify", actions: ["verify:unavailable"] } }, @@ -95,9 +95,9 @@ const rows: Row[] = [ // ---- merge, refusal, holds, batches, main CI { name: "refused PR with changed CI is retried", facts: { lastMerge: { outcome: "refused", reason: "x", ci: "pending", mergeable: "MERGEABLE" } }, expect: { state: "refused", path: "rule", actions: ["merge"], eligible: true } }, - { name: "refused PR in the same state waits, on every path", facts: { lastMerge: { outcome: "refused", reason: "x", ci: "success", mergeable: "MERGEABLE" } }, expect: { state: "refused", actions: [], eligible: true } }, + { name: "refused PR in the same state waits, on every path", facts: { lastMerge: { outcome: "refused", reason: "not ready at merge time: CI pending", ci: "success", mergeable: "MERGEABLE" } }, expect: { state: "refused", actions: [], eligible: true } }, { name: "refused PR waits also when it merges alone", facts: { verification: { state: "unavailable", summary: "s" }, decision: answered("merge"), lastMerge: { outcome: "refused", reason: "x", ci: "success", mergeable: "MERGEABLE" } }, expect: { state: "refused", actions: [] } }, - { name: "refusal without a recorded CI state waits", facts: { lastMerge: { outcome: "refused", reason: "x", ci: null, mergeable: null } }, expect: { state: "refused", actions: [] } }, + { name: "refusal without a recorded CI state waits", facts: { lastMerge: { outcome: "refused", reason: "not ready at merge time: CI pending", ci: null, mergeable: null } }, expect: { state: "refused", actions: [] } }, { name: "approved runs after a refusal release it", facts: { lastMerge: { outcome: "refused", reason: "x", ci: "success", mergeable: "MERGEABLE" }, runsApprovedAfterMerge: true }, expect: { state: "refused", actions: ["merge"] } }, { name: "held PR keeps its state and never merges", facts: { mergeHeld: true }, expect: { state: "ready", path: "rule", actions: [], eligible: false } }, { name: "held PR with an operator answer never merges", facts: { ...SIZE_L, decision: answered("merge"), mergeHeld: true }, expect: { state: "decision-answered-merge", actions: [], eligible: false } }, @@ -134,7 +134,7 @@ const rows: Row[] = [ { name: "scope answer plugin keeps it out", facts: { review: null, scopeAnswer: "plugin" }, expect: { state: "scope", actions: [] } }, { name: "draft without a review", facts: { review: null, draft: true }, expect: { state: "draft", actions: [] } }, { name: "draft with a take review stays in the queue", facts: { draft: true, verification: null }, expect: { state: "waiting-verify", actions: [] } }, - { name: "Opus said hold", facts: { review: { verdict: "hold" } }, expect: { state: "opus-hold", actions: [] } }, + { name: "Opus said hold", facts: { review: { verdict: "hold" } }, expect: { state: "opus-hold", actions: ["ask-merge"] } }, { name: "Opus said close", facts: { review: { verdict: "close" } }, expect: { state: "opus-close", actions: [] } }, { name: "backlog without a review", facts: { review: null, heldBacklog: true }, expect: { state: "backlog", actions: [] } }, { name: "duplicate hold without a review", facts: { review: null, heldDuplicate: true }, expect: { state: "duplicate", actions: [] } }, diff --git a/test/invariants.test.ts b/test/invariants.test.ts index af499e86..92263ce5 100644 --- a/test/invariants.test.ts +++ b/test/invariants.test.ts @@ -54,7 +54,7 @@ function randomPr(x: Rnd): PrFacts { verification: x.bool(0.1) ? null : { state: x.pick(["passed", "passed", "ci-enough", "failed", "error", "running", "planned", "stale", "unavailable"]) }, decision: { asked: x.bool(0.3), openQuestion: x.bool(0.15), answer: x.pick([null, null, null, "merge", "merge", "hold", "close"]), - mergeAnswerAfterReview: x.bool(0.6), inOpenGroup: x.bool(0.05), + mergeAnswerAfterReview: x.bool(0.6), inOpenGroup: x.bool(0.05), hold: { asked: x.bool(0.3), open: x.bool(0.1), answer: x.pick([null, null, "wait", "close"]), otherOpen: x.bool(0.1) }, }, premerge: x.bool(0.15) ? null : { tries: x.int(4), hasFindings: x.bool(0.85), unsure: false, defects: x.pick([0, 0, 0, 1, 2]), defectsAllFixable: x.bool(0.7), fixesSafe: x.bool(0.7), minor: x.int(2), error: null, diff --git a/test/pr-stalls.test.ts b/test/pr-stalls.test.ts new file mode 100644 index 00000000..09c7e68b --- /dev/null +++ b/test/pr-stalls.test.ts @@ -0,0 +1,108 @@ +// PR stalls: every PR that needs a person is asked (a decision) or shows a typed wait with the reason; nothing waits silently. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { decidePr } from "../src/core/decide.ts"; +import { UNKNOWN_GAP_MS, UNKNOWN_REREADS } from "../src/core/rules.ts"; +import { NOW, prFacts } from "./world.ts"; + +const kinds = (f: Parameters[0]) => decidePr(prFacts(f)).actions.filter((a) => a.kind !== "unassign").map((a) => `${a.kind}${a.params?.hold ? ":hold" : ""}${a.params?.withdraw ? ":withdraw" : ""}${typeof a.params?.bucket === "string" ? `:${a.params.bucket}` : ""}`); +const cifix = (o: Record = {}) => ({ states: [] as string[], tries: 0, rerunAt: null, infraRuns: null, formattingTask: null, formatterEnded: true, totalPushes: 0, totalTries: 0, checksAt: null, skipReason: null, ...o }); +const HOLD = { review: { verdict: "hold" } } as const; + +test("a hold review asks the Hold question once, waits on the person, then on the author after Wait", () => { + assert.deepEqual(kinds(HOLD), ["ask-merge:hold"]); + const open = decidePr(prFacts({ ...HOLD, decision: { hold: { asked: true, open: true, answer: null, otherOpen: false } } })); + assert.deepEqual(open.actions.filter((a) => a.kind !== "unassign"), []); + assert.equal(open.waitKind, "person"); + const waiting = decidePr(prFacts({ ...HOLD, decision: { hold: { asked: true, open: false, answer: "wait", otherOpen: false } } })); + assert.equal(waiting.waitKind, "contributor"); +}); + +test("a Hold question left open for a head that is no longer held is set aside", () => { + assert.deepEqual(kinds({ review: { verdict: "take", stale: true }, decision: { hold: { asked: true, open: true, answer: null, otherOpen: false } } }).filter((k) => k.startsWith("ask-merge")), ["ask-merge:hold:withdraw"]); +}); + +test("CI red only on a check the CI fix skipped asks Merge? with the reason", () => { + const f = { ci: "failure", cifix: cifix({ states: ["skipped"], skipReason: "the gate checks passed; only an optional check failed" }) } as const; + const p = decidePr(prFacts({ ...f, size: "S" })); + assert.equal(p.state, "needs-decision"); + assert.ok(p.actions.some((a) => a.kind === "ask-merge")); + assert.ok(p.reasons.some((r) => r.includes("the CI fix has nothing to fix") && r.includes("optional check"))); + // A CI fix still working keeps the queue state. + assert.equal(decidePr(prFacts({ ci: "failure", cifix: cifix() })).state, "ci-failed"); +}); + +test("red CI that holds the review with no take review at the head asks the contributor", () => { + const f = { review: { verdict: "hold", head: "h0" }, ci: "failure", cifix: cifix(), reviewHold: { kind: "ci", wait: "CI on the latest commit to pass", red: true } } as const; + assert.deepEqual(kinds(f), ["cifix:ask"]); + const asked = decidePr(prFacts({ ...f, cifix: cifix({ states: ["asked"] }) })); + assert.equal(asked.waitKind, "contributor"); + const skipped = decidePr(prFacts({ ...f, cifix: cifix({ states: ["skipped"], skipReason: "nothing to fix" }) })); + assert.equal(skipped.waitKind, "person"); +}); + +test("a failed or errored verification asks Merge? with the failure, and the answer stands", () => { + for (const state of ["failed", "error"]) { + const p = decidePr(prFacts({ verification: { state, kind: "tests", summary: "2 tests fail", note: null } })); + assert.equal(p.state, "needs-decision"); + assert.ok(p.actions.some((a) => a.kind === "ask-merge")); + assert.ok(p.reasons.some((r) => r.startsWith("verification") && r.includes("2 tests fail"))); + const merged = decidePr(prFacts({ verification: { state, kind: "tests", summary: "2 tests fail", note: null }, decision: { asked: true, answer: "merge", mergeAnswerAfterReview: true } })); + assert.equal(merged.path, "operator"); + assert.ok(merged.actions.some((a) => a.kind === "merge")); + } +}); + +test("a mergeable state unknown after every re-read asks Merge?; before that the wait says how often it was read", () => { + const since = new Date(NOW - 10 * 3600_000).toISOString(); + const reading = decidePr(prFacts({ mergeable: "UNKNOWN", unknown: { since, rereads: 1, lastAt: new Date(NOW - 60_000).toISOString() } })); + assert.equal(reading.state, "waiting-ci"); + assert.match(reading.wait ?? "", /read again 1 of 3/); + const stuck = decidePr(prFacts({ mergeable: "UNKNOWN", unknown: { since, rereads: UNKNOWN_REREADS, lastAt: new Date(NOW - UNKNOWN_GAP_MS - 1).toISOString() } })); + assert.equal(stuck.state, "needs-decision"); + assert.ok(stuck.actions.some((a) => a.kind === "ask-merge")); + assert.ok(stuck.reasons.some((r) => r.includes("unknown"))); +}); + +test("a merge refused for a reason other than CI or mergeable asks Merge?; a state refusal waits for the change", () => { + const refused = (reason: string) => ({ lastMerge: { outcome: "refused", reason, ci: "success", mergeable: "MERGEABLE" } }); + const other = decidePr(prFacts(refused("REFUSED app#1: the PR touches a protected file"))); + assert.equal(other.state, "needs-decision"); + assert.ok(other.reasons.some((r) => r.includes("protected file"))); + const state = decidePr(prFacts(refused("not ready at merge time: CI pending, mergeable unknown"))); + assert.equal(state.state, "refused"); + // An operator who already answered Merge and was refused is shown a person wait with the reason. + const answered = decidePr(prFacts({ ...refused("REFUSED app#1: the PR touches a protected file"), decision: { asked: true, answer: "merge", mergeAnswerAfterReview: true } })); + assert.equal(answered.waitKind, "person"); + assert.match(answered.wait ?? "", /protected file/); +}); + +test("the Hold question is written once per head, prepared like other questions, and set aside by a new review", async () => { + const { world } = await import("./world-db.ts"); + const { askHoldDecisions } = await import("../src/act/index.ts"); + const { saveOpus } = await import("../src/review/opus.ts"); + const w = world().repo().pr(1).review(1, { verdict: "hold", reason: "needs a design call" }); + try { + assert.equal(w.prPlan(1).state, "opus-hold"); + const ids = askHoldDecisions(w.db, new Date().toISOString()); + assert.deepEqual(ids, ["app#1:hold@" + (w.prPlan(1).head ?? "")]); + const d = w.rows("SELECT kind, question, options, facts FROM decisions WHERE id = ?", ids[0]!)[0]!; + assert.equal(d.kind, "hold"); + assert.deepEqual((JSON.parse(String(d.options)) as { key: string }[]).map((o) => o.key), ["wait", "close"]); + assert.ok(String(d.facts).includes("needs a design call")); + // Asked: the plan waits on a person and does not ask again. + assert.deepEqual(w.prPlan(1).actions.filter((a) => a.kind === "ask-merge"), []); + assert.equal(w.prPlan(1).waitKind, "person"); + assert.deepEqual(askHoldDecisions(w.db, new Date().toISOString()), []); + // A new review at the same head sets the question aside; a hold again asks it anew. + saveOpus(w.db, "rv2", { repo: "app", number: 1, head_oid: w.prPlan(1).head! }, { mode: "full", base: null, model: "m", review: { ref: "app#1", verdict: "hold", sure: true, reason: "still open", fixes: [], risks: [], summary: null, why: null, public: null, conflicts: [], claims: [], blocked_by: [] } }); + assert.equal(w.rows("SELECT 1 FROM decisions WHERE id LIKE '%:hold@%~replaced-%'").length, 1); + assert.equal(askHoldDecisions(w.db, new Date().toISOString()).length, 1); + } finally { w.close(); } +}); + +test("a hold review whose item has another open question waits for it instead of replacing it", () => { + const p = decidePr(prFacts({ ...HOLD, decision: { hold: { asked: false, open: false, answer: null, otherOpen: true } } })); + assert.deepEqual(p.actions.filter((a) => a.kind !== "unassign"), []); + assert.equal(p.waitKind, "person"); +}); diff --git a/test/world.ts b/test/world.ts index cb4fdd1a..1008d676 100644 --- a/test/world.ts +++ b/test/world.ts @@ -14,10 +14,10 @@ const base = (): PrFacts => ({ repoFacts: { mergeApproved: true, pushApproved: true, commentApproved: true, ciApproved: true, noCi: false, mainRed: false }, review: { head: HEAD, at: REVIEW_AT, verdict: "take", unsure: false, mode: "full", reason: "ok", fixes: 0, stale: false, staleActionable: false }, post: { postable: true, posted: { head: HEAD, at: "2026-11-04T10:01:00.000Z", opusAt: REVIEW_AT } }, - checksHere: true, checksOpen: true, ci: "success", mergeable: "MERGEABLE", runs: null, + checksHere: true, checksOpen: true, ci: "success", mergeable: "MERGEABLE", unknown: null, runs: null, lastMerge: null, runsApprovedAfterMerge: false, verification: { state: "passed", kind: "build", summary: null, note: null }, verifyUnavailable: null, - decision: { asked: false, openQuestion: false, answer: null, mergeAnswerAfterReview: false, inOpenGroup: false }, + decision: { asked: false, openQuestion: false, answer: null, mergeAnswerAfterReview: false, inOpenGroup: false, hold: { asked: false, open: false, answer: null, otherOpen: false } }, premerge: { at: "2026-11-04T10:30:00.000Z", tries: 0, hasFindings: true, unsure: false, defects: 0, defectsAllFixable: true, fixesSafe: true, minor: 0, error: null }, premergeFixUsed: false, sensitive: [], statementConflicts: [], pushable: true, pushChain: [HEAD], conflict: null, inActiveBatch: false, fixup: null, carry: [], lint: [], cifix: null, postmerge: null, batch: null, mainFix: false, changesRequested: null, gateFailureNote: null, }); diff --git a/web/src/api/mock/conversationMock.ts b/web/src/api/mock/conversationMock.ts index 5b53ccba..11de46b1 100644 --- a/web/src/api/mock/conversationMock.ts +++ b/web/src/api/mock/conversationMock.ts @@ -56,6 +56,23 @@ function mergeChoices(n: number): DecisionChoices { return { id: `ch-${n}`, decisionId: "designcraft#1484:merge", pick: { core: "o:merge", reason: "Review and CI are green and the author is whitelisted. The data duplicates the language pack, so a follow-up issue covers moving onto it." }, cores, source: "prepare", at: at(5) }; } +/** A Hold question: a new review is always offered first, then a fix-up, waiting for the author, closing and Later. */ +function holdChoices(): DecisionChoices { + const cores: ChoiceCore[] = [ + { key: "x:review", label: "Review the PR again", autocraft: "reviews the PR again, then asks again if needed", writes: [], drafted: false, extras: [] }, + { + key: "fixup-merge", label: "Fix up first, then merge", autocraft: "pushes the fix-up, reviews again, merges if both pass", + params: { instructions: "Mark the pasted range dirty in `paste_cells` before recalculating, and add a regression test for a dependent cell." }, + writes: ["push", "merge"], drafted: true, + extras: [{ id: "e1", kind: "comment", tag: "comment", on: true, text: "Thanks for the fix. The paste path also has to set the dirty flag; I'm pushing that change, then merging." }], + }, + { key: "o:wait", label: "Wait for the author", autocraft: "keeps it open and leaves it to the author; asks again after a new commit or review", writes: [], drafted: true, extras: [{ id: "e1", kind: "comment", tag: "comment", on: true, text: "The review found that the paste path skips the dirty flag. Could you update the PR?" }] }, + { key: "o:close", label: "Close", autocraft: "records the answer and stops working on it", params: { reason: "" }, writes: ["comment", "close"], drafted: false, extras: [] }, + { key: "backlog", label: "Later", autocraft: "moves it to the Backlog", writes: [], drafted: false, extras: [] }, + ]; + return { id: "ch-h1", decisionId: "gridcraft#1012:hold", pick: { core: "o:wait", reason: "The paste path needs a design call from the author before a fix-up can be written." }, cores, source: "prepare", at: at(5) }; +} + /** A scope question where the item was already done: Opus adds a close-as-done core. */ function scopeChoices(n: number): DecisionChoices { const cores: ChoiceCore[] = [ @@ -151,7 +168,7 @@ function seed(): ConversationTurn[] { /** In-memory conversations. Only designcraft#1484 starts with one; an operator's message is answered after a few seconds. */ export function createConversationMock(me: User, changed: () => void, settle?: (repo: string, number: number, option: string, note: string | null) => void, hooks?: { reprepare?: (decisionId: string) => void }, derive?: (repo: string, number: number) => DecisionChoices | null): Pick { // The open choices by item; a run that settles the question removes them. - const choices = new Map([[REF, mergeChoices(1)], ["photocraft#4127", scopeChoices(1)], ["gridcraft#977", { ...mergeChoices(1), id: "ch-g1", decisionId: "gridcraft#977:merge", pick: null }]]); + const choices = new Map([[REF, mergeChoices(1)], ["photocraft#4127", scopeChoices(1)], ["gridcraft#977", { ...mergeChoices(1), id: "ch-g1", decisionId: "gridcraft#977:merge", pick: null }], ["gridcraft#1012", holdChoices()]]); let epoch = 1; const failedOnce = new Set(); if (hooks) diff --git a/web/src/api/mock/fixtures.ts b/web/src/api/mock/fixtures.ts index 56b5746c..d27c064c 100644 --- a/web/src/api/mock/fixtures.ts +++ b/web/src/api/mock/fixtures.ts @@ -28,6 +28,7 @@ import type { const WRITES: Partial>> = { scope: { close: "closes it on GitHub" }, close: { close: "closes the PR on GitHub" }, + hold: { close: "closes the PR on GitHub" }, duplicate: { close: "closes it on GitHub" }, merge: { merge: "merges on GitHub", close: "closes the PR on GitHub" }, }; @@ -378,6 +379,25 @@ const SEEDS: Seed[] = [ size: [9412, 3870, 38], cls: [["haiku", "performance", "unclear"], ["jev", "infra", "no"]], }, + { + kind: "hold", + repo: "gridcraft", + number: 1012, + title: "Formula bar: recalculate on paste without the dirty flag", + question: "The review put this PR on hold. What next?", + context: ["The Opus review says hold: it neither takes the PR as it is nor closes it, and nothing happens until a person decides."], + facts: ["review reason: the paste path skips the dirty flag, so dependent cells keep stale values; the fix touches the evaluator core", "author: 3 merged, whitelisted, size M", "head commit 9f3c2ab41d07"], + options: [ + { key: "wait", label: "Wait for the author", hint: "Keep it open and leave it to the author; asked again after a new commit or review." }, + { key: "close", label: "Close", hint: "Not wanted as it is; post a short comment and close the PR." }, + ], + recommended: "wait", + recommendedReason: "The paste path needs a design call from the author before a fix-up can be written.", + ageH: 5, + author: "quill-m", + size: [214, 38, 6], + cls: [["haiku", "bugfix", "unclear"], ["jev", "bugfix", "no"]], + }, { kind: "merge", repo: "gridcraft", diff --git a/web/src/api/types.ts b/web/src/api/types.ts index a316041b..0e0da1cf 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -18,7 +18,7 @@ export interface ItemShown { title: string | null; } -export type DecisionKind = "scope" | "duplicate" | "close" | "merge" | "split" | "other"; +export type DecisionKind = "scope" | "duplicate" | "close" | "merge" | "hold" | "split" | "other"; export interface OptionTexts { option: string; diff --git a/web/src/lib/links.ts b/web/src/lib/links.ts index f5ecdf6d..1cfe7db9 100644 --- a/web/src/lib/links.ts +++ b/web/src/lib/links.ts @@ -16,7 +16,7 @@ export const repoSlug = (repo: string): string => `${ownerOfRepo(repo)}/${shortR export const githubItemUrl = (repo: string, number: number, kind?: ItemKind | null): string => `https://github.com/${ownerOfRepo(repo)}/${encodeURIComponent(shortRepo(repo))}/${kind === "pr" ? "pull" : "issues"}/${number}`; -const KIND_ORDER = ["scope", "duplicate", "close", "merge", "split", "other"]; +const KIND_ORDER = ["scope", "duplicate", "close", "merge", "hold", "split", "other"]; /** `/items//`; the repo is the short name the dashboard shows. */ export const itemPath = (repo: string, number: number): string => `/items/${encodeURIComponent(shortRepo(repo))}/${number}`; diff --git a/web/src/modules/decisions/parts.tsx b/web/src/modules/decisions/parts.tsx index 855f99ad..272d71ed 100644 --- a/web/src/modules/decisions/parts.tsx +++ b/web/src/modules/decisions/parts.tsx @@ -4,6 +4,7 @@ import { CaretRightIcon, QuestionIcon, ProhibitIcon, + PauseIcon, CopyIcon, GitMergeIcon, ArrowsSplitIcon, @@ -25,6 +26,7 @@ export const KIND_ICON: Record = { scope: TargetIcon, duplicate: CopyIcon, close: ProhibitIcon, + hold: PauseIcon, merge: GitMergeIcon, split: ArrowsSplitIcon, other: QuestionIcon, diff --git a/web/src/modules/decisions/state.ts b/web/src/modules/decisions/state.ts index a6e96d2d..084dcfdb 100644 --- a/web/src/modules/decisions/state.ts +++ b/web/src/modules/decisions/state.ts @@ -9,6 +9,7 @@ export const KIND_LABEL: Record = { duplicate: "Duplicates", close: "Close approval", merge: "Merge approval", + hold: "Hold", split: "Split", other: "Question", }; diff --git a/web/src/modules/home/views.tsx b/web/src/modules/home/views.tsx index edc8e561..d1ac36c6 100644 --- a/web/src/modules/home/views.tsx +++ b/web/src/modules/home/views.tsx @@ -14,9 +14,9 @@ import { useUser } from "../../shell/UserContext"; import { KIND_ICON } from "../decisions/parts"; import type { ViewProps } from "../../registry/types"; -const NEED_LABEL: Record = { merge: "Merge?", scope: "Scope", duplicate: "Duplicates", close: "Close", split: "Split", other: "Other", security: "Security", feedback: "Feedback", stopped: "Stopped" }; +const NEED_LABEL: Record = { merge: "Merge?", scope: "Scope", duplicate: "Duplicates", close: "Close", hold: "Hold", split: "Split", other: "Other", security: "Security", feedback: "Feedback", stopped: "Stopped" }; const NEED_ICON: Record = { ...KIND_ICON, security: ShieldWarningIcon, feedback: ChatTeardropTextIcon, stopped: XCircleIcon }; -const KIND_ORDER: NeedKind[] = ["merge", "security", "scope", "duplicate", "close", "split", "other", "feedback", "stopped"]; +const KIND_ORDER: NeedKind[] = ["merge", "security", "scope", "duplicate", "close", "hold", "split", "other", "feedback", "stopped"]; const NEED_TO: Partial> = { security: "/security", feedback: "/needs?tab=feedback", stopped: "/needs?tab=stopped" }; const SHOWN: ItemPhase[] = ["Triage", "Waiting for a person", "Review", "Fixing", "Verifying", "In queue", "Merged", "Closed"]; const PHASE_LABEL: Partial> = { "Waiting for a person": "Waiting", Merged: "Merged today", Closed: "Closed today" };