mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-27 16:49:34 +01:00
Main CI fix step: queries built with Kysely
This commit is contained in:
1 parent
a88b4f543f
commit
9c19d3caab
6 files changed
+48
-32
No files matched your search
@@ -31,10 +31,10 @@ export async function mainFixApprovals(db: Db, repos: string[]): Promise<Map<str
|
||||
|
||||
// Returns false when nothing changed.
|
||||
export async function setMainFixApproval(db: Db, by: string, repo: string, approved: boolean): Promise<boolean> {
|
||||
if (!await db.prepare("SELECT 1 FROM main.tracked_repos WHERE name = ?").get(repo)) throw new Error(`${repo} is not tracked`);
|
||||
if (!await db.get(db.k.selectFrom("main.tracked_repos").select("name").where("name", "=", repo))) throw new Error(`${repo} is not tracked`);
|
||||
if ((await mainFixApprovalOf(db, repo) !== null) === approved) return false;
|
||||
if (approved) await db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?)").run(key(repo), JSON.stringify({ by, at: new Date().toISOString() }));
|
||||
else await db.prepare("DELETE FROM main.settings WHERE key = ?").run(key(repo));
|
||||
if (approved) await db.run(db.k.insertInto("main.settings").values({ key: key(repo), value: JSON.stringify({ by, at: new Date().toISOString() }) }));
|
||||
else await db.run(db.k.deleteFrom("main.settings").where("key", "=", key(repo)));
|
||||
await audit(db, by, approved ? "mainfix-approve" : "mainfix-revoke", repo);
|
||||
return true;
|
||||
}
|
||||
+21
-14
@@ -10,6 +10,7 @@
|
||||
// autocraft-server main-fix --repo R [--apply]
|
||||
// autocraft-server main-fix-approval [--repo R]
|
||||
import { leaseItem } from "../runner/leases.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { CLI_BY, type By } from "../core/gates.ts";
|
||||
import { guardRepo } from "../core/guard.ts";
|
||||
import { actionable, ask, getDecision } from "../decisions.ts";
|
||||
@@ -109,16 +110,21 @@ export function parseVerdicts(text: string, checks: string[]): Verdict[] | null
|
||||
// ---- rows ---------------------------------------------------------------------
|
||||
|
||||
const rowsAt = async (db: Db, repo: string, head: string): Promise<FixRow[]> =>
|
||||
await db.prepare('SELECT * FROM main_fixes WHERE repo = ? AND head_sha = ? ORDER BY "check"').all(repo, head) as FixRow[];
|
||||
await db.all(db.k.selectFrom("main_fixes").select(kx.cols("main_fixes")).$narrowType<{ verdict: MainFixVerdict }>()
|
||||
.where("repo", "=", repo).where("head_sha", "=", head).orderBy("check"));
|
||||
|
||||
async function save(db: Db, row: Omit<FixRow, "updated_at"> & { updated_at?: string }, at: string): Promise<void> {
|
||||
const { updated_at: _, ...r } = row;
|
||||
await db.prepare(`INSERT INTO main_fixes (repo, head_sha, "check", verdict, state, reason, run_id, run_url, excerpt, decision_id, issue_number, pr_number, pr_url, patch, files, lint_task, lint_round, lint_state, session, created_at, updated_at)
|
||||
VALUES (:repo, :head_sha, :check, :verdict, :state, :reason, :run_id, :run_url, :excerpt, :decision_id, :issue_number, :pr_number, :pr_url, :patch, :files, :lint_task, :lint_round, :lint_state, :session, :created_at, :at)
|
||||
ON CONFLICT (repo, head_sha, "check") DO UPDATE SET verdict = excluded.verdict, state = excluded.state, reason = excluded.reason, run_id = excluded.run_id,
|
||||
run_url = excluded.run_url, excerpt = excluded.excerpt, decision_id = excluded.decision_id, issue_number = excluded.issue_number, pr_number = excluded.pr_number, pr_url = excluded.pr_url,
|
||||
patch = excluded.patch, files = excluded.files, lint_task = excluded.lint_task, lint_round = excluded.lint_round, lint_state = excluded.lint_state, session = excluded.session, updated_at = excluded.updated_at`)
|
||||
.run({ ...r, at });
|
||||
await db.run(db.k.insertInto("main_fixes")
|
||||
.values({
|
||||
repo: r.repo, head_sha: r.head_sha, check: r.check, verdict: r.verdict, state: r.state, reason: r.reason, run_id: r.run_id, run_url: r.run_url, excerpt: r.excerpt,
|
||||
decision_id: r.decision_id, issue_number: r.issue_number, pr_number: r.pr_number, pr_url: r.pr_url, patch: r.patch, files: r.files, lint_task: r.lint_task,
|
||||
lint_round: r.lint_round, lint_state: r.lint_state, session: r.session, created_at: r.created_at, updated_at: at,
|
||||
})
|
||||
.onConflict((oc) => oc.columns(["repo", "head_sha", "check"]).doUpdateSet(kx.excluded([
|
||||
"verdict", "state", "reason", "run_id", "run_url", "excerpt", "decision_id", "issue_number", "pr_number", "pr_url",
|
||||
"patch", "files", "lint_task", "lint_round", "lint_state", "session", "updated_at",
|
||||
]))));
|
||||
}
|
||||
|
||||
const setState = async (db: Db, r: FixRow, state: string, reason: string | null, at: string, extra: Partial<FixRow> = {}): Promise<FixRow> => {
|
||||
@@ -141,7 +147,7 @@ type Current = { headSha: string; branch: string; state: string; culprit: string
|
||||
async function currentOf(db: Db, repo: string): Promise<Current | null> {
|
||||
const r = (await mainCiRepos(db)).find((x) => x.repo === repo);
|
||||
if (!r) return null;
|
||||
const changed = await db.prepare("SELECT state_changed_at AS at FROM main_ci WHERE repo = ? AND head_sha = ?").get(repo, r.headSha) as { at: string } | undefined;
|
||||
const changed = await db.get(db.k.selectFrom("main_ci").select("state_changed_at as at").where("repo", "=", repo).where("head_sha", "=", r.headSha));
|
||||
const stateChangedAt = changed?.at ?? "";
|
||||
return { headSha: r.headSha, branch: r.branch, state: r.state, culprit: r.culprit?.sha ?? r.headSha, culpritPr: r.culprit?.pr ?? null, redSince: r.redSince ?? stateChangedAt, stateChangedAt };
|
||||
}
|
||||
@@ -160,7 +166,7 @@ export async function mainFixDue(db: Db, repo: string): Promise<boolean> {
|
||||
const rows = await rowsAt(db, repo, cur.headSha);
|
||||
if (cur.state === "red") return rows.length === 0 || rows.some((r) => r.state === "rerun-requested" || r.state === "needs-fix");
|
||||
// A row left at needs-fix by an older head is closed by the next run.
|
||||
return rows.some((r) => r.state === "rerun-requested") || (cur.state !== "running" && !!await db.prepare("SELECT 1 FROM main_fixes WHERE repo = ? AND state = 'needs-fix'").get(repo));
|
||||
return rows.some((r) => r.state === "rerun-requested") || (cur.state !== "running" && !!await db.get(db.k.selectFrom("main_fixes").select("repo").where("repo", "=", repo).where("state", "=", "needs-fix").limit(1)));
|
||||
}
|
||||
|
||||
const issueTitle = (check: string): string => `Main CI fails: ${cleanLine(check, 100)}`;
|
||||
@@ -185,7 +191,7 @@ const inputOf = (repo: string, f: CiFailure): MainFixInput => ({
|
||||
/** A decision's state as the rows show it. */
|
||||
async function fromDecision(db: Db, id: string): Promise<{ state: string; issue: number | null }> {
|
||||
const d = await getDecision(db, id);
|
||||
const issue = (await db.prepare("SELECT issue_number AS n FROM main_fixes WHERE decision_id = ? AND issue_number IS NOT NULL LIMIT 1").get(id) as { n: number } | undefined)?.n ?? null;
|
||||
const issue = (await db.get(db.k.selectFrom("main_fixes").select("issue_number as n").where("decision_id", "=", id).where("issue_number", "is not", null).limit(1)))?.n ?? null;
|
||||
if (issue !== null) return { state: "issue-opened", issue };
|
||||
if (d?.answer === NOT_NOW && d.applied_at) return { state: "declined", issue: null };
|
||||
return { state: "asked", issue: null };
|
||||
@@ -268,8 +274,9 @@ async function settleReruns(db: Db, repo: string, cur: Current, deps: MainFixDep
|
||||
async function applyAnswers(db: Db, repo: string, deps: MainFixDeps, log: (l: string) => void, s: MainFixSummary, by: By): Promise<void> {
|
||||
for (const a of (await actionable(db)).filter((x) => x.kind === "other" && isMainFixDecision(repo, x.id))) {
|
||||
const at = deps.now().toISOString();
|
||||
const rows = await db.prepare("SELECT * FROM main_fixes WHERE decision_id = ? ORDER BY created_at DESC, head_sha").all(a.id) as FixRow[];
|
||||
const done = async (): Promise<void> => void await db.prepare("UPDATE main.decisions SET applied_at = ? WHERE id = ? AND applied_at IS NULL").run(at, a.id);
|
||||
const rows = await db.all(db.k.selectFrom("main_fixes").select(kx.cols("main_fixes")).$narrowType<{ verdict: MainFixVerdict }>()
|
||||
.where("decision_id", "=", a.id).orderBy("created_at", "desc").orderBy("head_sha"));
|
||||
const done = async (): Promise<void> => void await db.run(db.k.updateTable("main.decisions").set({ applied_at: at }).where("id", "=", a.id).where("applied_at", "is", null));
|
||||
if (a.answer === NOT_NOW) { for (const r of rows) await setState(db, r, "declined", r.reason, at); await done(); continue; }
|
||||
if (a.answer !== OPEN_ISSUE) continue;
|
||||
const row = rows[0];
|
||||
@@ -337,7 +344,7 @@ export const commands = {
|
||||
const repo = args[i + 1]!;
|
||||
const db = await openDb();
|
||||
if (args.includes("--apply")) { await runMainFix(db, { repo }); return; }
|
||||
for (const r of await db.prepare('SELECT head_sha, "check", verdict, state, reason FROM main_fixes WHERE repo = ? ORDER BY created_at DESC LIMIT 50').all(repo) as { head_sha: string; check: string; verdict: string; state: string; reason: string | null }[])
|
||||
for (const r of await db.all(db.k.selectFrom("main_fixes").select(["head_sha", "check", "verdict", "state", "reason"]).where("repo", "=", repo).orderBy("created_at", "desc").limit(50)))
|
||||
console.log(`${r.head_sha.slice(0, 8)}\t${r.check}\t${r.verdict}\t${r.state}\t${r.reason ?? ""}`);
|
||||
},
|
||||
},
|
||||
@@ -346,7 +353,7 @@ export const commands = {
|
||||
async run(args: string[]): Promise<void> {
|
||||
const i = args.indexOf("--repo");
|
||||
const db = await openDb();
|
||||
const repos = i >= 0 ? [args[i + 1]!] : (await db.prepare("SELECT name FROM tracked_repos ORDER BY name").all() as { name: string }[]).map((r) => r.name);
|
||||
const repos = i >= 0 ? [args[i + 1]!] : (await db.all(db.k.selectFrom("tracked_repos").select("name").orderBy("name"))).map((r) => r.name);
|
||||
for (const r of repos) {
|
||||
const a = await mainFixApprovalOf(db, r);
|
||||
console.log(`${r}\t${a ? `approved by ${a.by} at ${a.at}` : "not approved"}`);
|
||||
|
||||
+19
-7
@@ -31,6 +31,8 @@ import { MAIN_FIX_BRANCH_PREFIX } from "../mainci/index.ts";
|
||||
import type { Gh } from "../merge/safe-merge.ts";
|
||||
import { cleanLine } from "../review/post-template.ts";
|
||||
import type { FixRow } from "./index.ts";
|
||||
import type { MainFixVerdict } from "./types.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
import { optionalChecks } from "../optional-checks.ts";
|
||||
import { ownerOf, slugOf } from "../owners.ts";
|
||||
import { POOL_MAX, pool } from "../classify/run.ts";
|
||||
@@ -53,7 +55,7 @@ const PATCH_MODEL = CLAUDE_PROMPTS["cifix.patch"].models[0]!;
|
||||
|
||||
/** Whether a repo has stored patches to collect: the lint task of one ended, or its head is not the current one. */
|
||||
export async function lintReady(db: Db, repo: string, current: string): Promise<boolean> {
|
||||
const rows = await db.prepare("SELECT head_sha, lint_task FROM main_fixes WHERE repo = ? AND state = 'linting'").all(repo) as { head_sha: string; lint_task: number | null }[];
|
||||
const rows = await db.all(db.k.selectFrom("main_fixes").select(["head_sha", "lint_task"]).where("repo", "=", repo).where("state", "=", "linting"));
|
||||
return await someSeq(rows, async (r) => r.head_sha !== current || r.lint_task === null || (await readLint(db, r.lint_task)).kind !== "pending");
|
||||
}
|
||||
|
||||
@@ -99,11 +101,17 @@ export function prBody(r: { head: string; checks: { name: string; runUrl: string
|
||||
* open PR updated after the red that names a failing check or changes a file the failure names.
|
||||
*/
|
||||
async function coveringPr(c: Ctx, checks: string[], files: string[], since: string): Promise<number | null> {
|
||||
const ours = await c.db.prepare(`SELECT DISTINCT f.pr_number AS n FROM main_fixes f LEFT JOIN items i ON i.repo = f.repo AND i.number = f.pr_number
|
||||
WHERE f.repo = ? AND f.state = 'pr-opened' AND f.pr_number IS NOT NULL AND f.updated_at >= ? AND COALESCE(i.state, 'OPEN') = 'OPEN' ORDER BY f.pr_number LIMIT 1`).get(c.repo, since) as { n: number } | undefined;
|
||||
const ours = await c.db.get(c.db.k.selectFrom("main_fixes as f")
|
||||
.leftJoin("items as i", (j) => j.onRef("i.repo", "=", "f.repo").onRef("i.number", "=", "f.pr_number"))
|
||||
.select("f.pr_number as n").distinct()
|
||||
.where("f.repo", "=", c.repo).where("f.state", "=", "pr-opened").where("f.pr_number", "is not", null).where("f.updated_at", ">=", since)
|
||||
.where((eb) => eb(eb.fn.coalesce("i.state", eb.val("OPEN")), "=", "OPEN"))
|
||||
.orderBy("f.pr_number").limit(1));
|
||||
if (ours) return ours.n;
|
||||
const prs = await c.db.prepare(`SELECT number, title, body FROM items WHERE repo = ? AND kind = 'pr' AND state = 'OPEN'
|
||||
AND (COALESCE(updated_at, '') > ? OR COALESCE(created_at, '') > ?) ORDER BY number LIMIT ${MAX_PRS}`).all(c.repo, since, since) as { number: number; title: string | null; body: string | null }[];
|
||||
const prs = await c.db.all(c.db.k.selectFrom("items").select(["number", "title", "body"])
|
||||
.where("repo", "=", c.repo).where("kind", "=", "pr").where("state", "=", "OPEN")
|
||||
.where((eb) => eb.or([eb(eb.fn.coalesce("updated_at", eb.val("")), ">", since), eb(eb.fn.coalesce("created_at", eb.val("")), ">", since)]))
|
||||
.orderBy("number").limit(MAX_PRS));
|
||||
const names = checks.map((x) => x.toLowerCase());
|
||||
for (const p of prs) {
|
||||
const text = `${p.title ?? ""}\n${p.body ?? ""}`.toLowerCase();
|
||||
@@ -295,7 +303,9 @@ async function attempt(c: Ctx, rows: FixRow[], count: () => void, ledger: Sessio
|
||||
/** Takes the repo's `needs-fix` and `linting` rows head by head; `onHandled` is called once per head that reaches the model work. */
|
||||
export async function openFixPrs(c: Ctx, onHandled?: () => void): Promise<{ opened: number; skipped: number; failed: number; linting: number }> {
|
||||
const out = { opened: 0, skipped: 0, failed: 0, linting: 0 };
|
||||
const rows = await c.db.prepare("SELECT * FROM main_fixes WHERE repo = ? AND state IN ('needs-fix', 'linting') AND verdict = 'code' ORDER BY created_at, head_sha, \"check\"").all(c.repo) as FixRow[];
|
||||
const rows = await c.db.all(c.db.k.selectFrom("main_fixes").select(kx.cols("main_fixes")).$narrowType<{ verdict: MainFixVerdict }>()
|
||||
.where("repo", "=", c.repo).where("state", "in", ["needs-fix", "linting"]).where("verdict", "=", "code")
|
||||
.orderBy("created_at").orderBy("head_sha").orderBy("check"));
|
||||
const byHead = new Map<string, FixRow[]>();
|
||||
const ledger = new SessionLedger();
|
||||
for (const r of rows) (byHead.get(r.head_sha) ?? byHead.set(r.head_sha, []).get(r.head_sha)!).push(r);
|
||||
@@ -313,7 +323,9 @@ export async function openFixPrs(c: Ctx, onHandled?: () => void): Promise<{ open
|
||||
if (!release) return;
|
||||
try {
|
||||
// Another job may have moved the rows on before the lease was taken.
|
||||
const now = await c.db.prepare("SELECT * FROM main_fixes WHERE repo = ? AND head_sha = ? AND state IN ('needs-fix', 'linting') AND verdict = 'code' ORDER BY created_at, \"check\"").all(c.repo, group[0]!.head_sha) as FixRow[];
|
||||
const now = await c.db.all(c.db.k.selectFrom("main_fixes").select(kx.cols("main_fixes")).$narrowType<{ verdict: MainFixVerdict }>()
|
||||
.where("repo", "=", c.repo).where("head_sha", "=", group[0]!.head_sha).where("state", "in", ["needs-fix", "linting"]).where("verdict", "=", "code")
|
||||
.orderBy("created_at").orderBy("check"));
|
||||
if (!now.length) return;
|
||||
// Rows that turned red after the patch was stored wait until it is collected.
|
||||
const stored = now.filter((r) => r.state === "linting");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// What AutoCraft is doing about a red default branch, in words for the Main CI page. Read-only.
|
||||
import { mainFixApprovals } from "./approval.ts";
|
||||
import type { Db } from "../db/index.ts";
|
||||
import * as kx from "../db/kx.ts";
|
||||
|
||||
/** Shown first when a head has rows in several states: what needs a person comes before what is running. */
|
||||
const ORDER = ["fix-failed", "needs-fix", "linting", "asked", "pr-opened", "rerun-requested", "issue-opened", "declined", "nothing-to-do", "rerun-passed"] as const;
|
||||
@@ -27,8 +28,8 @@ export async function autocraftText(db: Db, repo: string, headSha: string, state
|
||||
export async function autocraftTexts(db: Db, heads: { repo: string; headSha: string; state: string }[]): Promise<Map<string, string | null>> {
|
||||
const out = new Map<string, string | null>();
|
||||
if (!heads.length) return out;
|
||||
const rows = await db.prepare("SELECT repo, head_sha, state, pr_number FROM main_fixes WHERE (repo, head_sha) IN (SELECT value ->> 0, value ->> 1 FROM json_each(?))")
|
||||
.all(JSON.stringify(heads.map((h) => [h.repo, h.headSha]))) as { repo: string; head_sha: string; state: string; pr_number: number | null }[];
|
||||
const rows = await db.all(db.k.selectFrom("main_fixes").select(["repo", "head_sha", "state", "pr_number"])
|
||||
.where(kx.tupleIn(db, ["repo", "head_sha"], heads.map((h) => [h.repo, h.headSha]), ["text", "text"])));
|
||||
const fixes = new Map<string, typeof rows>();
|
||||
for (const r of rows) (fixes.get(`${r.repo}\0${r.head_sha}`) ?? fixes.set(`${r.repo}\0${r.head_sha}`, []).get(`${r.repo}\0${r.head_sha}`)!).push(r);
|
||||
const first = (k: string) => { const states = new Set((fixes.get(k) ?? []).map((r) => r.state)); return ORDER.find((s) => states.has(s)); };
|
||||
|
||||
@@ -43,7 +43,7 @@ async function world() {
|
||||
const db = await connectDb(join(mkdtempSync(join(dir, "db-")), "t.db"));
|
||||
await db.run(db.k.insertInto("tracked_repos").values({ name: "app", added_by: "op", added_at: T0, pipeline: 1 }));
|
||||
await setMainFixApproval(db, "op", "app", true);
|
||||
await db.prepare("INSERT INTO main_ci (repo, head_sha, branch, state, failing, checks, first_seen_at, state_changed_at, updated_at) VALUES ('app', ?, 'main', 'red', '[]', '[]', ?, ?, ?)").run(head, T0, T0, T0);
|
||||
await db.run(db.k.insertInto("main_ci").values({ repo: "app", head_sha: head, branch: "main", state: "red", failing: "[]", checks: "[]", first_seen_at: T0, state_changed_at: T0, updated_at: T0 }));
|
||||
const row: FixRow = { repo: "app", head_sha: head, check: "gate / test", verdict: "code", state: "needs-fix", reason: null, run_id: 11, run_url: null, excerpt: null, decision_id: null, issue_number: null, pr_number: null, pr_url: null, patch: null, files: null, lint_task: null, lint_round: null, lint_state: null, session: null, created_at: T0, updated_at: T0 };
|
||||
await onCodeVerdict(db, row, "a compile error", T0);
|
||||
|
||||
@@ -95,7 +95,7 @@ async function finishLint(db: Db, clippy: string): Promise<number> {
|
||||
}
|
||||
const CLEAN = '{"reason":"build-finished","success":true}\n';
|
||||
const FINDING = JSON.stringify({ reason: "compiler-message", message: { level: "warning", message: "redundant", code: { code: "clippy::redundant_clone" }, spans: [{ file_name: "src/lib.rs", line_start: 5, line_end: 5, is_primary: true }], rendered: "warning: redundant\n" } });
|
||||
const stateOf = async (db: Db) => (await db.prepare("SELECT state, lint_round AS round, pr_number AS pr, reason FROM main_fixes").get() as { state: string; round: number | null; pr: number | null; reason: string | null });
|
||||
const stateOf = async (db: Db) => (await db.get(db.k.selectFrom("main_fixes").select(["state", "lint_round as round", "pr_number as pr", "reason"])))!;
|
||||
|
||||
test("the step stores the patch and ends; the next run opens the PR once lint is clean", async () => {
|
||||
const w = await world();
|
||||
|
||||
@@ -295,13 +295,9 @@ src/live.ts
|
||||
src/liveness.ts
|
||||
|
||||
|
||||
src/mainfix/approval.ts
|
||||
|
||||
src/mainfix/index.ts
|
||||
|
||||
src/mainfix/pr.ts
|
||||
|
||||
src/mainfix/status.ts
|
||||
|
||||
src/memory/retrieve.ts
|
||||
|
||||
|
||||
Reference in new issue
Block a user