mirror of
https://github.com/storytold/autocraft.git
synced 2026-12-01 10:33:55 +01:00
Review, post-merge and memory code read and write through the data modules: loaders for facts, discussion, holds, carry, posts and diff facts; saveReviews and savePostmerge for review rows; retired decision, carry-over and scope paths removed
This commit is contained in:
1 parent
c8c181b2e2
commit
ee5de35df8
20 files changed
+510
-979
No files matched your search
@@ -1,7 +1,8 @@
|
||||
// The owner statements a review of a PR gets: the closest ones to the PR's embedding, from the PR's own repo.
|
||||
import type { OwnerStatement } from "../review/opus-parse.ts";
|
||||
import { STATEMENT_PROMPT_CHARS } from "../review/opus-parse.ts";
|
||||
import { quietExprFor } from "../security/quiet.ts";
|
||||
import { loadStatementPools } from "../data/conversations/index.ts";
|
||||
import { loadEmbeddingVectors } from "../data/triage/index.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
|
||||
/** How many statements a review sees. */
|
||||
@@ -21,17 +22,14 @@ const asFloats = (b: Uint8Array): Float32Array => new Float32Array(b.buffer.slic
|
||||
* operators' words reach a review only for the repo they were said about, and a quiet PR stays unnamed until its advisory.
|
||||
*/
|
||||
export async function relatedStatements(db: Db, repo: string, number: number): Promise<OwnerStatement[]> {
|
||||
const pr = await db.get(db.k.selectFrom("item_embeddings").select(["model", "vec"]).where("repo", "=", repo).where("number", "=", number));
|
||||
const pr = (await loadEmbeddingVectors(db, [{ repo, number }])).get(`${repo}#${number}`);
|
||||
if (!pr) return [];
|
||||
const q = asFloats(pr.vec);
|
||||
const rows = await db.all(db.k.selectFrom("owner_statements")
|
||||
.select(["id", "source_kind", "repo", "number", "item_title", "text", "at", "embedding"])
|
||||
.where("model", "=", pr.model).where("embedding", "is not", null).where("repo", "=", repo).where("number", "is distinct from", number)
|
||||
.where((eb) => eb.not(eb.and([eb("number", "is not", null), quietExprFor(db, eb, "owner_statements.repo", "owner_statements.number")])))
|
||||
.$narrowType<{ embedding: Uint8Array }>());
|
||||
const rows = (await loadStatementPools(db, [repo], [pr.model])).get(repo) ?? [];
|
||||
const hits: (OwnerStatement & { score: number })[] = [];
|
||||
for (const r of rows) {
|
||||
const v = asFloats(r.embedding);
|
||||
if (r.number === number) continue;
|
||||
const v = asFloats(r.vec);
|
||||
if (v.length !== q.length) continue;
|
||||
let dot = 0;
|
||||
for (let i = 0; i < q.length; i++) dot += q[i]! * v[i]!;
|
||||
|
||||
+10
-109
@@ -1,133 +1,34 @@
|
||||
// Owner memory: what the operators said once (a decision's answer note, a comment on GitHub, a message in an AutoCraft
|
||||
// conversation) is kept as a statement with an embedding. Reviews of related work get the closest statements (retrieve.ts).
|
||||
// Owner memory: what the operators said once (a comment on GitHub, a message in an AutoCraft conversation) is kept as a
|
||||
// statement with an embedding. Reviews of related work get the closest statements (retrieve.ts).
|
||||
import type { Embedder } from "../embed/model.ts";
|
||||
import { BODY_CHARS, cleanBody } from "../embed/text.ts";
|
||||
import { toBlob } from "../embed/store.ts";
|
||||
import { forEachSeq } from "../async-seq.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { STATEMENT_BATCH, collectStatements as collectOwnerStatements, loadStatementWork, setStatementVectors } from "../data/conversations/index.ts";
|
||||
|
||||
export type StatementKind = "decision-note" | "comment" | "conversation";
|
||||
|
||||
/** Statements shorter than this ("LGTM", "thanks") say nothing worth remembering. */
|
||||
export const STATEMENT_MIN_CHARS = 15;
|
||||
export const STATEMENT_MAX_CHARS = 2000;
|
||||
|
||||
/**
|
||||
* Text that AutoCraft posted itself starts with the note line of src/github/note.ts (`_AI-generated ...` or `_Automated ...`),
|
||||
* also when an operator chose to post it. Bots are never operators; the login check covers an operator account used by automation.
|
||||
*/
|
||||
const ownPost = (db: Db, eb: kx.Eb) => eb.or([
|
||||
kx.like(db, "c.body", eb.val("\\_AI-generated%"), "\\"),
|
||||
kx.like(db, "c.body", eb.val("\\_Automated%"), "\\"),
|
||||
kx.like(db, "c.author", eb.val("%[bot]")),
|
||||
]);
|
||||
|
||||
const tag = (eb: kx.Eb, value: string) => eb.cast<string>(eb.val(value), "text");
|
||||
|
||||
const textLength = (eb: kx.Eb, col: string) => eb.fn<number>("length", [eb.fn("trim", [col])]);
|
||||
|
||||
const newSources = (db: Db) => db.k.selectFrom("decisions as d")
|
||||
.innerJoin("access as a", (j) => j.onRef("a.login", "=", "d.answered_by").on("a.role", "=", "operator")
|
||||
.on((eb) => eb(eb.fn.coalesce("d.answered_role", eb.val("operator")), "=", "operator")))
|
||||
.select((eb) => [tag(eb, "decision-note").as("kind"), "d.id as sid", "d.repo", "d.number", eb.fn<string>("trim", ["d.answer_note"]).as("text"), "d.answered_by as author", "d.answered_at as at"])
|
||||
.where("d.repo", "is not", null).where("d.answer_note", "is not", null)
|
||||
.where((eb) => eb(textLength(eb, "d.answer_note"), ">=", STATEMENT_MIN_CHARS))
|
||||
.where("d.answer", "not in", ["withdrawn", "superseded", "handled"])
|
||||
.$narrowType<{ repo: string }>()
|
||||
.unionAll(db.k.selectFrom("comments as c")
|
||||
.innerJoin("access as a", (j) => j.onRef("a.login", "=", "c.author").on("a.role", "=", "operator"))
|
||||
.select((eb) => [tag(eb, "comment").as("kind"), "c.id as sid", "c.repo", "c.number", eb.fn<string>("trim", ["c.body"]).as("text"), "c.author", "c.created_at as at"])
|
||||
.where("c.kind", "in", ["comment", "review"])
|
||||
.where((eb) => eb.and([eb(textLength(eb, "c.body"), ">=", STATEMENT_MIN_CHARS), eb.not(ownPost(db, eb))])))
|
||||
.unionAll(db.k.selectFrom("conversation_turns as t")
|
||||
.innerJoin("access as a", (j) => j.onRef("a.login", "=", "t.login").on("a.role", "=", "operator"))
|
||||
.select((eb) => [tag(eb, "conversation").as("kind"), eb.cast<string>("t.id", "text").as("sid"), "t.repo", "t.number", eb.fn<string>("trim", ["t.body"]).as("text"), "t.login as author", "t.at"])
|
||||
.where("t.kind", "=", "operator")
|
||||
.where((eb) => eb.and([eb(eb.fn.coalesce("t.status", eb.val("")), "<>", "failed"), eb(textLength(eb, "t.body"), ">=", STATEMENT_MIN_CHARS)])));
|
||||
|
||||
/**
|
||||
* The database id of a GitHub comment from its GraphQL node id ("IC_kwDO…": base64url of a MessagePack array [0, repo id, comment id]);
|
||||
* null when the id has another shape.
|
||||
*/
|
||||
export function commentDatabaseId(node: string): string | null {
|
||||
const m = /^IC_(.+)$/.exec(node);
|
||||
if (!m) return null;
|
||||
const b = Buffer.from(m[1]!, "base64url");
|
||||
let at = 0;
|
||||
const num = (): bigint | null => {
|
||||
const t = b[at++];
|
||||
if (t === undefined) return null;
|
||||
if (t < 0x80) return BigInt(t);
|
||||
const size = t === 0xcc ? 1 : t === 0xcd ? 2 : t === 0xce ? 4 : t === 0xcf ? 8 : 0;
|
||||
if (!size || at + size > b.length) return null;
|
||||
let v = 0n;
|
||||
for (let i = 0; i < size; i++) v = (v << 8n) | BigInt(b[at++]!);
|
||||
return v;
|
||||
};
|
||||
if (b[at++] !== 0x93 || num() !== 0n || num() === null) return null;
|
||||
const id = num();
|
||||
return id === null ? null : String(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The comments and reviews AutoCraft wrote, from the audit rows of its GitHub writes: comment ids are the number after
|
||||
* `#issuecomment-` in a stored URL, review ids are the node id in `details.review`. Posts from before the note line existed
|
||||
* carry no prefix, and they come from the owner's account, so only the audit tells them apart.
|
||||
*/
|
||||
async function postedIds(db: Db): Promise<{ numbers: Set<string>; nodes: Set<string> }> {
|
||||
const numbers = new Set<string>(), nodes = new Set<string>();
|
||||
const rows = await db.all(db.k.selectFrom("audit").select("details")
|
||||
.where((eb) => eb.or([kx.like(db, "details", eb.val("%issuecomment-%")), kx.like(db, "details", eb.val('%"review"%'))])));
|
||||
for (const r of rows) {
|
||||
for (const m of (r.details ?? "").matchAll(/#issuecomment-(\d+)/g)) numbers.add(m[1]!);
|
||||
try { const v = (JSON.parse(r.details ?? "{}") as { review?: unknown }).review; if (typeof v === "string") nodes.add(v); } catch { /* not JSON: none */ }
|
||||
}
|
||||
return { numbers, nodes };
|
||||
}
|
||||
export { STATEMENT_MAX_CHARS, STATEMENT_MIN_CHARS, commentDatabaseId } from "../data/conversations/index.ts";
|
||||
export type StatementKind = "comment" | "conversation";
|
||||
|
||||
/** Adds the sources that have no statement yet; returns how many. Needs no model. */
|
||||
export async function collectStatements(db: Db): Promise<number> {
|
||||
const rows = await db.all(db.k.selectFrom(newSources(db).as("s"))
|
||||
.select(["s.kind", "s.sid", "s.repo", "s.number", "s.text", "s.author", "s.at"])
|
||||
.where("s.at", "is not", null)
|
||||
.where((eb) => eb.not(eb.exists(eb.selectFrom("owner_statements as o").select(eb.lit(1).as("one"))
|
||||
.whereRef("o.source_kind", "=", "s.kind").whereRef("o.source_id", "=", "s.sid"))))
|
||||
.$narrowType<{ author: string; at: string }>());
|
||||
const own = await postedIds(db);
|
||||
let n = 0;
|
||||
for (const r of rows) {
|
||||
if (r.kind === "comment") {
|
||||
const num = commentDatabaseId(r.sid);
|
||||
if (own.nodes.has(r.sid) || (num !== null && own.numbers.has(num))) continue;
|
||||
}
|
||||
const t = r.number === null ? undefined : (await db.get(db.k.selectFrom("items").select("title").where("repo", "=", r.repo).where("number", "=", r.number)))?.title;
|
||||
n += Number((await db.run(db.k.insertInto("owner_statements")
|
||||
.values({ source_kind: r.kind, source_id: r.sid, repo: r.repo, number: r.number, item_title: t ?? "", author: r.author, text: r.text.slice(0, STATEMENT_MAX_CHARS), at: r.at })
|
||||
.onConflict((oc) => oc.doNothing()))).changes);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
export const collectStatements = async (db: Db): Promise<number> => await collectOwnerStatements(db);
|
||||
|
||||
/** What a statement is embedded from: the item's title, then what was said. */
|
||||
export const statementText = (title: string, text: string): string => `${title.trim()}\n${cleanBody(text).slice(0, BODY_CHARS)}`.trim();
|
||||
|
||||
const waiting = (eb: kx.Eb, modelId: string) => eb.or([eb("embedding", "is", null), eb("model", "is distinct from", modelId)]);
|
||||
|
||||
/** Whether there are sources to collect or statements to embed with `modelId`. */
|
||||
export async function statementsDue(db: Db, modelId: string): Promise<boolean> {
|
||||
await collectStatements(db);
|
||||
return !!await db.get(db.k.selectFrom("owner_statements").select("id").where((eb) => waiting(eb, modelId)).limit(1));
|
||||
return (await loadStatementWork(db, modelId, 1)).length > 0;
|
||||
}
|
||||
|
||||
/** Collects new statements and embeds the ones without a vector of this model; returns how many were embedded. */
|
||||
export async function embedStatements(db: Db, embedder: Embedder, batch = 32): Promise<number> {
|
||||
export async function embedStatements(db: Db, embedder: Embedder, batch = STATEMENT_BATCH): Promise<number> {
|
||||
await collectStatements(db);
|
||||
const todo = await db.all(db.k.selectFrom("owner_statements").select(["id", "item_title", "text"]).where((eb) => waiting(eb, embedder.id)).orderBy("id"));
|
||||
const todo = await loadStatementWork(db, embedder.id, Number.MAX_SAFE_INTEGER);
|
||||
for (let i = 0; i < todo.length; i += batch) {
|
||||
const part = todo.slice(i, i + batch);
|
||||
const vecs = await embedder.embed(part.map((t) => statementText(t.item_title, t.text)), "item");
|
||||
await forEachSeq(part, async (t, k) => await db.run(db.k.updateTable("owner_statements").set({ embedding: toBlob(vecs[k]!), model: embedder.id }).where("id", "=", t.id)));
|
||||
await setStatementVectors(db, part.map((t, k) => ({ id: t.id, vec: toBlob(vecs[k]!), model: embedder.id })));
|
||||
}
|
||||
return todo.length;
|
||||
}
|
||||
+7
-14
@@ -14,8 +14,8 @@ import { createIssue, IssueError, type Writer } from "../github/write.ts";
|
||||
import { pipelineLogin } from "../review/discussion.ts";
|
||||
import { ghFileExists, type FileChecker } from "../review/diff.ts";
|
||||
import { issueBody, issueTitle, refusal } from "./template.ts";
|
||||
import { pilotExprFor } from "../pilot.ts";
|
||||
import { excluded } from "../db/kx.ts";
|
||||
import { claimFollowups, followupKey, saveFollowups } from "../data/review/index.ts";
|
||||
import { listItems, loadRepos } from "../data/mirror/index.ts";
|
||||
import { isQuiet } from "../security/quiet.ts";
|
||||
import { dedupeDefects, pendingDefects, recentFiled, reviewOf, followupsOf, type FollowupState, type PendingDefect } from "./select.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
@@ -39,20 +39,13 @@ type Extra = { issue?: { number: number; url: string }; duplicateOf?: number | n
|
||||
const rowOf = (d: PendingDefect): Row => ({ repo: d.repo, number: d.number, review_at: d.review_at, finding: d.finding, title: d.f.title });
|
||||
|
||||
async function setFollowup(db: Db, d: Row, state: FollowupState, at: string, x: Extra = {}): Promise<void> {
|
||||
await db.run(db.k.insertInto("postmerge_followups")
|
||||
.values({ repo: d.repo, number: d.number, review_at: d.review_at, finding: d.finding, title: d.title, issue_number: x.issue?.number ?? null, url: x.issue?.url ?? null, state, at,
|
||||
duplicate_of: x.duplicateOf ?? null, attempts: x.attempts ?? 0, note: x.note ?? null })
|
||||
.onConflict((oc) => oc.columns(["repo", "number", "review_at", "finding"]).doUpdateSet(excluded(["title", "issue_number", "url", "state", "at", "duplicate_of", "attempts", "note"]))));
|
||||
await saveFollowups(db, [{ repo: d.repo, number: d.number, review_at: d.review_at, finding: d.finding, title: d.title, issue_number: x.issue?.number ?? null, url: x.issue?.url ?? null, state, at,
|
||||
duplicate_of: x.duplicateOf ?? null, attempts: x.attempts ?? 0, note: x.note ?? null }]);
|
||||
}
|
||||
|
||||
/** Writes the `filing` row unless another process already holds or finished this finding. */
|
||||
async function claim(db: Db, d: Row, at: string, attempts: number): Promise<boolean> {
|
||||
return await db.write(async () => {
|
||||
const cur = await db.get(db.k.selectFrom("postmerge_followups").select("state").where("repo", "=", d.repo).where("number", "=", d.number).where("review_at", "=", d.review_at).where("finding", "=", d.finding));
|
||||
if (cur?.state === "filing" || cur?.state === "filed") return false;
|
||||
await setFollowup(db, d, "filing", at, { attempts });
|
||||
return true;
|
||||
});
|
||||
return (await claimFollowups(db, [{ ...d, attempts }], { at })).has(followupKey(d));
|
||||
}
|
||||
|
||||
const oneLine = (e: unknown): string => String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 300);
|
||||
@@ -67,7 +60,7 @@ async function fileDefect(db: Db, deps: FileDeps, w: Writer, g: GuardedRepo, d:
|
||||
const { repo } = d, ref = `${repo}#${d.number}`, row = rowOf(d);
|
||||
const at = () => deps.now().toISOString();
|
||||
if (d.f.file) {
|
||||
const branch = (await db.get(db.k.selectFrom("repos").select("default_branch").where("name", "=", repo)))?.default_branch ?? "main";
|
||||
const branch = (await loadRepos(db, { names: [repo] })).get(repo)?.default_branch ?? "main";
|
||||
if (await deps.fileExists(repo, branch, d.f.file) === false) {
|
||||
await setFollowup(db, row, "skipped-stale", at(), { note: `${d.f.file} is not on ${branch}` });
|
||||
log(` ${ref}: not filed: ${d.f.file} is no longer on ${branch}`);
|
||||
@@ -169,7 +162,7 @@ export async function fileFinding(db: Db, ref: string, index: number, log: (line
|
||||
if (f.severity !== "defect") throw new Error(`finding ${index} of ${ref} is minor; only defects are filed`);
|
||||
if (!await commentApprovalOf(db, repo)) throw new Error(`commenting in ${repo} is not approved`);
|
||||
if (await isQuiet(db, repo, number)) throw new Error(`${ref} is a quiet pull request: its fix is not public yet, so no issue is filed about it`);
|
||||
if (!await db.get(db.k.selectNoFrom((eb) => eb.lit(1).as("one")).where((eb) => pilotExprFor(db, eb, eb.val(repo), eb.cast<number>(eb.val(number), "bigint"))))) throw new Error(`${ref} is outside the pipeline's scope (pipeline flag or pilot)`);
|
||||
if (!(await listItems(db, { repos: [repo], numbers: [number], inScope: true }, "ref")).length) throw new Error(`${ref} is outside the pipeline's scope (pipeline flag or pilot)`);
|
||||
const have = (await followupsOf(db, repo, number)).find((x) => x.review_at === r.at && x.finding === index);
|
||||
if (have?.state === "filed" || have?.state === "filing") throw new Error(`finding ${index} of ${ref} is already ${have.state === "filed" ? `filed as issue ${have.issue_number}` : "being filed with an unknown outcome; check GitHub"}`);
|
||||
await audit(db, OPERATOR, "postmerge-file-one", ref, { finding: index });
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// CLI of the post-merge review stage: `autocraft-server postmerge review <repo>#<n> [--again]`,
|
||||
// `autocraft-server postmerge file <repo>#<n> <finding>` and `autocraft-server postmerge backfill --since <ISO date> [--yes]`.
|
||||
// Operator only: the box's shell is the operator's.
|
||||
import { audit } from "../dash/audit.ts";
|
||||
import { addAudit } from "../data/control/index.ts";
|
||||
import { isRunning } from "../data/jobs/index.ts";
|
||||
import { loadPostmerge } from "../data/review/index.ts";
|
||||
import { mergedPr } from "./select.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import { openDb } from "../db/open.ts";
|
||||
@@ -15,10 +17,10 @@ export async function reviewOne(db: Db, ref: string, again: boolean, log: (line:
|
||||
if (!m) throw new Error(`not a repo#number: ${ref}`);
|
||||
const repo = m[1]!, number = Number(m[2]);
|
||||
if (!await mergedPr(db, repo, number)) throw new Error(`${ref} was not merged by the pipeline`);
|
||||
if (!again && await db.get(db.k.selectFrom("postmerge_reviews").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", number).where("error", "is", null))) throw new Error(`${ref} has a post-merge review; add --again to review it again`);
|
||||
if (!again && (await loadPostmerge(db, [{ repo, number }])).get(ref)?.error === null) throw new Error(`${ref} has a post-merge review; add --again to review it again`);
|
||||
// The runner's job reviews any candidate of its repo; two reviews of one PR at once would replace each other's rows.
|
||||
if (await db.get(db.k.selectFrom("jobs").select((eb) => eb.lit(1).as("one")).where("step", "=", "postmerge").where("state", "=", "running").where("repo", "=", repo).limit(1))) throw new Error(`a postmerge job is running for ${repo}; try again when it has finished`);
|
||||
await audit(db, ACTOR, "postmerge-review", ref, { again });
|
||||
if ((await isRunning(db, [{ step: "postmerge", repo }])).size) throw new Error(`a postmerge job is running for ${repo}; try again when it has finished`);
|
||||
await addAudit(db, [{ login: ACTOR, action: "postmerge-review", target: ref, details: { again } }]);
|
||||
const { runPostmerge } = await import("./review.ts");
|
||||
await runPostmerge(db, { repo, only: [number] }, log);
|
||||
}
|
||||
|
||||
+11
-12
@@ -1,15 +1,13 @@
|
||||
// The related items and earlier reviews of a PR that the post-merge, review and pre-merge prompts show.
|
||||
import type { PostmergeReviewRow, RelatedItem } from "./parse.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { loadItems, searchItems } from "../data/mirror/index.ts";
|
||||
import { loadReviewHistory } from "../data/review/index.ts";
|
||||
|
||||
/** Our earlier Opus reviews of the PR, oldest first. */
|
||||
export async function reviewHistory(db: Db, repo: string, number: number): Promise<PostmergeReviewRow[]> {
|
||||
const list = <T>(s: string | null): T[] => { try { const v = JSON.parse(s ?? "[]") as unknown; return Array.isArray(v) ? (v as T[]) : []; } catch { return []; } };
|
||||
return (await db.all(db.k.selectFrom("opus_review_history").select(["head_oid", "at", "verdict", "sure", "reason", "risks", "fixes"])
|
||||
.where("repo", "=", repo).where("number", "=", number).where("verdict", "is not", null).orderBy("at").orderBy(kx.rowid("opus_review_history"))
|
||||
.$narrowType<{ verdict: string }>()))
|
||||
.map((r) => ({ head: r.head_oid, verdict: r.verdict, sure: r.sure === 1, reason: r.reason ?? "", risks: list<string>(r.risks), fixes: list(r.fixes), at: r.at }));
|
||||
const rows = (await loadReviewHistory(db, [{ repo, number }])).get(`${repo}#${number}`) ?? [];
|
||||
return rows.map((r) => ({ head: r.head, verdict: r.verdict, sure: r.sure, reason: r.reason ?? "", risks: r.risks, fixes: r.fixes as PostmergeReviewRow["fixes"], at: r.at }));
|
||||
}
|
||||
|
||||
const REVIEW_REASON_CHARS = 600, REVIEW_NOTE_CHARS = 300, REVIEW_NOTES = 8, REVIEW_FIXES = 10;
|
||||
@@ -34,13 +32,14 @@ export const RELATED_CLOSED_DAYS = 30;
|
||||
export async function relatedOpen(db: Db, repo: string, number: number, files: string[], at = Date.now()): Promise<RelatedItem[]> {
|
||||
const needles = [`#${number}`, ...files.slice(0, 30)];
|
||||
const since = new Date(at - RELATED_CLOSED_DAYS * 86400_000).toISOString();
|
||||
const rows = await db.all(db.k.selectFrom("items as i").select(["i.number", "i.kind", "i.state", "i.title", "i.body"]).where("i.repo", "=", repo)
|
||||
.where((eb) => eb.or([eb("i.state", "=", "OPEN"), eb(eb.fn.coalesce("i.closed_at", "i.merged_at", "i.updated_at"), ">=", since)]))
|
||||
.where("i.number", "<>", number)
|
||||
.where((eb) => eb.or(needles.flatMap((n) => { const like = eb.val(`%${kx.likeEscape(n)}%`); return [kx.like(db, "i.title", like, "\\"), kx.like(db, "i.body", like, "\\")]; })))
|
||||
.orderBy("i.number").limit(60).$narrowType<{ kind: "issue" | "pr" }>());
|
||||
// The text index finds the candidates; the checks below decide, as the exact-text test always did.
|
||||
const hits = await db.together(() => Promise.all(needles.map((n) => searchItems(db, `"${n.replace(/"/g, " ")}"`, { repos: [repo], limit: 200 }))));
|
||||
const refs = [...new Set(hits.flat().map((h) => h.ref))].map((ref) => ({ repo, number: Number(ref.slice(ref.lastIndexOf("#") + 1)) })).filter((r) => r.number !== number);
|
||||
const rows = [...(await loadItems(db, refs, "text")).values()]
|
||||
.filter((i) => i.state === "OPEN" || (i.closed_at ?? i.merged_at ?? i.updated_at ?? "") >= since)
|
||||
.sort((x, y) => x.number - y.number).slice(0, 60);
|
||||
const byNumber = new RegExp(String.raw`(?<![\w/])#${number}(?!\d)`);
|
||||
return rows
|
||||
.filter((r) => { const text = `${r.title ?? ""}\n${r.body ?? ""}`; return byNumber.test(text) || files.some((f) => text.includes(f)); })
|
||||
.slice(0, 40).map((r) => ({ number: r.number, kind: r.kind, state: r.state === "OPEN" ? "open" as const : "closed" as const, title: (r.title ?? "").slice(0, 160) }));
|
||||
.slice(0, 40).map((r) => ({ number: r.number, kind: r.kind as RelatedItem["kind"], state: r.state === "OPEN" ? "open" as const : "closed" as const, title: (r.title ?? "").slice(0, 160) }));
|
||||
}
|
||||
+32
-44
@@ -5,8 +5,6 @@ import { poolRoom, takersCut } from "../agents/call.ts";
|
||||
import { pool } from "../classify/run.ts";
|
||||
import { runModelStep } from "../agents/step.ts";
|
||||
import { POSTMERGE_OPUS } from "../agents/steps.ts";
|
||||
import { audit } from "../dash/audit.ts";
|
||||
import { mergeDefect } from "../push-outcomes.ts";
|
||||
import { CLAUDE_PROMPTS } from "../prompts/index.ts";
|
||||
import { referenceDir } from "../reference.ts";
|
||||
import { defaultSemanticDeps, type SemanticDeps } from "../reference-lint.ts";
|
||||
@@ -16,11 +14,15 @@ import { REPO_PATH } from "../sandbox/command.ts";
|
||||
import { checkoutForCommit, checkoutForPr } from "../sandbox/index.ts";
|
||||
import { MAX_MERGED_DIFF_CHARS, type FiledBefore, type Finding, type PostmergeCommit, type PostmergePr } from "./parse.ts";
|
||||
import { relatedOpen, reviewHistory } from "./related.ts";
|
||||
import { followupsOf, MAX_RETRIES, mergedPr, selectPostmerge, type MergedPr } from "./select.ts";
|
||||
import { mergedPr, selectPostmerge, type MergedPr } from "./select.ts";
|
||||
import { jobItem } from "../runner/job-items.ts";
|
||||
import { flatMapSeq, forEachSeq, mapSeq } from "../async-seq.ts";
|
||||
import { flatMapSeq } from "../async-seq.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import { excluded, like } from "../db/kx.ts";
|
||||
import { addAudit, tripMergeBreakers, writeSetting } from "../data/control/index.ts";
|
||||
import { loadPushEdges } from "../data/changes/index.ts";
|
||||
import { loadMergedInfo } from "../data/merge/index.ts";
|
||||
import { loadItems, loadShown } from "../data/mirror/index.ts";
|
||||
import { countUnreviewedMerges, loadFollowups, savePostmerge } from "../data/review/index.ts";
|
||||
|
||||
const PROMPT = CLAUDE_PROMPTS["postmerge.opus"];
|
||||
const now = () => new Date().toISOString();
|
||||
@@ -51,26 +53,22 @@ export function defaultPostmergeDeps(db: Db): PostmergeDeps {
|
||||
};
|
||||
}
|
||||
|
||||
/** Commits the pipeline added to the PR: conflict merges, fix-ups and parts carried over from duplicates, oldest first. */
|
||||
/** Commits the pipeline added to the PR: conflict merges, fix-ups and CI fixes that moved its head, oldest first. */
|
||||
async function pipelineCommits(db: Db, repo: string, number: number): Promise<PostmergeCommit[]> {
|
||||
const rows = [
|
||||
...(await db.all(db.k.selectFrom("conflict_merges").select(["to_head as sha", "created_at as at", "reason as note"]).where("repo", "=", repo).where("number", "=", number).where("state", "=", "merged")))
|
||||
.map((r) => ({ ...r, kind: "conflict-merge" as const, note: r.note ?? "merged the base branch into the PR" })),
|
||||
...(await db.all(db.k.selectFrom("fixups").select(["to_head as sha", "created_at as at", "reason as note"]).where("repo", "=", repo).where("number", "=", number).where("state", "=", "pushed")))
|
||||
.map((r) => ({ ...r, kind: "fix-up" as const, note: r.note ?? "pushed the fixes of the review" })),
|
||||
...(await db.all(db.k.selectFrom("ci_fixes").select(["to_head as sha", "created_at as at", "reason as note"]).where("repo", "=", repo).where("number", "=", number).where("state", "=", "pushed")))
|
||||
.map((r) => ({ ...r, kind: "ci-fix" as const, note: r.note ?? "pushed a fix for the failing CI check" })),
|
||||
...(await db.all(db.k.selectFrom("dupe_carries").select(["to_head as sha", "updated_at as at", "outcome as note"]).where("repo", "=", repo).where("number", "=", number).where((eb) => like(db, "outcome", eb.val("pushed%")))))
|
||||
.map((r) => ({ ...r, kind: "duplicate-carry" as const, note: "carried parts of closed duplicates onto the PR" })),
|
||||
];
|
||||
return rows.sort((a, b) => a.at.localeCompare(b.at)).map(({ kind, sha, note }) => ({ kind, sha, note }));
|
||||
const KIND = { conflict: ["conflict-merge", "merged the base branch into the PR"], fixup: ["fix-up", "pushed the fixes of the review"], cifix: ["ci-fix", "pushed a fix for the failing CI check"] } as const;
|
||||
const edges = (await loadPushEdges(db, [{ repo, number }])).get(`${repo}#${number}`) ?? [];
|
||||
return edges.filter((e) => e.state === "pushed" || e.state === "merged")
|
||||
.sort((a, b) => a.at.localeCompare(b.at))
|
||||
.map((e) => ({ kind: KIND[e.kind][0], sha: e.to, note: e.reason ?? KIND[e.kind][1] }));
|
||||
}
|
||||
|
||||
/** Follow-up issues earlier reviews of the PR filed, with their current state; one still in `filing` has an unknown outcome. */
|
||||
export async function filedBefore(db: Db, repo: string, number: number): Promise<FiledBefore[]> {
|
||||
return await mapSeq((await followupsOf(db, repo, number)).filter((f) => f.state === "filed" || f.state === "filing"), async (f) => {
|
||||
const it = f.issue_number === null ? undefined : await db.get(db.k.selectFrom("items").select("state").where("repo", "=", repo).where("number", "=", f.issue_number));
|
||||
return { number: f.issue_number, state: f.state === "filing" ? "unknown" as const : it?.state === "OPEN" || !it ? "open" as const : "closed" as const, title: f.title };
|
||||
const filed = ((await loadFollowups(db, [{ repo, number }])).get(`${repo}#${number}`) ?? []).filter((f) => f.state === "filed" || f.state === "filing");
|
||||
const shown = await loadShown(db, filed.flatMap((f) => (f.issue_number === null ? [] : [{ repo, number: f.issue_number }])));
|
||||
return filed.map((f) => {
|
||||
const it = f.issue_number === null ? undefined : shown.get(`${repo}#${f.issue_number}`);
|
||||
return { number: f.issue_number, state: f.state === "filing" ? "unknown" as const : it?.state === "open" || !it ? "open" as const : "closed" as const, title: f.title };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -83,7 +81,7 @@ async function prepare(db: Db, c: MergedPr, deps: PostmergeDeps): Promise<Prepar
|
||||
if (!cd.files.length && cd.testsOmitted.length) cd = codeDiff(d.text, true);
|
||||
if (!cd.files.length) return { kind: "error", error: "held: the merge changed no code files" };
|
||||
if (cd.text.length > deps.maxChars) return { kind: "error", error: "held: too large to review automatically" };
|
||||
const it = await db.get(db.k.selectFrom("items").select(["title", "body", "author"]).where("repo", "=", c.repo).where("number", "=", c.number));
|
||||
const it = (await loadItems(db, [{ repo: c.repo, number: c.number }], "text")).get(refOf(c));
|
||||
const input: PostmergePr = {
|
||||
ref: refOf(c), title: it?.title ?? "", body: it?.body ?? "", author: it?.author ?? null, merge_sha: d.sha ?? c.head_oid, method: c.method,
|
||||
files: cd.files, tests_omitted: cd.testsOmitted, lockfiles_omitted: cd.lockfilesOmitted,
|
||||
@@ -99,24 +97,14 @@ async function prepare(db: Db, c: MergedPr, deps: PostmergeDeps): Promise<Prepar
|
||||
* one's follow-up rows, so the PR's filed follow-ups stay known. A `retry:` error is stored as held at the third try.
|
||||
*/
|
||||
export async function saveReview(db: Db, c: { repo: string; number: number }, r: { sha: string; runId: string | null; model: string | null; findings: Finding[] | null; error: string | null; at?: string }): Promise<void> {
|
||||
const at = r.at ?? now();
|
||||
// A failed second try never replaces a stored review.
|
||||
if (r.error && await db.get(db.k.selectFrom("postmerge_reviews").select((eb) => eb.lit(1).as("one")).where("repo", "=", c.repo).where("number", "=", c.number).where("error", "is", null))) return;
|
||||
let error = r.error, tries = 0;
|
||||
if (error?.startsWith("retry:")) {
|
||||
tries = ((await db.get(db.k.selectFrom("postmerge_reviews").select("tries").where("repo", "=", c.repo).where("number", "=", c.number)))?.tries ?? 0) + 1;
|
||||
if (tries >= MAX_RETRIES) error = `held: gave up after ${tries} tries (${error.slice("retry:".length).trim()})`;
|
||||
}
|
||||
await db.run(db.k.insertInto("postmerge_reviews")
|
||||
.values({ repo: c.repo, number: c.number, merge_sha: r.sha, at, model: r.model, run_id: r.runId, findings: r.findings ? JSON.stringify(r.findings) : null, error, tries })
|
||||
.onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet(excluded(["merge_sha", "at", "model", "run_id", "findings", "error", "tries"]))));
|
||||
const skip = (state: string, f: Finding, i: number, duplicateOf: number | null) => db.run(db.k.insertInto("postmerge_followups")
|
||||
.values({ repo: c.repo, number: c.number, review_at: at, finding: i, title: f.title, issue_number: null, url: null, state, at, duplicate_of: duplicateOf })
|
||||
.onConflict((oc) => oc.doNothing()));
|
||||
await mergeDefect(db, c.repo, c.number, (r.findings ?? []).filter((f) => f.severity === "defect").length);
|
||||
await forEachSeq((r.findings ?? []), async (f, i) => {
|
||||
if (f.severity === "minor") await skip("skipped-minor", f, i, null);
|
||||
else if (f.duplicate_of !== null) await skip("skipped-duplicate", f, i, f.duplicate_of);
|
||||
const ref = refOf(c);
|
||||
const merged = (await loadMergedInfo(db, [c])).get(ref);
|
||||
await db.write(async () => {
|
||||
const { defects } = await savePostmerge(db, [{ repo: c.repo, number: c.number, merge_sha: r.sha, at: r.at ?? now(), model: r.model, run_id: r.runId, findings: r.findings as never, error: r.error }]);
|
||||
const n = defects.get(ref) ?? 0;
|
||||
if (n > 0 && merged) {
|
||||
await tripMergeBreakers(db, [{ repo: c.repo, number: c.number, mergedAt: merged.lastAt, reason: `the post-merge review of ${ref} found ${n} defect${n === 1 ? "" : "s"}`, evidence: [ref] }]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -170,11 +158,11 @@ export async function queueBackfill(db: Db, by: string, since: string, o: { yes?
|
||||
const iso = new Date(since).toISOString();
|
||||
const days = ((o.now ?? Date.now()) - Date.parse(iso)) / 86400_000;
|
||||
if (days > BACKFILL_FREE_DAYS && !o.yes) throw new Error(`--since is ${Math.floor(days)} days back; every merged PR since then gets a model review and its defects are filed publicly. Add --yes to confirm`);
|
||||
await db.run(db.k.insertInto("settings").values({ key: "postmerge_since", value: iso }).onConflict((oc) => oc.column("key").doUpdateSet(excluded(["value"]))));
|
||||
await audit(db, by, "postmerge-backfill", null, { since: iso, confirmed: o.yes === true });
|
||||
return (await db.get(db.k.selectFrom((eb) => eb.selectFrom("merges as m").select(["m.repo", "m.number"]).distinct().where("m.outcome", "=", "merged").where("m.at", ">=", iso)
|
||||
.where((e) => e.not(e.exists(e.selectFrom("postmerge_reviews as r").select(e.lit(1).as("one")).whereRef("r.repo", "=", "m.repo").whereRef("r.number", "=", "m.number")))).as("d"))
|
||||
.select((eb) => eb.fn.countAll<number>().as("n"))))!.n;
|
||||
await db.write(async () => {
|
||||
await writeSetting(db, "postmerge_since", iso);
|
||||
await addAudit(db, [{ login: by, action: "postmerge-backfill", target: null, details: { since: iso, confirmed: o.yes === true } }]);
|
||||
});
|
||||
return await countUnreviewedMerges(db, iso);
|
||||
}
|
||||
|
||||
export { RELATED_CLOSED_DAYS, relatedOpen } from "./related.ts";
|
||||
+28
-58
@@ -1,14 +1,13 @@
|
||||
// Which merged PRs still need a post-merge review and which defects still need an issue, from the local tables only.
|
||||
import { quietFixPrs } from "../security/quiet.ts";
|
||||
import { pilotExprFor } from "../pilot.ts";
|
||||
import { loadQuiet } from "../data/security/index.ts";
|
||||
import { listItems } from "../data/mirror/index.ts";
|
||||
import { loadMergedInfo } from "../data/merge/index.ts";
|
||||
import { loadFollowupFixPrs, loadFollowups, loadPendingDefects, loadPostmerge, loadRecentFiled } from "../data/review/index.ts";
|
||||
import { planned } from "../core/select.ts";
|
||||
import type { PlanSet } from "../core/plan-set.ts";
|
||||
import type { Finding } from "./parse.ts";
|
||||
import { RETRY_AFTER_MS } from "../core/rules.ts";
|
||||
import { flatMapSeq } from "../async-seq.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import type { NotNull } from "kysely";
|
||||
|
||||
/** A review that failed with a `retry:` error is tried again after this long. */
|
||||
export { RETRY_AFTER_MS };
|
||||
@@ -22,23 +21,25 @@ export const MAX_RETRIES = 3;
|
||||
|
||||
/** PRs whose Plan holds a `postmerge` action: a pipeline merge landed since the `postmerge_since` setting and no usable review is stored (a `retry:` error counts as missing an hour after it failed; the third is stored as held). Oldest merge first. */
|
||||
export async function selectPostmerge(db: Db, repo: string, now = Date.now(), run?: string | null, plans?: PlanSet): Promise<MergedPr[]> {
|
||||
return (await flatMapSeq((await planned(db, "postmerge", { repo, now, ...(run !== undefined ? { run } : {}), ...(plans ? { plans } : {}) })), async (p) => await mergedPr(db, repo, p.facts.number) ?? []))
|
||||
const rows = await planned(db, "postmerge", { repo, now, ...(run !== undefined ? { run } : {}), ...(plans ? { plans } : {}) });
|
||||
return [...(await mergedPrs(db, repo, rows.map((p) => p.facts.number))).values()]
|
||||
.sort((a, b) => (a.merged_at < b.merged_at ? -1 : a.merged_at > b.merged_at ? 1 : 0) || a.number - b.number);
|
||||
}
|
||||
|
||||
/** The PRs among `numbers` that the pipeline merged, by number. */
|
||||
async function mergedPrs(db: Db, repo: string, numbers: number[]): Promise<Map<number, MergedPr>> {
|
||||
const out = new Map<number, MergedPr>();
|
||||
if (!numbers.length) return out;
|
||||
for (const [key, m] of await loadMergedInfo(db, numbers.map((number) => ({ repo, number })))) {
|
||||
const number = Number(key.slice(key.lastIndexOf("#") + 1));
|
||||
out.set(number, { repo, number, head_oid: m.lastHead, merged_at: m.firstAt, method: m.method, batch: m.viaBatch ? 1 : 0 });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The merged PR `repo#number`, whatever its review state, or null when the pipeline did not merge it. */
|
||||
export async function mergedPr(db: Db, repo: string, number: number): Promise<MergedPr | null> {
|
||||
return await db.get(db.k.selectFrom("merges as m").select((eb) => [
|
||||
"m.repo", "m.number",
|
||||
eb.selectFrom("merges as x").select("x.head_oid").whereRef("x.repo", "=", "m.repo").whereRef("x.number", "=", "m.number").where("x.outcome", "=", "merged")
|
||||
.orderBy("x.at", "desc").orderBy(kx.rowid("merges", "x"), "desc").limit(1).as("head_oid"),
|
||||
eb.fn.min<string>("m.at").as("merged_at"),
|
||||
eb.selectFrom("merges as x").select("x.method").whereRef("x.repo", "=", "m.repo").whereRef("x.number", "=", "m.number").where("x.outcome", "=", "merged")
|
||||
.orderBy("x.at", "desc").orderBy(kx.rowid("merges", "x"), "desc").limit(1).as("method"),
|
||||
eb.case().when(eb.exists(eb.selectFrom("merge_batch_prs as bp").innerJoin("merge_batches as mb", "mb.id", "bp.batch_id").select(eb.lit(1).as("one"))
|
||||
.whereRef("mb.repo", "=", "m.repo").whereRef("bp.number", "=", "m.number").where("mb.state", "=", "merged"))).then(1).else(0).end().as("batch"),
|
||||
]).where("m.repo", "=", repo).where("m.number", "=", number).where("m.outcome", "=", "merged").groupBy(["m.repo", "m.number"])
|
||||
.$narrowType<{ head_oid: string }>()) ?? null;
|
||||
return (await mergedPrs(db, repo, [number])).get(number) ?? null;
|
||||
}
|
||||
|
||||
export type StoredReview = { repo: string; number: number; merge_sha: string; at: string; model: string | null; error: string | null; findings: Finding[] };
|
||||
@@ -51,16 +52,15 @@ export function parseStored(json: string | null): Finding[] {
|
||||
}
|
||||
|
||||
export async function reviewOf(db: Db, repo: string, number: number): Promise<StoredReview | null> {
|
||||
const r = await db.get(db.k.selectFrom("postmerge_reviews").select(["repo", "number", "merge_sha", "at", "model", "error", "findings"]).where("repo", "=", repo).where("number", "=", number));
|
||||
return r ? { ...r, findings: parseStored(r.findings) } : null;
|
||||
const r = (await loadPostmerge(db, [{ repo, number }])).get(`${repo}#${number}`);
|
||||
return r ? { repo: r.repo, number: r.number, merge_sha: r.merge_sha, at: r.at, model: r.model, error: r.error, findings: r.findings as Finding[] } : null;
|
||||
}
|
||||
|
||||
export type FollowupState = "filing" | "filed" | "failed" | "skipped-duplicate" | "skipped-limit" | "skipped-minor" | "skipped-stale" | "skipped-text";
|
||||
export type Followup = { repo: string; number: number; review_at: string; finding: number; title: string; issue_number: number | null; url: string | null; state: FollowupState; at: string; duplicate_of: number | null; attempts: number; note: string | null };
|
||||
|
||||
export async function followupsOf(db: Db, repo: string, number: number): Promise<Followup[]> {
|
||||
return await db.all(db.k.selectFrom("postmerge_followups").select(kx.cols("postmerge_followups")).where("repo", "=", repo).where("number", "=", number)
|
||||
.orderBy("review_at").orderBy("finding").$narrowType<{ state: FollowupState }>());
|
||||
return (await loadFollowups(db, [{ repo, number }])).get(`${repo}#${number}`) as Followup[] ?? [];
|
||||
}
|
||||
|
||||
/** A failed filing is tried again this long after its attempt (1 h after the first, 6 h after the second); three attempts at most. */
|
||||
@@ -75,8 +75,7 @@ export function retryDue(f: Pick<Followup, "state" | "attempts" | "at">, now = D
|
||||
|
||||
/** The PR is the Fix PR of a follow-up issue this stage filed. */
|
||||
export async function fixesFollowup(db: Db, repo: string, number: number): Promise<boolean> {
|
||||
return await db.get(db.k.selectFrom("fix_attempts as fa").innerJoin("postmerge_followups as pf", (j) => j.onRef("pf.repo", "=", "fa.repo").onRef("pf.issue_number", "=", "fa.number"))
|
||||
.select((eb) => eb.lit(1).as("one")).where("fa.repo", "=", repo).where((eb) => kx.like(db, "fa.pr_url", eb.val(`%/pull/${number}`))).limit(1)) !== undefined;
|
||||
return (await loadFollowupFixPrs(db, [{ repo, number }])).has(`${repo}#${number}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,34 +99,11 @@ export type PendingDefect = { repo: string; number: number; review_at: string; f
|
||||
* skipped-limit row, or a failed row whose backoff has passed. A review held by `heldReason`, and the review of a quiet pull request, has none.
|
||||
*/
|
||||
export async function pendingDefects(db: Db, repo?: string, now = Date.now()): Promise<PendingDefect[]> {
|
||||
const rows = await db.all(db.k.selectFrom("postmerge_reviews as r").select(["r.repo", "r.number", "r.at", "r.model", "r.findings"])
|
||||
.$if(repo !== undefined, (q) => q.where("r.repo", "=", repo!)).where("r.error", "is", null).where((eb) => pilotExprFor(db, eb, "r.repo", "r.number"))
|
||||
.orderBy("r.at").orderBy("r.number"));
|
||||
const out: PendingDefect[] = [];
|
||||
if (!rows.length) return out;
|
||||
const quiet = await quietFixPrs(db, repo);
|
||||
// The follow-ups of each PR and the Fix PR links of follow-up issues, read once (followupsOf and fixesFollowup per PR).
|
||||
const followups = new Map<string, Followup[]>();
|
||||
for (const f of await db.all(db.k.selectFrom("postmerge_followups").select(kx.cols("postmerge_followups")).$if(repo !== undefined, (q) => q.where("repo", "=", repo!))
|
||||
.orderBy("review_at").orderBy("finding").$narrowType<{ state: FollowupState }>())) (followups.get(`${f.repo}#${f.number}`) ?? followups.set(`${f.repo}#${f.number}`, []).get(`${f.repo}#${f.number}`)!).push(f);
|
||||
const fixUrls = await db.all(db.k.selectFrom("fix_attempts as fa").innerJoin("postmerge_followups as pf", (j) => j.onRef("pf.repo", "=", "fa.repo").onRef("pf.issue_number", "=", "fa.number"))
|
||||
.select(["fa.repo", "fa.pr_url"]).$if(repo !== undefined, (q) => q.where("fa.repo", "=", repo!)).where("fa.pr_url", "is not", null).$narrowType<{ pr_url: NotNull }>());
|
||||
// As `pr_url LIKE '%/pull/<number>'`: LIKE ignores ASCII case.
|
||||
const fixes = (r: string, n: number): boolean => fixUrls.some((u) => u.repo === r && u.pr_url.toLowerCase().endsWith(`/pull/${n}`));
|
||||
for (const r of rows) {
|
||||
// A security fix gets no public text until its advisory is published: its findings stay on the dashboard.
|
||||
if (quiet.has(`${r.repo}#${r.number}`)) continue;
|
||||
const prFollowups = followups.get(`${r.repo}#${r.number}`) ?? [];
|
||||
if (await heldBy(prFollowups, async () => fixes(r.repo, r.number), r.at)) continue;
|
||||
const have = prFollowups.filter((x) => x.review_at === r.at);
|
||||
parseStored(r.findings).forEach((f, i) => {
|
||||
if (f.severity !== "defect" || f.duplicate_of !== null) return;
|
||||
const row = have.find((x) => x.finding === i);
|
||||
if (row && row.state !== "skipped-limit" && !retryDue(row, now)) return;
|
||||
out.push({ repo: r.repo, number: r.number, review_at: r.at, finding: i, f, model: r.model, attempts: row?.attempts ?? 0 });
|
||||
});
|
||||
}
|
||||
return out;
|
||||
// A security fix gets no public text until its advisory is published: its findings stay on the dashboard.
|
||||
const merged = await listItems(db, { kind: "pr", states: ["MERGED"], inScope: true, ...(repo !== undefined ? { repos: [repo] } : {}) }, "ref");
|
||||
const quiet = await loadQuiet(db, merged.map((m) => `${m.repo}#${m.number}`));
|
||||
const keys = merged.filter((m) => !quiet.has(`${m.repo}#${m.number}`)).map((m) => ({ repo: m.repo, number: m.number }));
|
||||
return await loadPendingDefects(db, keys, { now }) as unknown as PendingDefect[];
|
||||
}
|
||||
|
||||
const words = (t: string): Set<string> => new Set(t.toLowerCase().replace(/[^a-z0-9]+/g, " ").split(" ").filter((w) => w.length > 2));
|
||||
@@ -146,13 +122,7 @@ export const sameDefect = (a: Finding, b: Finding): boolean =>
|
||||
|
||||
/** Defects this stage filed (or is filing) in the last 30 days, with the finding's file and line from the review they came from. */
|
||||
export async function recentFiled(db: Db, repo: string, now = Date.now()): Promise<{ number: number; f: Finding }[]> {
|
||||
const since = new Date(now - 30 * 86400_000).toISOString();
|
||||
const rows = await db.all(db.k.selectFrom("postmerge_followups").select(["number", "review_at", "finding"]).where("repo", "=", repo).where("state", "in", ["filed", "filing"]).where("at", ">=", since));
|
||||
return await flatMapSeq(rows, async (x) => {
|
||||
const r = await reviewOf(db, repo, x.number);
|
||||
const f = r && r.at === x.review_at ? r.findings[x.finding] : undefined;
|
||||
return f ? [{ number: x.number, f }] : [];
|
||||
});
|
||||
return await loadRecentFiled(db, repo, { now }) as { number: number; f: Finding }[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+50
-134
@@ -1,9 +1,9 @@
|
||||
// What can keep a PR's review from changing: another open item the review named as the reason for its hold.
|
||||
import { isHiddenRepo, type HiddenRepos } from "../hidden-sql.ts";
|
||||
import { filterSeq, someSeq } from "../async-seq.ts";
|
||||
import type { NotNull } from "kysely";
|
||||
import type { HiddenRepos } from "../hidden-sql.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { loadItems } from "../data/mirror/index.ts";
|
||||
import { loadLatestReviews } from "../data/review/index.ts";
|
||||
import { loadWorkflowFacts } from "../data/workflow/index.ts";
|
||||
|
||||
const REF = /^([\w.-]+)#(\d+)$/;
|
||||
|
||||
@@ -24,148 +24,64 @@ export function storedBlockedBy(s: string | null | undefined): string[] {
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
/**
|
||||
* The refs that still block: a tracked item that is open and, for an issue, has an unanswered decision. An untracked, closed or
|
||||
* merged item, or an issue with nothing left to decide, blocks nothing.
|
||||
*/
|
||||
export async function openBlockers(db: Db, refs: readonly string[]): Promise<string[]> {
|
||||
return await filterSeq(refs, async (ref) => {
|
||||
const m = REF.exec(ref);
|
||||
if (!m) return false;
|
||||
const i = await db.get(db.k.selectFrom("main.items").select(["kind", "state"]).where("repo", "=", m[1]!).where("number", "=", Number(m[2])));
|
||||
if (!i || i.state !== "OPEN") return false;
|
||||
return i.kind === "pr" || !!await db.get(db.k.selectFrom("main.decisions").select((eb) => eb.lit(1).as("one")).where("repo", "=", m[1]!).where("number", "=", Number(m[2])).where("answer", "is", null).limit(1));
|
||||
/** What the blocker rules read per named ref (keys `repo#number`): the item, whether a person is asked about it, and its latest review. */
|
||||
export type BlockerReads = { item: Map<string, { kind: string; state: string }>; pending: Set<string>; latest: Map<string, { verdict: string; blocked_by: string[] }> };
|
||||
|
||||
const keyOf = (ref: string): string | null => { const m = REF.exec(ref); return m ? `${m[1]}#${Number(m[2])}` : null; };
|
||||
|
||||
/** The items, open asks and latest reviews of `refs`, in one wave. */
|
||||
export async function loadBlockerReads(db: Db, refs: Iterable<string>): Promise<BlockerReads> {
|
||||
const keys = new Map<string, { repo: string; number: number }>();
|
||||
for (const ref of refs) { const m = REF.exec(ref); if (m) keys.set(`${m[1]}#${Number(m[2])}`, { repo: m[1]!, number: Number(m[2]) }); }
|
||||
const out: BlockerReads = { item: new Map(), pending: new Set(), latest: new Map() };
|
||||
if (!keys.size) return out;
|
||||
const list = [...keys.values()];
|
||||
const [items, wf, latest] = await db.together(() => Promise.all([loadItems(db, list, "ref"), loadWorkflowFacts(db, list), loadLatestReviews(db, list)]));
|
||||
for (const [k, i] of items) out.item.set(k, i);
|
||||
// What an unanswered decision meant: a person is asked about the item's workflow.
|
||||
for (const [k, w] of wf.live) if (w.state === "recommending" || w.state === "blocked") out.pending.add(k);
|
||||
for (const [k, r] of latest) out.latest.set(k, { verdict: r.verdict, blocked_by: r.blocked_by });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The refs that still block: a tracked item that is open and, for an issue, has a person asked about it. */
|
||||
export function openFrom(reads: BlockerReads, refs: readonly string[]): string[] {
|
||||
return refs.filter((ref) => {
|
||||
const k = keyOf(ref);
|
||||
const i = k === null ? undefined : reads.item.get(k);
|
||||
return !!i && i.state === "OPEN" && (i.kind === "pr" || reads.pending.has(k!));
|
||||
});
|
||||
}
|
||||
|
||||
/** An untracked, closed or merged item, or an issue with nothing left to decide, blocks nothing. */
|
||||
export async function openBlockers(db: Db, refs: readonly string[]): Promise<string[]> {
|
||||
return openFrom(await loadBlockerReads(db, refs), refs);
|
||||
}
|
||||
|
||||
/** A hold's blocker list is ignored after this long: the PR then gets one fresh review. */
|
||||
export const BLOCKED_EXPIRES_MS = 14 * 24 * 3600_000;
|
||||
|
||||
/**
|
||||
* The blockers of the review of `self` made at `at` that still hold: open (openBlockers), not past BLOCKED_EXPIRES_MS, and not
|
||||
* themselves waiting on `self` (two PRs blocking each other would never be reviewed).
|
||||
* The blockers of the review of `self` made at `at` that still hold: open, not past BLOCKED_EXPIRES_MS, and not
|
||||
* themselves waiting on `self` (two PRs blocking each other would never be reviewed). `stored` is the review's `blocked_by` list.
|
||||
*/
|
||||
export async function activeBlockers(db: Db, self: string, stored: string | null | undefined, at: string, nowMs: number = Date.now()): Promise<string[]> {
|
||||
const refs = storedBlockedBy(stored);
|
||||
if (!refs.length || nowMs - Date.parse(at) > BLOCKED_EXPIRES_MS) return [];
|
||||
return await filterSeq((await openBlockers(db, refs)), async (ref) => {
|
||||
const [repo, n] = ref.split("#");
|
||||
const l = await db.get(db.k.selectFrom("main.opus_reviews as o").select(["o.verdict", "o.blocked_by"]).$narrowType<{ verdict: NotNull }>()
|
||||
.where("o.repo", "=", repo!).where("o.number", "=", Number(n)).where("o.verdict", "is not", null).orderBy("o.at", "desc").orderBy(kx.rowid("main.opus_reviews", "o"), "desc").limit(1));
|
||||
return !(l?.verdict === "hold" && storedBlockedBy(l.blocked_by).includes(self));
|
||||
export function activeFrom(reads: BlockerReads, self: string, stored: readonly string[], at: string, nowMs: number): string[] {
|
||||
if (!stored.length || nowMs - Date.parse(at) > BLOCKED_EXPIRES_MS) return [];
|
||||
return openFrom(reads, stored).filter((ref) => {
|
||||
const l = reads.latest.get(keyOf(ref)!);
|
||||
return !(l?.verdict === "hold" && l.blocked_by.includes(self));
|
||||
});
|
||||
}
|
||||
|
||||
type BlockerReads = { item: Map<string, { kind: string; state: string }>; pending: Set<string>; latest: Map<string, { verdict: string; blocked_by: string | null }> };
|
||||
/** Whether any of `refs` has a person asked about it: the wait is then on a person. */
|
||||
export const hasOpenQuestion = (reads: BlockerReads, refs: readonly string[]): boolean => refs.some((r) => { const k = keyOf(r); return k !== null && reads.pending.has(k); });
|
||||
|
||||
/** What openBlockers and activeBlockers read per ref, read once for many refs (keys `repo#number`). */
|
||||
async function blockerReads(db: Db, refs: string[]): Promise<BlockerReads> {
|
||||
const keys = new Map<string, [string, number]>();
|
||||
for (const ref of refs) { const m = REF.exec(ref); if (m) keys.set(`${m[1]}#${Number(m[2])}`, [m[1]!, Number(m[2])]); }
|
||||
const out: BlockerReads = { item: new Map(), pending: new Set(), latest: new Map() };
|
||||
if (!keys.size) return out;
|
||||
const pairs = [...keys.values()];
|
||||
for (const r of await db.all(db.k.selectFrom("main.items as i").select(["i.repo", "i.number", "i.kind", "i.state"]).where(kx.refIn(db, "i", pairs)))) out.item.set(`${r.repo}#${r.number}`, r);
|
||||
for (const r of await db.all(db.k.selectFrom("main.decisions as d").select(["d.repo", "d.number"]).distinct().where(kx.refIn(db, "d", pairs)).where("d.answer", "is", null)))
|
||||
out.pending.add(`${r.repo}#${r.number}`);
|
||||
const ranked = db.k.selectFrom("main.opus_reviews as o")
|
||||
.select((eb) => ["o.repo", "o.number", "o.verdict", "o.blocked_by", eb.fn.agg<number>("row_number", []).over((w) => w.partitionBy(["o.repo", "o.number"]).orderBy("o.at", "desc").orderBy(kx.rowid("main.opus_reviews", "o"), "desc")).as("k")])
|
||||
.where(kx.refIn(db, "o", pairs)).where("o.verdict", "is not", null);
|
||||
for (const r of await db.all(db.k.selectFrom(ranked.as("r")).select(["r.repo", "r.number", "r.verdict", "r.blocked_by"]).$narrowType<{ verdict: NotNull }>().where("r.k", "=", 1))) out.latest.set(`${r.repo}#${r.number}`, r);
|
||||
return out;
|
||||
/** Retired with the decisions: no decision names the PRs whose review it holds any more. */
|
||||
export async function blocksFacts(_db: Db, _repo: string | null, _number: number | null, _hidden: HiddenRepos): Promise<string[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/** activeBlockers from reads made for many reviews at once. */
|
||||
function activeFrom(reads: BlockerReads, self: string, stored: string | null | undefined, at: string, nowMs: number): string[] {
|
||||
const refs = storedBlockedBy(stored);
|
||||
if (!refs.length || nowMs - Date.parse(at) > BLOCKED_EXPIRES_MS) return [];
|
||||
return refs.filter((ref) => {
|
||||
const m = REF.exec(ref);
|
||||
if (!m) return false;
|
||||
const k = `${m[1]}#${Number(m[2])}`;
|
||||
const i = reads.item.get(k);
|
||||
if (!i || i.state !== "OPEN" || (i.kind !== "pr" && !reads.pending.has(k))) return false;
|
||||
const l = reads.latest.get(k);
|
||||
return !(l?.verdict === "hold" && storedBlockedBy(l.blocked_by).includes(self));
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether any of the refs has an open decision: the wait is then on a person. */
|
||||
export async function hasOpenQuestion(db: Db, refs: readonly string[]): Promise<boolean> {
|
||||
return await someSeq(refs, async (ref) => {
|
||||
const m = REF.exec(ref);
|
||||
return !!m && !!await db.get(db.k.selectFrom("main.decisions").select((eb) => eb.lit(1).as("one")).where("repo", "=", m[1]!).where("number", "=", Number(m[2])).where("answer", "is", null).limit(1));
|
||||
});
|
||||
}
|
||||
|
||||
/** The rowid of the latest review with a verdict of the PR of the review `o` (an expression in a query that has `main.opus_reviews as o`). */
|
||||
const latestRowid = (eb: kx.AnyEb) => kx.schemaEb(eb).selectFrom("main.opus_reviews as l").select(kx.rowid("main.opus_reviews", "l").as("rid"))
|
||||
.where("l.repo", "=", eb.ref("o.repo")).where("l.number", "=", eb.ref("o.number")).where("l.verdict", "is not", null)
|
||||
.orderBy("l.at", "desc").orderBy(kx.rowid("main.opus_reviews", "l"), "desc").limit(1);
|
||||
|
||||
/** Facts for an open decision naming the PRs whose review it holds (derived from their stored holds; the decision row is not written). PRs of repos in `hidden` are not named. */
|
||||
export async function blocksFacts(db: Db, repo: string | null, number: number | null, hidden: HiddenRepos): Promise<string[]> {
|
||||
if (repo === null || number === null) return [];
|
||||
const me = `${repo}#${number}`;
|
||||
const rows = await db.all(db.k.selectFrom("main.opus_reviews as o").innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "o.repo").onRef("i.number", "=", "o.number").on("i.state", "=", "OPEN"))
|
||||
.select(["o.repo", "o.number", "o.at", "o.blocked_by"]).$narrowType<{ blocked_by: NotNull }>()
|
||||
.where("o.verdict", "is not", null).where((eb) => kx.like(db, "o.blocked_by", eb.val(`%"${me}"%`)))
|
||||
.where((eb) => eb(kx.rowid("main.opus_reviews", "o"), "=", latestRowid(eb)))
|
||||
.where("o.verdict", "=", "hold").orderBy("o.repo").orderBy("o.number").limit(5));
|
||||
return (await filterSeq(rows, async (r) => !isHiddenRepo(hidden, r.repo) && (await activeBlockers(db, `${r.repo}#${r.number}`, r.blocked_by, r.at)).includes(me))).map((r) => `Blocks the review of ${r.repo}#${r.number}`);
|
||||
}
|
||||
|
||||
/** `blocksFacts` for every PR at once: the facts by blocked ref ("repo#number"), from one scan of the latest holds. For a page of decisions. */
|
||||
export async function blocksIndex(db: Db, hidden: HiddenRepos): Promise<Map<string, string[]>> {
|
||||
const rows = await db.all(db.k.selectFrom("main.opus_reviews as o").innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "o.repo").onRef("i.number", "=", "o.number").on("i.state", "=", "OPEN"))
|
||||
.select(["o.repo", "o.number", "o.at", "o.blocked_by"]).$narrowType<{ blocked_by: NotNull }>()
|
||||
.where("o.verdict", "=", "hold").where((eb) => kx.like(db, "o.blocked_by", eb.val('%"%')))
|
||||
.where((eb) => eb(kx.rowid("main.opus_reviews", "o"), "=", latestRowid(eb)))
|
||||
.orderBy("o.repo").orderBy("o.number"));
|
||||
const out = new Map<string, string[]>();
|
||||
const nowMs = Date.now();
|
||||
const shown = rows.filter((r) => !isHiddenRepo(hidden, r.repo));
|
||||
const reads = await blockerReads(db, shown.flatMap((r) => (nowMs - Date.parse(r.at) > BLOCKED_EXPIRES_MS ? [] : storedBlockedBy(r.blocked_by))));
|
||||
for (const r of shown) {
|
||||
const self = `${r.repo}#${r.number}`;
|
||||
for (const ref of activeFrom(reads, self, r.blocked_by, r.at, nowMs)) {
|
||||
const facts = out.get(ref) ?? [];
|
||||
if (facts.length < 5) facts.push(`Blocks the review of ${self}`);
|
||||
out.set(ref, facts);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* activeBlockers() and hasOpenQuestion() for many PRs, for one planner pass: the items, open decisions and latest reviews of the
|
||||
* refs are read in one batch (blockerReads) per new set of refs, starting with every ref a stored hold names.
|
||||
*/
|
||||
export function blockersLoader(db: Db): { active: (self: string, stored: string | null | undefined, at: string, nowMs: number) => Promise<string[]>; openQuestion: (refs: readonly string[]) => Promise<boolean> } {
|
||||
const reads: BlockerReads = { item: new Map(), pending: new Set(), latest: new Map() };
|
||||
const asked = new Set<string>();
|
||||
const key = (ref: string): string | null => { const m = REF.exec(ref); return m ? `${m[1]}#${Number(m[2])}` : null; };
|
||||
const ensure = async (refs: readonly string[]): Promise<void> => {
|
||||
const fresh = refs.filter((r) => { const k = key(r); if (k === null || asked.has(k)) return false; asked.add(k); return true; });
|
||||
if (!fresh.length) return;
|
||||
const r = await blockerReads(db, fresh);
|
||||
for (const [k, v] of r.item) reads.item.set(k, v);
|
||||
for (const k of r.pending) reads.pending.add(k);
|
||||
for (const [k, v] of r.latest) reads.latest.set(k, v);
|
||||
};
|
||||
let started = false;
|
||||
const start = async (): Promise<void> => {
|
||||
if (started) return;
|
||||
started = true;
|
||||
await ensure((await db.all(db.k.selectFrom("main.opus_reviews").select("blocked_by").distinct().where("verdict", "=", "hold").where("blocked_by", "is not", null))).flatMap((r) => storedBlockedBy(r.blocked_by)));
|
||||
};
|
||||
const openQuestion = async (refs: readonly string[]): Promise<boolean> => { await start(); await ensure(refs); return refs.some((r) => { const k = key(r); return k !== null && reads.pending.has(k); }); };
|
||||
const active = async (self: string, stored: string | null | undefined, at: string, nowMs: number): Promise<string[]> => {
|
||||
const refs = storedBlockedBy(stored);
|
||||
if (!refs.length || nowMs - Date.parse(at) > BLOCKED_EXPIRES_MS) return [];
|
||||
await start();
|
||||
await ensure(refs);
|
||||
return activeFrom(reads, self, stored, at, nowMs);
|
||||
};
|
||||
return { active, openQuestion };
|
||||
/** Retired with the decisions. */
|
||||
export async function blocksIndex(_db: Db, _hidden: HiddenRepos): Promise<Map<string, string[]>> {
|
||||
return new Map();
|
||||
}
|
||||
+16
-10
@@ -1,22 +1,28 @@
|
||||
// The Carry step: stores the carried review (carry.ts) for each PR whose Plan holds a `carry` action. Calls no model.
|
||||
import { planned } from "../core/select.ts";
|
||||
import { staleReviews } from "./discussion.ts";
|
||||
import { carriedReview, CARRIED } from "./carry.ts";
|
||||
import { saveOpus } from "./opus.ts";
|
||||
import { carriedReviews, CARRIED } from "./carry.ts";
|
||||
import { currentJobId } from "../agents/call.ts";
|
||||
import { loadRepos } from "../data/mirror/index.ts";
|
||||
import { saveReviews, type SaveReviewInput } from "../data/review/index.ts";
|
||||
import { jobItem } from "../runner/job-items.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
|
||||
export async function runCarry(db: Db, repo: string, log: (line: string) => void = console.log): Promise<number> {
|
||||
const stale = await staleReviews(db, repo);
|
||||
const runId = `carry-${repo}-${new Date().toISOString().replace(/[-:]/g, "").slice(0, 15)}`;
|
||||
let n = 0;
|
||||
for (const { facts: f, action } of await planned(db, "carry", { repo })) {
|
||||
const c = { repo, number: f.number, head_oid: action.head! };
|
||||
const k = await carriedReview(db, c, stale);
|
||||
const rows = await planned(db, "carry", { repo });
|
||||
const carried = await carriedReviews(db, rows.map(({ facts: f, action }) => ({ repo, number: f.number, head_oid: action.head! })), stale);
|
||||
const [repos] = await Promise.all([loadRepos(db, { names: [repo] })]);
|
||||
const saves: SaveReviewInput[] = [];
|
||||
for (const { facts: f, action } of rows) {
|
||||
const k = carried.get(`${repo}#${f.number}`);
|
||||
if (!k) continue;
|
||||
await saveOpus(db, runId, c, { mode: CARRIED, base: k.from, baseRef: k.baseRef, model: CARRIED, review: k.review, snap: { seen: k.seen, hash: k.hash } });
|
||||
await jobItem(db, repo, f.number, `carried review: ${k.review.reason}`, log);
|
||||
n++;
|
||||
saves.push({ runId, repo, number: f.number, head: action.head!, mode: CARRIED, base: k.from, baseRef: k.baseRef, defaultBranch: repos.get(repo)?.default_branch ?? null, model: CARRIED,
|
||||
review: { verdict: k.review.verdict, sure: k.review.sure, reason: k.review.reason, fixes: k.review.fixes as never, risks: k.review.risks, workflow: (k.review.workflow ?? null) as never, summary: k.review.summary, why: k.review.why, public: k.review.public, conflicts: k.review.conflicts, claims: k.review.claims },
|
||||
snap: { seen: k.seen, hash: k.hash }, blockedBy: [], jobId: currentJobId() });
|
||||
}
|
||||
return n;
|
||||
await saveReviews(db, saves);
|
||||
for (const sv of saves) await jobItem(db, repo, sv.number, `carried review: ${sv.review.reason}`, log);
|
||||
return saves.length;
|
||||
}
|
||||
+66
-38
@@ -1,53 +1,81 @@
|
||||
// A take or take-fix verdict carries over our own checked fix-up: when the only change since a sure review is the fix-up commit
|
||||
// whose patch the patch check approved (and whose lint passed, since it was pushed), the new head gets the same verdict without an Opus call.
|
||||
import { ourCommitsSince } from "./ours.ts";
|
||||
import { ourCommitsLoader } from "./ours.ts";
|
||||
import type { OpusReview } from "./opus-parse.ts";
|
||||
import { reviewAfterBaseMerge } from "./own-diff.ts";
|
||||
import { defaultBranchOf } from "../merge/base.ts";
|
||||
import type { NotNull } from "kysely";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { loadFixupVerdicts, loadPushEdges, type PushEdge } from "../data/changes/index.ts";
|
||||
import { loadItems, loadRepos } from "../data/mirror/index.ts";
|
||||
import { loadReviewRows, loadReviewTexts, type ReviewRow } from "../data/review/index.ts";
|
||||
|
||||
export const CARRIED = "carried";
|
||||
|
||||
export type Carried = { review: OpusReview; from: string; seen: string; hash: string | null; baseRef: string | null };
|
||||
type Cand = { repo: string; number: number; head_oid: string };
|
||||
|
||||
/**
|
||||
* The review to record at `c.head_oid` as carried from the latest earlier review, with that review's discussion mark; null when it does not carry.
|
||||
* The review to record at each `c.head_oid` as carried from the latest earlier review, with that review's discussion mark; a PR that does not carry has no entry.
|
||||
* `stale` is the set of "repo#n@head" whose review is stale (staleReviews): a review that has not read the discussion as it is now is not carried,
|
||||
* and a head that already has a review (stale, being reviewed again) is never carried from an earlier one. A review read against
|
||||
* another base branch than the PR has now is not carried either; a carried review keeps the base its source read.
|
||||
*/
|
||||
export async function carriedReview(db: Db, c: { repo: string; number: number; head_oid: string }, stale: Set<string> = new Set()): Promise<{ review: OpusReview; from: string; seen: string; hash: string | null; baseRef: string | null } | null> {
|
||||
const e = await db.get(db.k.selectFrom("opus_reviews").select(["head_oid", "verdict", "sure", "risks", "summary", "why", "conflicts", "fixes", "at", "seen_at", "disc_hash", "model", "base_ref"])
|
||||
.$narrowType<{ verdict: NotNull }>().where("repo", "=", c.repo).where("number", "=", c.number).where("head_oid", "<>", c.head_oid).where("verdict", "is not", null).where("model", "is not", null)
|
||||
.orderBy("at", "desc").orderBy(kx.rowid("opus_reviews"), "desc").limit(1));
|
||||
if (await db.get(db.k.selectFrom("opus_reviews").select((eb) => eb.lit(1).as("one")).where("repo", "=", c.repo).where("number", "=", c.number).where("head_oid", "=", c.head_oid).where("verdict", "is not", null))) return null;
|
||||
if (!e || stale.has(`${c.repo}#${c.number}@${e.head_oid}`) || (e.verdict !== "take" && e.verdict !== "take-fix") || e.sure !== 1) return null;
|
||||
const baseRef = e.base_ref ?? await defaultBranchOf(db, c.repo);
|
||||
const liveBase = (await db.get(db.k.selectFrom("items").select("base_ref").where("repo", "=", c.repo).where("number", "=", c.number)))?.base_ref ?? null;
|
||||
if (baseRef && liveBase && baseRef !== liveBase) return null;
|
||||
const path = await ourCommitsSince(db, c.repo, c.number, e.head_oid, c.head_oid);
|
||||
const list = <T>(s: string | null): T[] => { try { const v = JSON.parse(s ?? "[]") as unknown; return Array.isArray(v) ? (v as T[]) : []; } catch { return []; } };
|
||||
const merge = path.complete && path.commits.length === 1 && path.commits[0]!.kind === "base merge"
|
||||
? await db.get(db.k.selectFrom("conflict_merges").select("own_diff").where("repo", "=", c.repo).where("number", "=", c.number).where("to_head", "=", c.head_oid).where("state", "=", "merged")
|
||||
.orderBy(kx.rowid("conflict_merges"), "desc").limit(1)) : undefined;
|
||||
// Our merge of the base branch: the PR's own diff is what the review read, so an unchanged diff keeps the verdict and its fixes.
|
||||
if (merge && reviewAfterBaseMerge(merge.own_diff) === "carry") {
|
||||
const review: OpusReview = {
|
||||
ref: `${c.repo}#${c.number}`, verdict: e.verdict, sure: true, fixes: list(e.fixes), risks: list<string>(e.risks), summary: e.summary, why: e.why, public: null,
|
||||
reason: `carried from ${e.head_oid.slice(0, 7)}: the only change is our merge of the base branch, and the PR's own diff is unchanged`, conflicts: list(e.conflicts), claims: [], blocked_by: [],
|
||||
};
|
||||
return { review, from: e.head_oid, seen: e.seen_at ?? e.at, hash: e.disc_hash, baseRef };
|
||||
export async function carriedReviews(db: Db, cs: Cand[], stale: Set<string> = new Set()): Promise<Map<string, Carried>> {
|
||||
const out = new Map<string, Carried>();
|
||||
if (!cs.length) return out;
|
||||
const refs = cs.map((c) => ({ repo: c.repo, number: c.number }));
|
||||
const [rows, items, repos] = await db.together(() => Promise.all([
|
||||
loadReviewRows(db, refs), loadItems(db, refs, "pr"), loadRepos(db, { names: [...new Set(cs.map((c) => c.repo))] }),
|
||||
]));
|
||||
type Pick = { c: Cand; e: ReviewRow; baseRef: string | null };
|
||||
const picked: Pick[] = [];
|
||||
for (const c of cs) {
|
||||
const all = rows.get(`${c.repo}#${c.number}`) ?? [];
|
||||
const e = all.find((r) => r.head !== c.head_oid && r.model !== null);
|
||||
if (all.some((r) => r.head === c.head_oid)) continue;
|
||||
if (!e || stale.has(`${c.repo}#${c.number}@${e.head}`) || (e.verdict !== "take" && e.verdict !== "take-fix") || !e.sure) continue;
|
||||
const baseRef = e.base_ref ?? repos.get(c.repo)?.default_branch ?? null;
|
||||
const liveBase = items.get(`${c.repo}#${c.number}`)?.base_ref ?? null;
|
||||
if (baseRef && liveBase && baseRef !== liveBase) continue;
|
||||
picked.push({ c, e, baseRef });
|
||||
}
|
||||
// Exactly one commit, ours, a fix-up of the review's own fixes (not a pre-merge or carry-over fix-up).
|
||||
if (!path.complete || path.commits.length !== 1 || path.commits[0]!.kind !== "fix-up" || path.sources[0]) return null;
|
||||
const approved = await db.get(db.k.selectFrom("patch_checks").select("verdict").where("kind", "=", "fixup").where("repo", "=", c.repo).where("number", "=", c.number).where("subject", "=", e.head_oid)
|
||||
.orderBy("id", "desc").limit(1));
|
||||
if (approved?.verdict !== "approve") return null;
|
||||
const review: OpusReview = {
|
||||
ref: `${c.repo}#${c.number}`, verdict: "take", sure: true, fixes: [], risks: list<string>(e.risks), summary: e.summary,
|
||||
// A take-fix review's reason names the fixes the fix-up has since made; the carried verdict's reason is the carry itself.
|
||||
why: e.verdict === "take-fix" ? null : e.why, public: null,
|
||||
reason: `carried from ${e.head_oid.slice(0, 7)}: the only change is our checked fix-up`, conflicts: list(e.conflicts), claims: [], blocked_by: [],
|
||||
};
|
||||
return { review, from: e.head_oid, seen: e.seen_at ?? e.at, hash: e.disc_hash, baseRef };
|
||||
if (!picked.length) return out;
|
||||
const pickedRefs = picked.map((p) => ({ repo: p.c.repo, number: p.c.number }));
|
||||
const ours = ourCommitsLoader(db, pickedRefs);
|
||||
const paths = await Promise.all(picked.map((p) => ours(p.c.repo, p.c.number, p.e.head, p.c.head_oid)));
|
||||
const [texts, edges] = await db.together(() => Promise.all([
|
||||
loadReviewTexts(db, picked.map((p) => ({ repo: p.c.repo, number: p.c.number, head: p.e.head }))),
|
||||
loadPushEdges(db, pickedRefs),
|
||||
]));
|
||||
const fixups: { ref: string; subject: string }[] = [];
|
||||
picked.forEach((p, i) => {
|
||||
const path = paths[i]!;
|
||||
if (path.complete && path.commits.length === 1 && path.commits[0]!.kind === "fix-up" && !path.sources[0]) fixups.push({ ref: `${p.c.repo}#${p.c.number}`, subject: p.e.head });
|
||||
});
|
||||
const verdicts = await loadFixupVerdicts(db, fixups);
|
||||
picked.forEach((p, i) => {
|
||||
const { c, e, baseRef } = p, path = paths[i]!, key = `${c.repo}#${c.number}`;
|
||||
const t = texts.get(`${key}@${e.head}`);
|
||||
const base = { ref: key, summary: t?.summary ?? null, risks: e.risks, conflicts: e.conflicts as unknown as OpusReview["conflicts"], claims: [], blocked_by: [] as string[], public: null };
|
||||
const from = e.head, seen = e.seen_at ?? e.at, hash = e.disc_hash;
|
||||
const merge = path.complete && path.commits.length === 1 && path.commits[0]!.kind === "base merge"
|
||||
? (edges.get(key) as PushEdge[] | undefined)?.find((x) => x.kind === "conflict" && x.to === c.head_oid && x.state === "merged") : undefined;
|
||||
// Our merge of the base branch: the PR's own diff is what the review read, so an unchanged diff keeps the verdict and its fixes.
|
||||
if (merge && reviewAfterBaseMerge(merge.ownDiff ?? null) === "carry") {
|
||||
out.set(key, { review: { ...base, verdict: e.verdict, sure: true, fixes: e.fixes as OpusReview["fixes"], why: t?.why ?? null,
|
||||
reason: `carried from ${e.head.slice(0, 7)}: the only change is our merge of the base branch, and the PR's own diff is unchanged` }, from, seen, hash, baseRef });
|
||||
return;
|
||||
}
|
||||
// Exactly one commit, ours, a fix-up of the review's own fixes (not a pre-merge or carry-over fix-up).
|
||||
if (!path.complete || path.commits.length !== 1 || path.commits[0]!.kind !== "fix-up" || path.sources[0]) return;
|
||||
if (verdicts.get(`${key}@${e.head}`) !== "approve") return;
|
||||
out.set(key, { review: { ...base, verdict: "take", sure: true, fixes: [],
|
||||
// A take-fix review's reason names the fixes the fix-up has since made; the carried verdict's reason is the carry itself.
|
||||
why: e.verdict === "take-fix" ? null : t?.why ?? null, reason: `carried from ${e.head.slice(0, 7)}: the only change is our checked fix-up` }, from, seen, hash, baseRef });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** carriedReviews() for one PR. */
|
||||
export async function carriedReview(db: Db, c: Cand, stale: Set<string> = new Set()): Promise<Carried | null> {
|
||||
return (await carriedReviews(db, [c], stale)).get(`${c.repo}#${c.number}`) ?? null;
|
||||
}
|
||||
+17
-21
@@ -1,12 +1,13 @@
|
||||
// CI and merge state of PR heads: one GraphQL query per chunk of PRs, stored in pr_checks.
|
||||
import { ownerOf } from "../owners.ts";
|
||||
import { keepKnownMergeableExpr, type Querier } from "../mirror.ts";
|
||||
import { pilotExpr } 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";
|
||||
import type { Querier } from "../mirror.ts";
|
||||
import { overallAt, type Suite } from "../merge/ci-approval.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { resolvePushes } from "../data/control/index.ts";
|
||||
import { noteMergeable, recordRuns } from "../data/merge/index.ts";
|
||||
import { listItems, loadChecks, saveChecks as saveCheckRows } from "../data/mirror/index.ts";
|
||||
import { loadReviewsAt } from "../data/review/index.ts";
|
||||
|
||||
/** PRs per query: 100 check contexts each keeps a query well under GitHub's node limit. */
|
||||
export const CHECKS_PER_QUERY = 40;
|
||||
@@ -112,25 +113,20 @@ export function parseChecks(repo: string, repository: Record<string, PrNode | nu
|
||||
export async function saveChecks(db: Db, rows: PrChecks[], at = new Date().toISOString()): Promise<void> {
|
||||
// A PR read twice keeps its last reading: a multi-row upsert cannot touch one row twice.
|
||||
rows = [...new Map(rows.map((r) => [`${r.repo}#${r.number}`, r])).values()];
|
||||
if (rows.length) await db.write(async () => {
|
||||
for (const part of kx.batches(rows))
|
||||
await db.run(db.k.insertInto("pr_checks").values(part.map((r) => ({
|
||||
repo: r.repo, number: r.number, head_oid: r.head_oid, state: r.state, is_draft: r.is_draft ? 1 : 0, overall: r.overall, checks: JSON.stringify(r.checks),
|
||||
mergeable: r.mergeable, maintainer_can_modify: r.maintainer_can_modify ? 1 : 0, fetched_at: at,
|
||||
}))).onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet((eb) => ({
|
||||
...kx.excluded(["head_oid", "state", "is_draft", "overall", "checks", "maintainer_can_modify", "fetched_at"])(eb),
|
||||
mergeable: keepKnownMergeableExpr(eb, "pr_checks"),
|
||||
}))));
|
||||
});
|
||||
await saveCheckRows(db, rows.map((r) => ({
|
||||
repo: r.repo, number: r.number, head_oid: r.head_oid, state: r.state, is_draft: r.is_draft ? 1 : 0, overall: r.overall, checks: JSON.stringify(r.checks),
|
||||
mergeable: r.mergeable, maintainer_can_modify: r.maintainer_can_modify ? 1 : 0, fetched_at: at,
|
||||
})), at);
|
||||
await recordRuns(db, rows, at);
|
||||
await resolvePushes(db, rows, at);
|
||||
await noteMergeable(db, rows, at);
|
||||
await resolvePushes(db, rows.map((r) => ({ repo: r.repo, number: r.number, head_oid: r.head_oid, checks: JSON.stringify(r.checks) })), at);
|
||||
const reviews = await loadReviewsAt(db, rows.map((r) => ({ repo: r.repo, number: r.number, head: r.head_oid })));
|
||||
const taken = new Set([...reviews].filter(([, r]) => r.verdict === "take" || r.verdict === "take-fix").map(([k]) => k));
|
||||
await noteMergeable(db, rows, at, taken);
|
||||
}
|
||||
|
||||
/** Fetches and stores the checks of the given PRs (all open PRs of the repo when none are given). */
|
||||
export async function refreshChecks(db: Db, client: Querier, repo: string, numbers?: number[], log: (line: string) => void = () => {}): Promise<PrChecks[]> {
|
||||
const list = numbers ?? (await db.all(db.k.selectFrom("items as i").select("i.number").where("i.repo", "=", repo).where("i.kind", "=", "pr").where("i.state", "=", "OPEN")
|
||||
.where((eb) => pilotExpr(db, eb, "i")).orderBy("i.number"))).map((r) => r.number);
|
||||
const list = numbers ?? (await listItems(db, { repos: [repo], kind: "pr", states: ["OPEN"], inScope: true }, "ref")).map((r) => r.number);
|
||||
const all: PrChecks[] = [];
|
||||
// Rows are stored once BATCH_ROWS are read (and at the end), so the statements per PR stay a fraction of one.
|
||||
let unsaved: PrChecks[] = [];
|
||||
@@ -156,6 +152,6 @@ export async function refreshChecks(db: Db, client: Querier, repo: string, numbe
|
||||
|
||||
/** The stored checks of a PR; `overall` reads "pending" while workflow runs wait for approval at that head (see overallAt). */
|
||||
export async function checksOf(db: Db, repo: string, number: number): Promise<{ head_oid: string; overall: Overall; mergeable: string | null; maintainer_can_modify: number | null } | undefined> {
|
||||
const r = await db.get(db.k.selectFrom("pr_checks").select(["head_oid", "overall", "mergeable", "maintainer_can_modify"]).$narrowType<{ overall: Overall }>().where("repo", "=", repo).where("number", "=", number));
|
||||
return r && { ...r, overall: await overallAt(db, repo, number, r.head_oid, r.overall) as Overall };
|
||||
const r = (await loadChecks(db, [{ repo, number }])).get(`${repo}#${number}`);
|
||||
return r && { head_oid: r.head_oid, overall: await overallAt(db, repo, number, r.head_oid, r.overall) as Overall, mergeable: r.mergeable, maintainer_can_modify: r.maintainer_can_modify };
|
||||
}
|
||||
+16
-31
@@ -13,7 +13,9 @@ import { mayBeRun, mergeSteps, workflowSteps, type WorkflowSteps } from "../core
|
||||
import { lockfileNeedsWhole } from "../core/lockfiles.ts";
|
||||
import { sensitiveReasons } from "../core/sensitive.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { setting, writeSetting } from "../data/control/index.ts";
|
||||
import { loadAllDiffFacts, loadDiffFacts, markDiffRead, removeDiffFacts, saveDiffFacts, setDiffFactsIf, type DiffFactsRow } from "../data/mirror/index.ts";
|
||||
import { loadLatestReviews } from "../data/review/index.ts";
|
||||
|
||||
// gh picks its account from the working directory, so it runs in this repo.
|
||||
const REPO_DIR = fileURLToPath(new URL("../..", import.meta.url));
|
||||
@@ -191,7 +193,7 @@ export async function cachedDiff(db: Db, repo: string, number: number, head: str
|
||||
const text = readFileSync(file, "utf8");
|
||||
const extras = cachedDiffExtras(repo, number, head);
|
||||
// A diff cached before its facts were stored gets them on its next read.
|
||||
if (!await db.get(db.k.selectFrom("diff_facts").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", number).where("head_oid", "=", head))) await recordDiffFacts(db, repo, number, head);
|
||||
if (!(await loadDiffFacts(db, [{ ref: `${repo}#${number}`, head }])).size) await recordDiffFacts(db, repo, number, head);
|
||||
// An entry whose extras the rule still waits for is read again only by the re-read (see `rereadDiff`).
|
||||
if (!opts.reread) return { ok: true, text, ...(stored !== undefined ? { base: stored } : {}), ...(extras ? { extras } : {}) };
|
||||
}
|
||||
@@ -268,7 +270,7 @@ export async function noteReread(db: Db, repo: string, number: number, head: str
|
||||
writeFileSync(f, JSON.stringify({ count: diffRereads(repo, number, head).count + 1, at }));
|
||||
// A failed read with no diff cached here (a new runner pod) keeps the stored facts; the time still spaces the next try.
|
||||
if (diffFactsOfCache(repo, number, head)) await recordDiffFacts(db, repo, number, head);
|
||||
else await db.run(db.k.updateTable("diff_facts").set({ last_read: at }).where("repo", "=", repo).where("number", "=", number).where("head_oid", "=", head));
|
||||
else await markDiffRead(db, [{ ref: `${repo}#${number}`, head }], at);
|
||||
}
|
||||
|
||||
/** The re-reads recorded for a diff and the time of the last one. */
|
||||
@@ -305,7 +307,7 @@ export async function dropCachedDiff(db: Db, repo: string, number: number, head:
|
||||
rmSync(`${file}.base`, { force: true });
|
||||
rmSync(`${file}.files.json`, { force: true });
|
||||
rmSync(`${file}.reread`, { force: true });
|
||||
await db.run(db.k.deleteFrom("diff_facts").where("repo", "=", repo).where("number", "=", number).where("head_oid", "=", head));
|
||||
await removeDiffFacts(db, [{ ref: `${repo}#${number}`, head }]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -328,13 +330,11 @@ export function diffFactsOfCache(repo: string, number: number, head: string): Di
|
||||
};
|
||||
}
|
||||
|
||||
const rowOf = (repo: string, number: number, head: string, f: DiffFacts): DiffFactsRow =>
|
||||
({ repo, number, head_oid: head, reasons: JSON.stringify(f.reasons), lines: f.lines, pending: f.pending ? 1 : 0, last_read: f.lastRead });
|
||||
|
||||
async function writeFacts(db: Db, repo: string, number: number, head: string, f: DiffFacts): Promise<void> {
|
||||
await db.run(db.k.insertInto("diff_facts").values({ repo, number, head_oid: head, reasons: JSON.stringify(f.reasons), lines: f.lines, pending: f.pending ? 1 : 0, last_read: f.lastRead })
|
||||
.onConflict((oc) => oc.columns(["repo", "number", "head_oid"]).doUpdateSet(kx.excluded(["reasons", "lines", "pending", "last_read"]))
|
||||
.where((eb) => eb.or([
|
||||
eb("diff_facts.reasons", "is distinct from", eb.ref("excluded.reasons")), eb("diff_facts.lines", "is distinct from", eb.ref("excluded.lines")),
|
||||
eb("diff_facts.pending", "is distinct from", eb.ref("excluded.pending")), eb("diff_facts.last_read", "is distinct from", eb.ref("excluded.last_read")),
|
||||
]))));
|
||||
await saveDiffFacts(db, [rowOf(repo, number, head, f)], "upsert-if-changed");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -365,7 +365,7 @@ export function diffFactsRules(): string {
|
||||
/** Rows per write transaction of `buildDiffFacts`: the writer lock is held for one batch, never for the whole rebuild. */
|
||||
export const DIFF_FACTS_BATCH = 100;
|
||||
|
||||
type StoredFacts = { reasons: string | null; lines: number | null; pending: number | null; last_read: number | null };
|
||||
type StoredFacts = DiffFactsRow;
|
||||
|
||||
/**
|
||||
* Computes the stored facts again when they were computed by other rules than this code's (or never): the facts of every
|
||||
@@ -379,15 +379,12 @@ type StoredFacts = { reasons: string | null; lines: number | null; pending: numb
|
||||
*/
|
||||
export async function buildDiffFacts(db: Db, opts: { batch?: number } = {}): Promise<{ computed: number; pending: number } | null> {
|
||||
const rules = diffFactsRules();
|
||||
if ((await db.get(db.k.selectFrom("settings").select("value").where("key", "=", DIFF_FACTS_KEY)))?.value === rules) return null;
|
||||
if (await setting(db, DIFF_FACTS_KEY) === rules) return null;
|
||||
const stored = new Map<string, { repo: string; number: number; head: string; row: StoredFacts | null }>();
|
||||
for (const r of await db.all(db.k.selectFrom("diff_facts").select(["repo", "number", "head_oid", "reasons", "lines", "pending", "last_read"]))) {
|
||||
for (const r of (await loadAllDiffFacts(db)).values()) {
|
||||
stored.set(`${r.repo}#${r.number}@${r.head_oid}`, { repo: r.repo, number: r.number, head: r.head_oid, row: r });
|
||||
}
|
||||
const reviewed = await db.all(db.k.selectFrom("opus_reviews as r").select(["r.repo", "r.number", "r.head_oid"]).where("r.verdict", "is not", null)
|
||||
.where((eb) => eb(kx.rowid("opus_reviews", "r"), "=", eb.selectFrom("opus_reviews as x").select(kx.rowid("opus_reviews", "x").as("rid"))
|
||||
.whereRef("x.repo", "=", "r.repo").whereRef("x.number", "=", "r.number").where("x.verdict", "is not", null)
|
||||
.orderBy("x.at", "desc").orderBy(kx.rowid("opus_reviews", "x"), "desc").limit(1))));
|
||||
const reviewed = [...(await loadLatestReviews(db, { mode: "full" })).values()].map((r) => ({ repo: r.repo, number: r.number, head_oid: r.head }));
|
||||
for (const r of reviewed) {
|
||||
const key = `${r.repo}#${r.number}@${r.head_oid}`;
|
||||
if (!stored.has(key)) stored.set(key, { repo: r.repo, number: r.number, head: r.head_oid, row: null });
|
||||
@@ -404,9 +401,9 @@ export async function buildDiffFacts(db: Db, opts: { batch?: number } = {}): Pro
|
||||
}
|
||||
const size = Math.max(1, opts.batch ?? DIFF_FACTS_BATCH);
|
||||
for (let i = 0; i < changes.length; i += size) {
|
||||
await db.write(async () => { for (const c of changes.slice(i, i + size)) await writeFactsIf(db, c.repo, c.number, c.head, c.was, c.to); });
|
||||
await setDiffFactsIf(db, changes.slice(i, i + size).map((c) => ({ key: { ref: `${c.repo}#${c.number}`, head: c.head }, was: c.was, to: rowOf(c.repo, c.number, c.head, c.to) })));
|
||||
}
|
||||
await db.run(db.k.insertInto("settings").values({ key: DIFF_FACTS_KEY, value: rules }).onConflict((oc) => oc.column("key").doUpdateSet(kx.excluded(["value"]))));
|
||||
await writeSetting(db, DIFF_FACTS_KEY, rules);
|
||||
return { computed, pending };
|
||||
}
|
||||
|
||||
@@ -414,18 +411,6 @@ const parseReasons = (s: string | null): string[] => {
|
||||
try { const v = JSON.parse(s ?? "[]") as unknown; return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; } catch { return []; }
|
||||
};
|
||||
|
||||
/** Writes the facts of a head only while its row still holds `was` (absent when null): a compare-and-write. */
|
||||
async function writeFactsIf(db: Db, repo: string, number: number, head: string, was: StoredFacts | null, f: DiffFacts): Promise<void> {
|
||||
const values = { reasons: JSON.stringify(f.reasons), lines: f.lines, pending: f.pending ? 1 : 0, last_read: f.lastRead };
|
||||
if (!was) {
|
||||
await db.run(db.k.insertInto("diff_facts").values({ repo, number, head_oid: head, ...values }).onConflict((oc) => oc.columns(["repo", "number", "head_oid"]).doNothing()));
|
||||
return;
|
||||
}
|
||||
await db.run(db.k.updateTable("diff_facts").set(values).where("repo", "=", repo).where("number", "=", number).where("head_oid", "=", head)
|
||||
.where("reasons", "is not distinct from", was.reasons).where("lines", "is not distinct from", was.lines)
|
||||
.where("pending", "is not distinct from", was.pending).where("last_read", "is not distinct from", was.last_read));
|
||||
}
|
||||
|
||||
/** The base branch a cached diff was computed against; null when unknown. */
|
||||
export function cachedDiffBase(repo: string, number: number, head: string): string | null {
|
||||
const f = join(diffCacheDir(), repo, `${number}-${head}.diff.base`);
|
||||
|
||||
+54
-181
@@ -3,9 +3,8 @@
|
||||
// Also decides when a PR's review is stale because someone else wrote on it after them.
|
||||
// All text here is written by outsiders and is passed on as untrusted data.
|
||||
import { createHash } from "node:crypto";
|
||||
import { audit } from "../dash/audit.ts";
|
||||
import { isBotCommand, isBotLogin } from "./bots.ts";
|
||||
import { BLOCKED_EXPIRES_MS, blockersLoader, storedBlockedBy } from "./blockers.ts";
|
||||
import { BLOCKED_EXPIRES_MS, activeFrom, loadBlockerReads } from "./blockers.ts";
|
||||
import type { Querier } from "../mirror.ts";
|
||||
import { FORMAL_REVIEWS, recordGate, recordGateFailure, type ReviewFact } from "../merge/changes-requested.ts";
|
||||
import { ENTRY_LIMIT, TOTAL_LIMIT, type DiscussionEntry } from "./parse.ts";
|
||||
@@ -13,18 +12,16 @@ import { ownerOf } from "../owners.ts";
|
||||
import type { Exec } from "../fixup/git.ts";
|
||||
import { pipelineMe, setPipelineLogin } from "../github/pipeline-account.ts";
|
||||
import { allOwnLogins, ownLogins } from "../github/identity.ts";
|
||||
import { setting } from "../settings-read.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { loginsWithRole } from "../data/access/index.ts";
|
||||
import { setting } from "../data/control/index.ts";
|
||||
import { loadItems, loadRepos, openItemKeys } from "../data/mirror/index.ts";
|
||||
import { loadDiscussionEntries, loadPosts, loadReviewFacts, loadReviewsAt, markStale, type ReviewFacts } from "../data/review/index.ts";
|
||||
|
||||
/** Setting that holds the pipeline account's login (also read by src/merge/queue.ts). */
|
||||
const LOGIN_KEY = "pipeline_login";
|
||||
/** Prefix of the setting that marks a PR's reviews stale on an operator's request; the value is the time. */
|
||||
const STALE_KEY = "review_stale:";
|
||||
|
||||
/** Discussion-triggered re-reviews of one PR per UTC day; a head change or an operator request is not counted. */
|
||||
export const MAX_RERUNS_PER_DAY = 3;
|
||||
const RERUN_KEY = "review_rerun:";
|
||||
|
||||
/** Sections whose text is tool output or instructions for other tools, not a claim about the change. */
|
||||
const NOISE_SUMMARY = /prompt for|analysis chain|scripts? executed|fingerprint|committable|additional context|learnings|ai agents|review info|walkthrough|sequence diagram|related pull requests|suggested labels/i;
|
||||
@@ -96,51 +93,18 @@ export function discussionHash(xs: { id: string; body: string | null }[]): strin
|
||||
/** What a review read: when, and a hash of the counted entries. */
|
||||
export type Snapshot = { seen: string; hash: string | null };
|
||||
|
||||
/** The logins notOurs excludes. With no login known, '' stands in, so authorless rows stay out as before. */
|
||||
const ownList = (own: Set<string>): string[] => (own.size ? [...own] : [""]);
|
||||
|
||||
/** Condition for "written by someone other than us" (`c` is the comments table alias): not our logins, not our review post, and not a comment the pipeline wrote (its audited text) under an operator's own login. */
|
||||
const notOurs = (db: Db, eb: kx.Eb, own: Set<string>) => eb.and([
|
||||
kx.inList(db, eb.fn.coalesce("c.author", eb.val("")), ownList(own), "text", true),
|
||||
eb("c.id", "not in", eb.selectFrom("review_posts as rp").select("rp.review_id").whereRef("rp.repo", "=", "c.repo").whereRef("rp.number", "=", "c.number")),
|
||||
eb.not(eb.exists(eb.selectFrom("main.audit as au").select(eb.lit(1).as("one")).where((a) => a.and([
|
||||
a("au.target", "=", a(a(a.ref("c.repo"), "||", a.val("#")), "||", kx.exprOf(a, "c.number"))),
|
||||
a("c.body", "is not", null),
|
||||
a(kx.jsonText(db, "au.details", "$.text"), "=", a.ref("c.body")),
|
||||
])))),
|
||||
]);
|
||||
|
||||
type MirrorRow = { id: string; kind: string | null; author: string | null; created_at: string | null; body: string | null; review_state: string | null; counted: number | null; maint: number };
|
||||
const mirrorRows = async (db: Db, repo: string, number: number): Promise<MirrorRow[]> => {
|
||||
const own = await ownLogins(db, repo);
|
||||
return await db.all(db.k.selectFrom("comments as c")
|
||||
.select((eb) => ["c.id", "c.kind", "c.author", "c.created_at", "c.body", "c.review_state", "c.counted",
|
||||
eb.case().when(eb.and([
|
||||
eb.or([
|
||||
eb("c.author_association", "in", MAINTAINER_ASSOCIATIONS),
|
||||
eb.exists(eb.selectFrom("main.access as a").select(eb.lit(1).as("one"))
|
||||
.where((e) => e(e.fn<string>("lower", [e.ref("a.login")]), "=", e.fn<string>("lower", [e.ref("c.author")])))
|
||||
.where("a.role", "in", ["operator", "maintainer"])),
|
||||
]),
|
||||
eb(eb.fn.coalesce("c.author", eb.val("")), "<>", eb.fn.coalesce(eb.selectFrom("items as i").select("i.author").whereRef("i.repo", "=", "c.repo").whereRef("i.number", "=", "c.number"), eb.val(""))),
|
||||
])).then(1).else(0).end().as("maint")])
|
||||
.where("c.repo", "=", repo).where("c.number", "=", number)
|
||||
.where((eb) => notOurs(db, eb, own))
|
||||
.orderBy("c.created_at", (o) => o.asc().nullsFirst()).orderBy(kx.rowid("comments", "c")));
|
||||
};
|
||||
|
||||
/** Comments and review bodies from the mirror: the fallback for a call that has no GitHub connection. */
|
||||
async function mirrorDiscussion(db: Db, repo: string, number: number): Promise<{ entries: DiscussionEntry[]; hash: string; maint: Set<number> }> {
|
||||
const rows = await mirrorRows(db, repo, number);
|
||||
const rows = (await loadDiscussionEntries(db, [{ repo, number }])).get(`${repo}#${number}`) ?? [];
|
||||
const entries: DiscussionEntry[] = [];
|
||||
const maint = new Set<number>();
|
||||
for (const r of rows) {
|
||||
const body = cleanBody(r.body);
|
||||
if (!body) continue;
|
||||
if (r.maint === 1) maint.add(entries.length);
|
||||
if (r.maint) maint.add(entries.length);
|
||||
entries.push({ kind: r.kind === "review" ? "review" : "comment", author: r.author, at: r.created_at, ...(r.kind === "review" ? { state: r.review_state } : {}), body: clip(body, ENTRY_LIMIT) });
|
||||
}
|
||||
return { entries, hash: discussionHash(rows.filter((r) => r.counted === 1)), maint };
|
||||
return { entries, hash: discussionHash(rows.filter((r) => r.counted)), maint };
|
||||
}
|
||||
|
||||
export const DISCUSSION_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
||||
@@ -179,13 +143,13 @@ export async function liveDiscussion(q: Querier, db: Db, repo: string, number: n
|
||||
const pr = res?.repository?.pullRequest;
|
||||
if (!pr) throw new Error(`${repo}#${number} not found on GitHub`);
|
||||
const own = await ownLogins(db, repo);
|
||||
const posted = new Set((await db.all(db.k.selectFrom("review_posts").select("review_id").where("repo", "=", repo).where("number", "=", number))).map((r) => r.review_id));
|
||||
const posted = new Set([...(await loadPosts(db, [{ repo, number }])).values()].map((r) => r.review_id));
|
||||
const mine = (a: Author | undefined, id?: string) => (!!a?.login && own.has(a.login)) || (!!id && posted.has(id));
|
||||
const prAuthor: string | null = pr.author?.login ?? null;
|
||||
const entries: DiscussionEntry[] = [];
|
||||
const counted: { id: string; body: string | null }[] = [];
|
||||
let newest: string | null = null, newestMaint: string | null = null;
|
||||
const dash = new Set((await db.all(db.k.selectFrom("main.access").select("login").where("role", "in", ["operator", "maintainer"]))).map((r) => r.login.toLowerCase()));
|
||||
const dash = new Set((await loginsWithRole(db, ["operator", "maintainer"])).map((r) => r.toLowerCase()));
|
||||
const isMaint = (login: string | null | undefined, assoc: string | undefined) => MAINTAINER_ASSOCIATIONS.includes(assoc ?? "") || (!!login && dash.has(login.toLowerCase()));
|
||||
// The PR author's own words never rank as a maintainer's, whatever their association.
|
||||
const otherMaint = (login: string | null | undefined, assoc: string | undefined) => isMaint(login, assoc) && login !== prAuthor;
|
||||
@@ -279,76 +243,20 @@ export async function discussionOf(db: Db, repo: string, number: number, live?:
|
||||
return fit(m.entries, m.maint, m.maint, { seen, hash: m.hash });
|
||||
}
|
||||
|
||||
const staleKey = (repo: string, number: number) => `${STALE_KEY}${repo}#${number}`;
|
||||
export type DiscussionState = Map<string, { newest: string; /** The hash of the counted entries. */ hash: () => Promise<string>; /** Newest counted entry by a maintainer (OWNER, MEMBER, COLLABORATOR or a dashboard user); "" when none. */ maint: string }>;
|
||||
|
||||
export type DiscussionState = Map<string, { newest: string; /** The hash of the counted entries, read on first use. */ hash: () => Promise<string>; /** Newest counted entry by a maintainer (OWNER, MEMBER, COLLABORATOR or a dashboard user); "" when none. */ maint: string }>;
|
||||
export const discussionStateOf = (facts: ReviewFacts): DiscussionState => new Map([...facts.discussion].map(([ref, d]) => [ref, { newest: d.newest, maint: d.maint, hash: async () => discussionHash(d.counted ?? []) }]));
|
||||
|
||||
const MAINTAINER_ASSOCIATIONS = ["OWNER", "MEMBER", "COLLABORATOR"];
|
||||
/** The open PRs of `repo` (every repo without one) as a key source. */
|
||||
const prKeys = (repo?: string) => openItemKeys({ ...(repo !== undefined ? { repos: [repo] } : {}), kind: "pr" });
|
||||
|
||||
// The queue recomputes on every `steps` change, which comment writes don't move. Comments bump `items`, our posts
|
||||
// bump `reviews`, and the pipeline login is part of the key, so an unchanged signature means unchanged input.
|
||||
const stateMemo = new WeakMap<Db, Map<string, { sig: string; state: DiscussionState }>>();
|
||||
|
||||
/** Newest counted comment or review by someone else, and the hash of those, per PR "repo#n" from the mirror (issues are left out). Callers must not modify the result. */
|
||||
/** Newest counted comment or review by someone else, and the hash of those, per open PR "repo#n" from the mirror. */
|
||||
export async function discussionState(db: Db, repo?: string): Promise<DiscussionState> {
|
||||
const seqs = await db.all(db.k.selectFrom("change_seq").select(["topic", "seq"]).where("topic", "in", ["items", "reviews"]).orderBy("topic"));
|
||||
const sig = JSON.stringify([seqs, [...await allOwnLogins(db)]]);
|
||||
const memo = stateMemo.get(db) ?? new Map<string, { sig: string; state: DiscussionState }>();
|
||||
stateMemo.set(db, memo);
|
||||
const key = repo ?? "";
|
||||
const hit = memo.get(key);
|
||||
if (hit && hit.sig === sig && seqs.length === 2) return hit.state;
|
||||
const state = await computeDiscussionState(db, repo);
|
||||
memo.set(key, { sig, state });
|
||||
return state;
|
||||
return discussionStateOf(await loadReviewFacts(db, prKeys(repo), { now: Date.now() }));
|
||||
}
|
||||
|
||||
async function computeDiscussionState(db: Db, repo?: string): Promise<DiscussionState> {
|
||||
const own = repo ? await ownLogins(db, repo) : await allOwnLogins(db);
|
||||
const rows = await db.all(db.k.selectFrom("comments as c")
|
||||
.select((eb) => ["c.repo", "c.number",
|
||||
eb.fn.coalesce(eb.fn.max<string | null>("c.created_at"), eb.val("")).as("newest"),
|
||||
eb.fn.coalesce(eb.fn.max<string | null>(eb.case().when(eb.or([
|
||||
eb("c.author_association", "in", MAINTAINER_ASSOCIATIONS),
|
||||
eb.exists(eb.selectFrom("main.access as a").select(eb.lit(1).as("one")).whereRef("a.login", "=", "c.author").where("a.role", "in", ["operator", "maintainer"])),
|
||||
])).then(eb.ref("c.created_at")).end()), eb.val("")).as("maint")])
|
||||
.$if(repo !== undefined, (q) => q.where("c.repo", "=", repo!))
|
||||
.where("c.counted", "=", 1)
|
||||
.where((eb) => notOurs(db, eb, own))
|
||||
.where((eb) => eb.not(eb.exists(eb.selectFrom("main.items as i").select(eb.lit(1).as("one")).whereRef("i.repo", "=", "c.repo").whereRef("i.number", "=", "c.number").where("i.kind", "=", "issue"))))
|
||||
.groupBy(["c.repo", "c.number"]));
|
||||
// The hash needs the comment text; callers ask for it only after a newer entry than a review's snapshot, so it is read on first use (primeHashes reads many in one query).
|
||||
const known = new Map<string, string>();
|
||||
const texts = async (keys: { repo: string; number: number }[]): Promise<Map<string, { id: string; body: string | null }[]>> => {
|
||||
const by = new Map<string, { id: string; body: string | null }[]>(keys.map((k) => [`${k.repo}#${k.number}`, []]));
|
||||
for (const c of await db.all(db.k.selectFrom("comments as c")
|
||||
.innerJoin(kx.refPairs(db, keys.map((k) => [k.repo, k.number] as const), "j"), (j) => j.onRef("c.repo", "=", "j.repo").onRef("c.number", "=", "j.number"))
|
||||
.select(["c.repo", "c.number", "c.id", "c.body"])
|
||||
.where("c.counted", "=", 1).where((eb) => notOurs(db, eb, own))))
|
||||
by.get(`${c.repo}#${c.number}`)?.push(c);
|
||||
return by;
|
||||
};
|
||||
const prime = async (keys: { repo: string; number: number }[]) => {
|
||||
for (const [k, v] of await texts(keys)) known.set(k, discussionHash(v));
|
||||
};
|
||||
const rowOf = new Map(rows.map((r) => [`${r.repo}#${r.number}`, r]));
|
||||
const state: DiscussionState = new Map(rows.map((r) => {
|
||||
const k = `${r.repo}#${r.number}`;
|
||||
return [k, { newest: r.newest, maint: r.maint, hash: async () => { if (!known.has(k)) await prime([r]); return known.get(k)!; } }];
|
||||
}));
|
||||
primers.set(state, async (refs) => {
|
||||
const keys = [...new Set(refs)].filter((k) => !known.has(k)).flatMap((k) => rowOf.get(k) ?? []);
|
||||
if (keys.length) await prime(keys);
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
const primers = new WeakMap<DiscussionState, (refs: Iterable<string>) => Promise<void>>();
|
||||
|
||||
/** Reads the hashes of the entries of `refs` in one query; an entry not primed reads its own on first use. */
|
||||
export async function primeHashes(state: DiscussionState, refs: Iterable<string>): Promise<void> {
|
||||
await primers.get(state)?.(refs);
|
||||
}
|
||||
/** Reads the hashes of the entries of `refs`: the loaded state carries them already. */
|
||||
export async function primeHashes(_state: DiscussionState, _refs: Iterable<string>): Promise<void> {}
|
||||
|
||||
/** Whether the newest maintainer entry is newer than `seen`: maintainerSince() then needs the hash. */
|
||||
const maintNewer = (state: { maint: string } | undefined, seen: string): boolean => !!state && !!state.maint && sec(state.maint) > sec(seen);
|
||||
@@ -372,93 +280,61 @@ export function changedSince(state: { newest: string; hash: string } | undefined
|
||||
return !!state && sec(state.newest) > sec(seen) && state.hash !== hash;
|
||||
}
|
||||
|
||||
const MAINTAINER_ASSOCIATIONS = ["OWNER", "MEMBER", "COLLABORATOR"];
|
||||
|
||||
const day = (nowMs: number) => new Date(nowMs).toISOString().slice(0, 10);
|
||||
export const nextUtcMidnight = (ms: number): number => { const d = new Date(ms); return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1); };
|
||||
const rerunKey = (repo: string, number: number, nowMs: number = Date.now()) => `${RERUN_KEY}${repo}#${number}:${day(nowMs)}`;
|
||||
/** Today's rerun counters of every PR in one read, by setting key. */
|
||||
const rerunsToday = async (db: Db, nowMs: number): Promise<Map<string, string>> =>
|
||||
new Map((await db.all(db.k.selectFrom("main.settings").select(["key", "value"]).where((eb) => kx.like(db, "key", eb.val(`${kx.likeEscape(RERUN_KEY)}%:${day(nowMs)}`), "\\")))).flatMap((m) => m.value === null ? [] : [[m.key, m.value] as const]));
|
||||
|
||||
/** Whether an operator request or the merge-time discussion check marked the PR stale after `since` (such re-reviews are not counted). */
|
||||
export async function markedStaleSince(db: Db, repo: string, number: number, since: string): Promise<boolean> {
|
||||
const v = await setting(db, staleKey(repo, number));
|
||||
return !!v && v > since;
|
||||
const m = (await loadReviewFacts(db, [{ repo, number }], { now: Date.now() })).marks.get(`${repo}#${number}`);
|
||||
return !!m?.staleAt && m.staleAt > since;
|
||||
}
|
||||
|
||||
/** markedStaleSince() for every PR, with the marks read in one query. */
|
||||
export async function staleMarksSince(db: Db): Promise<(repo: string, number: number, since: string) => boolean> {
|
||||
const marks = new Map((await db.all(db.k.selectFrom("main.settings").select(["key", "value"]).where((eb) => kx.like(db, "key", eb.val(`${STALE_KEY}%`))))).map((m) => [m.key, m.value]));
|
||||
return (repo, number, since) => { const v = marks.get(staleKey(repo, number)); return !!v && v > since; };
|
||||
}
|
||||
/** markedStaleSince() for the marks of a loaded set of PRs. */
|
||||
export const staleMarksOf = (facts: ReviewFacts): ((repo: string, number: number, since: string) => boolean) =>
|
||||
(repo, number, since) => { const v = facts.marks.get(`${repo}#${number}`)?.staleAt; return !!v && v > since; };
|
||||
|
||||
/** Counts a same-head re-review against the PR's daily cap and forgets earlier days. */
|
||||
export async function countRerun(db: Db, repo: string, number: number): Promise<void> {
|
||||
await db.run(db.k.deleteFrom("main.settings").where((eb) => kx.like(db, "key", eb.val(`${RERUN_KEY}${repo}#${number}:%`))).where("key", "<>", rerunKey(repo, number)));
|
||||
await db.run(db.k.insertInto("main.settings").values({ key: rerunKey(repo, number), value: "1" })
|
||||
.onConflict((oc) => oc.column("key").doUpdateSet((eb) => ({ value: eb.cast<string>(eb(eb.cast<number>("main.settings.value", "bigint"), "+", eb.lit(1)), "text") }))));
|
||||
}
|
||||
|
||||
type ReviewedRow = { repo: string; number: number; head_oid: string; at: string; seen_at: string | null; disc_hash: string | null; blocked_by: string | null; rebased: number | null };
|
||||
|
||||
// A pass calls staleReviews() several times; the rows change only with the `items`, `reviews` and `repos` topics.
|
||||
const reviewedMemo = new WeakMap<Db, Map<string, { sig: string; rows: ReviewedRow[] }>>();
|
||||
|
||||
async function reviewedRows(db: Db, repo?: string): Promise<ReviewedRow[]> {
|
||||
const seqs = await db.all(db.k.selectFrom("change_seq").select(["topic", "seq"]).where("topic", "in", ["items", "reviews", "repos"]).orderBy("topic"));
|
||||
const sig = JSON.stringify(seqs);
|
||||
const memo = reviewedMemo.get(db) ?? new Map<string, { sig: string; rows: ReviewedRow[] }>();
|
||||
reviewedMemo.set(db, memo);
|
||||
const hit = memo.get(repo ?? "");
|
||||
if (hit && hit.sig === sig && seqs.length === 3) return hit.rows;
|
||||
const rows = await db.all(db.k.selectFrom("opus_reviews as r")
|
||||
.leftJoin("items as i", (j) => j.onRef("i.repo", "=", "r.repo").onRef("i.number", "=", "r.number"))
|
||||
.leftJoin("repos as p", "p.name", "r.repo")
|
||||
.select((eb) => ["r.repo", "r.number", "r.head_oid", "r.at", "r.seen_at", "r.disc_hash", "r.blocked_by",
|
||||
eb.case().when(eb.and([
|
||||
eb("i.base_ref", "is not", null),
|
||||
eb(eb.fn.coalesce("r.base_ref", "p.default_branch"), "is not", null),
|
||||
eb("i.base_ref", "<>", eb.fn.coalesce("r.base_ref", "p.default_branch")),
|
||||
])).then(1).else(0).end().as("rebased")])
|
||||
.where("r.verdict", "is not", null)
|
||||
.$if(repo !== undefined, (q) => q.where("r.repo", "=", repo!)));
|
||||
memo.set(repo ?? "", { sig, rows });
|
||||
return rows;
|
||||
}
|
||||
/** The daily cap of discussion- and base-triggered re-reviews counts today's counter of the PR. */
|
||||
const cappedToday = (facts: ReviewFacts, ref: string, now: number): boolean => {
|
||||
const m = facts.marks.get(ref);
|
||||
return !!m && m.rerunDay === day(now) && m.rerunCount >= MAX_RERUNS_PER_DAY;
|
||||
};
|
||||
|
||||
/**
|
||||
* PRs, as "repo#n@head", whose Opus review read the discussion before a counted comment or review that it
|
||||
* PRs, as "repo#n@head", whose latest Opus review read the discussion before a counted comment or review that it
|
||||
* did not read, that an operator marked stale, or whose diff was read against another base branch than the PR has now
|
||||
* (a review that recorded none counts as read against the default branch). With `respectCap`, PRs that already had
|
||||
* MAX_RERUNS_PER_DAY discussion- or base-triggered re-reviews today are left out (an operator mark is never capped).
|
||||
* `now` is the time of the decision (default: the clock); `refresh` is told, per "repo#number", when the answer changes with the clock
|
||||
* alone (a blocker list expiring, the daily cap ending at UTC midnight).
|
||||
* alone (a blocker list expiring, the daily cap ending at UTC midnight). Open PRs only.
|
||||
*/
|
||||
export async function staleReviews(db: Db, repo?: string, respectCap = false, opts: { now?: number; refresh?: (ref: string, at: number) => void } = {}): Promise<Set<string>> {
|
||||
const now = opts.now ?? Date.now();
|
||||
const rows = await reviewedRows(db, repo);
|
||||
const state = await discussionState(db, repo);
|
||||
await primeHashes(state, rows.filter((r) => maintNewer(state.get(`${r.repo}#${r.number}`), r.seen_at ?? r.at)).map((r) => `${r.repo}#${r.number}`));
|
||||
const marks = new Map((await db.all(db.k.selectFrom("main.settings").select(["key", "value"]).where((eb) => kx.like(db, "key", eb.val(`${STALE_KEY}%`))))).map((m) => [m.key.slice(STALE_KEY.length), m.value]));
|
||||
const keys = prKeys(repo);
|
||||
const [facts, items, repos] = await db.together(() => Promise.all([
|
||||
loadReviewFacts(db, keys, { now }), loadItems(db, keys, "pr"), loadRepos(db, repo !== undefined ? { names: [repo] } : { all: true }),
|
||||
]));
|
||||
const state = discussionStateOf(facts);
|
||||
const reads = await loadBlockerReads(db, [...facts.latest.values()].flatMap((r) => r.blocked_by));
|
||||
const marked = staleMarksOf(facts);
|
||||
const out = new Set<string>();
|
||||
let todays: Map<string, string> | undefined;
|
||||
const capped = async (r: { repo: string; number: number }) => {
|
||||
todays ??= await rerunsToday(db, now);
|
||||
return Number(todays.get(rerunKey(r.repo, r.number, now)) ?? 0) >= MAX_RERUNS_PER_DAY;
|
||||
};
|
||||
let loaded: ReturnType<typeof blockersLoader> | undefined;
|
||||
const blockers = () => (loaded ??= blockersLoader(db));
|
||||
for (const r of rows) {
|
||||
const ref = `${r.repo}#${r.number}`;
|
||||
const marked = (marks.get(ref) ?? "") > r.at;
|
||||
for (const [ref, r] of facts.latest) {
|
||||
const it = items.get(ref);
|
||||
if (!it) continue;
|
||||
const reviewedBase = r.base_ref ?? repos.get(r.repo)?.default_branch ?? null;
|
||||
const rebased = !!it.base_ref && !!reviewedBase && it.base_ref !== reviewedBase;
|
||||
const isMarked = marked(r.repo, r.number, r.at);
|
||||
// On a head that has a review, only a maintainer's words (or an operator's request) make it stale: the PR author's comments feed the next review but do not start one.
|
||||
const talked = await maintainerSince(state.get(ref), r.seen_at ?? r.at, r.disc_hash);
|
||||
// A hold that waited for other items is reviewed once when none is open any more.
|
||||
const blocked = !!r.blocked_by && storedBlockedBy(r.blocked_by).length > 0 ? await blockers().active(ref, r.blocked_by, r.at, now) : null;
|
||||
const blocked = r.blocked_by.length > 0 ? activeFrom(reads, ref, r.blocked_by, r.at, now) : null;
|
||||
const unblocked = blocked !== null && blocked.length === 0;
|
||||
if (blocked?.length) opts.refresh?.(ref, Date.parse(r.at) + BLOCKED_EXPIRES_MS + 1);
|
||||
if (!marked && !unblocked && (talked || r.rebased === 1) && respectCap && await capped(r)) opts.refresh?.(ref, nextUtcMidnight(now));
|
||||
if (!marked && !unblocked && !((talked || r.rebased === 1) && !(respectCap && await capped(r)))) continue;
|
||||
out.add(`${ref}@${r.head_oid}`);
|
||||
const capped = (talked || rebased) && respectCap && cappedToday(facts, ref, now);
|
||||
if (!isMarked && !unblocked && capped) opts.refresh?.(ref, nextUtcMidnight(now));
|
||||
if (!isMarked && !unblocked && !((talked || rebased) && !capped)) continue;
|
||||
out.add(`${ref}@${r.head}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -480,18 +356,15 @@ export async function ensurePipelineLogin(db: Db, _q: Querier, run?: Exec): Prom
|
||||
export async function liveGate(db: Db, q: Querier, repo: string, number: number, head: string): Promise<{ moved: boolean; blocked: string | null }> {
|
||||
const live = await liveDiscussion(q, db, repo, number);
|
||||
const blocked = await recordGate(db, repo, number, live.formal, live.reviewDecision);
|
||||
const snap = await db.get(db.k.selectFrom("opus_reviews").select((eb) => [eb.fn.coalesce("seen_at", "at").as("seen"), "disc_hash as hash"])
|
||||
.where("repo", "=", repo).where("number", "=", number).where("head_oid", "=", head).where("verdict", "is not", null));
|
||||
if (!snap || !live.newestMaint || !changedSince({ newest: live.newestMaint, hash: live.snap.hash! }, snap.seen, snap.hash)) return { moved: false, blocked };
|
||||
await db.run(db.k.insertInto("main.settings").values({ key: staleKey(repo, number), value: new Date().toISOString() }).onConflict((oc) => oc.column("key").doUpdateSet(kx.excluded(["value"]))));
|
||||
const snap = (await loadReviewsAt(db, [{ repo, number, head }])).get(`${repo}#${number}@${head}`);
|
||||
if (!snap || !live.newestMaint || !changedSince({ newest: live.newestMaint, hash: live.snap.hash! }, snap.seen_at ?? snap.at, snap.disc_hash)) return { moved: false, blocked };
|
||||
await markStale(db, [{ repo, number }], null);
|
||||
return { moved: true, blocked };
|
||||
}
|
||||
|
||||
/** Operator request: its review counts as older than now, so Opus reviews it again. */
|
||||
export async function markReviewsStale(db: Db, by: string, repo: string, number: number): Promise<void> {
|
||||
const at = new Date().toISOString();
|
||||
await db.run(db.k.insertInto("main.settings").values({ key: staleKey(repo, number), value: at }).onConflict((oc) => oc.column("key").doUpdateSet(kx.excluded(["value"]))));
|
||||
await audit(db, by, "review-again", `${repo}#${number}`, { stale: true });
|
||||
await markStale(db, [{ repo, number }], by);
|
||||
}
|
||||
|
||||
/** liveGate with retries; null when the read still fails, so the caller skips the PR this run instead of merging blind. */
|
||||
|
||||
+45
-92
@@ -1,14 +1,16 @@
|
||||
// Reasons a due review waits: another item blocks the PR, CI at its head has not passed, the PR used its reviews for the day,
|
||||
// the last review is too recent, or the last attempts at this head failed.
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { audit } from "../dash/audit.ts";
|
||||
import { effectiveCi, effectiveCiWith, optionalChecksOf } from "../optional-checks.ts";
|
||||
import { BLOCKED_EXPIRES_MS, BLOCKS_REVIEW, blockersLoader, storedBlockedBy } from "./blockers.ts";
|
||||
import { MAX_RERUNS_PER_DAY, discussionState, maintainerSince, nextUtcMidnight, staleMarksSince, type DiscussionState } from "./discussion.ts";
|
||||
import { effectiveCiWith, optionalChecksOf } from "../optional-checks.ts";
|
||||
import { BLOCKED_EXPIRES_MS, BLOCKS_REVIEW, activeFrom, hasOpenQuestion, loadBlockerReads } from "./blockers.ts";
|
||||
import { MAX_RERUNS_PER_DAY, maintainerSince, discussionStateOf, nextUtcMidnight, staleMarksOf } from "./discussion.ts";
|
||||
import { ourCommitsLoader } from "./ours.ts";
|
||||
import { setting } from "../settings-read.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import type { NotNull } from "kysely";
|
||||
import type { KeySource } from "../data/keys.ts";
|
||||
import { saveSettings, setting } from "../data/control/index.ts";
|
||||
import { loadReviewRunCounts } from "../data/inference/index.ts";
|
||||
import { loadChecks } from "../data/mirror/index.ts";
|
||||
import { loadReviewFacts, recordReviewFailures } from "../data/review/index.ts";
|
||||
import { loadLegs } from "../data/workflow/index.ts";
|
||||
|
||||
/** Opus review calls of one PR per UTC day, new heads, re-runs and failed calls together (a reply-fix turn is part of its review). */
|
||||
export const MAX_REVIEWS_PER_DAY = MAX_RERUNS_PER_DAY;
|
||||
@@ -20,7 +22,6 @@ const MIN_INTERVAL_MAX = 7 * 24 * 60;
|
||||
|
||||
/** Waits after the 1st, 2nd and 3rd failed review at one head; a 4th failure holds the head until a new commit or Review again. */
|
||||
export const FAILURE_BACKOFF_MS = [10 * 60_000, 30 * 60_000, 2 * 3600_000];
|
||||
const FAIL_KEY = "review_fail:";
|
||||
|
||||
export async function reviewMinInterval(db: Db): Promise<number> {
|
||||
const v = await setting(db, MIN_INTERVAL_KEY);
|
||||
@@ -32,20 +33,13 @@ export async function setReviewMinInterval(db: Db, input: unknown, by: string):
|
||||
const n = typeof input === "number" ? input : typeof input === "string" && /^[0-9]+$/.test(input) ? Number(input) : NaN;
|
||||
if (!Number.isInteger(n) || n < 0 || n > MIN_INTERVAL_MAX) throw new Error(`the minimum minutes between reviews must be a whole number from 0 to ${MIN_INTERVAL_MAX}`);
|
||||
const was = await reviewMinInterval(db);
|
||||
await db.run(db.k.insertInto("main.settings").values({ key: MIN_INTERVAL_KEY, value: String(n) }).onConflict((oc) => oc.column("key").doUpdateSet(kx.excluded(["value"]))));
|
||||
if (n !== was) await audit(db, by, "review-min-interval", "pipeline", { minutes: n, was });
|
||||
await saveSettings(db, [{ key: MIN_INTERVAL_KEY as never, value: String(n) }], by, n !== was ? { action: "review-min-interval", target: "pipeline", details: { minutes: n, was } } : { action: "settings-save", target: "settings" });
|
||||
return n;
|
||||
}
|
||||
|
||||
const failKey = (repo: string, number: number, head: string) => `${FAIL_KEY}${repo}#${number}@${head}`;
|
||||
|
||||
/** Counts a review call at this head that gave no valid review; the earlier heads' counts are forgotten. */
|
||||
export async function recordReviewFailure(db: Db, repo: string, number: number, head: string, nowMs: number = Date.now()): Promise<void> {
|
||||
const key = failKey(repo, number, head);
|
||||
const cur = await setting(db, key);
|
||||
const n = (Number(cur?.split("|")[0]) || 0) + 1;
|
||||
await db.run(db.k.deleteFrom("main.settings").where((eb) => kx.like(db, "key", eb.val(`${FAIL_KEY}${repo}#${number}@%`))).where("key", "<>", key));
|
||||
await db.run(db.k.insertInto("main.settings").values({ key, value: `${n}|${new Date(nowMs).toISOString()}` }).onConflict((oc) => oc.column("key").doUpdateSet(kx.excluded(["value"]))));
|
||||
await recordReviewFailures(db, [{ repo, number, head, at: new Date(nowMs).toISOString() }]);
|
||||
}
|
||||
|
||||
/** `until`: when a timed wait ends (ms), so the planner wakes then. `red`: a ci hold whose head's CI has failed (not still running). */
|
||||
@@ -53,9 +47,10 @@ export type ReviewHold = { kind: "blocked" | "ci" | "cap" | "interval" | "failed
|
||||
|
||||
/** CI at the PR's head as the review gate reads it: "ok" (passed, or no checks and none pending), "pending", "failure", or "unknown" when the stored checks describe another head. */
|
||||
export async function headCi(db: Db, repo: string, number: number, head: string): Promise<"ok" | "pending" | "failure" | "unknown"> {
|
||||
const c = await db.get(db.k.selectFrom("main.pr_checks").select(["head_oid", "overall", "checks"]).where("repo", "=", repo).where("number", "=", number));
|
||||
const [checks, optional] = await Promise.all([loadChecks(db, [{ repo, number }]), optionalChecksOf(db)]);
|
||||
const c = checks.get(`${repo}#${number}`);
|
||||
if (!c || c.head_oid !== head) return "unknown";
|
||||
const o = await effectiveCi(db, repo, c.overall, c.checks);
|
||||
const o = effectiveCiWith(optional(repo), c.overall, c.checks);
|
||||
return o === "pending" ? "pending" : o === "failure" ? "failure" : "ok";
|
||||
}
|
||||
|
||||
@@ -70,109 +65,67 @@ export { nextUtcMidnight };
|
||||
* `refresh` is told when a hold without an `until` of its own ends with the clock (a blocker list expiring).
|
||||
*/
|
||||
export async function reviewHolds(db: Db, nowMs: number = Date.now(), refs?: Iterable<string>): Promise<(repo: string, number: number, head: string, refresh?: (at: number) => void) => Promise<ReviewHold | null>> {
|
||||
// Each table is read once, on first use, for every PR (or only `refs`, "repo#number"), keyed by `repo#number`.
|
||||
const only = refs ? [...refs] : null;
|
||||
const once = <T>(load: () => Promise<T>): (() => Promise<T>) => { let v: T | undefined; return async () => (v ??= await load()); };
|
||||
const keyOf = (r: { repo: string; number: number }) => `${r.repo}#${r.number}`;
|
||||
type Last = { k: string; head_oid: string; at: string; verdict: string; seen_at: string | null; disc_hash: string | null; blocked_by: string | null };
|
||||
const lastReviews = once(async () => {
|
||||
const out = new Map<string, Last>();
|
||||
const rows = await db.all(db.k.selectFrom("main.opus_reviews as o")
|
||||
.select(["o.repo", "o.number", "o.head_oid", "o.at", "o.verdict", "o.seen_at", "o.disc_hash", "o.blocked_by"])
|
||||
.where("o.verdict", "is not", null)
|
||||
.$if(!!only, (q) => q.where(kx.refIn(db, "o", only!)))
|
||||
.$narrowType<{ verdict: NotNull }>()
|
||||
.orderBy("o.at", "desc").orderBy(kx.rowid("main.opus_reviews", "o"), "desc"));
|
||||
for (const r of rows) if (!out.has(keyOf(r))) out.set(keyOf(r), { ...r, k: keyOf(r) });
|
||||
return out;
|
||||
});
|
||||
type Count = { k: string; n: number; last: string | null };
|
||||
const countMap = (load: () => Promise<{ repo: string; number: number; n: number; last: string | null }[]>) =>
|
||||
once(async () => new Map((await load()).map((r): [string, Count] => [keyOf(r), { k: keyOf(r), n: r.n, last: r.last }])));
|
||||
const history = countMap(() => db.all(db.k.selectFrom("main.opus_review_history as h")
|
||||
.select((eb) => ["h.repo", "h.number", eb.fn.count<number>(eb.case().when("h.at", ">=", today).then(1).end()).as("n"), eb.fn.max<string | null>("h.at").as("last")])
|
||||
.where("h.model", "is not", null).where("h.model", "<>", "carried")
|
||||
.where((eb) => eb(eb.fn.coalesce("h.mode", eb.val("")), "<>", "carried"))
|
||||
.$if(!!only, (q) => q.where(kx.refIn(db, "h", only!)))
|
||||
.groupBy(["h.repo", "h.number"])));
|
||||
// One review call per job and PR: the reply-lint fix turn is a follow-up run of the same job, not another review.
|
||||
const runs = countMap(() => db.all(db.k.selectFrom((eb) => eb.selectFrom("main.agent_run_items as i")
|
||||
.innerJoin("main.agent_runs as r", "r.id", "i.run_id")
|
||||
.select((eb2) => ["i.repo", "i.number", eb2.fn.min<string>("r.started_at").as("s")])
|
||||
.where("r.step", "=", "opus-review")
|
||||
.$if(!!only, (q) => q.where(kx.refIn(db, "i", only!)))
|
||||
.groupBy(["i.repo", "i.number"]).groupBy((eb2) => eb2.fn.coalesce("r.job_id", eb2("r.id", "*", -1)))
|
||||
.as("x"))
|
||||
.select((eb) => ["x.repo", "x.number", eb.fn.count<number>(eb.case().when("x.s", ">=", today).then(1).end()).as("n"), eb.fn.max<string | null>("x.s").as("last")])
|
||||
.groupBy(["x.repo", "x.number"])));
|
||||
// Everything is read once, for every PR (or only `refs`, "repo#number"), keyed by `repo#number`.
|
||||
const keys: KeySource = refs ? [...refs].map((r) => ({ repo: r.slice(0, r.lastIndexOf("#")), number: Number(r.slice(r.lastIndexOf("#") + 1)) })) : { mode: "full" };
|
||||
const today = new Date(nowMs).toISOString().slice(0, 10);
|
||||
const interval = await reviewMinInterval(db) * 60_000;
|
||||
const [facts, runs, legs, checks, optional] = await db.together(() => Promise.all([
|
||||
loadReviewFacts(db, keys, { now: nowMs }), loadReviewRunCounts(db, keys, today), loadLegs(db, keys, { activeOnly: true }),
|
||||
loadChecks(db, keys, { checksOnlyIfFailing: true }), optionalChecksOf(db),
|
||||
]));
|
||||
const lastReviews = facts.latest;
|
||||
const history = facts.reviewsToday;
|
||||
const staleSince = staleMarksOf(facts);
|
||||
// A "Queue items" row at the head it started on (no fix-up, no push since) asks for no review of its own: CI, the cap and the interval hold it as any PR.
|
||||
const preapproved = once(async () => new Set((await db.all(db.k.selectFrom("main.preapprovals as p").select(["p.repo", "p.number", "p.head"])
|
||||
.where("p.state", "=", "review")
|
||||
.where((eb) => eb.or([eb("p.fix_id", "is not", null), eb("p.head", "<>", eb.ref("p.from_head"))]))
|
||||
.$if(!!only, (q) => q.where(kx.refIn(db, "p", only!))))).flatMap((r) => (r.head === null ? [] : [`${keyOf(r)}@${r.head}`]))));
|
||||
const failures = once(async () => new Map((await db.all(db.k.selectFrom("main.settings").select(["key", "value"])
|
||||
.where((eb) => kx.like(db, "key", eb.val(`${FAIL_KEY}%`))))).map((r) => [r.key, r.value])));
|
||||
// The checks list only where effectiveCiWith() reads it: a failure.
|
||||
const checks = once(async () => new Map((await db.all(db.k.selectFrom("main.pr_checks as c")
|
||||
.select((eb) => ["c.repo", "c.number", "c.head_oid", "c.overall", eb.case().when("c.overall", "=", "failure").then(eb.ref("c.checks")).end().as("checks")])
|
||||
.$if(!!only, (q) => q.where(kx.refIn(db, "c", only!))))).map((r) => [keyOf(r), r])));
|
||||
const optional = once(async () => await optionalChecksOf(db));
|
||||
const staleSince = once(async () => await staleMarksSince(db));
|
||||
const blockers = once(async () => blockersLoader(db));
|
||||
const ourPath = once(async () => ourCommitsLoader(db));
|
||||
const preapproved = new Set([...legs.values()].flat().filter((p) => p.state === "review" && (p.fix_id !== null || p.head !== p.from_head) && p.head !== null).map((p) => `${p.repo}#${p.number}@${p.head}`));
|
||||
const states = discussionStateOf(facts);
|
||||
const reads = await loadBlockerReads(db, [...lastReviews.values()].filter((r) => r.verdict === "hold").flatMap((r) => r.blocked_by));
|
||||
const ourPath = ourCommitsLoader(db, keys);
|
||||
// CI at the head as headCi() reads it.
|
||||
const ciAt = async (repo: string, number: number, head: string): Promise<"ok" | "pending" | "failure" | "unknown"> => {
|
||||
const c = (await checks()).get(`${repo}#${number}`);
|
||||
const c = checks.get(`${repo}#${number}`);
|
||||
if (!c || c.head_oid !== head) return "unknown";
|
||||
const o = effectiveCiWith((await optional())(repo), c.overall, c.checks);
|
||||
const o = effectiveCiWith(optional(repo), c.overall, c.checks);
|
||||
return o === "pending" ? "pending" : o === "failure" ? "failure" : "ok";
|
||||
};
|
||||
const interval = await reviewMinInterval(db) * 60_000;
|
||||
const today = new Date(nowMs).toISOString().slice(0, 10);
|
||||
const states = new Map<string, DiscussionState>();
|
||||
const stateOf = async (repo: string): Promise<DiscussionState> => {
|
||||
let state = states.get(repo);
|
||||
if (!state) states.set(repo, (state = await discussionState(db, repo)));
|
||||
return state;
|
||||
};
|
||||
return async (repo, number, head, refresh) => {
|
||||
const ref = `${repo}#${number}`;
|
||||
const last = (await lastReviews()).get(ref);
|
||||
const last = lastReviews.get(ref);
|
||||
// The failure backoff holds even after a request: a review that keeps failing is not retried on every pass.
|
||||
const failed = (await failures()).get(failKey(repo, number, head));
|
||||
const mark = facts.marks.get(ref);
|
||||
const failed = mark && mark.failHead === head && mark.failCount > 0 ? mark : undefined;
|
||||
if (failed) {
|
||||
const [n, at] = [Number(failed.split("|")[0]), Date.parse(failed.split("|")[1] ?? "")];
|
||||
const [n, at] = [failed.failCount, Date.parse(failed.failAt ?? "")];
|
||||
const delay = FAILURE_BACKOFF_MS[n - 1];
|
||||
if (delay === undefined) {
|
||||
// Final. A request newer than the last failure grants one more try; a failure then stamps a newer time and makes it final again.
|
||||
const since = failed.split("|")[1] ?? "";
|
||||
const asked = (await staleSince())(repo, number, since) || await maintainerSince((await stateOf(repo)).get(`${repo}#${number}`), since, null);
|
||||
const since = failed.failAt ?? "";
|
||||
const asked = staleSince(repo, number, since) || await maintainerSince(states.get(ref), since, null);
|
||||
if (!asked) return { kind: "failed", wait: `its review failed ${n} times at this commit; a new commit, a Review again press or a maintainer's comment gives it one more try` };
|
||||
} else if (at + delay > nowMs) return { kind: "failed", wait: `the review after ${n} failed ${n === 1 ? "try" : "tries"} at this commit, from ${new Date(at + delay).toISOString().slice(11, 16)}`, until: at + delay };
|
||||
}
|
||||
// A person's pre-approved merge waits for the review of the head the pipeline pushed for it: that is their request for it, as a review-again press would be.
|
||||
if ((await preapproved()).has(`${ref}@${head}`)) return null;
|
||||
if (preapproved.has(`${ref}@${head}`)) return null;
|
||||
if (last) {
|
||||
const state = await stateOf(repo);
|
||||
// reviewRequestedSince() with the stale marks read once.
|
||||
if ((await staleSince())(repo, number, last.at) || await maintainerSince(state.get(ref), last.seen_at ?? last.at, last.disc_hash)) return null;
|
||||
if (staleSince(repo, number, last.at) || await maintainerSince(states.get(ref), last.seen_at ?? last.at, last.disc_hash)) return null;
|
||||
}
|
||||
let settled = false;
|
||||
if (last?.verdict === "hold" && storedBlockedBy(last.blocked_by).length) {
|
||||
const open = await (await blockers()).active(`${repo}#${number}`, last.blocked_by, last.at, nowMs);
|
||||
if (last?.verdict === "hold" && last.blocked_by.length) {
|
||||
const open = activeFrom(reads, ref, last.blocked_by, last.at, nowMs);
|
||||
if (open.length) {
|
||||
refresh?.(Date.parse(last.at) + BLOCKED_EXPIRES_MS + 1);
|
||||
return { kind: "blocked", wait: `${open.join(", ")}${BLOCKS_REVIEW}`, ...(await (await blockers()).openQuestion(open) ? { person: true } : {}) };
|
||||
return { kind: "blocked", wait: `${open.join(", ")}${BLOCKS_REVIEW}`, ...(hasOpenQuestion(reads, open) ? { person: true } : {}) };
|
||||
}
|
||||
settled = true;
|
||||
}
|
||||
const ci = await ciAt(repo, number, head);
|
||||
if (ci === "pending") return { kind: "ci", wait: "CI on the latest commit to finish" };
|
||||
if (ci === "failure" && last && !settled) return { kind: "ci", wait: "CI on the latest commit to pass", red: true };
|
||||
const ours = last && last.head_oid !== head ? await (await ourPath())(repo, number, last.head_oid, head) : null;
|
||||
const ours = last && last.head !== head ? await ourPath(repo, number, last.head, head) : null;
|
||||
if (ours?.complete && ours.commits.length) return null;
|
||||
const h = (await history()).get(ref) ?? { n: 0, last: null };
|
||||
const r = (await runs()).get(ref) ?? { n: 0, last: null };
|
||||
const h = history.get(ref) ?? { n: 0, last: null };
|
||||
const r = runs.get(ref) ?? { n: 0, last: null };
|
||||
if (Math.max(h.n, r.n) >= MAX_REVIEWS_PER_DAY) return { kind: "cap", wait: "review cap for today reached; next on a maintainer's request or tomorrow", until: nextUtcMidnight(nowMs) };
|
||||
if (interval) {
|
||||
// Successful reviews only: failed calls count toward the cap, and the failure backoff spaces their retries.
|
||||
|
||||
+3
-2
@@ -8,6 +8,7 @@ import { refreshChecks } from "./checks.ts";
|
||||
import { rereadUnknown } from "../merge/mergeable.ts";
|
||||
import { markReviewsStale, withRetry } from "./discussion.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import { listItems } from "../data/mirror/index.ts";
|
||||
import { openDb } from "../db/open.ts";
|
||||
|
||||
export type ChecksParams = { repo: string };
|
||||
@@ -39,8 +40,8 @@ export const commands = {
|
||||
const by = args[2] === "--by" && args[3] ? args[3] : "cli";
|
||||
if (args[0] !== "again" || !m || args.length !== (args[2] ? 4 : 2)) throw new Error("usage: autocraft-server review again <repo>#<number> [--by <login>]");
|
||||
const db = await openDb();
|
||||
const open = await db.get(db.k.selectFrom("items").select((eb) => eb.lit(1).as("one")).where("repo", "=", m[1]!).where("number", "=", Number(m[2])).where("kind", "=", "pr").where("state", "=", "OPEN"));
|
||||
if (!open) throw new Error(`${args[1]} is not an open pull request in the mirror`);
|
||||
const open = await listItems(db, { repos: [m[1]!], numbers: [Number(m[2])], kind: "pr", states: ["OPEN"] }, "ref");
|
||||
if (!open.length) throw new Error(`${args[1]} is not an open pull request in the mirror`);
|
||||
await markReviewsStale(db, by, m[1]!, Number(m[2]));
|
||||
console.log(`${args[1]}: its review is stale; Opus reviews it again`);
|
||||
},
|
||||
|
||||
@@ -3,21 +3,25 @@
|
||||
import { planned } from "../core/select.ts";
|
||||
import type { PrFacts } from "../core/plan.ts";
|
||||
import { type Size } from "./candidates.ts";
|
||||
import { mapSeq } from "../async-seq.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import { loadItems } from "../data/mirror/index.ts";
|
||||
|
||||
export type OpusCandidate = {
|
||||
repo: string; number: number; title: string; body: string; author_association: string | null;
|
||||
head_oid: string; lines_changed: number; size: Size; score: number | null;
|
||||
};
|
||||
|
||||
const candidateOf = (it: { title: string | null; body: string | null; author_association: string | null } | undefined, f: Pick<PrFacts, "repo" | "number" | "lines" | "size" | "score">, head: string, fallbackTitle: string): OpusCandidate =>
|
||||
({ repo: f.repo, number: f.number, title: it?.title ?? fallbackTitle, body: it?.body ?? "", author_association: it?.author_association ?? null, head_oid: head, lines_changed: f.lines, size: f.size, score: f.score });
|
||||
|
||||
/** The candidate of a PR at `head`: its text and author association from the items row, size and score from its facts. */
|
||||
export async function opusCandidateOf(db: Db, f: Pick<PrFacts, "repo" | "number" | "lines" | "size" | "score">, head: string, fallbackTitle = ""): Promise<OpusCandidate> {
|
||||
const it = await db.get(db.k.selectFrom("items").select(["title", "body", "author_association"]).where("repo", "=", f.repo).where("number", "=", f.number));
|
||||
return { repo: f.repo, number: f.number, title: it?.title ?? fallbackTitle, body: it?.body ?? "", author_association: it?.author_association ?? null, head_oid: head, lines_changed: f.lines, size: f.size, score: f.score };
|
||||
return candidateOf((await loadItems(db, [{ repo: f.repo, number: f.number }], "text")).get(`${f.repo}#${f.number}`), f, head, fallbackTitle);
|
||||
}
|
||||
|
||||
/** PRs of `repo` still to review, highest work score first. */
|
||||
export async function selectOpusCandidates(db: Db, repo: string, run?: string | null): Promise<OpusCandidate[]> {
|
||||
return await mapSeq((await planned(db, "review", { repo, ...(run !== undefined ? { run } : {}) })), async (p) => await opusCandidateOf(db, p.facts, p.action.head!));
|
||||
const rows = await planned(db, "review", { repo, ...(run !== undefined ? { run } : {}) });
|
||||
const items = await loadItems(db, rows.map((p) => ({ repo: p.facts.repo, number: p.facts.number })), "text");
|
||||
return rows.map((p) => candidateOf(items.get(`${p.facts.repo}#${p.facts.number}`), p.facts, p.action.head!, ""));
|
||||
}
|
||||
+57
-98
@@ -1,7 +1,6 @@
|
||||
// Stage 5, Review: Opus reviews every wanted PR, one PR per call, and its verdict is the
|
||||
// one every later stage reads (the `final_reviews` view). After a new push Opus reads only
|
||||
// the delta since the head it reviewed before. Reads GitHub (diffs); never writes to it.
|
||||
import { repoWorkflow } from "../workflow/store.ts";
|
||||
import { CLAUDE_PROMPTS } from "../prompts/index.ts";
|
||||
import { currentJobId, poolRoom, takersCut } from "../agents/call.ts";
|
||||
import { pool } from "../classify/run.ts";
|
||||
@@ -10,12 +9,9 @@ import { REVIEW_OPUS } from "../agents/steps.ts";
|
||||
import { Client, type Querier } from "../mirror.ts";
|
||||
import { checksOf, refreshChecks } from "./checks.ts";
|
||||
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 { withdrawHoldQuestion, withdrawMergeQuestion } from "../merge/withdraw.ts";
|
||||
import { headWasUnsure, mergeDecisionId, holdDecisionId } from "../merge/queue.ts";
|
||||
import { defaultBranchOf, recordLiveBase, reviewedBaseOf } from "../merge/base.ts";
|
||||
import { MAX_RERUNS_PER_DAY, discussionOf, ensurePipelineLogin, liveDiscussion, staleReviews, withRetry, type Snapshot } from "./discussion.ts";
|
||||
import { recordLiveBase } from "../merge/base.ts";
|
||||
import { relatedOpen, latestReview } from "../postmerge/related.ts";
|
||||
import type { DiscussionEntry } from "./parse.ts";
|
||||
import { reviewAfterBaseMerge } from "./own-diff.ts";
|
||||
@@ -32,8 +28,10 @@ import { jobItem } from "../runner/job-items.ts";
|
||||
import { filterSeq } from "../async-seq.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import { openDb } from "../db/open.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import type { NotNull } from "kysely";
|
||||
import { loadOwnDeltas, loadPatchFacts } from "../data/changes/index.ts";
|
||||
import { loadItems, loadRepos } from "../data/mirror/index.ts";
|
||||
import { loadReviewRows, loadReviewsAt, saveReviews, type ReviewRow } from "../data/review/index.ts";
|
||||
import { loadBlockerReads, openFrom } from "./blockers.ts";
|
||||
|
||||
const PROMPT = CLAUDE_PROMPTS["review.opus"];
|
||||
export { MAX_DIFF_CHARS };
|
||||
@@ -59,17 +57,13 @@ export type OpusSummary = {
|
||||
};
|
||||
|
||||
const now = () => new Date().toISOString();
|
||||
const scopeSettledField = async (db: Db, repo: string, number: number): Promise<{ scope_settled?: NonNullable<OpusPr["scope_settled"]> }> => {
|
||||
const s = await settledScope(db, repo, number);
|
||||
return s ? { scope_settled: s } : {};
|
||||
};
|
||||
const refOf = (c: { repo: string; number: number }) => `${c.repo}#${c.number}`;
|
||||
|
||||
export function defaultOpusDeps(): OpusDeps {
|
||||
return { querier: new Client(500), fetchDiff: ghDiff, fetchDelta: ghDelta, model: PROMPT.models[0]!, maxChars: MAX_DIFF_CHARS, checkout: (r, n, h) => checkoutForPr(r, n, h, console.log) };
|
||||
}
|
||||
|
||||
type Saved = { snap?: Snapshot; mode: "full" | "delta" | "carried"; base: string | null; model: string | null; review: OpusReview; /** The fixes this review was given as unapplied, with what the reply did with each. */ unapplied?: (UnappliedFix & { outcome: string })[];
|
||||
type Saved = { snap?: Snapshot; mode: "full" | "delta" | "carried"; base: string | null; model: string | null; review: OpusReview;
|
||||
/** The base branch the reviewed diff was read against (a delta or carried review: the earlier review's); absent: the cached diff's, else the mirrored base. */ baseRef?: string | null };
|
||||
|
||||
/**
|
||||
@@ -77,95 +71,57 @@ type Saved = { snap?: Snapshot; mode: "full" | "delta" | "carried"; base: string
|
||||
* stages row (take-fix counts as take). A second review of the same head counts against
|
||||
* the PR's daily cap unless an operator or a merge-time check asked for it.
|
||||
* A review of the head against another base than the one before it voids what was decided for the old diff:
|
||||
* the Merge answer, the pre-merge review and the verification.
|
||||
* the pre-merge review and the verification.
|
||||
*/
|
||||
export async function saveOpus(db: Db, runId: string | null, c: { repo: string; number: number; head_oid: string }, s: Saved): Promise<void> {
|
||||
const at = now(), r = s.review;
|
||||
const again = await db.get(db.k.selectFrom("opus_reviews").select("at").where("repo", "=", c.repo).where("number", "=", c.number).where("head_oid", "=", c.head_oid));
|
||||
const r = s.review, ref = refOf(c);
|
||||
const baseRef = s.baseRef !== undefined ? s.baseRef : await reviewedBase(db, c);
|
||||
const before = again ? await reviewedBaseOf(db, c.repo, c.number, c.head_oid) ?? await defaultBranchOf(db, c.repo) : null;
|
||||
const rebased = !!before && !!baseRef && before !== baseRef;
|
||||
const reviewed = await db.get(db.k.selectFrom("opus_reviews").select("at").where("repo", "=", c.repo).where("number", "=", c.number).where("head_oid", "=", c.head_oid).where("verdict", "is not", null));
|
||||
if (reviewed && !await markedStaleSince(db, c.repo, c.number, reviewed.at)) await countRerun(db, c.repo, c.number);
|
||||
// A head that was ever unsure keeps its Merge? question (and a person's answer to it) through a re-review that stays take or take-fix.
|
||||
// An answered question is withdrawn as for any re-review: the head then needs a new answer.
|
||||
const unanswered = !!await db.get(db.k.selectFrom("decisions").select((eb) => eb.lit(1).as("one")).where("id", "=", mergeDecisionId(c.repo, c.number, c.head_oid)).where("answer", "is", null));
|
||||
const keepsQuestion = !!again && !rebased && unanswered && (r.verdict === "take" || r.verdict === "take-fix") && await headWasUnsure(db, c.repo, c.number, c.head_oid);
|
||||
// An answered, unapplied merge answer stands through a re-review at the same head and base unless the verdict got worse.
|
||||
const keepsAnswer = !!again && !rebased && (r.verdict === "take" || r.verdict === "take-fix") && r.sure
|
||||
&& !!await db.get(db.k.selectFrom("decisions").select((eb) => eb.lit(1).as("one")).where("id", "=", mergeDecisionId(c.repo, c.number, c.head_oid)).where("answer", "=", "merge").where("applied_at", "is", null));
|
||||
if (again && !keepsQuestion && !keepsAnswer) {
|
||||
const worse = r.verdict === "take" || r.verdict === "take-fix" ? "the new review is unsure" : `the new review is a ${r.verdict}`;
|
||||
await withdrawMergeQuestion(db, c.repo, c.number, c.head_oid, at, rebased ? `the base branch changed from ${before} to ${baseRef}` : `superseded by a new review: ${worse}`);
|
||||
}
|
||||
if (rebased) {
|
||||
await db.run(db.k.deleteFrom("premerge_reviews").where("repo", "=", c.repo).where("number", "=", c.number).where("head_oid", "=", c.head_oid));
|
||||
await db.run(db.k.updateTable("verifications").set({ state: "stale" }).where("repo", "=", c.repo).where("number", "=", c.number).where("head_sha", "=", c.head_oid));
|
||||
}
|
||||
// The Hold question belongs to one review: a review made again at the head asks it anew if the verdict is still hold.
|
||||
// An unanswered or Wait-answered question stays while the verdict is still hold: its review time moves, so the prepare is written again.
|
||||
const holdId = holdDecisionId(c.repo, c.number, c.head_oid);
|
||||
const keepsHold = r.verdict === "hold" && !!await db.get(db.k.selectFrom("decisions").select((eb) => eb.lit(1).as("one")).where("id", "=", holdId).where((eb) => eb.or([eb("answer", "is", null), eb("answer", "=", "wait")])));
|
||||
if (again && !keepsHold) await 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.
|
||||
await db.run(db.k.insertInto("main.opus_review_history")
|
||||
.columns(["repo", "number", "head_oid", "at", "model", "mode", "verdict", "sure", "reason", "risks", "fixes", "summary", "why", "public_review", "claims", "blocked_by"])
|
||||
.expression((eb) => eb.selectFrom("main.opus_reviews as o")
|
||||
.select(["o.repo", "o.number", "o.head_oid", "o.at", "o.model", "o.mode", "o.verdict", "o.sure", "o.reason", "o.risks", "o.fixes", "o.summary", "o.why", "o.public_review", "o.claims", "o.blocked_by"])
|
||||
.where((eb) => eb.not(eb.exists(eb.selectFrom("main.opus_review_history as h").select(eb.lit(1).as("one"))
|
||||
.whereRef("h.repo", "=", "o.repo").whereRef("h.number", "=", "o.number").whereRef("h.head_oid", "=", "o.head_oid").whereRef("h.at", "=", "o.at"))))
|
||||
.where("o.repo", "=", c.repo).where("o.number", "=", c.number).where("o.head_oid", "=", 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;
|
||||
// Only open tracked items other than the PR can block it: a reference that is already closed would end the wait at once.
|
||||
// A scope question is no blocker once a person has settled scope for this PR.
|
||||
const scopeSettled = await settledScope(db, c.repo, c.number) !== null;
|
||||
const blockers = r.verdict === "hold" ? await filterSeq((await openBlockers(db, r.blocked_by.filter((x) => x !== `${c.repo}#${c.number}`))), async (b) => !(scopeSettled && await isScopeQuestion(db, b))) : [];
|
||||
const blockedBy = blockers.length ? JSON.stringify(blockers) : null;
|
||||
await db.run(db.k.insertInto("opus_review_history").values({ repo: c.repo, number: c.number, head_oid: c.head_oid, at, model: s.model, mode: s.mode, verdict: r.verdict,
|
||||
sure: r.sure ? 1 : 0, reason: r.reason, risks, fixes, summary: r.summary, why: r.why, public_review: pub, claims, blocked_by: blockedBy,
|
||||
trigger: again ? (await markedStaleSince(db, c.repo, c.number, again.at) ? "operator" : rebased ? "base" : "discussion") : "new-head", job_id: currentJobId() }));
|
||||
await db.run(db.k.insertInto("opus_reviews").values({ repo: c.repo, number: c.number, head_oid: c.head_oid, run_id: runId, at, model: s.model, mode: s.mode, base_head: s.base,
|
||||
verdict: r.verdict, sure: r.sure ? 1 : 0, reason: r.reason, fixes, risks, public_review: pub, seen_at: s.snap?.seen ?? at, disc_hash: s.snap?.hash ?? null, summary: r.summary,
|
||||
why: r.why, conflicts: r.conflicts.length ? JSON.stringify(r.conflicts) : null, claims, blocked_by: blockedBy, base_ref: baseRef, workflow: r.workflow ? JSON.stringify(r.workflow) : null })
|
||||
.onConflict((oc) => oc.columns(["repo", "number", "head_oid"]).doUpdateSet(kx.excluded(["run_id", "at", "model", "mode", "base_head", "verdict", "sure", "reason", "fixes", "risks", "public_review",
|
||||
"seen_at", "disc_hash", "summary", "why", "conflicts", "claims", "blocked_by", "base_ref", "workflow"]))));
|
||||
await db.run(db.k.deleteFrom("main.settings").where("key", "=", `review_fail:${c.repo}#${c.number}@${c.head_oid}`));
|
||||
await db.run(db.k.deleteFrom("opus_carried_fixes").where("repo", "=", c.repo).where("number", "=", c.number).where("head_oid", "=", c.head_oid));
|
||||
for (const u of s.unapplied ?? []) {
|
||||
await db.run(db.k.insertInto("opus_carried_fixes").values({ repo: c.repo, number: c.number, head_oid: c.head_oid, from_head: u.head, file: u.file, change: u.change, outcome: u.outcome, at }));
|
||||
}
|
||||
await db.run(db.k.insertInto("main.stages").values({ repo: c.repo, number: c.number, stage: "reviewed", at, actor: "opus-review", note: `${r.verdict}${r.sure ? "" : " (unsure)"} at ${c.head_oid.slice(0, 7)}: ${r.reason}` }));
|
||||
await db.run(db.k.insertInto("main.stages").values({ repo: c.repo, number: c.number, stage: r.verdict === "take-fix" ? "take" : r.verdict, at, actor: "opus-review", note: r.reason }));
|
||||
const [repos, blockers] = await Promise.all([
|
||||
loadRepos(db, { names: [c.repo] }),
|
||||
// Only open tracked items other than the PR can block it: a reference that is already closed would end the wait at once.
|
||||
r.verdict === "hold" ? openBlockerRefs(db, r.blocked_by.filter((x) => x !== ref)) : Promise.resolve([] as string[]),
|
||||
]);
|
||||
await saveReviews(db, [{
|
||||
runId, repo: c.repo, number: c.number, head: c.head_oid, mode: s.mode, base: s.base, baseRef: baseRef ?? null, defaultBranch: repos.get(c.repo)?.default_branch ?? null,
|
||||
model: s.model, review: { verdict: r.verdict, sure: r.sure, reason: r.reason, fixes: r.fixes as never, risks: r.risks, workflow: (r.workflow ?? null) as never, summary: r.summary, why: r.why, public: r.public, conflicts: r.conflicts, claims: r.claims },
|
||||
...(s.snap ? { snap: { seen: s.snap.seen, hash: s.snap.hash } } : {}), blockedBy: blockers, jobId: currentJobId(),
|
||||
}]);
|
||||
}
|
||||
|
||||
/** The refs among `refs` that still block a hold. */
|
||||
async function openBlockerRefs(db: Db, refs: string[]): Promise<string[]> {
|
||||
return openFrom(await loadBlockerReads(db, refs), refs);
|
||||
}
|
||||
|
||||
/** The Opus review of the PR's latest earlier head that a model wrote (not a too-large hold), for the delta. */
|
||||
export async function earlierOpus(db: Db, c: { repo: string; number: number; head_oid: string }, skip = 0): Promise<EarlierOpus | null> {
|
||||
const o = await db.get(db.k.selectFrom("opus_reviews").select(["head_oid", "verdict", "sure", "reason", "fixes"]).$narrowType<{ verdict: NotNull }>()
|
||||
.where("repo", "=", c.repo).where("number", "=", c.number).where("head_oid", "<>", c.head_oid).where("verdict", "is not", null).where("model", "is not", null)
|
||||
.orderBy("at", "desc").orderBy(kx.rowid("opus_reviews"), "desc").limit(1).offset(skip));
|
||||
if (!o) return null;
|
||||
let fixes: EarlierOpus["fixes"] = [];
|
||||
try { fixes = JSON.parse(o.fixes ?? "[]") as EarlierOpus["fixes"]; } catch { /* none */ }
|
||||
return { head: o.head_oid, verdict: o.verdict, sure: o.sure === 1, reason: o.reason ?? "", fixes };
|
||||
const o = earlierRows(await loadReviewRows(db, [{ repo: c.repo, number: c.number }]), c)[skip];
|
||||
return o ? earlierOf(o) : null;
|
||||
}
|
||||
|
||||
/** The PR's reviews of other heads that a model wrote (not a too-large hold), newest first. */
|
||||
const earlierRows = (rows: Map<string, ReviewRow[]>, c: { repo: string; number: number; head_oid: string }): ReviewRow[] =>
|
||||
(rows.get(`${c.repo}#${c.number}`) ?? []).filter((r) => r.head !== c.head_oid && r.model !== null);
|
||||
|
||||
const earlierOf = (o: ReviewRow): EarlierOpus => ({ head: o.head, verdict: o.verdict, sure: o.sure, reason: o.reason ?? "", fixes: o.fixes as EarlierOpus["fixes"] });
|
||||
|
||||
/**
|
||||
* The fixes of the PR's latest earlier reviewed head, when that review was a take-fix whose fixes were never pushed
|
||||
* and never posted as a comment (a conflict merge of ours or an author push made a new head first).
|
||||
*/
|
||||
export async function unappliedFixes(db: Db, c: { repo: string; number: number; head_oid: string }): Promise<UnappliedFix[]> {
|
||||
export async function unappliedFixes(db: Db, c: { repo: string; number: number; head_oid: string }, rows?: Map<string, ReviewRow[]>): Promise<UnappliedFix[]> {
|
||||
// A hold in between (an author push the reviewer could not judge) does not make the older take-fix's fixes moot.
|
||||
let e = await earlierOpus(db, c);
|
||||
if (e?.verdict === "hold") e = await earlierOpus(db, c, 1);
|
||||
const [first, second] = earlierRows(rows ?? await loadReviewRows(db, [{ repo: c.repo, number: c.number }]), c);
|
||||
const e = first && first.verdict === "hold" ? second : first;
|
||||
if (!e || e.verdict !== "take-fix") return [];
|
||||
if (await db.get(db.k.selectFrom("fixups").select((eb) => eb.lit(1).as("one")).where("repo", "=", c.repo).where("number", "=", c.number).where("from_head", "=", e.head).where("state", "in", ["pushed", "asked"]))) return [];
|
||||
return e.fixes.filter((f) => typeof f?.file === "string" && !!f.file.trim() && typeof f.change === "string").map((f) => ({ head: e.head, file: f.file, change: f.change }));
|
||||
const facts = (await loadPatchFacts(db, [{ repo: c.repo, number: c.number }])).get(refOf(c));
|
||||
if (facts?.fixups.some((f) => f.fromHead === e.head && (f.state === "pushed" || f.state === "asked"))) return [];
|
||||
return (e.fixes as { file: string; change: string }[]).filter((f) => typeof f?.file === "string" && !!f.file.trim() && typeof f.change === "string").map((f) => ({ head: e.head, file: f.file, change: f.change }));
|
||||
}
|
||||
|
||||
/** The base branch the review's diff was computed against; the mirrored base when the cached diff does not say. */
|
||||
async function reviewedBase(db: Db, c: { repo: string; number: number; head_oid: string }): Promise<string | null> {
|
||||
return cachedDiffBase(c.repo, c.number, c.head_oid)
|
||||
?? (await db.get(db.k.selectFrom("items").select("base_ref").where("repo", "=", c.repo).where("number", "=", c.number)))?.base_ref ?? null;
|
||||
return cachedDiffBase(c.repo, c.number, c.head_oid) ?? (await loadItems(db, [{ repo: c.repo, number: c.number }], "pr")).get(refOf(c))?.base_ref ?? null;
|
||||
}
|
||||
|
||||
/** `base`: the earlier head a delta was read from; `baseRef`: the base branch the whole PR diff was read against. */
|
||||
@@ -181,7 +137,11 @@ export type PreparedOpus =
|
||||
* review that must not be anchored on the first one (the pre-merge review); the snapshot then marks the time of the read.
|
||||
*/
|
||||
export async function prepareOpusInput(db: Db, repo: string, c: OpusCandidate, deps: OpusDeps, log: (line: string) => void, opts: { independent?: boolean } = {}): Promise<PreparedOpus> {
|
||||
const liveBase = (await db.get(db.k.selectFrom("items").select("base_ref").where("repo", "=", repo).where("number", "=", c.number)))?.base_ref;
|
||||
const ref = refOf(c);
|
||||
const [items, rows, repos] = await db.together(() => Promise.all([
|
||||
loadItems(db, [{ repo, number: c.number }], "pr"), loadReviewRows(db, [{ repo, number: c.number }]), loadRepos(db, { names: [repo] }),
|
||||
]));
|
||||
const liveBase = items.get(ref)?.base_ref;
|
||||
const d = await cachedDiff(db, repo, c.number, c.head_oid, deps.fetchDiff, liveBase);
|
||||
if (!d.ok) return d.tooLarge ? { kind: "large", mode: "full", base: null, baseRef: liveBase ?? null } : { kind: "no-diff", error: d.error };
|
||||
const baseRef = d.base ?? liveBase ?? null;
|
||||
@@ -199,38 +159,38 @@ export async function prepareOpusInput(db: Db, repo: string, c: OpusCandidate, d
|
||||
mode: "full", earlier_opus: null, diff: cd.text,
|
||||
related_open: await relatedOpen(db, repo, c.number, cd.files), review_history: await latestReview(db, repo, c.number, c.head_oid),
|
||||
};
|
||||
return { kind: "ready", input: { ...input, statements: await relatedStatements(db, repo, c.number), ...await scopeSettledField(db, repo, c.number) }, snap: { seen: now(), hash: null }, mode: "full", base: null, baseRef };
|
||||
return { kind: "ready", input: { ...input, statements: await relatedStatements(db, repo, c.number) }, snap: { seen: now(), hash: null }, mode: "full", base: null, baseRef };
|
||||
}
|
||||
let mode: "full" | "delta" = "full", diff = cd.text, base: string | null = null;
|
||||
// A delta stands on the earlier review only when that review read the PR against the same base branch; after a retarget the whole diff is reviewed.
|
||||
const prior = await earlierOpus(db, c);
|
||||
const priorBase = prior ? await reviewedBaseOf(db, repo, c.number, prior.head) ?? await defaultBranchOf(db, repo) : null;
|
||||
const priorRow = earlierRows(rows, c)[0];
|
||||
const prior = priorRow ? earlierOf(priorRow) : null;
|
||||
const priorBase = priorRow ? priorRow.base_ref ?? repos.get(repo)?.default_branch ?? null : null;
|
||||
const earlier = prior && (priorBase === null || baseRef === null || priorBase === baseRef) ? prior : null;
|
||||
// A merge commit of ours carries the base branch's changes since the earlier head, so a delta of the heads would show unrelated changes: the delta is taken between the PR's own diffs.
|
||||
const merged = await db.get(db.k.selectFrom("conflict_merges").select(["from_head", "own_diff", "own_delta"]).where("repo", "=", repo).where("number", "=", c.number).where("to_head", "=", c.head_oid).where("state", "=", "merged")
|
||||
.orderBy(kx.rowid("conflict_merges"), "desc").limit(1));
|
||||
const merged = (await loadOwnDeltas(db, [{ ref, toHead: c.head_oid }])).get(`${ref}@${c.head_oid}`);
|
||||
if (earlier && !merged) {
|
||||
const delta = await deps.fetchDelta(repo, earlier.head, c.head_oid);
|
||||
// A delta whose test files do not all fit is not used: the full diff shows them.
|
||||
const dd = delta.ok ? codeDiff(delta.text, deps.maxChars) : null;
|
||||
if (dd && !dd.testsOmitted.length) { mode = "delta"; diff = dd.text; base = earlier.head; }
|
||||
else if (!delta.ok) log(` ${refOf(c)}: delta since ${earlier.head.slice(0, 7)} unavailable (${delta.error}); full diff`);
|
||||
} else if (earlier && merged?.own_delta && reviewAfterBaseMerge(merged.own_diff) === "delta" && merged.from_head === earlier.head && earlier.sure && (earlier.verdict === "take" || earlier.verdict === "take-fix")) {
|
||||
} else if (earlier && merged?.ownDelta && reviewAfterBaseMerge(merged.ownDiff) === "delta" && merged.fromHead === earlier.head && earlier.sure && (earlier.verdict === "take" || earlier.verdict === "take-fix")) {
|
||||
// The delta was computed from the local commits when the merge was made; the diff of the earlier head is never fetched by number.
|
||||
const dd = codeDiff(merged.own_delta, deps.maxChars);
|
||||
const dd = codeDiff(merged.ownDelta, deps.maxChars);
|
||||
if (dd.text && !dd.testsOmitted.length) { mode = "delta"; diff = dd.text; base = earlier.head; }
|
||||
}
|
||||
if (diff.length > deps.maxChars) return { kind: "large", mode, base, baseRef };
|
||||
let discussion: DiscussionEntry[], snap: Snapshot, maintDropped: boolean;
|
||||
try {
|
||||
// What the PR's previous review read is not lost to the budget silently: only maintainers' words since then must fit.
|
||||
const since = (await db.get(db.k.selectFrom("opus_reviews").select((eb) => eb.fn.coalesce("seen_at", "at").as("seen")).where("repo", "=", repo).where("number", "=", c.number).where("verdict", "is not", null)
|
||||
.orderBy("at", "desc").orderBy(kx.rowid("opus_reviews"), "desc").limit(1)))?.seen ?? "";
|
||||
const latest = rows.get(ref)?.[0];
|
||||
const since = latest ? latest.seen_at ?? latest.at : "";
|
||||
({ entries: discussion, snap, maintDropped } = await discussionOf(db, repo, c.number, deps.querier ? await withRetry(() => liveDiscussion(deps.querier!, db, repo, c.number)) : undefined, since));
|
||||
} catch (e) {
|
||||
return { kind: "no-threads", error: String((e as Error).message ?? e) };
|
||||
}
|
||||
const unapplied = await unappliedFixes(db, c);
|
||||
const unapplied = await unappliedFixes(db, c, rows);
|
||||
// Our own commits since the earlier reviewed head, for the reviewer to check against what was asked of them.
|
||||
const ours = earlier ? (await ourCommitsSince(db, repo, c.number, earlier.head, c.head_oid)).commits.map(({ from: _from, ...x }) => x) : [];
|
||||
const input: OpusPr = {
|
||||
@@ -239,7 +199,6 @@ export async function prepareOpusInput(db: Db, repo: string, c: OpusCandidate, d
|
||||
mode, earlier_opus: mode === "delta" ? earlier : null, ...(unapplied.length ? { unapplied_fixes: unapplied } : {}), ...(ours.length ? { pipeline_commits: ours } : {}), diff, discussion,
|
||||
related_open: await relatedOpen(db, repo, c.number, cd.files),
|
||||
statements: await relatedStatements(db, repo, c.number),
|
||||
...await scopeSettledField(db, repo, c.number),
|
||||
};
|
||||
return { kind: "ready", input, snap, mode, base, baseRef, ...(maintDropped ? { maintDropped } : {}) };
|
||||
}
|
||||
@@ -268,7 +227,7 @@ export async function runOpusReview(db: Db, params: OpusParams, log: (line: stri
|
||||
return summary;
|
||||
}
|
||||
const asked = cands.length;
|
||||
const holds = await reviewHolds(db);
|
||||
const holds = await reviewHolds(db, Date.now(), cands.map(refOf));
|
||||
const byNumber = new Map(live.map((l) => [l.number, l]));
|
||||
cands = await filterSeq(cands, async (c) => {
|
||||
const l = byNumber.get(c.number);
|
||||
@@ -308,7 +267,7 @@ export async function runOpusReview(db: Db, params: OpusParams, log: (line: stri
|
||||
const { input, snap, mode, base, baseRef } = p;
|
||||
const checkout = (await deps.checkout?.(repo, c.number, c.head_oid)) ?? undefined;
|
||||
if (checkout) input.repo_dir = REPO_PATH;
|
||||
if (await repoWorkflow(db, repo) === "new") input.workflow = true;
|
||||
input.workflow = true;
|
||||
const dir = referenceDir(repo);
|
||||
const semantic = dir ? deps.semantic ?? defaultSemanticDeps(db, input.ref) : undefined;
|
||||
const r = await runModelStep(db, REVIEW_OPUS, input, {
|
||||
@@ -331,7 +290,7 @@ export async function runOpusReview(db: Db, params: OpusParams, log: (line: stri
|
||||
}
|
||||
// A maintainer's word the model was not shown leaves the take to a person.
|
||||
if (p.maintDropped && got.sure && (got.verdict === "take" || got.verdict === "take-fix")) got = { ...got, sure: false, risks: [...got.risks, "a maintainer's comment was left out of the review for length"] };
|
||||
await saveOpus(db, runId, c, { mode, base, baseRef, model: (r.ok && r.model) || deps.model, review: got, snap, unapplied: outcomes });
|
||||
await saveOpus(db, runId, c, { mode, base, baseRef, model: (r.ok && r.model) || deps.model, review: got, snap });
|
||||
await tally(c, got);
|
||||
} else {
|
||||
await recordReviewFailure(db, c.repo, c.number, c.head_oid);
|
||||
|
||||
+42
-92
@@ -1,113 +1,63 @@
|
||||
// The commits our pipeline pushed to a PR between two heads, for the review prompt and for carrying a verdict over our own fix-up.
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import type { KeySource } from "../data/keys.ts";
|
||||
import { loadPushEdges, madeBy as pushMadeBy, type PushEdge } from "../data/changes/index.ts";
|
||||
import { loadFixesAsked } from "../data/review/index.ts";
|
||||
|
||||
export type OurCommit = { kind: "fix-up" | "pre-merge fix" | "operator fix-up" | "CI fix" | "base merge" | "carry"; sha: string; note: string; fixes_meant: string[]; from: string };
|
||||
export type OurCommit = { kind: "fix-up" | "pre-merge fix" | "operator fix-up" | "CI fix" | "base merge"; sha: string; note: string; fixes_meant: string[]; from: string };
|
||||
|
||||
type Row = { from: string; kind: OurCommit["kind"]; note: string | null; source?: string | null };
|
||||
|
||||
/** What a carry commit holds: parts of the closed duplicates, named with their authors. */
|
||||
async function carriedNote(db: Db, repo: string, decision: string | null): Promise<string> {
|
||||
const rows = decision ? await db.all(db.k.selectFrom("dupe_group_items as g").leftJoin("items as i", (j) => j.on("i.repo", "=", repo).onRef("i.number", "=", "g.number"))
|
||||
.select(["g.number", "i.author"]).where("g.decision_id", "=", decision).where("g.kind", "=", "pr").where("g.role", "=", "close").orderBy("g.number")) : [];
|
||||
return rows.length ? `parts carried from the closed duplicate PRs ${rows.map((x) => `#${x.number}${x.author ? ` by ${x.author}` : ""}`).join(", ")}: code written by those authors, not by the pipeline` : "parts carried from closed duplicate PRs: code written by their authors, not by the pipeline";
|
||||
}
|
||||
|
||||
type Pushes = {
|
||||
a?: { f: string; reason: string | null; source: string | null; carry_decision: string | null };
|
||||
// Read only when the earlier kinds found none.
|
||||
b: () => Promise<{ f: string; reason: string | null; kind: string } | undefined>;
|
||||
c: () => Promise<{ f: string; reason: string | null } | undefined>;
|
||||
d: () => Promise<{ f: string } | undefined>;
|
||||
};
|
||||
|
||||
/** The commit of ours that made `head`, or null when no push of ours ended there (a contributor's commit). */
|
||||
async function madeBy(db: Db, repo: string, number: number, head: string): Promise<Row | null> {
|
||||
return await madeFrom(db, repo, {
|
||||
a: await db.get(db.k.selectFrom("fixups").select(["from_head as f", "reason", "source", "carry_decision"])
|
||||
.where("repo", "=", repo).where("number", "=", number).where("to_head", "=", head).where("state", "=", "pushed").orderBy(kx.rowid("fixups"), "desc").limit(1)),
|
||||
b: async () => await db.get(db.k.selectFrom("ci_fixes").select(["head as f", "reason", "kind"])
|
||||
.where("repo", "=", repo).where("number", "=", number).where("to_head", "=", head).where("state", "=", "pushed").orderBy(kx.rowid("ci_fixes"), "desc").limit(1)),
|
||||
c: async () => await db.get(db.k.selectFrom("conflict_merges").select(["from_head as f", "reason"])
|
||||
.where("repo", "=", repo).where("number", "=", number).where("to_head", "=", head).where("state", "=", "merged").orderBy(kx.rowid("conflict_merges"), "desc").limit(1)),
|
||||
d: async () => await db.get(db.k.selectFrom("dupe_carries").select(["from_head as f"]).$narrowType<{ f: string }>()
|
||||
.where("repo", "=", repo).where("number", "=", number).where("to_head", "=", head).where((eb) => kx.like(db, "outcome", eb.val("pushed%"))).where("from_head", "is not", null)
|
||||
.orderBy(kx.rowid("dupe_carries")).limit(1)),
|
||||
});
|
||||
function madeBy(edges: readonly PushEdge[], head: string): Row | null {
|
||||
const m = pushMadeBy(edges, head);
|
||||
if (!m) return null;
|
||||
if (m.kind === "fixup") return { from: m.from, kind: m.source === "premerge" ? "pre-merge fix" : m.source === "operator" ? "operator fix-up" : "fix-up", note: m.reason, source: m.source };
|
||||
if (m.kind === "cifix") return { from: m.from, kind: "CI fix", note: m.reason ?? `fix for the failing ${m.ciKind} check` };
|
||||
return { from: m.from, kind: "base merge", note: m.reason ?? "merged the base branch into the PR" };
|
||||
}
|
||||
|
||||
/** madeBy() from the pushes that ended at the head: a fix-up, else a CI fix, else a base merge, else a carry-over. */
|
||||
async function madeFrom(db: Db, repo: string, p: Pushes): Promise<Row | null> {
|
||||
const a = p.a;
|
||||
if (a?.source === "carry") return { from: a.f, kind: "carry", note: await carriedNote(db, repo, a.carry_decision), source: a.source };
|
||||
if (a) return { from: a.f, kind: a.source === "premerge" ? "pre-merge fix" : a.source === "operator" ? "operator fix-up" : "fix-up", note: a.reason, source: a.source };
|
||||
const b = await p.b();
|
||||
if (b) return { from: b.f, kind: "CI fix", note: b.reason ?? `fix for the failing ${b.kind} check` };
|
||||
const c = await p.c();
|
||||
if (c) return { from: c.f, kind: "base merge", note: c.reason ?? "merged the base branch into the PR" };
|
||||
const d = await p.d();
|
||||
if (d) return { from: d.f, kind: "carry", note: "carried parts of closed duplicates onto the PR" };
|
||||
return null;
|
||||
type OurPath = { commits: OurCommit[]; complete: boolean; sources: (string | null | undefined)[] };
|
||||
|
||||
/** The way back from `head`: the push rows, newest first, until `earlier` or a commit that is not ours. */
|
||||
function walk(edges: readonly PushEdge[], earlier: string, head: string): { rows: { sha: string; row: Row }[]; complete: boolean } {
|
||||
const rows: { sha: string; row: Row }[] = [];
|
||||
let h = head;
|
||||
for (let i = 0; i < 20 && h !== earlier; i++) {
|
||||
const row = madeBy(edges, h);
|
||||
if (!row) break;
|
||||
rows.unshift({ sha: h, row });
|
||||
h = row.from;
|
||||
}
|
||||
return { rows, complete: h === earlier };
|
||||
}
|
||||
|
||||
/** The fixes the review at `head` asked for, as "file: change". */
|
||||
async function fixesAsked(db: Db, repo: string, number: number, head: string): Promise<string[]> {
|
||||
const r = await db.get(db.k.selectFrom("opus_review_history").select("fixes").where("repo", "=", repo).where("number", "=", number).where("head_oid", "=", head).where("verdict", "is not", null)
|
||||
.orderBy("at", "desc").orderBy(kx.rowid("opus_review_history"), "desc").limit(1));
|
||||
try {
|
||||
const v = JSON.parse(r?.fixes ?? "[]") as { file?: unknown; change?: unknown }[];
|
||||
return v.filter((x) => typeof x.file === "string" && typeof x.change === "string").slice(0, 8).map((x) => `${x.file}: ${x.change}`);
|
||||
} catch { return []; }
|
||||
}
|
||||
const pathOf = (rows: { sha: string; row: Row }[], complete: boolean, asked: (from: string) => string[]): OurPath => ({
|
||||
commits: rows.map(({ sha, row }) => ({ kind: row.kind, sha, from: row.from, note: row.note ?? "", fixes_meant: row.kind === "fix-up" ? asked(row.from) : [] })),
|
||||
complete, sources: rows.map((r) => r.row.source),
|
||||
});
|
||||
|
||||
/**
|
||||
* Our commits that lead from `earlier` to `head`, oldest first. `complete` is false when the way back from `head` meets a commit that
|
||||
* is not ours before it reaches `earlier` (a contributor pushed in between), so the list then holds only the newest part.
|
||||
*/
|
||||
export async function ourCommitsSince(db: Db, repo: string, number: number, earlier: string, head: string): Promise<OurPath> {
|
||||
return await walk(db, async (h) => await madeBy(db, repo, number, h), repo, number, earlier, head);
|
||||
const edges = (await loadPushEdges(db, [{ repo, number }])).get(`${repo}#${number}`) ?? [];
|
||||
const { rows, complete } = walk(edges, earlier, head);
|
||||
const froms = rows.filter((r) => r.row.kind === "fix-up").map((r) => ({ repo, number, head: r.row.from }));
|
||||
const asked = await loadFixesAsked(db, froms);
|
||||
return pathOf(rows, complete, (from) => asked.get(`${repo}#${number}@${from}`) ?? []);
|
||||
}
|
||||
|
||||
type OurPath = { commits: OurCommit[]; complete: boolean; sources: (string | null | undefined)[] };
|
||||
|
||||
/** ourCommitsSince() for many PRs: the pushes of every PR are read once, on first use. */
|
||||
export function ourCommitsLoader(db: Db): (repo: string, number: number, earlier: string, head: string) => Promise<OurPath> {
|
||||
let maps: { a: Map<string, Pushes["a"]>; b: Map<string, Awaited<ReturnType<Pushes["b"]>>>; c: Map<string, Awaited<ReturnType<Pushes["c"]>>>; d: Map<string, Awaited<ReturnType<Pushes["d"]>>> } | undefined;
|
||||
// The row each per-head read would give first: the newest for a, b and c, the first stored for d.
|
||||
const firstBy = <R extends { repo: string; number: number; to_head: string | null }>(rows: R[]): Map<string, Omit<R, "repo" | "number" | "to_head">> => {
|
||||
const m = new Map<string, Omit<R, "repo" | "number" | "to_head">>();
|
||||
for (const r of rows) {
|
||||
const k = `${r.repo}#${r.number}@${r.to_head}`;
|
||||
if (!m.has(k)) { const { repo, number, to_head, ...rest } = r; m.set(k, rest); }
|
||||
}
|
||||
return m;
|
||||
/**
|
||||
* ourCommitsSince() for many PRs of `keys`: the pushes are read once, on first use. The commits carry no `fixes_meant`: the callers
|
||||
* of the loader read only whether the path is complete and how many commits it has.
|
||||
*/
|
||||
export function ourCommitsLoader(db: Db, keys: KeySource): (repo: string, number: number, earlier: string, head: string) => Promise<OurPath> {
|
||||
let all: Map<string, PushEdge[]> | undefined;
|
||||
return async (repo, number, earlier, head) => {
|
||||
all ??= await loadPushEdges(db, keys);
|
||||
const { rows, complete } = walk(all.get(`${repo}#${number}`) ?? [], earlier, head);
|
||||
return pathOf(rows, complete, () => []);
|
||||
};
|
||||
const load = async () => (maps ??= {
|
||||
a: firstBy(await db.all(db.k.selectFrom("fixups").select(["repo", "number", "to_head", "from_head as f", "reason", "source", "carry_decision"])
|
||||
.where("state", "=", "pushed").where("to_head", "is not", null).orderBy(kx.rowid("fixups"), "desc"))),
|
||||
b: firstBy(await db.all(db.k.selectFrom("ci_fixes").select(["repo", "number", "to_head", "head as f", "reason", "kind"])
|
||||
.where("state", "=", "pushed").where("to_head", "is not", null).orderBy(kx.rowid("ci_fixes"), "desc"))),
|
||||
c: firstBy(await db.all(db.k.selectFrom("conflict_merges").select(["repo", "number", "to_head", "from_head as f", "reason"])
|
||||
.where("state", "=", "merged").where("to_head", "is not", null).orderBy(kx.rowid("conflict_merges"), "desc"))),
|
||||
d: firstBy(await db.all(db.k.selectFrom("dupe_carries").select(["repo", "number", "to_head", "from_head as f"]).$narrowType<{ f: string }>()
|
||||
.where((eb) => kx.like(db, "outcome", eb.val("pushed%"))).where("from_head", "is not", null).where("to_head", "is not", null).orderBy(kx.rowid("dupe_carries")))),
|
||||
});
|
||||
return async (repo, number, earlier, head) => await walk(db, async (h) => {
|
||||
const m = await load(), k = `${repo}#${number}@${h}`;
|
||||
return await madeFrom(db, repo, { a: m.a.get(k), b: async () => m.b.get(k), c: async () => m.c.get(k), d: async () => m.d.get(k) });
|
||||
}, repo, number, earlier, head);
|
||||
}
|
||||
|
||||
async function walk(db: Db, madeBy: (head: string) => Promise<Row | null>, repo: string, number: number, earlier: string, head: string): Promise<OurPath> {
|
||||
const commits: OurCommit[] = [], sources: (string | null | undefined)[] = [];
|
||||
let h = head, complete = false;
|
||||
for (let i = 0; i < 20 && h !== earlier; i++) {
|
||||
const row = await madeBy(h);
|
||||
if (!row) break;
|
||||
commits.unshift({ kind: row.kind, sha: h, from: row.from, note: row.note ?? "", fixes_meant: row.kind === "fix-up" ? await fixesAsked(db, repo, number, row.from) : [] });
|
||||
sources.unshift(row.source);
|
||||
h = row.from;
|
||||
}
|
||||
complete = h === earlier;
|
||||
return { commits, complete, sources };
|
||||
}
|
||||
+26
-18
@@ -3,10 +3,9 @@
|
||||
import { CARRIED } from "./carry.ts";
|
||||
import { parsePublic, storedClaims, type PublicReview } from "./opus-parse.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { loadReviewRows, loadReviewTexts, type ReviewRow, type ReviewTexts } from "../data/review/index.ts";
|
||||
|
||||
type Row = { head_oid: string; at: string; model: string | null; mode: string | null; base_head: string | null; verdict: string; sure: number | null; public_review: string | null; claims: string | null };
|
||||
const COLS = ["head_oid", "at", "model", "mode", "base_head", "verdict", "sure", "public_review", "claims"] as const;
|
||||
type Row = ReviewRow & Pick<ReviewTexts, "public_review" | "claims">;
|
||||
const MAX_STEPS = 20;
|
||||
|
||||
export type PostSource = {
|
||||
@@ -35,25 +34,34 @@ const safeJson = (s: string): unknown => {
|
||||
|
||||
/** The review to post at `head`, or null when the head has none. */
|
||||
export async function postSource(db: Db, repo: string, number: number, head: string): Promise<PostSource | null> {
|
||||
const get = (h: string) => db.get(db.k.selectFrom("opus_reviews").select(COLS).$narrowType<{ verdict: string }>()
|
||||
.where("repo", "=", repo).where("number", "=", number).where("head_oid", "=", h).where("verdict", "is not", null)
|
||||
.orderBy("at", "desc").orderBy(kx.rowid("opus_reviews"), "desc").limit(1));
|
||||
return await sourceFrom(get, head);
|
||||
return await (await postSourcesOf(db, [`${repo}#${number}`]))(repo, number, head);
|
||||
}
|
||||
|
||||
/** postSource() for the given PRs ("repo#number"), with their reviews read once. */
|
||||
/**
|
||||
* postSource() for the given PRs ("repo#number"), with their reviews read once. The public text and claims are read for each PR's
|
||||
* latest head up front and for another head (a carried review's source) when the walk reaches it.
|
||||
*/
|
||||
export async function postSourcesOf(db: Db, refs: readonly string[]): Promise<(repo: string, number: number, head: string) => Promise<PostSource | null>> {
|
||||
const rows = new Map<string, Row>();
|
||||
const rows = new Map<string, ReviewRow>();
|
||||
const texts = new Map<string, Pick<ReviewTexts, "public_review" | "claims">>();
|
||||
if (refs.length) {
|
||||
for (const r of await db.all(db.k.selectFrom(kx.refPairs(db, refs, "j")).innerJoin("opus_reviews as o", (jn) => jn.onRef("o.repo", "=", "j.repo").onRef("o.number", "=", "j.number"))
|
||||
.select(["o.repo", "o.number", ...COLS.map((c) => `o.${c}` as const)]).$narrowType<{ verdict: string }>().where("o.verdict", "is not", null)
|
||||
.orderBy("o.at", "desc").orderBy(kx.rowid("opus_reviews", "o"), "desc"))) {
|
||||
const { repo, number, ...row } = r;
|
||||
const k = `${repo}#${number}@${row.head_oid}`;
|
||||
if (!rows.has(k)) rows.set(k, row);
|
||||
const keys = refs.map((r) => ({ repo: r.slice(0, r.lastIndexOf("#")), number: Number(r.slice(r.lastIndexOf("#") + 1)) }));
|
||||
const all = await loadReviewRows(db, keys);
|
||||
const latest: { repo: string; number: number; head: string }[] = [];
|
||||
for (const [ref, list] of all) {
|
||||
for (const r of list) rows.set(`${ref}@${r.head}`, r);
|
||||
if (list[0]) latest.push({ repo: list[0].repo, number: list[0].number, head: list[0].head });
|
||||
}
|
||||
for (const [k, t] of await loadReviewTexts(db, latest)) texts.set(k, t);
|
||||
}
|
||||
return async (repo, number, head) => await sourceFrom(async (h) => rows.get(`${repo}#${number}@${h}`), head);
|
||||
const get = async (repo: string, number: number, h: string): Promise<Row | undefined> => {
|
||||
const k = `${repo}#${number}@${h}`, r = rows.get(k);
|
||||
if (!r) return undefined;
|
||||
let t = texts.get(k);
|
||||
if (!t) { t = (await loadReviewTexts(db, [{ repo, number, head: h }])).get(k) ?? { public_review: null, claims: null }; texts.set(k, t); }
|
||||
return { ...r, public_review: t.public_review, claims: t.claims };
|
||||
};
|
||||
return async (repo, number, head) => await sourceFrom((h) => get(repo, number, h), head);
|
||||
}
|
||||
|
||||
async function sourceFrom(get: (head: string) => Promise<Row | undefined>, head: string): Promise<PostSource | null> {
|
||||
@@ -69,9 +77,9 @@ async function sourceFrom(get: (head: string) => Promise<Row | undefined>, head:
|
||||
// A walk that ends on a carried row (chain over the cap, or a missing base row) has no model to name.
|
||||
const hasPublic = src.public_review !== null;
|
||||
return {
|
||||
verdict: o.verdict, sure: o.sure !== 0, sourceVerdict: src.verdict,
|
||||
verdict: o.verdict, sure: o.sure, sourceVerdict: src.verdict,
|
||||
public: hasPublic ? parsePublic(safeJson(src.public_review!)) : { summary: "", points: [] },
|
||||
hasPublic, claims: storedClaims(safeJson(src.claims ?? "[]")),
|
||||
model: isCarried(src) ? null : src.model, reviewedAt: carried ? src.head_oid : o.head_oid, fixedIn: carried ? o.head_oid : null, at: o.at,
|
||||
model: isCarried(src) ? null : src.model, reviewedAt: carried ? src.head : o.head, fixedIn: carried ? o.head : null, at: o.at,
|
||||
};
|
||||
}
|
||||
+10
-9
@@ -15,11 +15,11 @@ import { isQueueState } from "../core/plan.ts";
|
||||
import { CLI_BY, type By } from "../core/gates.ts";
|
||||
import { Client, GithubError, type Querier } from "../mirror.ts";
|
||||
import { prInfo } from "../merge/index.ts";
|
||||
import { postSource } from "./post-source.ts";
|
||||
import { postSourcesOf } from "./post-source.ts";
|
||||
import { loadPosts, saveReviewPosts } from "../data/review/index.ts";
|
||||
import { reviewBody, recommendation } from "./post-template.ts";
|
||||
import { jobItem } from "../runner/job-items.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { openDb } from "../db/open.ts";
|
||||
|
||||
const ACTOR = "review-post";
|
||||
@@ -46,19 +46,21 @@ export const defaultPostDeps = (): PostDeps => ({ querier: new Client(1000), now
|
||||
* held duplicates and items outside the pilot.
|
||||
*/
|
||||
export async function postCandidates(db: Db, repo: string): Promise<PostCandidate[]> {
|
||||
const posted = (number: number) => db.get(db.k.selectFrom("review_posts").select(["review_id", "posted_as"]).where("repo", "=", repo).where("number", "=", number));
|
||||
// A review is edited only by the lane that posted it: a NULL `posted_as` is a row from before it was recorded, written by the box account.
|
||||
const lane = (as: string | null | undefined): "legacy" | "app" => (as && as !== "legacy" ? "app" : "legacy");
|
||||
const nowLane = await githubIdentity(db) === "app" ? "app" : "legacy";
|
||||
const out: PostCandidate[] = [];
|
||||
for (const { facts: f, plan, action } of await planned(db, "post-review", { repo })) {
|
||||
const rows = await planned(db, "post-review", { repo });
|
||||
const refs = rows.map((p) => ({ repo, number: p.facts.number }));
|
||||
const [posts, source] = await Promise.all([loadPosts(db, refs), postSourcesOf(db, refs.map((r) => `${r.repo}#${r.number}`))]);
|
||||
for (const { facts: f, plan, action } of rows) {
|
||||
const head = action.head!;
|
||||
const o = await postSource(db, repo, f.number, head);
|
||||
const o = await source(repo, f.number, head);
|
||||
if (!o) continue;
|
||||
// A newer review with no public text still edits an earlier post, so the verdict line stays current.
|
||||
const pub = o.public;
|
||||
if (!pub) continue;
|
||||
const prev = await posted(f.number);
|
||||
const prev = posts.get(`${repo}#${f.number}`);
|
||||
const editId = prev && lane(prev.posted_as) === nowLane ? prev.review_id ?? null : null;
|
||||
out.push({
|
||||
repo, number: f.number, head_oid: head, editId, opusAt: o.at, model: o.model,
|
||||
@@ -115,7 +117,7 @@ export async function runReviewPost(db: Db, params: PostParams, log: (line: stri
|
||||
if (c.editId) {
|
||||
try {
|
||||
await editReview(w, d.querier, g, c.editId, REVIEW_NOTE(c), c.body);
|
||||
await db.run(db.k.updateTable("review_posts").set({ head_oid: c.head_oid, edited_at: at, opus_at: c.opusAt, posted_as: as }).where("repo", "=", repo).where("number", "=", c.number));
|
||||
await saveReviewPosts(db, [{ kind: "edited", repo, number: c.number, head: c.head_oid, edited_at: at, opus_at: c.opusAt, posted_as: as }]);
|
||||
s.edited.push(refOf(c));
|
||||
edited = true;
|
||||
} catch (e) {
|
||||
@@ -127,8 +129,7 @@ export async function runReviewPost(db: Db, params: PostParams, log: (line: stri
|
||||
const id = await postReview(w, d.querier, g, live.id, REVIEW_NOTE(c), c.body);
|
||||
if (!id) throw new Error("GitHub returned no review");
|
||||
// Every column is written: a fresh post clears the edit time of the review it replaces.
|
||||
await db.run(db.k.insertInto("review_posts").values({ repo, number: c.number, review_id: id, head_oid: c.head_oid, posted_at: at, edited_at: null, opus_at: c.opusAt, posted_as: as })
|
||||
.onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet(kx.excluded(["review_id", "head_oid", "posted_at", "edited_at", "opus_at", "posted_as"]))));
|
||||
await saveReviewPosts(db, [{ kind: "posted", repo, number: c.number, review_id: id, head: c.head_oid, posted_at: at, edited_at: null, opus_at: c.opusAt, posted_as: as }]);
|
||||
s.posted.push(refOf(c));
|
||||
}
|
||||
await jobItem(db, c.repo, c.number, `${edited ? "edited" : "posted"} review at ${c.head_oid.slice(0, 7)}`, log);
|
||||
|
||||
Reference in new issue
Block a user