diff --git a/src/decisions.ts b/src/decisions.ts index ec1895b0..c9497e58 100644 --- a/src/decisions.ts +++ b/src/decisions.ts @@ -1,17 +1,17 @@ // Decisions for people. The pipeline asks them with the CLI; only a signed-in // person on the dashboard answers them. The one command that sets answers is // the operator's bulk Backlog (`decisions backlog`), which only holds items. -import { settledBy, settledBySql } from "./settlers.ts"; -import { lockLiveSql } from "./answers/hold.ts"; +import { settledBy, settledByExpr } from "./settlers.ts"; +import { lockLiveExpr } from "./answers/hold.ts"; import { readFileSync } from "node:fs"; import { userInfo } from "node:os"; import { audit } from "./dash/audit.ts"; import { inPilot } from "./pilot.ts"; import { filterSeq, someSeq } from "./async-seq.ts"; import type { Db } from "./db/index.ts"; -import { distinctFrom } from "./db/portable.ts"; import * as kx from "./db/kx.ts"; -import type { AliasableExpression, SqlBool } from "kysely"; +import type { AliasableExpression, Expression, Insertable, SqlBool } from "kysely"; +import type { DB } from "./db/types.ts"; import { openDb } from "./db/open.ts"; export const KINDS = ["scope", "duplicate", "close", "merge", "hold", "split", "other", "backlog"] as const; @@ -86,9 +86,9 @@ export function snoozedExpr(eb: kx.AnyEb, a = "decisions"): AliasableExpression< /** A settled decision makes the drafts still proposed on its item obsolete (the ask card, the other options' drafts) and replaces its own choices. */ export async function replaceProposedCards(db: Db, repo: string | null, number: number | null, decisionId: string): Promise { if (repo && number !== null) { - await db.prepare("UPDATE main.conversation_cards SET state = 'replaced' WHERE repo = ? AND number = ? AND state = 'proposed'").run(repo, number); + await db.run(db.k.updateTable("main.conversation_cards").set({ state: "replaced" }).where("repo", "=", repo).where("number", "=", number).where("state", "=", "proposed")); // Only the choices of the decision that settled: another open decision of the item keeps its own. - await db.prepare("UPDATE main.decision_choices SET state = 'replaced' WHERE decision_id = ? AND state = 'current'").run(decisionId); + await db.run(db.k.updateTable("main.decision_choices").set({ state: "replaced" }).where("decision_id", "=", decisionId).where("state", "=", "current")); } } @@ -105,8 +105,10 @@ export const exceptionsOf = (d: DecisionRow): Exception[] => j(d.ex export const isBatch = (d: DecisionRow): boolean => d.number === null; export const reposOf = (d: DecisionRow): string[] => [...new Set(itemsOf(d).map((r) => r.repo).concat(d.repo ? [d.repo] : []))].sort(); +const decisionRows = (db: Db) => db.k.selectFrom("decisions").select(kx.cols("decisions")).$narrowType<{ kind: Kind }>(); + export async function getDecision(db: Db, id: string): Promise { - return await db.prepare("SELECT * FROM decisions WHERE id = ?").get(id) as DecisionRow | undefined; + return await db.get(decisionRows(db).where("id", "=", id)); } const ASK_FIELDS = ["kind", "repo", "number", "items", "question", "context", "facts", "options", "recommended", "recommended_reason", "public_text", "asked_at", "asked_by", "docket", "summary", "summary_by", "summary_at"] as const; @@ -117,7 +119,7 @@ const SUMMARY_FIELDS: readonly string[] = ["summary", "summary_by", "summary_at" const str = (v: unknown): string | null => (typeof v === "string" && v ? v : null); // Validates one question from the pipeline and returns the column values. -export function validateAsk(q: Record): Record { +export function validateAsk(q: Record): Record & Insertable { const err = (m: string) => new Error(`decision ${String(q.id ?? "?")}: ${m}`); if (typeof q.id !== "string" || !q.id) throw err("id is required"); if (!KINDS.includes(q.kind as Kind) || q.kind === BACKLOG_KIND) throw err(`kind must be one of ${KINDS.filter((k) => k !== BACKLOG_KIND).join(", ")}`); @@ -158,26 +160,28 @@ export function validateAsk(q: Record): Record[], inTransaction = false): Promise<{ inserted: number; updated: number }> { const rows = questions.map(validateAsk); - const cols = ["id", ...ASK_FIELDS]; - const changed = `(${distinctFrom(db, "excluded.question", "decisions.question")} OR ${distinctFrom(db, "excluded.options", "decisions.options")})`; - const keepsPick = "(decisions.prepared_at IS NOT NULL AND NOT " + changed + ")"; - // Postgres needs the existing row's columns qualified: bare names are ambiguous with `excluded`. - const set = (c: string): string => - SUMMARY_FIELDS.includes(c) ? `${c} = COALESCE(excluded.${c}, decisions.${c})` - : c === "recommended" || c === "recommended_reason" ? `${c} = CASE WHEN ${keepsPick} THEN decisions.${c} ELSE excluded.${c} END` - : `${c} = excluded.${c}`; - const stmt = db.prepare(`INSERT INTO main.decisions (${cols.join(",")}) VALUES (${cols.map((c) => `:${c}`).join(",")}) - ON CONFLICT(id) DO UPDATE SET ${ASK_FIELDS.map(set).join(", ")}, recommended_by = CASE WHEN ${keepsPick} THEN decisions.recommended_by ELSE NULL END, - prepared_at = CASE WHEN ${changed} THEN NULL ELSE decisions.prepared_at END, - recommend_failures = CASE WHEN ${changed} THEN NULL ELSE decisions.recommend_failures END, - snoozed_by = CASE WHEN ${changed} THEN NULL ELSE decisions.snoozed_by END, - snoozed_at = CASE WHEN ${changed} THEN NULL ELSE decisions.snoozed_at END`); - const exists = db.prepare("SELECT 1 FROM decisions WHERE id = ?"); let inserted = 0, updated = 0; const write = async () => { for (const r of rows) { - if (await exists.get(r.id as string)) updated++; else inserted++; - await stmt.run(r); + if (await db.get(db.k.selectFrom("decisions").select("id").where("id", "=", r.id))) updated++; else inserted++; + await db.run(db.k.insertInto("main.decisions").values(r).onConflict((oc) => oc.column("id").doUpdateSet((eb) => { + const was = (c: string) => kx.exprOf(eb, `main.decisions.${c}`); + const changed = eb.or([eb("excluded.question", "is distinct from", was("question")), eb("excluded.options", "is distinct from", was("options"))]); + const keepsPick = eb.and([eb(was("prepared_at"), "is not", null), eb.not(changed)]); + const set: Record> = {}; + for (const c of ASK_FIELDS) { + set[c] = SUMMARY_FIELDS.includes(c) ? eb.fn.coalesce(`excluded.${c}`, `main.decisions.${c}`) + : c === "recommended" || c === "recommended_reason" ? eb.case().when(keepsPick).then(was(c)).else(eb.ref(`excluded.${c}`)).end() + : eb.ref(`excluded.${c}`); + } + const clearOnChange = (c: "prepared_at" | "recommend_failures" | "snoozed_by" | "snoozed_at") => eb.case().when(changed).then(eb.lit(null)).else(was(c)).end(); + return { + ...set, + recommended_by: eb.case().when(keepsPick).then(was("recommended_by")).else(eb.lit(null)).end(), + prepared_at: clearOnChange("prepared_at"), recommend_failures: clearOnChange("recommend_failures"), + snoozed_by: clearOnChange("snoozed_by"), snoozed_at: clearOnChange("snoozed_at"), + }; + }))); } }; if (inTransaction) await write(); else await db.write(write); @@ -190,12 +194,12 @@ export async function ask(db: Db, questions: Record[], inTransa export type Actionable = { id: string; kind: Kind; repo: string | null; number: number | null; items: Ref[]; answer: string; exceptions: Exception[] }; export async function operators(db: Db): Promise> { - return new Set((await db.prepare("SELECT login FROM access WHERE role = 'operator'").all() as { login: string }[]).map((r) => r.login)); + return new Set((await db.all(db.k.selectFrom("access").select("login").where("role", "=", "operator"))).map((r) => r.login)); } export async function actionable(db: Db): Promise { - const rows = await db.prepare(`SELECT * FROM decisions WHERE answer IS NOT NULL AND answer <> '${BACKLOG.key}' AND applied_at IS NULL - AND ${settledBySql(db, "decisions")} ORDER BY answered_at`).all() as DecisionRow[]; + const rows = await db.all(decisionRows(db).where("answer", "is not", null).where("answer", "<>", BACKLOG.key).where("applied_at", "is", null) + .where((eb) => settledByExpr(db, eb, "decisions")).orderBy("answered_at", (o) => o.asc().nullsFirst())); return rows.map((d) => ({ id: d.id, kind: d.kind, repo: d.repo, number: d.number, items: itemsOf(d), answer: d.answer!, exceptions: exceptionsOf(d).map((e) => ({ repo: e.repo, number: e.number, answer: e.answer })), @@ -208,14 +212,13 @@ export type BacklogResult = { applied: boolean; decisions: { id: string; kind: K /** Open decisions in scope: of the repo when given, and, with `outsidePilot`, none of whose items is in the pilot (with no pilot set, none is outside). */ export async function backlogCandidates(db: Db, scope: BacklogScope): Promise { if (!scope.outsidePilot && !scope.repo) throw new Error("name a scope: outsidePilot or a repo"); - const rows = await db.prepare("SELECT * FROM decisions WHERE answer IS NULL ORDER BY asked_at, id").all() as DecisionRow[]; - const members = db.prepare("SELECT repo, number FROM dupe_group_items WHERE decision_id = ?"); + const rows = await db.all(decisionRows(db).where("answer", "is", null).orderBy("asked_at").orderBy("id")); return await filterSeq(rows, async (d) => { - const refs = [...itemsOf(d), ...(await members.all(d.id) as Ref[])]; + const refs = [...itemsOf(d), ...(await db.all(db.k.selectFrom("dupe_group_items").select(["repo", "number"]).where("decision_id", "=", d.id)))]; if (scope.repo && !reposOf(d).includes(scope.repo) && !refs.some((x) => x.repo === scope.repo)) return false; // Outside the scope: no item in a repo whose pipeline is on and, with an item pilot, in that pilot. // An item held for its outside author (src/outside.ts) is in scope: the hold is temporary. - return !scope.outsidePilot || !await someSeq(refs, async (x) => await inPilot(db, x.repo, x.number) || !!await db.prepare("SELECT 1 FROM main.outside_holds WHERE repo = ? AND number = ?").get(x.repo, x.number)); + return !scope.outsidePilot || !await someSeq(refs, async (x) => await inPilot(db, x.repo, x.number) || !!await db.get(db.k.selectFrom("main.outside_holds").select("repo").where("repo", "=", x.repo).where("number", "=", x.number))); }); } @@ -225,9 +228,11 @@ export async function backlogOpen(db: Db, scope: BacklogScope, by: string, apply const decisions = rows.map((d) => ({ id: d.id, kind: d.kind, repo: d.repo, number: d.number })); if (!apply) return { applied: false, decisions }; await db.write(async () => { - const set = db.prepare(`UPDATE main.decisions SET answer = ?, answer_note = NULL, exceptions = ?, answered_by = ?, answered_at = ?, adopted_opinion = NULL, snoozed_by = NULL, snoozed_at = NULL WHERE id = ? AND answer IS NULL AND NOT ${lockLiveSql("decisions")}`); for (const d of rows) { - if ((await set.run(BACKLOG.key, isBatch(d) ? "[]" : null, by, at, d.id)).changes === 1) await audit(db, by, "answer", d.id, { answer: BACKLOG.key, bulk: true }); + const set = db.k.updateTable("main.decisions") + .set({ answer: BACKLOG.key, answer_note: null, exceptions: isBatch(d) ? "[]" : null, answered_by: by, answered_at: at, adopted_opinion: null, snoozed_by: null, snoozed_at: null }) + .where("id", "=", d.id).where("answer", "is", null).where((eb) => eb.not(lockLiveExpr(db, eb, "decisions"))); + if ((await db.run(set)).changes === 1) await audit(db, by, "answer", d.id, { answer: BACKLOG.key, bulk: true }); } await audit(db, by, "backlog-bulk", null, { ...scope, count: rows.length }); }); @@ -240,16 +245,13 @@ export async function backlogOpen(db: Db, scope: BacklogScope, by: string, apply * trigger only, so it is rebuilt from the remaining stages rows. */ export function clearAskedStage(db: Db): (repo: string, number: number, decisionId: string) => Promise { - const stage = db.prepare("DELETE FROM main.stages WHERE repo = ? AND number = ? AND stage = 'needs-decision' AND note = ?"); - const latest = db.prepare("SELECT stage, at FROM stages WHERE repo = ? AND number = ? ORDER BY at DESC, rowid DESC LIMIT 1"); - const reviewed = db.prepare("SELECT 1 FROM stages WHERE repo = ? AND number = ? AND stage = 'reviewed' LIMIT 1"); - const put = db.prepare("UPDATE item_stage SET stage = ?, at = ?, reviewed = ? WHERE repo = ? AND number = ?"); - const drop = db.prepare("DELETE FROM item_stage WHERE repo = ? AND number = ?"); return async (repo, number, decisionId) => { - await stage.run(repo, number, `scope decision ${decisionId}`); - const l = await latest.get(repo, number) as { stage: string; at: string } | undefined; - if (l) await put.run(l.stage, l.at, await reviewed.get(repo, number) ? 1 : 0, repo, number); - else await drop.run(repo, number); + await db.run(db.k.deleteFrom("main.stages").where("repo", "=", repo).where("number", "=", number).where("stage", "=", "needs-decision").where("note", "=", `scope decision ${decisionId}`)); + const l = await db.get(db.k.selectFrom("stages").select(["stage", "at"]).where("repo", "=", repo).where("number", "=", number).orderBy("at", "desc").orderBy(kx.rowid("stages"), "desc").limit(1)); + if (l) { + const reviewed = await db.get(db.k.selectFrom("stages").select("stage").where("repo", "=", repo).where("number", "=", number).where("stage", "=", "reviewed").limit(1)); + await db.run(db.k.updateTable("item_stage").set({ stage: l.stage, at: l.at, reviewed: reviewed ? 1 : 0 }).where("repo", "=", repo).where("number", "=", number)); + } else await db.run(db.k.deleteFrom("item_stage").where("repo", "=", repo).where("number", "=", number)); }; } @@ -263,12 +265,12 @@ export async function withdrawOpen(db: Db, scope: BacklogScope, by: string, appl const decisions = rows.map((d) => ({ id: d.id, kind: d.kind, repo: d.repo, number: d.number })); if (!apply) return { applied: false, decisions }; await db.write(async () => { - const del = db.prepare("DELETE FROM main.decisions WHERE id = ? AND answer IS NULL"); - const side = ["decision_opinions", "decision_comments", "decision_claims"].map((t) => db.prepare(`DELETE FROM ${t} WHERE decision_id = ?`)); const clear = clearAskedStage(db); for (const d of rows) { - if ((await del.run(d.id)).changes !== 1) continue; - for (const s of side) await s.run(d.id); + if ((await db.run(db.k.deleteFrom("main.decisions").where("id", "=", d.id).where("answer", "is", null))).changes !== 1) continue; + await db.run(db.k.deleteFrom("decision_opinions").where("decision_id", "=", d.id)); + await db.run(db.k.deleteFrom("decision_comments").where("decision_id", "=", d.id)); + await db.run(db.k.deleteFrom("decision_claims").where("decision_id", "=", d.id)); await clear(d.repo!, d.number!, d.id); await audit(db, by, "withdraw", d.id, { repo: d.repo, number: d.number, question: d.question }); } @@ -280,19 +282,19 @@ const testKey = (repo: string): string => `test_repo:${repo}`; /** Test repos accept answers from the CLI (`decisions answer`), so a session can run scenarios on them without a person pressing buttons. */ export async function isTestRepo(db: Db, repo: string): Promise { - return await db.prepare("SELECT 1 FROM main.settings WHERE key = ?").get(testKey(repo)) !== undefined; + return await db.get(db.k.selectFrom("main.settings").select("key").where("key", "=", testKey(repo))) !== undefined; } export async function testRepos(db: Db): Promise { - return (await db.prepare("SELECT key FROM main.settings WHERE key LIKE 'test_repo:%' ORDER BY key").all() as { key: string }[]).map((r) => r.key.slice("test_repo:".length)); + return (await db.all(db.k.selectFrom("main.settings").select("key").where((eb) => kx.like(db, "key", eb.val("test_repo:%"))).orderBy("key"))).map((r) => r.key.slice("test_repo:".length)); } /** Returns false when nothing changed. */ export async function setTestRepo(db: Db, by: string, repo: string, on: boolean): Promise { - 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 isTestRepo(db, repo) === on) return false; - if (on) await db.prepare("INSERT INTO main.settings (key, value) VALUES (?, '1')").run(testKey(repo)); - else await db.prepare("DELETE FROM main.settings WHERE key = ?").run(testKey(repo)); + if (on) await db.run(db.k.insertInto("main.settings").values({ key: testKey(repo), value: "1" })); + else await db.run(db.k.deleteFrom("main.settings").where("key", "=", testKey(repo))); await audit(db, by, "test-repo", repo, { on }); return true; } @@ -309,7 +311,7 @@ export async function answerAsSession(db: Db, id: string, option: string, login: const { textsFor, textsHash } = await import("./dupes/texts.ts"); const texts = d.id.includes(":dupegroup:") ? await textsFor(db, id, option) : []; await applyAnswer(db, d, login, { answer: option, note, ...(texts.length && { textsHash: textsHash(texts) }) }, "cli", "session"); - await db.prepare("DELETE FROM decision_claims WHERE decision_id = ?").run(id); + await db.run(db.k.deleteFrom("decision_claims").where("decision_id", "=", id)); return (await getDecision(db, id))!; } @@ -341,7 +343,7 @@ function cardRepos(c: { repo: string; params: string }): string[] { /** Runs a proposed card as `login` the way the dashboard's button does; test repos only, operator logins only. */ export async function cardAsSession(db: Db, id: number, login: string, opts: { note?: string; skip?: number[] } = {}): Promise<{ state: string; result: string | null; error: string | null }> { - const c = await db.prepare("SELECT id, repo, number, params, state FROM main.conversation_cards WHERE id = ?").get(id) as { id: number; repo: string; number: number; params: string; state: string } | undefined; + const c = await db.get(db.k.selectFrom("main.conversation_cards").select(["id", "repo", "number", "params", "state"]).where("id", "=", id)); if (!c) throw new Error(`no card ${id}`); const outside = await filterSeq([...new Set(cardRepos(c))], async (r) => !await isTestRepo(db, r)); if (outside.length) throw new Error(`refused: ${outside.join(", ")} is not marked as a test repo (decisions test-repo REPO on)`); @@ -350,14 +352,15 @@ export async function cardAsSession(db: Db, id: number, login: string, opts: { n const { card, ran } = await doCard(db, id, login, opts); if (!ran) throw new Error(`card ${id} is ${card.state}, not proposed`); await audit(db, login, "card", `${c.repo}#${c.number}`, { card: id, source: "cli", via: "session" }); - const after = await db.prepare("SELECT state, result, error FROM main.conversation_cards WHERE id = ?").get(id) as { state: string; result: string | null; error: string | null }; - return after; + const after = await db.get(db.k.selectFrom("main.conversation_cards").select(["state", "result", "error"]).where("id", "=", id)); + return after!; } async function cardsCmd(args: string[]): Promise { const m = /^(.+)#(\d+)$/.exec(args[0] ?? ""); if (!m) throw new Error("usage: decisions cards REPO#N"); - const rows = await (await openDb()).prepare("SELECT id, kind, state, description FROM main.conversation_cards WHERE repo = ? AND number = ? ORDER BY id").all(m[1]!, Number(m[2])) as { id: number; kind: string; state: string; description: string | null }[]; + const db = await openDb(); + const rows = await db.all(db.k.selectFrom("main.conversation_cards").select(["id", "kind", "state", "description"]).where("repo", "=", m[1]!).where("number", "=", Number(m[2])).orderBy("id")); for (const r of rows) console.log(`${r.id}\t${r.kind}\t${r.state}\t${r.description ?? ""}`); } @@ -439,12 +442,11 @@ async function list(args: string[]): Promise { const which = args.includes("--all") ? "all" : args.includes("--answered") ? "answered" : "open"; const ri = args.indexOf("--repo"); const repo = ri >= 0 ? args[ri + 1] : undefined; - const where = [which === "open" ? "answer IS NULL" : which === "answered" ? "answer IS NOT NULL" : "1"]; - if (repo) where.push("(repo = :repo OR items LIKE :like)"); - const params: Record = {}; - if (repo) Object.assign(params, { repo, like: `%"repo":"${repo}"%` }); const db = await openDb(); - const rows = await db.prepare(`SELECT * FROM decisions WHERE ${where.join(" AND ")} ORDER BY asked_at`).all(params) as DecisionRow[]; + const rows = await db.all(decisionRows(db) + .$if(which === "open", (q) => q.where("answer", "is", null)).$if(which === "answered", (q) => q.where("answer", "is not", null)) + .$if(!!repo, (q) => q.where((eb) => eb.or([eb("repo", "=", repo!), kx.like(db, "items", eb.val(`%"repo":"${repo}"%`))]))) + .orderBy("asked_at")); for (const d of rows) { const target = isBatch(d) ? `batch of ${itemsOf(d).length}` : `${d.repo}#${d.number}`; const by = isBacklog(d.answer) || await settledBy(db, d) ? "" : " (not actionable: not answered by someone who settles)"; diff --git a/test/api.test.ts b/test/api.test.ts index 79d018dc..64648b63 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -188,7 +188,7 @@ describe("api", () => { test("the decisions list narrows to one item: its own decisions and the duplicate groups that list it", async () => { const boss = await signedIn("boss"); - await db.prepare("INSERT INTO dupe_group_items (decision_id, repo, number, kind, role, target, detail, base_role, base_target, head) VALUES ('photocraft:dupegroup:4', 'photocraft', 5, 'issue', 'close', 4, NULL, 'close', 4, NULL)").run(); + await db.run(db.k.insertInto("dupe_group_items").values({ decision_id: "photocraft:dupegroup:4", repo: "photocraft", number: 5, kind: "issue", role: "close", target: 4, detail: null, base_role: "close", base_target: 4, head: null })); const ids = async (n: number) => (await boss.get(`/api/decisions?repo=photocraft&number=${n}`)).decisions.map((d) => d.id).sort(); assert.deepEqual(await ids(1), [P1]); assert.deepEqual(await ids(5), ["photocraft:dupegroup:4"]); @@ -212,7 +212,7 @@ describe("api", () => { assert.equal(await audits(), before); assert.equal((await maint.get(dpath(P1))).opinions.some((o) => o.login === "viewer1"), false); assert.equal((await maint.get(dpath(P1, "/thread"))).length, 0); - assert.equal((await db.prepare("SELECT COUNT(*) AS n FROM decision_claims WHERE login = 'viewer1'").get() as { n: number }).n, 0); + assert.equal((await db.get(db.k.selectFrom("decision_claims").select((eb) => eb.fn.countAll().as("n")).where("login", "=", "viewer1")))!.n, 0); const d1 = await pal.post(dpath(P1, "/feedback"), { option: "plugin", text: `pal ${MARKER}` }); const pOp = d1.opinions.find((o) => o.login === "pal")!; @@ -326,12 +326,12 @@ describe("api", () => { assert.ok(!(await ids("open")).includes(P2)); assert.deepEqual(await ids("snoozed"), [P2]); // Feedback after the snooze wakes it. - await db.prepare("INSERT INTO decision_comments (id, decision_id, login, at, body) VALUES ('wake1', ?, 'maint', ?, 'More news')").run(P2, new Date(Date.now() + 60_000).toISOString()); + await db.run(db.k.insertInto("decision_comments").values({ id: "wake1", decision_id: P2, login: "maint", at: new Date(Date.now() + 60_000).toISOString(), body: "More news" })); assert.equal((await boss.get(dpath(P2))).snoozed, null); assert.ok((await ids("open")).includes(P2)); assert.deepEqual(await ids("snoozed"), []); // A force-push wakes it too (the earlier comment is removed so it does not wake the new snooze). - await db.prepare("DELETE FROM decision_comments WHERE id = 'wake1'").run(); + await db.run(db.k.deleteFrom("decision_comments").where("id", "=", "wake1")); await boss.post(dpath(P2, "/snooze"), { on: true }); assert.deepEqual(await ids("snoozed"), [P2]); const d2 = (await db.get(db.k.selectFrom("decisions").select(["repo", "number"]).where("id", "=", P2)))!; @@ -354,7 +354,7 @@ describe("api", () => { await boss.post(dpath(id, "/answer"), { answer: "accept", textsHash: ot.hash }, 409); const fresh = (await boss.get(dpath(id))).optionTexts[0]!; // Adopting an opinion approves the same texts, so it needs the same hash. - await db.prepare("INSERT INTO decision_opinions (id, decision_id, login, option, note, at, permission) VALUES ('op1', ?, 'maint', 'accept', NULL, 'now', 'write')").run(id); + await db.run(db.k.insertInto("decision_opinions").values({ id: "op1", decision_id: id, login: "maint", option: "accept", note: null, at: "now", permission: "write" })); await boss.post(dpath(id, "/adopt"), { opinionId: "op1" }, 409); await boss.post(dpath(id, "/adopt"), { opinionId: "op1", textsHash: ot.hash }, 409); assert.equal((await boss.post(dpath(id, "/adopt"), { opinionId: "op1", textsHash: fresh.hash })).answer, "accept"); @@ -363,7 +363,7 @@ describe("api", () => { await db.prepare("INSERT INTO dupe_group_posts (decision_id, number, step, url, at) VALUES (?, 5, 'comment', 'https://x/c', 'now')").run(id); await boss.post(dpath(id, "/undo"), undefined, 409); await db.run(db.k.updateTable("main.decisions").set({ applied_at: "now" }).where("id", "=", id)); - await db.prepare("DELETE FROM decision_opinions WHERE id = 'op1'").run(); + await db.run(db.k.deleteFrom("decision_opinions").where("id", "=", "op1")); }); test("adopt records the operator's answer and credits the opinion; opinions close once answered", async () => { diff --git a/test/cli-answer.test.ts b/test/cli-answer.test.ts index d85da3d3..c23bc853 100644 --- a/test/cli-answer.test.ts +++ b/test/cli-answer.test.ts @@ -5,12 +5,12 @@ import { connectDb } from "../src/db/open.ts"; test("a session answers only on test repos, as an operator, and the audit row says so", async () => { const db = await connectDb(":memory:"); - for (const r of ["sandbox", "real"]) await db.prepare("INSERT INTO tracked_repos (name) VALUES (?)").run(r); - await db.prepare("INSERT INTO access (login, role) VALUES ('op', 'operator'), ('viewer', 'viewer')").run(); - const ask = db.prepare("INSERT INTO decisions (id, kind, repo, number, question, options, asked_at) VALUES (?, 'scope', ?, 1, 'Q?', ?, ?)"); + for (const r of ["sandbox", "real"]) await db.run(db.k.insertInto("tracked_repos").values({ name: r })); + await db.run(db.k.insertInto("access").values([{ login: "op", role: "operator" }, { login: "viewer", role: "viewer" }])); const opts = JSON.stringify([{ key: "yes", label: "Yes" }, { key: "no", label: "No" }]); - await ask.run("d-real", "real", opts, new Date().toISOString()); - await ask.run("d-box", "sandbox", opts, new Date().toISOString()); + const ask = (id: string, repo: string) => db.run(db.k.insertInto("decisions").values({ id, kind: "scope", repo, number: 1, question: "Q?", options: opts, asked_at: new Date().toISOString() })); + await ask("d-real", "real"); + await ask("d-box", "sandbox"); await assert.rejects(answerAsSession(db, "d-real", "yes", "op"), /not marked as a test repo/); await setTestRepo(db, "cli", "sandbox", true); @@ -28,13 +28,14 @@ test("a session answers only on test repos, as an operator, and the audit row sa test("a session runs a card only when every repo it writes to is a test repo", async () => { const db = await connectDb(":memory:"); - for (const r of ["sandbox", "real"]) await db.prepare("INSERT INTO tracked_repos (name) VALUES (?)").run(r); - await db.prepare("INSERT INTO access (login, role) VALUES ('op', 'operator'), ('viewer', 'viewer')").run(); + for (const r of ["sandbox", "real"]) await db.run(db.k.insertInto("tracked_repos").values({ name: r })); + await db.run(db.k.insertInto("access").values([{ login: "op", role: "operator" }, { login: "viewer", role: "viewer" }])); await setTestRepo(db, "cli", "sandbox", true); - const card = db.prepare("INSERT INTO conversation_cards (turn_id, repo, number, kind, params, description) VALUES (1, ?, 1, 'resolution', ?, 'd') RETURNING id"); - const onReal = Number((await card.get("real", JSON.stringify({ kind: "resolution", steps: [] })) as { id: number }).id); - const toReal = Number((await card.get("sandbox", JSON.stringify({ kind: "resolution", steps: [{ kind: "transfer", to: "real" }] })) as { id: number }).id); - const local = Number((await card.get("sandbox", JSON.stringify({ kind: "resolution", steps: [] })) as { id: number }).id); + const card = async (repo: string, params: unknown) => + (await db.get(db.k.insertInto("conversation_cards").values({ turn_id: 1, repo, number: 1, kind: "resolution", params: JSON.stringify(params), description: "d" }).returning("id")))!.id; + const onReal = await card("real", { kind: "resolution", steps: [] }); + const toReal = await card("sandbox", { kind: "resolution", steps: [{ kind: "transfer", to: "real" }] }); + const local = await card("sandbox", { kind: "resolution", steps: [] }); await assert.rejects(cardAsSession(db, onReal, "op"), /real is not marked as a test repo/); await assert.rejects(cardAsSession(db, toReal, "op"), /real is not marked as a test repo/); await assert.rejects(cardAsSession(db, local, "viewer"), /not an operator/); diff --git a/test/close-reasons.test.ts b/test/close-reasons.test.ts index da3221e3..b5e38521 100644 --- a/test/close-reasons.test.ts +++ b/test/close-reasons.test.ts @@ -26,7 +26,7 @@ const dupGroup = async (w: World) => { await ask(w.db, [{ id: "app:dupegroup:7", kind: "duplicate", repo: "app", number: 7, question: "Keep #7 and close #8?", options: [{ key: "accept", label: "Use this answer" }, { key: "distinct", label: "Not duplicates" }] }]); await w.db.prepare("INSERT INTO dupe_groups (decision_id, repo, source) VALUES ('app:dupegroup:7', 'app', 'model')").run(); for (const [n, role, target] of [[7, "keep", null], [8, "close", 7]] as const) - await w.db.prepare("INSERT INTO dupe_group_items (decision_id, repo, number, kind, role, target, base_role, base_target) VALUES ('app:dupegroup:7', 'app', ?, 'issue', ?, ?, ?, ?)").run(n, role, target, role, target); + await w.db.run(w.db.k.insertInto("dupe_group_items").values({ decision_id: "app:dupegroup:7", repo: "app", number: n, kind: "issue", role, target, base_role: role, base_target: target })); await w.db.prepare("INSERT INTO dupe_group_texts (decision_id, option, number, step, text) VALUES ('app:dupegroup:7', 'accept', 8, 'close', 'Duplicate of #7.')").run(); await w.answerDecision("app:dupegroup:7", "accept"); await applyDuplicateAnswers(w.db, T1); diff --git a/test/discord-alerts.test.ts b/test/discord-alerts.test.ts index 3b7bf633..84479674 100644 --- a/test/discord-alerts.test.ts +++ b/test/discord-alerts.test.ts @@ -40,10 +40,10 @@ test("alerts: opt-in, a new decision reaches only people who may settle it, a pr await db.run(db.k.insertInto("tracked_repos").values({ name: "app", added_by: "op", added_at: T0, pipeline: 1 })); await db.run(db.k.insertInto("repos").values({ name: "app", visibility: "public" })); for (const n of [2, 3, 4, 5]) await db.run(db.k.insertInto("items").values({ repo: "app", number: n, kind: "pr", state: "OPEN", title: `PR ${n}`, body: "Body", author: "someone", head_oid: "sha", created_at: T0, updated_at: T0, labels: "[]" })); - for (const [login, role] of [["op", "operator"], ["mia", "maintainer"], ["vi", "viewer"]]) await db.prepare("INSERT INTO access (login, role) VALUES (?, ?)").run(login, role); + for (const [login, role] of [["op", "operator"], ["mia", "maintainer"], ["vi", "viewer"]]) await db.run(db.k.insertInto("access").values({ login, role })); // Mia may settle while maintainer writes are on, the app acts for her on the repo and her write permission is fresh. await setMaintainerWrites(db, true); - await db.prepare("INSERT INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + await db.run(db.k.insertInto("settings").values({ key: "github_identity", value: "app" })); // The permission was read by a dashboard visit over a day ago: the alert pass reads it again from GitHub, once. await db.run(db.k.insertInto("repo_permissions").values({ login: "mia", repo: "app", permission: "write", checked_at: new Date(Date.now() - 30 * 3_600_000).toISOString() })); const reads: string[] = []; diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 5016c33d..708b99a0 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -310,12 +310,12 @@ describe("tools", () => { assert.equal(sent.isError, false, sent.text); assert.match(sent.text, /An operator answers/); assert.match(sent.text, /\(write\)/); - const o = await db.prepare("SELECT login, option, note, permission FROM decision_opinions WHERE decision_id = ? AND retracted_at IS NULL").get(P1) as Record; + const o = await db.get(db.k.selectFrom("decision_opinions").select(["login", "option", "note", "permission"]).where("decision_id", "=", P1).where("retracted_at", "is", null)); assert.deepEqual({ ...o }, { login: "maint", option: "plugin", note: "Checked against the reference app: it is a plugin there.", permission: "write" }); const a = await db.prepare("SELECT details FROM audit WHERE action = 'opinion' AND login = 'maint' AND target = ?").get(P1) as { details: string }; assert.equal(JSON.parse(a.details).via, "mcp"); assert.equal((await call(t, "send_feedback", { id: P1, text: "Plain comment." })).isError, false); - assert.ok(await db.prepare("SELECT 1 FROM decision_comments WHERE decision_id = ? AND body = 'Plain comment.'").get(P1)); + assert.ok(await db.get(db.k.selectFrom("decision_comments").select("id").where("decision_id", "=", P1).where("body", "=", "Plain comment."))); assert.equal((await call(t, "send_feedback", { id: P1, option: "nope" })).isError, true); assert.equal((await call(t, "send_feedback", { id: P1 })).isError, true); // Nothing is answered: the pipeline's actionable list stays empty. diff --git a/test/preapproval.test.ts b/test/preapproval.test.ts index b315a69b..4421927c 100644 --- a/test/preapproval.test.ts +++ b/test/preapproval.test.ts @@ -10,6 +10,7 @@ import { operatorEditable, splitChanges } from "../src/fixup/patch.ts"; import { operatorCommentText } from "../src/fixup/template.ts"; import { scopeToTracked } from "../src/repos.ts"; import { OPERATOR, T0, world, type World } from "./world-db.ts"; +import { excluded } from "../src/db/kx.ts"; import { queueAdd, queueOrigins, queuePage } from "../src/dash/api/queue-page.ts"; import type { Req } from "../src/dash/types.ts"; import type { CachedEntry } from "../src/core/plan-read.ts"; @@ -192,11 +193,11 @@ describe("pre-approved merge", () => { await pushed(w, 40, "sha40b"); await w.synced(40, "sha40b"); await scopeToTracked(w.db); - await w.db.prepare("DELETE FROM main.tracked_repos WHERE name = 'app'").run(); + await w.db.run(w.db.k.deleteFrom("main.tracked_repos").where("name", "=", "app")); await settle(w); assert.equal((await preapprovalOf(w.db, "app", 40))?.state, "fixup"); assert.equal((await w.rows("SELECT state FROM operator_fixups WHERE number = 40"))[0]!.state, "queued"); - await w.db.prepare("INSERT INTO main.tracked_repos (name, added_by, added_at, pipeline) VALUES ('app', ?, ?, 1)").run(OPERATOR, T0); + await w.db.run(w.db.k.insertInto("main.tracked_repos").values({ name: "app", added_by: OPERATOR, added_at: T0, pipeline: 1 })); await settle(w); assert.equal((await preapprovalOf(w.db, "app", 40))?.state, "review"); }); @@ -374,13 +375,13 @@ describe("queue items: an issue", () => { describe("queue items: who may add", () => { test("an operator; a maintainer only with maintainer writes on, the app identity and write access on the repo; never a viewer", async () => { const w = await (await (await (await fresh()).pr(51)).pr(52)).pr(53); - await w.db.prepare("INSERT OR IGNORE INTO access (login, role) VALUES ('maint', 'maintainer'), ('view', 'viewer')").run(); + await w.db.run(w.db.k.insertInto("access").values([{ login: "maint", role: "maintainer" }, { login: "view", role: "viewer" }]).onConflict((oc) => oc.doNothing())); const req = (n: number, login: string, role: string, write = true) => ({ query: new URLSearchParams(), json: { item: `app#${n}` }, user: { login, role, canWrite: async () => write, canRead: async () => true } }) as unknown as Req; await assert.rejects(queueAdd(w.db, req(51, "maint", "maintainer")), (e: Error & { status?: number }) => e.status === 403); - await w.db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('maintainer_writes', '1')").run(); + await w.db.run(w.db.k.insertInto("settings").values({ key: "maintainer_writes", value: "1" }).onConflict((oc) => oc.column("key").doUpdateSet(excluded(["value"])))); await assert.rejects(queueAdd(w.db, req(51, "maint", "maintainer")), (e: Error & { status?: number }) => e.status === 403); - await w.db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + await w.db.run(w.db.k.insertInto("settings").values({ key: "github_identity", value: "app" }).onConflict((oc) => oc.column("key").doUpdateSet(excluded(["value"])))); await assert.rejects(queueAdd(w.db, req(51, "maint", "maintainer", false)), (e: Error & { status?: number }) => e.status === 403); await assert.rejects(queueAdd(w.db, req(51, "view", "viewer")), (e: Error & { status?: number }) => e.status === 403); assert.equal(await preapprovalOf(w.db, "app", 51), null); @@ -398,8 +399,8 @@ describe("queue items: who may add", () => { describe("a maintainer's pre-approval after their dashboard session", () => { test("the pipeline reads the write permission again through the app: write keeps it, a failed read keeps it for an hour, read cancels it", async () => { const w = await (await (await fresh()).pr(61)).pr(62); - await w.db.prepare("INSERT OR IGNORE INTO access (login, role) VALUES ('maint', 'maintainer')").run(); - await w.db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('maintainer_writes', '1'), ('github_identity', 'app')").run(); + await w.db.run(w.db.k.insertInto("access").values({ login: "maint", role: "maintainer" }).onConflict((oc) => oc.doNothing())); + await w.db.run(w.db.k.insertInto("settings").values([{ key: "maintainer_writes", value: "1" }, { key: "github_identity", value: "app" }]).onConflict((oc) => oc.column("key").doUpdateSet(excluded(["value"])))); const stale = new Date(Date.now() - 11 * 60_000).toISOString(); const perm = async (permission: string, at: string) => await w.db.prepare("INSERT OR REPLACE INTO repo_permissions (login, repo, permission, checked_at) VALUES ('maint', 'app', ?, ?)").run(permission, at); diff --git a/test/raw-sql-not-converted.txt b/test/raw-sql-not-converted.txt index 58a21aae..5de99cad 100644 --- a/test/raw-sql-not-converted.txt +++ b/test/raw-sql-not-converted.txt @@ -191,7 +191,6 @@ src/decide/prepared.ts src/decisions-used.ts -src/decisions.ts src/discord/alerts.ts diff --git a/test/security-cli.test.ts b/test/security-cli.test.ts index e394f484..d99accec 100644 --- a/test/security-cli.test.ts +++ b/test/security-cli.test.ts @@ -10,7 +10,7 @@ import { connectDb } from "../src/db/open.ts"; test("the session refuses a repo that is not a test repo and a login that is not an operator", async () => { const db = await connectDb(join(SCRATCH, "cli.db")); - await db.prepare("INSERT OR IGNORE INTO main.tracked_repos (name, added_by, added_at) VALUES ('repo1', 'cli', 'x')").run(); + await db.run(db.k.insertInto("main.tracked_repos").values({ name: "repo1", added_by: "cli", added_at: "x" }).onConflict((oc) => oc.doNothing())); await addLogin(db, "cli", "op1", "operator", null); await addLogin(db, "cli", "view1", "viewer", null); await assert.rejects(async () => await requireSessionOperator(db, "repo1", "op1"), /not marked as a test repo/); diff --git a/test/visibility-sec3.test.ts b/test/visibility-sec3.test.ts index f1c2ae38..31808875 100644 --- a/test/visibility-sec3.test.ts +++ b/test/visibility-sec3.test.ts @@ -66,7 +66,7 @@ before(async () => { { id: "open-app#10:scope", kind: "scope", repo: "open-app", number: 10, question: "A or B?", options: OPTS, recommended: "a", summary: "s" }, { id: "open-app#2:scope", kind: "scope", repo: "open-app", number: 2, question: "A or B?", options: OPTS, recommended: "a", summary: "s" }, ]); - await db.prepare("INSERT INTO decision_comments (id, decision_id, login, at, body) VALUES ('c1', 'open-app#2:scope', 'maint', ?, 'MARK-QUIET-COMMENT')").run(now); + await db.run(db.k.insertInto("decision_comments").values({ id: "c1", decision_id: "open-app#2:scope", login: "maint", at: now, body: "MARK-QUIET-COMMENT" })); // A model call recorded without item rows, about the hidden repo. await finishRun(db, await insertRun(db, { jobId: null, step: "dupes.compare-prs.opus", stage: 1, promptId: "p", promptVersion: "1", provider: "claude", model: "m", accountId: null, items: [], prompt: "prompt about vault#7" }), { state: "done", output: "vault" }); await addLogin(db, "cli", "boss", "operator", null);