From e8bffa8f393c51a2eda5d6981292efd99122a75a Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:53:18 +0000 Subject: [PATCH 1/2] Dashboard SQL on both dialects: decisions and needs builders take the handle, JSON idioms through portable helpers, index hints and NOCASE through helpers, RETURNING for new ids, test upserts --- src/access.ts | 9 +++--- src/act/dupe-groups.ts | 4 +-- src/agents/runs.ts | 4 +-- src/answers/hold.ts | 17 ++++++----- src/classify/settled.ts | 3 +- src/core/facts.ts | 2 +- src/dash/api/batch-page.ts | 3 +- src/dash/api/decisions.ts | 59 ++++++++++++++++++------------------ src/dash/api/home.ts | 4 +-- src/dash/api/index.ts | 4 +-- src/dash/api/items.ts | 5 +-- src/dash/api/needs.ts | 50 ++++++++++++++++-------------- src/dash/api/queue-page.ts | 5 +-- src/dash/api/stats.ts | 11 ++++--- src/dash/mcp/index.ts | 5 +-- src/dash/mcp/tokens.ts | 3 +- src/db/portable.ts | 22 ++++++++++++++ src/decisions.ts | 20 ++++++------ src/discord/file-issue.ts | 5 +-- src/dupes/decide.ts | 2 +- src/merge/batch-store.ts | 6 ++-- src/merge/verify-override.ts | 2 +- src/mirror.ts | 2 +- src/review/candidates.ts | 6 ++-- src/review/diff.ts | 2 +- src/settlers.ts | 37 ++++++++++++++-------- test/api.test.ts | 12 ++++---- test/github-app.test.ts | 6 ++-- test/live-board.test.ts | 6 ++-- test/mcp-queue.test.ts | 4 +-- test/mcp.test.ts | 2 +- 31 files changed, 188 insertions(+), 134 deletions(-) diff --git a/src/access.ts b/src/access.ts index d63616ff0..1334ccab7 100644 --- a/src/access.ts +++ b/src/access.ts @@ -6,6 +6,7 @@ import type { Role } from "./dash/types.ts"; import { endAnswerTokens, endTokens } from "./dash/mcp/tokens.ts"; import { dropUserTokens } from "./dash/server/user-tokens.ts"; import type { Db } from "./db/index.ts"; +import { ciEq, nocase } from "./db/portable.ts"; import { openDb } from "./db/open.ts"; export type AccessRow = { login: string; role: Role; added_by: string | null; added_at: string | null; note: string | null }; @@ -18,7 +19,7 @@ export const isRole = (v: unknown): v is Role => (ROLES as readonly unknown[]).i export class AccessError extends Error {} export async function listAccess(db: Db): Promise { - return await db.prepare("SELECT login, role, added_by, added_at, note FROM access ORDER BY login COLLATE NOCASE").all() as AccessRow[]; + return await db.prepare(`SELECT login, role, added_by, added_at, note FROM access ORDER BY ${nocase(db, "login")}`).all() as AccessRow[]; } // The access entry's GitHub id is stored when the entry is added (or, for an @@ -47,7 +48,7 @@ async function endSessions(db: Db, login: string): Promise { /** Org setup links are an operator's: they end when their creator stops being one (the link flow also checks the creator's role). */ async function endSetupLinks(db: Db, login: string): Promise { - return Number((await db.prepare("UPDATE github_setup_links SET revoked_at = ? WHERE created_by = ? COLLATE NOCASE AND revoked_at IS NULL AND used_at IS NULL") + return Number((await db.prepare(`UPDATE github_setup_links SET revoked_at = ? WHERE ${ciEq(db, "created_by", "?")} AND revoked_at IS NULL AND used_at IS NULL`) .run(new Date().toISOString(), login)).changes); } @@ -91,8 +92,8 @@ export async function removeLogin(db: Db, by: string, login: string, opts: Acces const userTokens = await dropUserTokens(db, row.login); // A linked Discord account acts as the login (presses, alerts); the delete trigger takes the alert opt-ins with the links. // Matched in any letter case: the access list is, and the removal may name the login in another case than the link stores. - const discordLinks = Number((await db.prepare("DELETE FROM discord_links WHERE login = ? COLLATE NOCASE").run(row.login)).changes); - await db.prepare("DELETE FROM discord_link_codes WHERE login = ? COLLATE NOCASE").run(row.login); + const discordLinks = Number((await db.prepare(`DELETE FROM discord_links WHERE ${ciEq(db, "login", "?")}`).run(row.login)).changes); + await db.prepare(`DELETE FROM discord_link_codes WHERE ${ciEq(db, "login", "?")}`).run(row.login); const setupLinks = await endSetupLinks(db, row.login); await audit(db, by, "access-remove", row.login, { role: row.role, sessions, ...(mcpTokens ? { mcpTokens } : {}), ...(userTokens ? { userTokens } : {}), ...(discordLinks ? { discordLinks } : {}), ...(setupLinks ? { setupLinks } : {}) }); }); diff --git a/src/act/dupe-groups.ts b/src/act/dupe-groups.ts index 41239c4f3..7cd74aa78 100644 --- a/src/act/dupe-groups.ts +++ b/src/act/dupe-groups.ts @@ -46,14 +46,14 @@ type Decision = { id: string; answer: string }; export async function groupDecisionsToAct(db: Db, repo: string): Promise { return await db.prepare(`SELECT d.id, d.answer FROM decisions d JOIN dupe_groups g ON g.decision_id = d.id WHERE d.kind = 'duplicate' AND d.repo = ? AND d.answer IS NOT NULL AND d.answer NOT IN ('distinct', 'backlog') AND d.applied_at IS NULL - AND g.applied_answer = d.answer AND ${settledBySql("d")} ORDER BY d.answered_at`).all(repo) as Decision[]; + AND g.applied_answer = d.answer AND ${settledBySql(db, "d")} ORDER BY d.answered_at`).all(repo) as Decision[]; } /** Members the act step still has to close, over all repos: close-role members of the decisions above (as actOnGroups selects its closers) with no close record yet. The planner lists an act action for each. */ export async function groupClosersPending(db: Db): Promise<{ decisionId: string; repo: string; number: number }[]> { const rows = await db.prepare(`SELECT d.id, d.repo, gi.number FROM decisions d JOIN dupe_groups g ON g.decision_id = d.id JOIN dupe_group_items gi ON gi.decision_id = d.id WHERE d.kind = 'duplicate' AND d.repo IS NOT NULL AND d.id LIKE '%:dupegroup:%' AND d.answer IS NOT NULL AND d.answer NOT IN ('distinct', 'backlog') AND d.applied_at IS NULL - AND g.applied_answer = d.answer AND ${settledBySql("d")} AND gi.role = 'close' + AND g.applied_answer = d.answer AND ${settledBySql(db, "d")} AND gi.role = 'close' AND NOT EXISTS (SELECT 1 FROM dupe_group_posts p WHERE p.decision_id = d.id AND p.number = gi.number AND p.step = 'close') ORDER BY d.answered_at, gi.number`).all() as { id: string; repo: string; number: number }[]; return (await filterSeq(rows, async (r) => await inPilot(db, r.repo, r.number) && !await backlogHeld(db, r.repo, r.number))).map((r) => ({ decisionId: r.id, repo: r.repo, number: r.number })); diff --git a/src/agents/runs.ts b/src/agents/runs.ts index 543518610..107cd1af7 100644 --- a/src/agents/runs.ts +++ b/src/agents/runs.ts @@ -54,8 +54,8 @@ export const packPrompt = (prompt: string): Uint8Array => packText(scrub(prompt. export async function insertRun(db: Db, s: RunStart): Promise { const refs = s.items.slice(0, MAX_ITEM_REFS); const id = Number((await db.prepare(`INSERT INTO agent_runs (job_id, step, stage, prompt_id, prompt_version, provider, model, account_id, items, item_count, state, started_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?)`) - .run(s.jobId, s.step, s.stage, s.promptId, s.promptVersion, s.provider, s.model, s.accountId, JSON.stringify(refs), s.items.length, now())).lastInsertRowid); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?) RETURNING id`) + .get(s.jobId, s.step, s.stage, s.promptId, s.promptVersion, s.provider, s.model, s.accountId, JSON.stringify(refs), s.items.length, now()) as { id: number }).id); const ins = db.prepare("INSERT OR IGNORE INTO agent_run_items (run_id, repo, number) VALUES (?, ?, ?)"); for (const r of s.items) await ins.run(id, r.repo, r.number); await db.prepare("INSERT INTO agent_run_texts (run_id, prompt) VALUES (?, ?)").run(id, typeof s.prompt === "string" ? packPrompt(s.prompt) : s.prompt); diff --git a/src/answers/hold.ts b/src/answers/hold.ts index 58cdd0698..7703a6880 100644 --- a/src/answers/hold.ts +++ b/src/answers/hold.ts @@ -7,7 +7,8 @@ import { settledBy, settledBySql } from "../settlers.ts"; import { writeEffect } from "../act/index.ts"; import { queuePlace } from "../conversations/queue.ts"; import { findSeq } from "../async-seq.ts"; -import type { Db } from "../db/index.ts"; +import type { Db, Dialect } from "../db/index.ts"; +import { ciEq, quote } from "../db/portable.ts"; export const SETTLING = "settling"; export const DISPUTED = "disputed"; @@ -108,7 +109,7 @@ export async function disputeOn(db: Db, repo: string, number: number): Promise { const r = await db.prepare(`UPDATE main.decisions SET exec_state = ?, exec_reason = NULL, dispute_by = ?, dispute_reason = ?, dispute_at = ? - WHERE id = ? AND answer IS NOT NULL AND applied_at IS NULL AND answer <> ? AND answered_by <> ? COLLATE NOCASE + WHERE id = ? AND answer IS NOT NULL AND applied_at IS NULL AND answer <> ? AND NOT (${ciEq(db, "answered_by", "?")}) AND (exec_state IS NULL OR exec_state IN ('pending', 'waiting-token', 'waiting-permission', 'failed'))`).run(DISPUTED, by, reason, at, id, BACKLOG.key, by); if (r.changes !== 1) return false; await audit(db, by, "dispute", id, { reason }); @@ -123,14 +124,16 @@ export async function clearDispute(db: Db, id: string): Promise { * SQL (decisions unaliased): an answered, unapplied decision the viewer has to look at: a disputed one (the answerer, or any operator), or one an * operator has to reassign because its answerer no longer settles and its option writes to GitHub. */ -export function heldOpenSql(login: string, operator: boolean): string { - const me = `'${login.replace(/'/g, "''")}'`; +export function heldOpenSql(d: Dialect | { readonly dialect: Dialect }, login: string, operator: boolean): string { + const me = quote(login); + const pg = (typeof d === "string" ? d : d.dialect) === "postgres"; + const yes = pg ? "TRUE" : "1", no = pg ? "FALSE" : "0"; const writes = `((decisions.answer = 'close' AND decisions.kind IN ('scope', 'close', 'duplicate', 'merge', 'hold')) OR (decisions.answer = 'merge' AND decisions.kind = 'merge') OR (decisions.kind = 'duplicate' AND (decisions.answer = 'accept' OR decisions.answer LIKE 'keep:%')))`; // An open decision whose queued press someone disputed: the presser and operators look at it. const queuedDispute = `(decisions.answer IS NULL AND decisions.exec_state = '${SETTLING}' AND EXISTS (SELECT 1 FROM main.conversation_cards hc WHERE hc.state = 'queued' AND hc.dispute_by IS NOT NULL - AND decisions.exec_reason LIKE hc.id || ':%' AND ${operator ? "1" : `hc.acted_by = ${me} COLLATE NOCASE`}))`; + AND decisions.exec_reason LIKE hc.id || ':%' AND ${operator ? yes : ciEq(d, "hc.acted_by", me)}))`; return `(${queuedDispute} OR decisions.answer IS NOT NULL AND decisions.applied_at IS NULL AND decisions.answer <> '${BACKLOG.key}' AND decisions.id NOT LIKE '%~replaced-%' - AND ((decisions.exec_state = '${DISPUTED}' AND ${operator ? "1" : `decisions.answered_by = ${me} COLLATE NOCASE`}) - OR (${operator ? "1" : "0"} AND decisions.exec_state IS NOT '${DISPUTED}' AND decisions.answered_by IS NOT NULL AND decisions.answered_by <> 'pipeline' AND ${writes} AND NOT ${settledBySql("decisions")})))`; + AND ((decisions.exec_state = '${DISPUTED}' AND ${operator ? yes : ciEq(d, "decisions.answered_by", me)}) + OR (${operator ? yes : no} AND decisions.exec_state IS DISTINCT FROM '${DISPUTED}' AND decisions.answered_by IS NOT NULL AND decisions.answered_by <> 'pipeline' AND ${writes} AND NOT ${settledBySql(d, "decisions")})))`; } diff --git a/src/classify/settled.ts b/src/classify/settled.ts index c025bbfa3..41c4ae4f1 100644 --- a/src/classify/settled.ts +++ b/src/classify/settled.ts @@ -22,6 +22,7 @@ import { audit } from "../dash/audit.ts"; import { REFEREE_MAX_FAILURES } from "../core/item-rules.ts"; import { flagBand, JEV_NEEDS_DECISION_YES, JEV_SECURITY_YES } from "./parse.ts"; import type { Db } from "../db/index.ts"; +import { indexedBy } from "../db/portable.ts"; export const SURE = 0.9; @@ -107,7 +108,7 @@ function settleLabel(jev: (Verdict & { top: number | null }) | null, haiku: Verd /** The run of the newest Jev or Haiku-alone verdict: two indexed lookups, the newer wins. */ export async function newestVerdictRun(db: Db): Promise { const jev = await db.prepare("SELECT run_id, at FROM classifications WHERE classifier = 'jev' ORDER BY at DESC LIMIT 1").get() as { run_id: string; at: string } | undefined; - const alone = await db.prepare("SELECT run_id, at FROM main.classifications INDEXED BY classifications_alone WHERE classifier = 'haiku' AND input_hash IS NOT NULL ORDER BY at DESC LIMIT 1").get() as { run_id: string; at: string } | undefined; + const alone = await db.prepare(`SELECT run_id, at FROM main.classifications${indexedBy(db, "classifications_alone")} WHERE classifier = 'haiku' AND input_hash IS NOT NULL ORDER BY at DESC LIMIT 1`).get() as { run_id: string; at: string } | undefined; return (alone && (!jev || alone.at > jev.at) ? alone : jev)?.run_id ?? null; } diff --git a/src/core/facts.ts b/src/core/facts.ts index e5da505de..c2503a1d1 100644 --- a/src/core/facts.ts +++ b/src/core/facts.ts @@ -272,7 +272,7 @@ export async function loadPrFacts(db: Db, opts: LoadOptions = {}): Promise("SELECT DISTINCT d.repo || '#' || d.number AS k FROM decisions d WHERE d.kind = 'merge' AND d.answer IS NULL AND d.id NOT LIKE '%~replaced-%' /*narrow*/", "d"); // The settled Merge answers, by decision id: when they were given. - const mergeAnsweredAt = new Map((await db.prepare(`SELECT id, answered_at FROM decisions WHERE kind = 'merge' AND answer = 'merge' AND answered_at IS NOT NULL AND ${settledBySql("decisions")}`).all() as { id: string; answered_at: string }[]).map((d) => [d.id, d.answered_at])); + const mergeAnsweredAt = new Map((await db.prepare(`SELECT id, answered_at FROM decisions WHERE kind = 'merge' AND answer = 'merge' AND answered_at IS NOT NULL AND ${settledBySql(db, "decisions")}`).all() as { id: string; answered_at: string }[]).map((d) => [d.id, d.answered_at])); const answeredAfter = (id: string, at: string): boolean => { const a = mergeAnsweredAt.get(id); return a !== undefined && a > at; }; const pushChain = await pushChainOf(db); const ownHead = await ownHeadOf(db); diff --git a/src/dash/api/batch-page.ts b/src/dash/api/batch-page.ts index 92b1c8043..203b79e36 100644 --- a/src/dash/api/batch-page.ts +++ b/src/dash/api/batch-page.ts @@ -12,6 +12,7 @@ import { needVisible } from "./visible.ts"; import { ownerOf } from "../../owners.ts"; import { mapSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; +import { jsonText } from "../../db/portable.ts"; type AuditRow = { rowid: number; at: string; login: string; action: string; target: string | null; details: string | null }; @@ -55,7 +56,7 @@ export async function batchDetail(db: Db, id: number, staff: boolean): Promise(s: string | null | undefined, d: T): T => { if (!s) return d; @@ -145,7 +146,7 @@ export async function relatedIndex(db: Db): Promise { duplicatedBy.set(k, [...(duplicatedBy.get(k) ?? []), r.number]); } const linkedBy = new Map(); - for (const p of await db.prepare("SELECT repo, number, closing_issues FROM main.items INDEXED BY items_closing WHERE kind = 'pr' AND closing_issues IS NOT NULL AND closing_issues <> '[]'").all() as { repo: string; number: number; closing_issues: string }[]) + for (const p of await db.prepare(`SELECT repo, number, closing_issues FROM main.items${indexedBy(db, "items_closing")} WHERE kind = 'pr' AND closing_issues IS NOT NULL AND closing_issues <> '[]'`).all() as { repo: string; number: number; closing_issues: string }[]) for (const x of json(p.closing_issues, [])) if (typeof x === "number") linkedBy.set(`${p.repo}#${x}`, [...(linkedBy.get(`${p.repo}#${x}`) ?? []), p.number]); return { duplicatedBy, linkedBy }; } @@ -319,7 +320,7 @@ export async function decisionPage(db: Db, ds: DecisionRow[], viewer: Viewer): P const ids = JSON.stringify(ds.map((d) => d.id)); const singles = ds.filter((d) => !isBatch(d)).map((d) => ({ repo: d.repo!, number: d.number! })); const refs = JSON.stringify(singles.map((r) => [r.repo, r.number])); - const inRefs = (repo: string, number: string) => `(${repo}, ${number}) IN (SELECT value ->> 0, value ->> 1 FROM json_each(:refs))`; + const inRefs = (repo: string, number: string) => inTuples(db, [repo, number], ":refs", ["text", "bigint"]); const rows = async (sql: string, args: Record): Promise => await db.prepare(sql).all(args) as T[]; const itemSql = "SELECT repo, number, title, body, kind, state, closing_issues FROM items WHERE "; const items = new Map(); @@ -340,16 +341,16 @@ export async function decisionPage(db: Db, ds: DecisionRow[], viewer: Viewer): P const batchRefs = ds.filter(isBatch).flatMap((d) => itemsOf(d)); if (batchRefs.length) page.shown = await shownMap(db, batchRefs); for (const o of await rows(`SELECT decision_id, id, login, option, note, at, permission, via FROM decision_opinions - WHERE decision_id IN (SELECT value FROM json_each(:ids)) AND retracted_at IS NULL ORDER BY decision_id, at DESC`, { ids })) { + WHERE ${inList(db, "decision_id", ":ids")} AND retracted_at IS NULL ORDER BY decision_id, at DESC`, { ids })) { const { decision_id, ...op } = o; pushTo(page.opinions, decision_id, op); } const adopted = ds.flatMap((d) => (d.adopted_opinion ? [d.adopted_opinion] : [])); - if (adopted.length) for (const o of await rows("SELECT id, login, option, note, at, permission, via FROM decision_opinions WHERE id IN (SELECT value FROM json_each(:ids))", { ids: JSON.stringify(adopted) })) page.adopted.set(o.id, o); - for (const c of await rows(`SELECT decision_id, login, since FROM decision_claims WHERE decision_id IN (SELECT value FROM json_each(:ids)) AND at > :fresh AND login <> :me ORDER BY decision_id, at DESC`, + if (adopted.length) for (const o of await rows(`SELECT id, login, option, note, at, permission, via FROM decision_opinions WHERE ${inList(db, "id", ":ids")}`, { ids: JSON.stringify(adopted) })) page.adopted.set(o.id, o); + for (const c of await rows(`SELECT decision_id, login, since FROM decision_claims WHERE ${inList(db, "decision_id", ":ids")} AND at > :fresh AND login <> :me ORDER BY decision_id, at DESC`, { ids, fresh: new Date(Date.now() - CLAIM_TTL).toISOString(), me: viewer.login })) if (!page.claims.has(c.decision_id)) page.claims.set(c.decision_id, { login: c.login, since: c.since }); - for (const c of await rows<{ decision_id: string; n: number }>("SELECT decision_id, COUNT(*) AS n FROM decision_comments WHERE decision_id IN (SELECT value FROM json_each(:ids)) GROUP BY decision_id", { ids })) page.comments.set(c.decision_id, c.n); + for (const c of await rows<{ decision_id: string; n: number }>(`SELECT decision_id, COUNT(*) AS n FROM decision_comments WHERE ${inList(db, "decision_id", ":ids")} GROUP BY decision_id`, { ids })) page.comments.set(c.decision_id, c.n); if (singles.length) { // In the primary key's order within an item, as the one-item read walks it. for (const c of await rows(`SELECT repo, number, classifier, at, type_label, want, reference, reason, dup_of FROM classifications @@ -363,11 +364,11 @@ export async function decisionPage(db: Db, ds: DecisionRow[], viewer: Viewer): P } const heads = ds.flatMap((d) => { const h = riskHead(d); return h ? [[d.repo!, d.number!, h]] : []; }); if (heads.length) for (const o of await rows<{ repo: string; number: number; head_oid: string; risks: string | null }>(`SELECT repo, number, head_oid, risks FROM opus_reviews - WHERE (repo, number, head_oid) IN (SELECT value ->> 0, value ->> 1, value ->> 2 FROM json_each(:heads)) AND verdict IS NOT NULL`, { heads: JSON.stringify(heads) })) + WHERE ${inTuples(db, ["repo", "number", "head_oid"], ":heads", ["text", "bigint", "text"])} AND verdict IS NOT NULL`, { heads: JSON.stringify(heads) })) page.risks.set(`${o.repo}#${o.number}@${o.head_oid}`, { risks: o.risks }); const groups = ds.filter(isGroup).map((d) => d.id); if (groups.length) { - for (const g of await rows(`${GROUP_SQL} WHERE gi.decision_id IN (SELECT value FROM json_each(:ids))`, { ids: JSON.stringify(groups) })) { + for (const g of await rows(`${GROUP_SQL} WHERE ${inList(db, "gi.decision_id", ":ids")}`, { ids: JSON.stringify(groups) })) { const { decision_id, ...row } = g; pushTo(page.groups, decision_id, row); } @@ -375,7 +376,7 @@ export async function decisionPage(db: Db, ds: DecisionRow[], viewer: Viewer): P } if (!viewer.staff) { page.quiet = await quietFixPrs(db); - for (const m of await rows<{ decision_id: string; repo: string; number: number }>("SELECT decision_id, repo, number FROM dupe_group_items WHERE decision_id IN (SELECT value FROM json_each(:ids))", { ids })) + for (const m of await rows<{ decision_id: string; repo: string; number: number }>(`SELECT decision_id, repo, number FROM dupe_group_items WHERE ${inList(db, "decision_id", ":ids")}`, { ids })) pushTo(page.members, m.decision_id, { repo: m.repo, number: m.number }); } return page; @@ -454,35 +455,35 @@ export async function toDecision(db: Db, d: DecisionRow, viewer: Viewer): Promis const list = (req: Req, key: string): string[] => req.query.getAll(key).flatMap((v) => v.split(",")).map((s) => s.trim()).filter(Boolean); // Decisions touching any of the given repos: the decision's own repo, or an item of a batch. -export function inRepos(prefix: string, repos: string[], params: Record): string { +export function inRepos(db: Db, prefix: string, repos: string[], params: Record): string { const names = repos.map((r, k) => { params[`${prefix}${k}`] = r; return `:${prefix}${k}`; }).join(",") || "NULL"; - return `(COALESCE(repo IN (${names}), 0) OR EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(items) THEN items ELSE '[]' END) j - WHERE json_extract(j.value, '$.repo') IN (${names})))`; + return `(COALESCE(repo IN (${names}), FALSE) OR EXISTS (SELECT 1 FROM ${jsonEach(db, `CASE WHEN ${jsonValid(db, "items")} THEN items ELSE '[]' END`, "j")} + WHERE ${jsonText(db, "j.value", "$.repo")} IN (${names})))`; } /** SQL that leaves out decisions touching a hidden repo (the decision's own, or an item of a batch); null when nothing is hidden. */ -export function withoutHidden(hidden: HiddenRepos, params: Record): string | null { +export function withoutHidden(db: Db, hidden: HiddenRepos, params: Record): string | null { if (!filtered(hidden)) return null; const bind = (h: { sql: string; args: string[] }): string => { let k = 0; return h.sql.replace(/\?/g, () => { params[`hd${k}`] = h.args[k]!; return `:hd${k++}`; }); }; - if (!hidden.visible) return `NOT ${inRepos("hd", hidden, params)}`; + if (!hidden.visible) return `NOT ${inRepos(db, "hd", hidden, params)}`; // Allow-list: a decision is shown only when every repo it names (its own, and each item of a batch) is one the viewer may see. const own = bind(hiddenTest("repo", hidden)); - const member = bind(hiddenTest("json_extract(j.value, '$.repo')", hidden)); - return `NOT ((repo IS NOT NULL AND ${own}) OR EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(items) THEN items ELSE '[]' END) j WHERE json_extract(j.value, '$.repo') IS NOT NULL AND ${member}))`; + const member = bind(hiddenTest(`${jsonText(db, "j.value", "$.repo")}`, hidden)); + return `NOT ((repo IS NOT NULL AND ${own}) OR EXISTS (SELECT 1 FROM ${jsonEach(db, `CASE WHEN ${jsonValid(db, "items")} THEN items ELSE '[]' END`, "j")} WHERE ${jsonText(db, "j.value", "$.repo")} IS NOT NULL AND ${member}))`; } /** * SQL for the decisions a person has to look at (decisions unaliased): open ones they can settle, plus the disputes and unsettled answers they resolve * (src/answers/hold.ts). `everything` leaves out the can-settle test, for a view of all open questions; viewers always get it. */ -export function needingSql(req: Req, everything = false): string { +export function needingSql(db: Db, req: Req, everything = false): string { // A viewer settles nothing, so a can-settle default would leave them an empty list: they read every question they may see. everything ||= req.user.role === "viewer"; - const open = `answer IS NULL AND NOT ${SNOOZED_SQL}${everything ? "" : ` AND ${canSettleSql(req.user.login, req.user.role)}`}`; - return `((${open}) OR ${heldOpenSql(req.user.login, isOperator(req))})`; + const open = `answer IS NULL AND NOT ${SNOOZED_SQL}${everything ? "" : ` AND ${canSettleSql(db, req.user.login, req.user.role)}`}`; + return `((${open}) OR ${heldOpenSql(db, req.user.login, isOperator(req))})`; } /** @@ -491,8 +492,8 @@ export function needingSql(req: Req, everything = false): string { */ export async function openCounts(db: Db, req: Req): Promise { const params: Record = {}; - const hide = withoutHidden(await hiddenRepos(db, req), params); - const rows = await db.prepare(`SELECT repo, number, items FROM decisions WHERE ${needingSql(req)}${hide ? ` AND ${hide}` : ""}`).all(params) as Pick[]; + const hide = withoutHidden(db, await hiddenRepos(db, req), params); + const rows = await db.prepare(`SELECT repo, number, items FROM decisions WHERE ${needingSql(db, req)}${hide ? ` AND ${hide}` : ""}`).all(params) as Pick[]; const byRepo: Record = {}; for (const r of rows) for (const repo of reposOf(r as DecisionRow)) byRepo[repo] = (byRepo[repo] ?? 0) + 1; return { total: rows.length, byRepo }; @@ -513,7 +514,7 @@ export async function listDecisions(db: Db, req: Req): Promise { else if (status === "snoozed") where.push(SNOOZED_SQL); else if (status === "open" || status === "opinions") { // The person's own list unless asked for everything (`all=1`) or scoped to one item: only the questions they can settle, plus the disputes they resolve. - where.push(needingSql(req, q.get("all") === "1" || q.get("number") !== null)); + where.push(needingSql(db, req, q.get("all") === "1" || q.get("number") !== null)); } if (status === "opinions") where.push("(EXISTS (SELECT 1 FROM decision_opinions o WHERE o.decision_id = decisions.id AND o.retracted_at IS NULL) OR EXISTS (SELECT 1 FROM decision_comments c WHERE c.decision_id = decisions.id))"); const kinds = list(req, "kind").filter((k) => (KINDS as readonly string[]).includes(k)); @@ -523,10 +524,10 @@ export async function listDecisions(db: Db, req: Req): Promise { where.push("asked_at <= :before"); params.before = new Date(Date.now() - minAge * 86400_000).toISOString(); } - const hide = withoutHidden(await hiddenRepos(db, req), params); + const hide = withoutHidden(db, await hiddenRepos(db, req), params); if (hide) where.push(hide); const repos = [...new Set(list(req, "repo"))]; - if (repos.length) where.push(inRepos("rp", repos, params)); + if (repos.length) where.push(inRepos(db, "rp", repos, params)); // One item: the decision's own, or a batch or duplicate group that lists it as a member. const itemNo = q.get("number"); if (itemNo !== null && repos.length === 1) { @@ -534,8 +535,8 @@ export async function listDecisions(db: Db, req: Req): Promise { if (!Number.isInteger(n)) throw new HttpError(400, "number must be an item number"); params.itemRepo = repos[0]!; params.itemNo = String(n); - where.push(`((repo = :itemRepo AND number = :itemNo) OR EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(items) THEN items ELSE '[]' END) ij - WHERE json_extract(ij.value, '$.repo') = :itemRepo AND json_extract(ij.value, '$.number') = CAST(:itemNo AS INTEGER)) + where.push(`((repo = :itemRepo AND number = :itemNo) OR EXISTS (SELECT 1 FROM ${jsonEach(db, `CASE WHEN ${jsonValid(db, "items")} THEN items ELSE '[]' END`, "ij")} + WHERE ${jsonText(db, "ij.value", "$.repo")} = :itemRepo AND ${jsonNum(db, "ij.value", "$.number")} = CAST(:itemNo AS INTEGER)) OR EXISTS (SELECT 1 FROM dupe_group_items gm WHERE gm.decision_id = decisions.id AND gm.repo = :itemRepo AND gm.number = :itemNo))`); } @@ -588,7 +589,7 @@ export async function listDecisions(db: Db, req: Req): Promise { } const more = ids.length > limit; const shownIds = ids.slice(0, limit); - const rowOf = new Map((shownIds.length ? await db.prepare("SELECT * FROM decisions WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(shownIds.map((r) => r.id))) as DecisionRow[] : []).map((d) => [d.id, d])); + const rowOf = new Map((shownIds.length ? await db.prepare(`SELECT * FROM decisions WHERE ${inList(db, "id", "?")}`).all(JSON.stringify(shownIds.map((r) => r.id))) as DecisionRow[] : []).map((d) => [d.id, d])); const shown = shownIds.map((r) => rowOf.get(r.id)!); const viewer = shown.length ? await viewerWith(db, req) : viewerOf(req); viewer.prep = await prepareStates(db, shown); @@ -612,8 +613,8 @@ export async function forItem(db: Db, req: Req): Promise { const repo = shortRepo(req.params.repo!); const visible = new Set(await visibleRepos(db, req)); const rows = await db.prepare(`SELECT * FROM decisions WHERE (repo = :repo AND number = :n) OR (number IS NULL AND EXISTS ( - SELECT 1 FROM json_each(CASE WHEN json_valid(items) THEN items ELSE '[]' END) j - WHERE json_extract(j.value, '$.repo') = :repo AND json_extract(j.value, '$.number') = :n))`).all({ repo, n }) as unknown as DecisionRow[]; + SELECT 1 FROM ${jsonEach(db, `CASE WHEN ${jsonValid(db, "items")} THEN items ELSE '[]' END`, "j")} + WHERE ${jsonText(db, "j.value", "$.repo")} = :repo AND ${jsonNum(db, "j.value", "$.number")} = :n))`).all({ repo, n }) as unknown as DecisionRow[]; const viewer = await viewerWith(db, req); // A batch that also covers the item counts only when no single-item decision exists; it is the item's decision only by membership. const single = rows.filter((d) => d.number === n); diff --git a/src/dash/api/home.ts b/src/dash/api/home.ts index 52b1289aa..b2c936c54 100644 --- a/src/dash/api/home.ts +++ b/src/dash/api/home.ts @@ -38,8 +38,8 @@ async function phases(db: Db, hidden: string[]): Promise { const params: Record = {}; - const hide = withoutHidden(hidden, params); - const where = `${needingSql(req)}${hide ? ` AND ${hide}` : ""}`; + const hide = withoutHidden(db, hidden, params); + const where = `${needingSql(db, req)}${hide ? ` AND ${hide}` : ""}`; const byKind: Partial> = {}; for (const r of await db.prepare(`SELECT kind, COUNT(*) AS n FROM decisions WHERE ${where} GROUP BY kind`).all(params) as { kind: NeedKind; n: number }[]) byKind[r.kind] = r.n; // The Needs page's own counts, so the total is the nav badge's number for this user. diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index f1374a9ea..50f140028 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -342,7 +342,7 @@ async function progressItems(db: Db, hidden: HiddenRepos): Promise { const perHourPipeline = new Array(24).fill(0); const since = now - 24 * 3600_000; for (const r of await db.prepare(`WITH ${latestCte()} SELECT i.closed_at, l.stage IN ('merged', 'closed', 'fixed-by-us') AS ours - FROM ${CLOSED_ITEMS} LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number + FROM ${CLOSED_ITEMS(db)} LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number WHERE i.closed_at >= :since AND i.state <> 'OPEN' AND i.${TRACKED}${hideSql ? ` AND ${hideSql}` : ""}`).all({ ...hp, since: new Date(since).toISOString() }) as { closed_at: string; ours: number | null }[]) { const h = Math.floor((Date.parse(r.closed_at) - since) / 3600_000); if (h >= 0 && h < 24) { @@ -370,7 +370,7 @@ async function progressItems(db: Db, hidden: HiddenRepos): Promise { async function progress(db: Db, hidden: HiddenRepos): Promise { const heavy = await progressItems(db, hidden); const dp: Record = {}; - const hideDec = withoutHidden(hidden, dp); + const hideDec = withoutHidden(db, hidden, dp); const openDec = new Map(); let decisionsOpen = 0; for (const r of await db.prepare(`SELECT repo, number, items FROM decisions WHERE answer IS NULL${hideDec ? ` AND ${hideDec}` : ""}`).all(dp) as { repo: string | null; number: number | null; items: string | null }[]) { diff --git a/src/dash/api/items.ts b/src/dash/api/items.ts index f33019930..cf89ba75a 100644 --- a/src/dash/api/items.ts +++ b/src/dash/api/items.ts @@ -23,6 +23,7 @@ import { statusFromItem } from "../../core/item-status.ts"; import { ITEM_PHASES, PHASE_SQL, type ItemPhase, type ItemStatus, type ItemStatusList, type ItemStatusRow } from "./home-types.ts"; import { mapSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; +import { indexedBy } from "../../db/portable.ts"; const HAS_WORD = /[\p{L}\p{N}]/u; const quote = (s: string) => `"${s.replace(/"/g, "")}"`; @@ -272,7 +273,7 @@ export async function listItems(db: Db, req: Req): Promise { // scoping view the planner walks the repo index and sorts every open item. const byUpdated = !b.text && b.sort === "updated" && b.params.state !== undefined; const pageFrom = byUpdated - ? from(false).replace("FROM items i", "FROM main.items AS i INDEXED BY items_state_updated") + ? from(false).replace("FROM items i", `FROM main.items AS i${indexedBy(db, "items_state_updated")}`) : from(b.sort === "relevance"); const pageWhere = byUpdated ? [...where, "i.repo IN (SELECT name FROM main.tracked_repos)"] : where; const ids = (await db.prepare(pageFrom.replace("%COLS", "i.rowid AS rid") + whereSql(pageWhere) + @@ -369,7 +370,7 @@ export async function quickSearch(db: Db, req: Req): Promise { // A single word may be a login: that author's latest items first. if (/^[A-Za-z0-9-]{2,39}$/.test(q)) { // main.items with the index named: through the scoping view the planner picks the repo index. - rows = await db.prepare(`SELECT repo, number, kind, title, author, state FROM main.items INDEXED BY items_author_nocase + rows = await db.prepare(`SELECT repo, number, kind, title, author, state FROM main.items${indexedBy(db, "items_author_nocase")} WHERE author LIKE :p AND repo IN (SELECT name FROM main.tracked_repos)${hide ? ` AND ${hide}` : ""} ORDER BY state <> 'OPEN', updated_at DESC LIMIT 5`).all({ p: `${q}%`, ...hp }) as Hit[]; } diff --git a/src/dash/api/needs.ts b/src/dash/api/needs.ts index 104559cee..a4a245f18 100644 --- a/src/dash/api/needs.ts +++ b/src/dash/api/needs.ts @@ -19,6 +19,7 @@ import { isQuiet } from "../../security/quiet.ts"; import { canSeeInternals } from "./staff.ts"; import { filterSeq, mapSeq, reduceSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; +import { chr, inList, jsonText, nocase } from "../../db/portable.ts"; export const NEEDS_PAGE = 30; /** Older feedback is not asked for any more; the window also bounds the scans. */ @@ -26,14 +27,17 @@ const WINDOW_MS = 60 * 86_400_000; type Raw = { id: string; source: NeedsFeedbackRow["source"]; author: string; at: string; text: string; repo: string | null; number: number | null; decision: string | null; turn: number | null; comment: string | null; handled: number }; +/** `s` with spaces, newlines and tabs trimmed from both ends. */ +const trimText = (db: Db, s: string): string => db.dialect === "postgres" ? `btrim(${s}, ' ' || ${chr(db, 10, 9)})` : `TRIM(${s}, ' ' || char(10) || char(9))`; + // One SELECT per source, each with a `handled` flag. They share the parameters :since, :cur (newest time wanted), :own (the box account), :owns (JSON list of every login that is ours) and :bots. -const SOURCES: string[] = [ +const sources = (db: Db): string[] => [ // Feedback on a decision from anyone but an operator; handled once the decision was answered afterwards. - `SELECT 'decision-comment:' || c.id AS id, 'decision' AS source, c.login AS author, c.at, c.body AS text, d.repo, d.number, d.id AS decision, NULL AS turn, c.id AS comment, + `SELECT 'decision-comment:' || c.id AS id, 'decision' AS source, c.login AS author, c.at, c.body AS text, d.repo, d.number, d.id AS decision, CAST(NULL AS INTEGER) AS turn, c.id AS comment, d.answered_at IS NOT NULL AND d.answered_at > c.at AS handled FROM decision_comments c JOIN decisions d ON d.id = c.decision_id WHERE c.at >= :since AND c.at <= :cur AND NOT EXISTS (SELECT 1 FROM access a WHERE a.login = c.login AND a.role = 'operator')`, - `SELECT 'decision-opinion:' || o.id, 'decision', o.login, o.at, o.note, d.repo, d.number, d.id, NULL, NULL, + `SELECT 'decision-opinion:' || o.id, 'decision', o.login, o.at, o.note, d.repo, d.number, d.id, CAST(NULL AS INTEGER), NULL, d.answered_at IS NOT NULL AND d.answered_at > o.at FROM decision_opinions o JOIN decisions d ON d.id = o.decision_id WHERE o.at >= :since AND o.at <= :cur AND o.retracted_at IS NULL AND TRIM(COALESCE(o.note, '')) <> '' @@ -43,25 +47,25 @@ const SOURCES: string[] = [ FROM conversation_turns t WHERE t.kind = 'operator' AND t.at >= :since AND t.at <= :cur`, // A GitHub comment or review that names the pipeline login (flagged when written, so an index finds them); handled once the // pipeline login posted on the item afterwards. Nothing without a pipeline login. - `SELECT 'comment:' || c.id, 'github', c.author, c.created_at, c.body, c.repo, c.number, NULL, NULL, c.id, - EXISTS (SELECT 1 FROM comments a WHERE a.repo = c.repo AND a.number = c.number AND a.author IN (SELECT value FROM json_each(:owns)) AND a.created_at > c.created_at) + `SELECT 'comment:' || c.id, 'github', c.author, c.created_at, c.body, c.repo, c.number, NULL, CAST(NULL AS INTEGER), c.id, + EXISTS (SELECT 1 FROM comments a WHERE a.repo = c.repo AND a.number = c.number AND ${inList(db, "a.author", ":owns")} AND a.created_at > c.created_at) FROM comments c - WHERE :own <> '' AND c.mentions_pipeline = 1 AND c.created_at >= :since AND c.created_at <= :cur AND c.author IS NOT NULL AND c.author NOT IN (SELECT value FROM json_each(:owns))`, + WHERE :own <> '' AND c.mentions_pipeline = 1 AND c.created_at >= :since AND c.created_at <= :cur AND c.author IS NOT NULL AND ${inList(db, "c.author", ":owns", "text", true)}`, // The comment right after one of AutoCraft's own (a comment the audit log recorded with its URL and text, or the review we posted (audit `review-post`); the account's older manual comments do not count), on an item it commented on; bots do not count as replies. - `SELECT 'comment:' || c.id, 'github', c.author, c.created_at, c.body, c.repo, c.number, NULL, NULL, c.id, - EXISTS (SELECT 1 FROM comments a WHERE a.repo = c.repo AND a.number = c.number AND a.author IN (SELECT value FROM json_each(:owns)) AND a.created_at > c.created_at) - FROM (SELECT DISTINCT repo, number FROM comments WHERE author IN (SELECT value FROM json_each(:owns))) o JOIN comments c ON c.repo = o.repo AND c.number = o.number - WHERE :own <> '' AND c.mentions_pipeline = 0 AND c.created_at >= :since AND c.created_at <= :cur AND c.author IS NOT NULL AND c.author NOT IN (SELECT value FROM json_each(:owns)) AND c.author NOT LIKE '%[bot]' AND lower(c.author) NOT IN (SELECT value FROM json_each(:bots)) AND TRIM(COALESCE(c.body, '')) <> '' + `SELECT 'comment:' || c.id, 'github', c.author, c.created_at, c.body, c.repo, c.number, NULL, CAST(NULL AS INTEGER), c.id, + EXISTS (SELECT 1 FROM comments a WHERE a.repo = c.repo AND a.number = c.number AND ${inList(db, "a.author", ":owns")} AND a.created_at > c.created_at) + FROM (SELECT DISTINCT repo, number FROM comments WHERE ${inList(db, "author", ":owns")}) o JOIN comments c ON c.repo = o.repo AND c.number = o.number + WHERE :own <> '' AND c.mentions_pipeline = 0 AND c.created_at >= :since AND c.created_at <= :cur AND c.author IS NOT NULL AND ${inList(db, "c.author", ":owns", "text", true)} AND c.author NOT LIKE '%[bot]' AND lower(c.author) ${inList(db, "NOT", ":bots")} AND TRIM(COALESCE(c.body, '')) <> '' AND EXISTS (SELECT 1 FROM (SELECT p.id, p.author, p.body FROM comments p WHERE p.repo = c.repo AND p.number = c.number AND p.created_at < c.created_at ORDER BY p.created_at DESC LIMIT 1) q - WHERE q.author IN (SELECT value FROM json_each(:owns)) AND EXISTS (SELECT 1 FROM audit a WHERE a.target = c.repo || '#' || c.number - AND ((json_extract(a.details, '$.url') IS NOT NULL AND TRIM(REPLACE(json_extract(a.details, '$.text'), char(13), ''), ' ' || char(10) || char(9)) = TRIM(REPLACE(q.body, char(13), ''), ' ' || char(10) || char(9))) - OR (a.action = 'review-post' AND json_extract(a.details, '$.review') = q.id))))`, + WHERE ${inList(db, "q.author", ":owns")} AND EXISTS (SELECT 1 FROM audit a WHERE a.target = c.repo || '#' || c.number + AND ((${jsonText(db, "a.details", "$.url")} IS NOT NULL AND ${trimText(db, `REPLACE(${jsonText(db, "a.details", "$.text")}, ${chr(db, 13)}, '')`)} = ${trimText(db, `REPLACE(q.body, ${chr(db, 13)}, '')`)}) + OR (a.action = 'review-post' AND ${jsonText(db, "a.details", "$.review")} = q.id))))`, ]; const ownLogin = async (db: Db): Promise => (await db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value ?? ""; -function hiddenSql(hidden: HiddenRepos, params: Record): string { - if (!filtered(hidden)) return "1"; +function hiddenSql(db: Db, hidden: HiddenRepos, params: Record): string { + if (!filtered(hidden)) return db.dialect === "postgres" ? "TRUE" : "1"; const h = hiddenTest("repo", hidden); let k = 0; return `(repo IS NULL OR NOT (${h.sql.replace(/\?/g, () => { params[`h${k}`] = h.args[k]!; return `:h${k++}`; })}))`; @@ -81,8 +85,8 @@ async function quietRow(db: Db, r: Pick, me async function feedback(db: Db, hidden: HiddenRepos, cursor: { at: string; id: string } | null, limit: number, staff: boolean): Promise<{ rows: Raw[]; more: boolean; unhandled: number }> { const params: Record = { since: new Date(Date.now() - WINDOW_MS).toISOString(), own: await ownLogin(db), owns: JSON.stringify([...await allOwnLogins(db)]), bots: JSON.stringify(reviewBots()) }; - const union = SOURCES.map((s) => `SELECT * FROM (${s})`).join(" UNION ALL "); - const where = hiddenSql(hidden, params); + const union = sources(db).map((s) => `SELECT * FROM (${s})`).join(" UNION ALL "); + const where = hiddenSql(db, hidden, params); const size = limit * 3 + 1; // Feedback on a batch decision is hidden when the batch holds an item of a hidden repo. const batches = new Map(); @@ -107,7 +111,7 @@ async function feedback(db: Db, hidden: HiddenRepos, cursor: { at: string; id: s if (batch.length < size || !tail) break; pos = { at: tail.at, id: tail.id }; } - const open = await db.prepare(`SELECT source, number, decision, COUNT(*) AS n FROM (${union}) WHERE ${where} AND NOT handled GROUP BY source, number IS NULL, decision`).all({ ...params, cur: "9999" }) as { source: Raw["source"]; number: number | null; decision: string | null; n: number }[]; + const open = await db.prepare(`SELECT source, MAX(number) AS number, decision, COUNT(*) AS n FROM (${union}) WHERE ${where} AND NOT handled GROUP BY source, number IS NULL, decision`).all({ ...params, cur: "9999" }) as { source: Raw["source"]; number: number | null; decision: string | null; n: number }[]; const unhandled = await reduceSeq(open, async (sum, r) => sum + (await visible(r) ? r.n : 0), 0); // What staff wrote about a quiet pull request reaches viewers as the row only, as the decision and conversation APIs give it. const quiet = new Map(); @@ -143,8 +147,10 @@ export async function stopped(db: Db, hidden: HiddenRepos): Promise { const fb = await feedback(db, hidden, cursor, q.get("feedback") === "1" ? limit : 1, canSeeInternals(req)); // The same filter as the Needs you list: what this person settles, plus the disputes they resolve; a batch counts only when none of its items is in a hidden repo. const dp: Record = {}; - const hide = withoutHidden(hidden, dp); - const decisions = (await db.prepare(`SELECT COUNT(*) AS n FROM decisions WHERE ${needingSql(req)}${hide ? ` AND ${hide}` : ""}`).get(dp) as { n: number }).n; + const hide = withoutHidden(db, hidden, dp); + const decisions = (await db.prepare(`SELECT COUNT(*) AS n FROM decisions WHERE ${needingSql(db, req)}${hide ? ` AND ${hide}` : ""}`).get(dp) as { n: number }).n; const rows = await stopped(db, hidden); const last = fb.rows[fb.rows.length - 1]; return { diff --git a/src/dash/api/queue-page.ts b/src/dash/api/queue-page.ts index fb359a122..898ad5e02 100644 --- a/src/dash/api/queue-page.ts +++ b/src/dash/api/queue-page.ts @@ -23,6 +23,7 @@ import { readerOf, veiledFor } from "./reader.ts"; import { stageById } from "../../stages/registry.ts"; import { flatMapSeq, mapSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; +import { indexedBy } from "../../db/portable.ts"; export const TABS: QueueTab[] = ["all", "review", "fix", "verify", "merge"]; const NEXT_LIMIT = 10; @@ -201,7 +202,7 @@ export async function queueOrigins(db: Db, staff: boolean): Promise<(e: Pick> { - const rows = await db.prepare("SELECT repo, number, closing_issues FROM main.items INDEXED BY items_closing WHERE kind = 'pr' AND closing_issues IS NOT NULL AND closing_issues <> '[]'").all() as { repo: string; number: number; closing_issues: string }[]; + const rows = await db.prepare(`SELECT repo, number, closing_issues FROM main.items${indexedBy(db, "items_closing")} WHERE kind = 'pr' AND closing_issues IS NOT NULL AND closing_issues <> '[]'`).all() as { repo: string; number: number; closing_issues: string }[]; const out = new Map(); for (const r of rows) { try { @@ -298,7 +299,7 @@ async function markFast(db: Db, by: string, repo: string, number: number, w: num /** The open PRs of `repo` that close issue `issue` when they merge (GitHub's closing references, from the mirror). */ export async function openPrsClosing(db: Db, repo: string, issue: number): Promise { - const rows = await db.prepare("SELECT number, closing_issues FROM main.items INDEXED BY items_closing WHERE repo = ? AND kind = 'pr' AND state = 'OPEN' AND closing_issues IS NOT NULL AND closing_issues <> '[]'").all(repo) as { number: number; closing_issues: string }[]; + const rows = await db.prepare(`SELECT number, closing_issues FROM main.items${indexedBy(db, "items_closing")} WHERE repo = ? AND kind = 'pr' AND state = 'OPEN' AND closing_issues IS NOT NULL AND closing_issues <> '[]'`).all(repo) as { number: number; closing_issues: string }[]; return rows .filter((p) => { try { diff --git a/src/dash/api/stats.ts b/src/dash/api/stats.ts index ba0f7e118..8610e5f44 100644 --- a/src/dash/api/stats.ts +++ b/src/dash/api/stats.ts @@ -1,6 +1,7 @@ // Shared queries for the Progress, Repo and Run and cost pages. import { latestRun, settledTable } from "../../classify/settled.ts"; import type { Db } from "../../db/index.ts"; +import { indexedBy } from "../../db/portable.ts"; // Latest stage per item, from the item_stage table the stages trigger maintains. export const LATEST_SQL = `latest AS (SELECT repo, number, stage, reviewed FROM main.item_stage %W)`; @@ -15,8 +16,8 @@ export async function trackingStart(db: Db): Promise { // Closed items by date: main.items with its index named, because through the // scoping view the planner walks the repo index instead of the closed_at range. -export const CLOSED_ITEMS = "main.items AS i INDEXED BY items_closed"; -export const CREATED_ITEMS = "main.items AS i INDEXED BY items_created"; +export const CLOSED_ITEMS = (db: Db): string => `main.items AS i${indexedBy(db, "items_closed")}`; +export const CREATED_ITEMS = (db: Db): string => `main.items AS i${indexedBy(db, "items_created")}`; export const TRACKED = "repo IN (SELECT name FROM main.tracked_repos)"; const p = (repo?: string, extra: Record = {}): Record => (repo ? { repo, ...extra } : extra); @@ -52,7 +53,7 @@ export type DoneRow = { repo: string; merged_pipeline: number; closed_pipeline: // Done since tracking began. Merged PRs carry closed_at too, so one range covers both. export async function doneByRepo(db: Db, start: string, repo?: string): Promise { return (await db.prepare(`WITH ${latestCte(repo)}, d AS ( - SELECT i.repo, i.state, l.stage FROM ${CLOSED_ITEMS} LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number + SELECT i.repo, i.state, l.stage FROM ${CLOSED_ITEMS(db)} LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number WHERE i.closed_at >= :start AND i.state <> 'OPEN' AND i.${TRACKED} ${repo ? "AND i.repo = :repo" : ""}) SELECT repo, SUM(state = 'MERGED' AND stage = 'merged') AS merged_pipeline, @@ -75,8 +76,8 @@ export async function trend(db: Db, start: string, openNow: Map, if (d >= today || days.length > 365) break; } const r = repo ? "AND repo = :repo" : ""; - const created = await db.prepare(`SELECT repo, substr(created_at, 1, 10) AS d, COUNT(*) AS n FROM ${CREATED_ITEMS} WHERE created_at >= :start AND ${TRACKED} ${r} GROUP BY repo, d`).all(p(repo, { start })) as { repo: string; d: string; n: number }[]; - const closed = await db.prepare(`SELECT repo, substr(closed_at, 1, 10) AS d, COUNT(*) AS n FROM ${CLOSED_ITEMS} WHERE closed_at >= :start AND state <> 'OPEN' AND ${TRACKED} ${r} GROUP BY repo, d`).all(p(repo, { start })) as { repo: string; d: string; n: number }[]; + const created = await db.prepare(`SELECT repo, substr(created_at, 1, 10) AS d, COUNT(*) AS n FROM ${CREATED_ITEMS(db)} WHERE created_at >= :start AND ${TRACKED} ${r} GROUP BY repo, d`).all(p(repo, { start })) as { repo: string; d: string; n: number }[]; + const closed = await db.prepare(`SELECT repo, substr(closed_at, 1, 10) AS d, COUNT(*) AS n FROM ${CLOSED_ITEMS(db)} WHERE closed_at >= :start AND state <> 'OPEN' AND ${TRACKED} ${r} GROUP BY repo, d`).all(p(repo, { start })) as { repo: string; d: string; n: number }[]; const delta = new Map>(); const add = (repo: string, d: string, n: number) => { if (!delta.has(repo)) delta.set(repo, new Map()); diff --git a/src/dash/mcp/index.ts b/src/dash/mcp/index.ts index c68cbc708..27d609c17 100644 --- a/src/dash/mcp/index.ts +++ b/src/dash/mcp/index.ts @@ -25,6 +25,7 @@ import { HttpError, RateLimiter } from "../server/util.ts"; import type { Req, User } from "../types.ts"; import { mapSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; +import { ciEq, jsonText, jsonValid } from "../../db/portable.ts"; export const MCP_PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"]; const BODY_MAX = 20_000; @@ -605,7 +606,7 @@ async function heldFixups(db: Db, repos: string[], repo: string | null, limit: n return await db.prepare(`SELECT p.repo, p.number, p.head, i.title, i.author, p.note FROM item_plans p JOIN items i ON i.repo = p.repo AND i.number = p.number WHERE p.kind = 'pr' AND p.repo IN (${names}) AND i.state = 'OPEN' AND p.head = i.head_oid - AND json_valid(p.view) AND json_extract(p.view, '$.fixup') = 'hold' + AND ${jsonValid(db, "p.view")} AND ${jsonText(db, "p.view", "$.fixup")} = 'hold' AND NOT EXISTS (SELECT 1 FROM fixups f WHERE f.repo = p.repo AND f.number = p.number AND f.from_head = p.head AND f.state IN ('pushing', 'linting', 'pushed')) ORDER BY i.created_at, p.repo, p.number LIMIT :limit`).all(params) as Held[]; } @@ -712,7 +713,7 @@ async function myWork(env: McpEnv, raw: unknown): Promise { const start = new Date(); start.setUTCHours(0, 0, 0, 0); const rows = (await env.db.prepare(`SELECT id, prompt_id, items, state, started_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd FROM agent_runs - WHERE user_login = ? COLLATE NOCASE AND started_at >= ? ORDER BY id DESC LIMIT 200`).all(login, start.toISOString()) as + WHERE ${ciEq(env.db, "user_login", "?")} AND started_at >= ? ORDER BY id DESC LIMIT 200`).all(login, start.toISOString()) as { id: number; prompt_id: string; items: string; state: string; started_at: string; input_tokens: number | null; output_tokens: number | null; cache_read_tokens: number | null; cache_write_tokens: number | null; cost_usd: number | null }[]) .map((r) => ({ promptId: r.prompt_id, items: (JSON.parse(r.items) as { repo: string; number: number }[]).slice(0, 6).map((i) => `${i.repo}#${i.number}`), state: r.state, startedAt: r.started_at, diff --git a/src/dash/mcp/tokens.ts b/src/dash/mcp/tokens.ts index ee007b6b3..687ac1859 100644 --- a/src/dash/mcp/tokens.ts +++ b/src/dash/mcp/tokens.ts @@ -7,6 +7,7 @@ import type { Role } from "../types.ts"; import { randomToken, sha256hex } from "../server/crypto.ts"; import { HttpError } from "../server/util.ts"; import type { Db } from "../../db/index.ts"; +import { nocase } from "../../db/portable.ts"; const DAY = 86_400_000; export const MCP_TOKEN_TTL = 90 * DAY; @@ -98,7 +99,7 @@ export async function endAnswerTokens(db: Db, login: string): Promise { /** Every login's live tokens, for operators on the Access page. */ export async function listAllTokens(db: Db): Promise<(McpTokenRow & { login: string })[]> { - return (await db.prepare(`SELECT login, ${COLS} FROM mcp_tokens WHERE expires_at > ? ORDER BY login COLLATE NOCASE, created_at DESC, id DESC`) + return (await db.prepare(`SELECT login, ${COLS} FROM mcp_tokens WHERE expires_at > ? ORDER BY ${nocase(db, "login")}, created_at DESC, id DESC`) .all(new Date().toISOString()) as (Raw & { login: string })[]).map((r) => ({ ...toRow(r), login: r.login })); } diff --git a/src/db/portable.ts b/src/db/portable.ts index 38450ff4e..a5ce07b6a 100644 --- a/src/db/portable.ts +++ b/src/db/portable.ts @@ -10,6 +10,7 @@ * | --------------------------------------------- | ---------------------------------------- | * | `x IN (SELECT value FROM json_each(?))` | `inList(db, "x", "?", "bigint")` | * | `x IN (?, ?, ?)` from JS values (Kysely) | `inValues(db, sql.ref("x"), values)` | + * | `(a, b) IN (SELECT value ->> 0, value ->> 1 FROM json_each(?))` | `inTuples(db, ["a", "b"], "?", ["text", "bigint"])` | * | `json_extract(c, '$.a.b')` (a string) | `jsonText(db, "c", "$.a.b")` | * | `json_extract(c, '$.n')` (a number) | `jsonNum(db, "c", "$.n")` | * | `json_extract(c, '$.ok')` (true/false → 1/0) | `jsonBool(db, "c", "$.ok")` | @@ -19,6 +20,7 @@ * | `INSERT OR IGNORE INTO t ...` | `insertIgnore(db, "t (a, b) VALUES (?, ?)")` | * | `INSERT OR REPLACE INTO t ...` | `upsert(db, { table, cols, key })` | * | `a = b COLLATE NOCASE`, citext vs text | `ciEq(db, "a", "b")` | + * | `ORDER BY a COLLATE NOCASE` | `` `ORDER BY ${nocase(db, "a")}` `` | * | `a LIKE p` (case-insensitive) | `like(db, "a", "p")` | * | `ORDER BY x` on a nullable column | `nullsFirst(db, "x")` / `nullsLast(db, "x", "DESC")` | * | `a IS NOT b` / `a IS b` | `distinctFrom(db, "a", "b")` / `notDistinctFrom` | @@ -27,6 +29,7 @@ * | `char(10)` | `chr(db, 10)` | * | `strftime('%Y-%m-%dT%H:%M:%fZ', 'now')` | `?` bound to `nowParam()` | * | `rowid` | `rowidOf("table")` | + * | `t INDEXED BY idx` | `` `t${indexedBy(db, "idx")}` `` | * * JSON stays TEXT on Postgres: the JSON helpers cast with `::json` in the query. Paths are SQLite's (`$.a.b`, `$[0]`, * `$.a[2].b`, `$."odd key"`). @@ -58,6 +61,15 @@ export function inList(d: D, expr: string, param = "?", type: ElemType = "text", return `${expr} ${op} (SELECT ${v} FROM json_array_elements_text((${param})::json) AS value)`; } +/** + * `(a, b, ...) IN (the rows of a JSON array of arrays)`, bound as one parameter like `inList`: `[["app", 7], ...]` matches + * `a = 'app' AND b = 7`. `types` are the columns' types on Postgres, one per column. + */ +export function inTuples(d: D, cols: readonly string[], param: string, types: readonly ElemType[]): string { + if (!pgOf(d)) return `(${cols.join(", ")}) IN (SELECT ${cols.map((_, k) => `value ->> ${k}`).join(", ")} FROM json_each(${param}))`; + return `(${cols.join(", ")}) IN (SELECT ${types.map((t, k) => `(value ->> ${k})::${t}`).join(", ")} FROM json_array_elements((${param})::json) AS value)`; +} + /** Kysely: `expr IN (values)`: one parameter per value on SQLite, one array parameter on Postgres (`= ANY`). */ export function inValues(d: D, expr: Expression, values: readonly Param[]): RawBuilder { if (pgOf(d)) return sql`${expr} = ANY(${values as unknown as Param})`; @@ -251,3 +263,13 @@ export function rowidOf(table: string): string { if (!col) throw new Error(`rowidOf: table ${table} has no rowid`); return col; } + +/** ` INDEXED BY index` after a table name on SQLite; nothing on Postgres, whose planner takes no index hints. */ +export function indexedBy(d: D, index: string): string { + return pgOf(d) ? "" : ` INDEXED BY ${index}`; +} + +/** `expr` compared and sorted case-insensitively (ASCII, as SQLite's NOCASE), for ORDER BY and GROUP BY terms. */ +export function nocase(d: D, expr: string): string { + return pgOf(d) ? `(${expr})::citext` : `${expr} COLLATE NOCASE`; +} diff --git a/src/decisions.ts b/src/decisions.ts index 04558772c..d29af764b 100644 --- a/src/decisions.ts +++ b/src/decisions.ts @@ -138,18 +138,18 @@ 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 = "(excluded.question IS NOT question OR excluded.options IS NOT options)"; - const keepsPick = "(prepared_at IS NOT NULL AND NOT " + changed + ")"; + const changed = "(excluded.question IS DISTINCT FROM decisions.question OR excluded.options IS DISTINCT FROM decisions.options)"; + const keepsPick = "(decisions.prepared_at IS NOT NULL AND NOT " + changed + ")"; const set = (c: string): string => - SUMMARY_FIELDS.includes(c) ? `${c} = COALESCE(excluded.${c}, ${c})` - : c === "recommended" || c === "recommended_reason" ? `${c} = CASE WHEN ${keepsPick} THEN ${c} ELSE excluded.${c} END` + 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 recommended_by ELSE NULL END, - prepared_at = CASE WHEN ${changed} THEN NULL ELSE prepared_at END, - recommend_failures = CASE WHEN ${changed} THEN NULL ELSE recommend_failures END, - snoozed_by = CASE WHEN ${changed} THEN NULL ELSE snoozed_by END, - snoozed_at = CASE WHEN ${changed} THEN NULL ELSE snoozed_at END`); + 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 () => { @@ -173,7 +173,7 @@ export async function operators(db: Db): Promise> { 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("decisions")} ORDER BY answered_at`).all() as DecisionRow[]; + AND ${settledBySql(db, "decisions")} ORDER BY answered_at`).all() as DecisionRow[]; 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 })), diff --git a/src/discord/file-issue.ts b/src/discord/file-issue.ts index de5a8aa03..01aeac843 100644 --- a/src/discord/file-issue.ts +++ b/src/discord/file-issue.ts @@ -15,6 +15,7 @@ import { isPublicRepo } from "../public/status.ts"; import { jevJunk, junkBand, junkState, parseJunk, type JunkAsk } from "./junk-ask.ts"; import { failReporter, forgetReporterRow, newReporterState, readReporter, reporterToken } from "./reporter.ts"; import type { Db } from "../db/index.ts"; +import { jsonText } from "../db/portable.ts"; /** Filing from Discord under the person's account is built but off: the sign-in needs a Discord identity step first, so a forwarded sign-in link cannot link someone else's GitHub account. While off, the draft offers only the prefilled GitHub link and the sign-in routes answer 404. */ export const FILING_IN_DISCORD = false; @@ -130,9 +131,9 @@ export async function fileIssue(deps: FileDeps, req: FileRequest, hooks: FileHoo await db.prepare("DELETE FROM discord_filed WHERE at < ?").run(since); if (await count(db, "SELECT COUNT(*) AS c FROM discord_filed WHERE login = ? AND at >= ?", tok.login, since) >= PER_LOGIN) return { status: "refused", reason: `You have filed ${PER_LOGIN} issues from Discord in the last 24 hours.` }; if (await count(db, "SELECT COUNT(*) AS c FROM discord_filed WHERE repo = ? AND at >= ?", req.repo, since) >= PER_REPO) return { status: "refused", reason: "This repo has reached its limit of issues filed from Discord today." }; - if (await count(db, "SELECT COUNT(*) AS c FROM audit WHERE action = ? AND at >= ? AND json_extract(details, '$.state') <> 'failed'", AUDIT_ACTION, since) >= DAILY_WRITES) return { status: "refused", reason: "Filing from Discord has reached its daily limit." }; + if (await count(db, `SELECT COUNT(*) AS c FROM audit WHERE action = ? AND at >= ? AND ${jsonText(db, "details", "$.state")} <> 'failed'`, AUDIT_ACTION, since) >= DAILY_WRITES) return { status: "refused", reason: "Filing from Discord has reached its daily limit." }; // The slot is reserved before any await, so parallel sessions of one person cannot pass the limit together; every failure below frees it. - const slot = Number((await db.prepare("INSERT INTO discord_filed (repo, number, login, reporter, at) VALUES (?, 0, ?, ?, ?)").run(req.repo, tok.login, req.reporter, new Date(now).toISOString())).lastInsertRowid); + const slot = Number((await db.prepare("INSERT INTO discord_filed (repo, number, login, reporter, at) VALUES (?, 0, ?, ?, ?) RETURNING rowid").get(req.repo, tok.login, req.reporter, new Date(now).toISOString()) as { rowid: number }).rowid); let filed = false; try { const junk = await junkCheck(db, { title, body }, hooks.judge ?? modelJudge, log); diff --git a/src/dupes/decide.ts b/src/dupes/decide.ts index be993dea9..9fef7b787 100644 --- a/src/dupes/decide.ts +++ b/src/dupes/decide.ts @@ -270,7 +270,7 @@ export async function groupsToAsk(db: Db, repo?: string): Promise { */ export async function answersToApply(db: Db): Promise<{ id: string; refs: string[] }[]> { const rows = await db.prepare(`SELECT d.id, d.repo, d.number FROM decisions d WHERE d.kind = 'duplicate' AND d.answer IS NOT NULL AND d.answer <> 'backlog' AND d.applied_at IS NULL - AND ${settledBySql("d")} + AND ${settledBySql(db, "d")} AND ((d.id NOT LIKE '%:dupegroup:%' AND d.answer <> 'close' AND ${pilotSqlFor("d.repo", "d.number")}) OR (d.id LIKE '%:dupegroup:%' AND EXISTS (SELECT 1 FROM dupe_group_items gi WHERE gi.decision_id = d.id AND ${pilotSqlFor("gi.repo", "gi.number")}) AND COALESCE((SELECT g.applied_answer FROM dupe_groups g WHERE g.decision_id = d.id), '') <> d.answer))`).all() as { id: string; repo: string | null; number: number | null }[]; diff --git a/src/merge/batch-store.ts b/src/merge/batch-store.ts index 6dd5abdba..f08342fd8 100644 --- a/src/merge/batch-store.ts +++ b/src/merge/batch-store.ts @@ -102,9 +102,9 @@ export async function nextBranch(db: Db, repo: string, now: Date): Promise { - const r = await db.prepare("INSERT INTO main.merge_batches (repo, branch, state, base_sha, commit_sha, parent_id, task_id, created_at, updated_at) VALUES (?, ?, 'checking', ?, ?, ?, ?, ?, ?)") - .run(b.repo, b.branch, b.baseSha, b.commitSha, b.parentId, b.taskId ?? null, b.at, b.at); - const id = Number(r.lastInsertRowid); + const r = await db.prepare("INSERT INTO main.merge_batches (repo, branch, state, base_sha, commit_sha, parent_id, task_id, created_at, updated_at) VALUES (?, ?, 'checking', ?, ?, ?, ?, ?, ?) RETURNING id") + .get(b.repo, b.branch, b.baseSha, b.commitSha, b.parentId, b.taskId ?? null, b.at, b.at) as { id: number }; + const id = Number(r.id); const ins = db.prepare("INSERT INTO main.merge_batch_prs (batch_id, number, head_oid, position) VALUES (?, ?, ?, ?)"); await forEachSeq(b.members, async (m, i) => await ins.run(id, m.number, m.head_oid, i)); return id; diff --git a/src/merge/verify-override.ts b/src/merge/verify-override.ts index a38f48adb..3a437e237 100644 --- a/src/merge/verify-override.ts +++ b/src/merge/verify-override.ts @@ -11,7 +11,7 @@ export async function verifyOverride(db: Db, repo: string, number: number, head: if (!v) return false; const id = mergeDecisionId(repo, number, head); if (await db.prepare("SELECT 1 FROM audit WHERE target = ? AND action = 'answer' AND json_extract(details, '$.source') = 'preapproval' LIMIT 1").get(id)) return false; - return !!await db.prepare(`SELECT 1 FROM decisions WHERE id = ? AND kind = 'merge' AND answer = 'merge' AND answered_at > ? AND ${settledBySql("decisions")}`).get(id, v.finished_at); + return !!await db.prepare(`SELECT 1 FROM decisions WHERE id = ? AND kind = 'merge' AND answer = 'merge' AND answered_at > ? AND ${settledBySql(db, "decisions")}`).get(id, v.finished_at); } /** A Merge answer given before the verification failed does not cover the failure: it is set aside so the Merge? question is asked again with the failure as a reason. */ diff --git a/src/mirror.ts b/src/mirror.ts index 3a320a207..fe787d79f 100644 --- a/src/mirror.ts +++ b/src/mirror.ts @@ -330,7 +330,7 @@ function commentRows(repo: string, kind: Kind, n: Node, own: string[]): SQLInput /** SQL for an upsert's mergeable value: GitHub reports UNKNOWN while it recomputes, which must not replace a known value at the same head. */ export const KEEP_KNOWN_MERGEABLE = (table: string): string => - `CASE WHEN ${table}.head_oid IS excluded.head_oid AND ${table}.mergeable IN ('CONFLICTING','MERGEABLE') AND excluded.mergeable IS NOT 'CONFLICTING' AND excluded.mergeable IS NOT 'MERGEABLE' THEN ${table}.mergeable ELSE excluded.mergeable END`; + `CASE WHEN ${table}.head_oid IS NOT DISTINCT FROM excluded.head_oid AND ${table}.mergeable IN ('CONFLICTING','MERGEABLE') AND excluded.mergeable IS DISTINCT FROM 'CONFLICTING' AND excluded.mergeable IS DISTINCT FROM 'MERGEABLE' THEN ${table}.mergeable ELSE excluded.mergeable END`; /** `force` rewrites an item and its comments even when the row is unchanged (a comment edit leaves the item row as it was). */ /** diff --git a/src/review/candidates.ts b/src/review/candidates.ts index 91f161c21..719c12793 100644 --- a/src/review/candidates.ts +++ b/src/review/candidates.ts @@ -49,12 +49,12 @@ async function scopeRows(db: Db, extra: string): Promise> { */ export async function scopeAnswers(db: Db, operatorsOnly = false): Promise> { // A disputed answer does not count until it is kept. - return await scopeRows(db, `AND decisions.exec_state IS NOT 'disputed' ${operatorsOnly ? `AND ${settledBySql("decisions")}` : `AND NOT (${MAINTAINER_ANSWER} AND NOT ${settledBySql("decisions")})`}`); + return await scopeRows(db, `AND decisions.exec_state IS NOT 'disputed' ${operatorsOnly ? `AND ${settledBySql(db, "decisions")}` : `AND NOT (${MAINTAINER_ANSWER} AND NOT ${settledBySql(db, "decisions")})`}`); } /** Items whose latest scope answer is a maintainer's that no longer counts: the item waits for a decision again instead of being reviewed on it. */ export async function unsettledScope(db: Db): Promise> { - return new Set((await scopeRows(db, `AND ${MAINTAINER_ANSWER} AND NOT ${settledBySql("decisions")}`)).keys()); + return new Set((await scopeRows(db, `AND ${MAINTAINER_ANSWER} AND NOT ${settledBySql(db, "decisions")}`)).keys()); } /** @@ -66,7 +66,7 @@ export async function settledScope(db: Db, repo: string, number: number): Promis const answer = (await scopeAnswers(db)).get(ref); if (!answer || !KEEP_IN_CORE.includes(answer)) return null; const rows = await db.prepare(`SELECT answered_by, answer_note, repo, number, items FROM decisions - WHERE kind = 'scope' AND answer = ? AND answered_by IS NOT NULL AND answered_by <> 'pipeline' AND NOT (${MAINTAINER_ANSWER} AND NOT ${settledBySql("decisions")}) ORDER BY answered_at DESC`).all(answer) as + WHERE kind = 'scope' AND answer = ? AND answered_by IS NOT NULL AND answered_by <> 'pipeline' AND NOT (${MAINTAINER_ANSWER} AND NOT ${settledBySql(db, "decisions")}) ORDER BY answered_at DESC`).all(answer) as { answered_by: string; answer_note: string | null; repo: string | null; number: number | null; items: string | null }[]; const r = rows.find((x) => (x.number !== null ? x.repo === repo && x.number === number : parseRefs(x.items).some((i) => i.repo === repo && i.number === number))); if (!r) return null; diff --git a/src/review/diff.ts b/src/review/diff.ts index 13a128984..349ea8f99 100644 --- a/src/review/diff.ts +++ b/src/review/diff.ts @@ -328,7 +328,7 @@ export function diffFactsOfCache(repo: string, number: number, head: string): Di const putFacts = (db: Db) => db.prepare(`INSERT INTO diff_facts (repo, number, head_oid, reasons, lines, pending, last_read) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (repo, number, head_oid) DO UPDATE SET reasons = excluded.reasons, lines = excluded.lines, pending = excluded.pending, last_read = excluded.last_read - WHERE reasons IS NOT excluded.reasons OR lines IS NOT excluded.lines OR pending IS NOT excluded.pending OR last_read IS NOT excluded.last_read`); + WHERE diff_facts.reasons IS DISTINCT FROM excluded.reasons OR diff_facts.lines IS DISTINCT FROM excluded.lines OR diff_facts.pending IS DISTINCT FROM excluded.pending OR diff_facts.last_read IS DISTINCT FROM excluded.last_read`); const dropFacts = (db: Db) => db.prepare("DELETE FROM diff_facts WHERE repo = ? AND number = ? AND head_oid = ?"); async function writeFacts(db: Db, repo: string, number: number, head: string, f: DiffFacts | null): Promise { diff --git a/src/settlers.ts b/src/settlers.ts index 5020eebb0..ced7d775b 100644 --- a/src/settlers.ts +++ b/src/settlers.ts @@ -7,8 +7,13 @@ import { PERM_READ_TTL } from "./dash/server/sessions.ts"; import { HttpError } from "./dash/server/util.ts"; import { slugOf } from "./owners.ts"; import { everySeq } from "./async-seq.ts"; +import type { Dialect } from "./db/index.ts"; +import { jsonEach, jsonText, jsonValid, nowParam, quote } from "./db/portable.ts"; import type { Db } from "./db/index.ts"; +type D = Dialect | { readonly dialect: Dialect }; +const pgOf = (d: D): boolean => (typeof d === "string" ? d : d.dialect) === "postgres"; + export const MAINTAINER_WRITES_KEY = "maintainer_writes"; export const maintainerWritesOn = async (db: Db): Promise => @@ -133,12 +138,16 @@ export const settlesCheckedAtSql = (login: string, repo: string): string => `(CA * maintainer while `maintainer_writes` is on and every repo the decision covers (its own and its batch items') has the app's * identity, so its merge or close is made as that person. Checked wherever the pipeline reads answers. */ -export const settledBySql = (a: string): string => `(${a}.exec_state IS NOT 'disputed' AND (${a}.answered_by IN (SELECT login FROM main.access WHERE role = 'operator') +export const settledBySql = (d: D, a: string): string => `(${a}.exec_state IS DISTINCT FROM 'disputed' AND (${a}.answered_by IN (SELECT login FROM main.access WHERE role = 'operator') OR (${a}.answered_by IN ${SETTLER_LOGINS_SQL} - AND (${a}.repo IS NOT NULL OR json_array_length(CASE WHEN json_valid(${a}.items) THEN ${a}.items ELSE '[]' END) > 0) + AND (${a}.repo IS NOT NULL OR ${arrayLength(d, itemsOf(d, a))} > 0) AND NOT EXISTS (SELECT 1 WHERE ${a}.repo IS NOT NULL AND NOT EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'github_identity' AND s.value = 'app')) - AND NOT EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(${a}.items) THEN ${a}.items ELSE '[]' END) j - WHERE json_extract(j.value, '$.repo') IS NOT NULL AND NOT EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'github_identity' AND s.value = 'app')))))`; + AND NOT EXISTS (SELECT 1 FROM ${jsonEach(d, itemsOf(d, a), "j")} + WHERE ${jsonText(d, "j.value", "$.repo")} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'github_identity' AND s.value = 'app')))))`; + +/** A decision's `items` when it is valid JSON, else an empty array. */ +const itemsOf = (d: D, a: string): string => `CASE WHEN ${jsonValid(d, `${a}.items`)} THEN ${a}.items ELSE '[]' END`; +const arrayLength = (d: D, expr: string): string => pgOf(d) ? `json_array_length((${expr})::json)` : `json_array_length(${expr})`; /** The same check for one loaded decision row. */ export async function settledBy(db: Db, d: { answered_by: string | null; repo: string | null; items: string | null; exec_state?: string | null }, m: SettleMemo = settleMemo()): Promise { @@ -156,16 +165,20 @@ export async function settledBy(db: Db, d: { answered_by: string | null; repo: s * settles everything. A maintainer needs `maintainer_writes` on, and for the decision's repo and every batch item's repo the app's identity and a fresh * cached write permission. Anyone else settles nothing. */ -export function canSettleSql(login: string, role: string, a = "decisions"): string { - if (role === "operator") return "1"; - if (role !== "maintainer") return "0"; - const me = `'${login.replace(/'/g, "''")}'`; +export function canSettleSql(d: D, login: string, role: string, a = "decisions"): string { + const pg = pgOf(d); + if (role === "operator") return pg ? "TRUE" : "1"; + if (role !== "maintainer") return pg ? "FALSE" : "0"; + const me = quote(login); + // Postgres gets the cut-off as a literal; SQLite computes it in the statement. + const fresh = pg ? quote(nowParam({ offsetMs: -PERM_READ_TTL })) : `strftime('%Y-%m-%dT%H:%M:%fZ', 'now', '-${PERM_READ_TTL / 1000} seconds')`; const ok = (repo: string): string => `(EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'github_identity' AND s.value = 'app') AND EXISTS (SELECT 1 FROM main.repo_permissions rp WHERE rp.login = ${me} AND rp.repo = ${repo} AND rp.permission IN ${WRITE} - AND rp.checked_at > strftime('%Y-%m-%dT%H:%M:%fZ', 'now', '-${PERM_READ_TTL / 1000} seconds')))`; + AND rp.checked_at > ${fresh}))`; + const repoOf = jsonText(d, "j.value", "$.repo"); return `(EXISTS (SELECT 1 FROM main.settings WHERE key = '${MAINTAINER_WRITES_KEY}' AND value = '1') - AND (${a}.repo IS NOT NULL OR json_array_length(CASE WHEN json_valid(${a}.items) THEN ${a}.items ELSE '[]' END) > 0) + AND (${a}.repo IS NOT NULL OR ${arrayLength(d, itemsOf(d, a))} > 0) AND (${a}.repo IS NULL OR ${ok(`${a}.repo`)}) - AND NOT EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(${a}.items) THEN ${a}.items ELSE '[]' END) j - WHERE json_extract(j.value, '$.repo') IS NOT NULL AND NOT ${ok("json_extract(j.value, '$.repo')")}))`; + AND NOT EXISTS (SELECT 1 FROM ${jsonEach(d, itemsOf(d, a), "j")} + WHERE ${repoOf} IS NOT NULL AND NOT ${ok(repoOf)}))`; } diff --git a/test/api.test.ts b/test/api.test.ts index b89760a0c..10163c8db 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -47,7 +47,7 @@ before(async () => { await db.prepare("UPDATE items SET additions = 40, deletions = 3, changed_files = 7 WHERE repo = 'photocraft' AND number = 1").run(); await db.prepare("INSERT INTO comments (repo, number, id, kind, author, created_at, body) VALUES ('photocraft', 1, 'c1', 'comment', 'alice', ?, 'looks good')").run(now); await db.prepare("INSERT INTO classifications (repo, number, classifier, run_id, at, type_label, want, reason) VALUES ('photocraft', 1, 'haiku', 'r1', ?, 'small extra', 'yes', 'adds a filter')").run(now); - await db.script("INSERT OR REPLACE INTO repos (name, visibility) VALUES ('photocraft', 'public'), ('filmcraft', 'public')"); + await db.script("INSERT INTO repos (name, visibility) VALUES ('photocraft', 'public'), ('filmcraft', 'public') ON CONFLICT (name) DO UPDATE SET visibility = excluded.visibility"); await ask(db, [P1, P2, F3, P4].map((id) => { const [repo, rest] = id.split("#"); return { id, kind: id.endsWith("close") ? "close" : "scope", repo, number: Number(rest!.split(":")[0]), question: "Small extra or plugin?", options: OPTS, recommended: "small", summary: "Adds a filter." }; @@ -255,8 +255,8 @@ describe("api", () => { }); test("a maintainer settles only with maintainer_writes on, the app identity on the repo and write access; undo only their own", async () => { - const setting = async (on: boolean) => on ? await db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('maintainer_writes', '1')").run() : await db.prepare("DELETE FROM settings WHERE key = 'maintainer_writes'").run(); - const identity = async (app: boolean) => app ? await db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run() : await db.prepare("DELETE FROM settings WHERE key = 'github_identity'").run(); + const setting = async (on: boolean) => on ? await db.prepare("INSERT INTO settings (key, value) VALUES ('maintainer_writes', '1') ON CONFLICT (key) DO UPDATE SET value = excluded.value").run() : await db.prepare("DELETE FROM settings WHERE key = 'maintainer_writes'").run(); + const identity = async (app: boolean) => app ? await db.prepare("INSERT INTO settings (key, value) VALUES ('github_identity', 'app') ON CONFLICT (key) DO UPDATE SET value = excluded.value").run() : await db.prepare("DELETE FROM settings WHERE key = 'github_identity'").run(); const X1 = "photocraft#7:scope", X2 = "photocraft#8:scope"; await ask(db, [X1, X2].map((id) => ({ id, kind: "scope" as const, repo: "photocraft", number: Number(id.split("#")[1]!.split(":")[0]), question: "Small extra or plugin?", options: OPTS, recommended: "small", summary: "s" }))); const maint = await signedIn("maint"), pal = await signedIn("pal"), boss = await signedIn("boss"); @@ -274,12 +274,12 @@ describe("api", () => { assert.equal(d.answeredBy, "maint"); assert.equal(await auditCount("answer", "maint"), 1); assert.ok((await actionableIds()).includes(X1)); - assert.ok(await db.prepare(`SELECT 1 FROM decisions d WHERE d.id = ? AND ${settledBySql("d")}`).get(X1)); + assert.ok(await db.prepare(`SELECT 1 FROM decisions d WHERE d.id = ? AND ${settledBySql(db, "d")}`).get(X1)); await identity(false); assert.ok(!(await actionableIds()).includes(X1), "an answer on a repo that left the app identity stops counting"); - assert.equal(await db.prepare(`SELECT 1 FROM decisions d WHERE d.id = ? AND ${settledBySql("d")}`).get(X1), undefined, "nor at the SQL sites other than actionable()"); + assert.equal(await db.prepare(`SELECT 1 FROM decisions d WHERE d.id = ? AND ${settledBySql(db, "d")}`).get(X1), undefined, "nor at the SQL sites other than actionable()"); // Work and answers the maintainer started count only while the conditions hold; a flip to legacy stops them everywhere. - await db.prepare("INSERT OR REPLACE INTO repo_permissions (login, repo, permission, checked_at) VALUES ('maint', 'photocraft', 'write', ?)").run(new Date().toISOString()); + await db.prepare("INSERT INTO repo_permissions (login, repo, permission, checked_at) VALUES ('maint', 'photocraft', 'write', ?) ON CONFLICT (login, repo) DO UPDATE SET permission = excluded.permission, checked_at = excluded.checked_at").run(new Date().toISOString()); await db.prepare("INSERT INTO operator_fixups (repo, number, from_head, instructions, by, at) VALUES ('photocraft', 7, 'h1', 'fix it', 'maint', ?)").run(new Date().toISOString()); await identity(true); assert.ok(await queuedOperatorFix(db, "photocraft", 7, "h1")); diff --git a/test/github-app.test.ts b/test/github-app.test.ts index 1b75a058e..c4b1360f7 100644 --- a/test/github-app.test.ts +++ b/test/github-app.test.ts @@ -193,7 +193,7 @@ describe("github app registration", () => { }); test("app sign-in keeps the user's token sealed in user_tokens", async () => { - await db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + await db.prepare("INSERT INTO settings (key, value) VALUES ('github_identity', 'app') ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(); const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: secretsFile }; const s = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [] }); closers.push(s.close); @@ -275,7 +275,7 @@ describe("github app registration", () => { }); test("a refreshed app sign-in token reaches user_tokens", async () => { - await db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + await db.prepare("INSERT INTO settings (key, value) VALUES ('github_identity', 'app') ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(); const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: secretsFile }; const provider = new FakeProvider(permsFile, 300); const routes: Route[] = [{ method: "GET", pattern: "/api/test/can/:repo", handler: async (_db, r) => ({ json: { can: await r.user.canWrite(r.params.repo!) } }) }]; @@ -460,7 +460,7 @@ describe("github app registration", () => { writeFileSync(file, JSON.stringify({ other_key: "kept", github_app_id: "4242", github_app_slug: "autocraft-test", github_app_private_key: PEM, github_app_client_id: "Iv1.test", github_app_client_secret: CLIENT_SECRET, github_app_webhook_secret: "", github_app_owner: { login: "glasswing", type: "Organization" } }), { mode: 0o600 }); const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: file }; const githubApi = `http://127.0.0.1:${(github.address() as AddressInfo).port}`; - await db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + await db.prepare("INSERT INTO settings (key, value) VALUES ('github_identity', 'app') ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(); const appMode = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [], githubApi }); closers.push(appMode.close); const locked = await signedIn("boss", appMode.url); diff --git a/test/live-board.test.ts b/test/live-board.test.ts index 7f59bd33c..078f279f1 100644 --- a/test/live-board.test.ts +++ b/test/live-board.test.ts @@ -12,10 +12,10 @@ const ago = (min: number) => new Date(Date.now() - min * 60_000).toISOString(); test("the live board shows a running job with its call and build steps, an estimate from earlier runs, and drops idle ended jobs", async () => { const db = await connectDb(":memory:"); await db.prepare("INSERT INTO items (repo, number, kind, state, title, updated_at) VALUES ('app', 7, 'pr', 'OPEN', 'Fix the thing', ?)").run(ago(1)); - const job = db.prepare("INSERT INTO jobs (step, params, requested_by, requested_at, state, started_at, ended_at, progress, summary) VALUES (?, '{}', 'pipeline', ?, ?, ?, ?, ?, ?)"); + const job = db.prepare("INSERT INTO jobs (step, params, requested_by, requested_at, state, started_at, ended_at, progress, summary) VALUES (?, '{}', 'pipeline', ?, ?, ?, ?, ?, ?) RETURNING id"); // Earlier review jobs of 10, 12, 14 and 30 minutes and the 1-minute one below give the estimate. for (const m of [10, 12, 14, 30]) await job.run("review", ago(200), "done", ago(200), ago(200 - m), null, "old"); - const running = Number((await job.run("review", ago(5), "running", ago(5), null, "Reviewing app#7", null)).lastInsertRowid); + const running = Number((await job.get("review", ago(5), "running", ago(5), null, "Reviewing app#7", null) as { id: number }).id); await job.run("review", ago(3), "done", ago(4), ago(3), null, "nothing to do"); await db.prepare("INSERT INTO job_items (job_id, repo, number, at) VALUES (?, 'app', 7, ?)").run(running, ago(5)); await db.prepare(`INSERT INTO agent_runs (job_id, step, stage, prompt_id, prompt_version, provider, model, items, item_count, state, started_at, ended_at) @@ -43,7 +43,7 @@ test("viewers see no account label and no progress line that names a repo hidden const db = await connectDb(":memory:"); await db.script("INSERT INTO repos (name, visibility) VALUES ('app', 'public'), ('secret', 'private'); INSERT OR IGNORE INTO tracked_repos (name) VALUES ('app'), ('secret')"); await db.prepare("INSERT INTO claude_accounts (id, label) VALUES ('acc', 'Team account B')").run(); - const job = Number((await db.prepare("INSERT INTO jobs (step, params, requested_by, requested_at, state, started_at, progress) VALUES ('review', '{}', 'pipeline', ?, 'running', ?, 'Reviewing app#7')").run(ago(5), ago(5))).lastInsertRowid); + const job = Number((await db.prepare("INSERT INTO jobs (step, params, requested_by, requested_at, state, started_at, progress) VALUES ('review', '{}', 'pipeline', ?, 'running', ?, 'Reviewing app#7') RETURNING id").get(ago(5), ago(5)) as { id: number }).id); await db.prepare("INSERT INTO job_items (job_id, repo, number, at) VALUES (?, 'app', 7, ?)").run(job, ago(5)); const run = async (jobId: number | null, progress: string) => { const id = await insertRun(db, { jobId, step: "review", stage: 1, promptId: "p", promptVersion: "1", provider: "claude", model: "opus", accountId: "acc", items: [{ repo: "app", number: 7 }], prompt: "p" }); diff --git a/test/mcp-queue.test.ts b/test/mcp-queue.test.ts index 9ac7901ef..1c8b85ee4 100644 --- a/test/mcp-queue.test.ts +++ b/test/mcp-queue.test.ts @@ -113,9 +113,9 @@ describe("merge queue tools", () => { }; // Maintainer writes off, then on without the app identity: nothing changes. await refusedAll(); - await w.db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('maintainer_writes', '1')").run(); + await w.db.prepare("INSERT INTO settings (key, value) VALUES ('maintainer_writes', '1') ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(); await refusedAll(); - await w.db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + await w.db.prepare("INSERT INTO settings (key, value) VALUES ('github_identity', 'app') ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(); const r = await call(maint, "queue_pr", { item: "app#1", weight: 6 }); assert.equal(r.isError, false, r.text); assert.match(r.text, /The weight was ignored: only operators set fast-track weights/); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 374bff8fc..8d2c2d840 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -43,7 +43,7 @@ before(async () => { await ins.run("photocraft", 9, "pr", "OPEN", "Fix-up being pushed", "t", "tess", now, now, "h9"); await ins.run("photocraft", 10, "issue", "OPEN", "Add a sepia filter", "please", "ann", now, now, null); await db.script("INSERT OR IGNORE INTO tracked_repos (name, added_by, added_at) VALUES ('secretcraft', 'test', '2026-01-01T00:00:00Z')"); - await db.script("INSERT OR REPLACE INTO repos (name, visibility) VALUES ('photocraft', 'public'), ('filmcraft', 'public'), ('secretcraft', 'private')"); + await db.script("INSERT INTO repos (name, visibility) VALUES ('photocraft', 'public'), ('filmcraft', 'public'), ('secretcraft', 'private') ON CONFLICT (name) DO UPDATE SET visibility = excluded.visibility"); await ask(db, [P1, F3, S7, P10].map((id) => { const [repo, rest] = id.split("#"); return { id, kind: "scope", repo, number: Number(rest!.split(":")[0]), question: "Small extra or plugin?", options: OPTS, recommended: "small", summary: "Adds a filter." }; From 09376e1212a250965e3c1b0fb5170bfda2852c24 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:55:24 +0000 Subject: [PATCH 2/2] Dashboard SQL on both dialects: now, shown, work, limits, setup links and user-lane comparisons --- src/dash/api/limits.ts | 2 +- src/dash/api/needs.ts | 2 +- src/dash/api/now.ts | 9 +++++---- src/dash/api/shown.ts | 3 ++- src/dash/api/work.ts | 3 ++- src/dash/server/github-setup.ts | 7 ++++--- src/github/user-lane.ts | 5 +++-- 7 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/dash/api/limits.ts b/src/dash/api/limits.ts index ebb41c35f..6b47d677f 100644 --- a/src/dash/api/limits.ts +++ b/src/dash/api/limits.ts @@ -16,7 +16,7 @@ export async function pipelineSwitch(db: Db): Promise { export async function zeroLimits(db: Db): Promise<{ step: string; title: string }[]> { const steps = await loadSteps(); const perDay = new Map((await db.prepare("SELECT step, per_day FROM stage_limits").all() as { step: string; per_day: number | null }[]).map((r) => [r.step, r.per_day])); - const tripped = new Set((await db.prepare("SELECT stage FROM stage_trips WHERE active").all() as { stage: string }[]).map((r) => r.stage)); + const tripped = new Set((await db.prepare("SELECT stage FROM stage_trips WHERE active <> 0").all() as { stage: string }[]).map((r) => r.stage)); return LIMIT_STEPS .filter((step) => (perDay.has(step) ? perDay.get(step) : (DEFAULT_PER_DAY[step] ?? null)) === 0 && !(STEP_STAGE[step] && tripped.has(STEP_STAGE[step]!))) .map((step) => ({ step, title: steps.get(step)?.title ?? step })); diff --git a/src/dash/api/needs.ts b/src/dash/api/needs.ts index a4a245f18..a8450f506 100644 --- a/src/dash/api/needs.ts +++ b/src/dash/api/needs.ts @@ -142,7 +142,7 @@ export async function stopped(db: Db, hidden: HiddenRepos): Promise(rows: T[], key: (r: T) => K): Map => { /** The first `per` items of each run, by repo and number. */ const runItems = async (db: Db, ids: number[], per: number): Promise> => groupBy(ids.length ? await all<{ run_id: number; repo: string; number: number }>(db, `SELECT run_id, repo, number FROM (SELECT run_id, repo, number, ROW_NUMBER() OVER (PARTITION BY run_id ORDER BY repo, number) AS k - FROM agent_run_items WHERE run_id IN (SELECT value FROM json_each(?))) WHERE k <= ? ORDER BY run_id, repo, number`, JSON.stringify(ids), per) : [], (r) => r.run_id); + FROM agent_run_items WHERE ${inList(db, "run_id", "?", "bigint")}) WHERE k <= ? ORDER BY run_id, repo, number`, JSON.stringify(ids), per) : [], (r) => r.run_id); /** The PR numbers of each merge batch, in batch order. */ const batchPrs = async (db: Db, ids: number[]): Promise> => - groupBy(ids.length ? await all<{ batch_id: number; number: number }>(db, "SELECT batch_id, number FROM merge_batch_prs WHERE batch_id IN (SELECT value FROM json_each(?)) ORDER BY batch_id, position", JSON.stringify([...new Set(ids)])) : [], (r) => r.batch_id); + groupBy(ids.length ? await all<{ batch_id: number; number: number }>(db, `SELECT batch_id, number FROM merge_batch_prs WHERE ${inList(db, "batch_id", "?", "bigint")} ORDER BY batch_id, position`, JSON.stringify([...new Set(ids)])) : [], (r) => r.batch_id); /** Merge batch ids by repo and branch, joined by a NUL. */ async function batchIdsOf(db: Db, keys: [string, string][]): Promise> { const out = new Map(); if (!keys.length) return out; - for (const r of await all<{ id: number; repo: string; branch: string }>(db, "SELECT id, repo, branch FROM main.merge_batches WHERE (repo, branch) IN (SELECT value ->> 0, value ->> 1 FROM json_each(?)) ORDER BY id", JSON.stringify(keys))) + for (const r of await all<{ id: number; repo: string; branch: string }>(db, `SELECT id, repo, branch FROM main.merge_batches WHERE ${inTuples(db, ["repo", "branch"], "?", ["text", "text"])} ORDER BY id`, JSON.stringify(keys))) if (!out.has(`${r.repo}\0${r.branch}`)) out.set(`${r.repo}\0${r.branch}`, r.id); return out; } @@ -217,7 +218,7 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole const jobEntries = new Map; from: number; to: number }>(); const listed = [...running, ...finished].filter((j) => !(QUIET_STEPS.has(j.step) && j.state !== "failed")); const itemsOfJob = groupBy(listed.length ? await all<{ job_id: number; id: number; repo: string; number: number }>(db, - `SELECT job_id, id, repo, number FROM job_items WHERE job_id IN (SELECT value FROM json_each(?))${notHidden("repo", hidden)} ORDER BY id`, JSON.stringify(listed.map((j) => j.id)), ...hideArgs(hidden)) : [], (r) => r.job_id); + `SELECT job_id, id, repo, number FROM job_items WHERE ${inList(db, "job_id", "?", "bigint")}${notHidden("repo", hidden)} ORDER BY id`, JSON.stringify(listed.map((j) => j.id)), ...hideArgs(hidden)) : [], (r) => r.job_id); for (const j of [...running, ...finished]) { const live = j.state === "running"; if (QUIET_STEPS.has(j.step) && j.state !== "failed") { diff --git a/src/dash/api/shown.ts b/src/dash/api/shown.ts index 08486c8f0..0e124d69f 100644 --- a/src/dash/api/shown.ts +++ b/src/dash/api/shown.ts @@ -1,6 +1,7 @@ // Kind, state and title of mirrored items, for rows that show an item reference. import type { ItemRef, ItemShown, ItemState } from "../../../web/src/api/types.ts"; import type { Db } from "../../db/index.ts"; +import { inTuples } from "../../db/portable.ts"; const STATE: Record = { OPEN: "open", MERGED: "merged", CLOSED: "closed" }; export const itemState = (s: string | null | undefined): ItemState => STATE[s ?? ""] ?? "open"; @@ -21,7 +22,7 @@ export async function shownMap(db: Db, refs: Iterable<{ repo: string; number: nu for (const r of refs) keys.set(`${r.repo}#${r.number}`, [r.repo, r.number]); const out = new Map(); if (!keys.size) return out; - const rows = await db.prepare(`SELECT repo, number, kind, state, title FROM items WHERE (repo, number) IN (SELECT value ->> 0, value ->> 1 FROM json_each(?))`) + const rows = await db.prepare(`SELECT repo, number, kind, state, title FROM items WHERE ${inTuples(db, ["repo", "number"], "?", ["text", "bigint"])}`) .all(JSON.stringify([...keys.values()])) as { repo: string; number: number; kind: string; state: string; title: string | null }[]; for (const r of rows) out.set(`${r.repo}#${r.number}`, { kind: r.kind === "pr" ? "pr" : "issue", state: itemState(r.state), title: r.title }); return out; diff --git a/src/dash/api/work.ts b/src/dash/api/work.ts index b186d367e..d3b9d3202 100644 --- a/src/dash/api/work.ts +++ b/src/dash/api/work.ts @@ -8,6 +8,7 @@ import type { Req } from "../types.ts"; import { visibleRepos } from "./visible.ts"; import { readerOf, veiledFor } from "./reader.ts"; import type { Db } from "../../db/index.ts"; +import { jsonText } from "../../db/portable.ts"; type Row = { repo: string; number: number; kind: string; title: string | null; score: number; breakdown: string; next: string | null; label: string | null; item_state: string | null }; @@ -24,7 +25,7 @@ export async function work(db: Db, req: Req): Promise { const where = `i.state = 'OPEN' AND i.repo IN (${repos.map(() => "?").join(",")})${kind ? " AND i.kind = ?" : ""}`; const args = [...repos, ...(kind ? [kind] : [])]; const total = (await db.prepare(`SELECT COUNT(*) AS n FROM items i JOIN item_rank r ON r.repo = i.repo AND r.number = i.number WHERE ${where}`).get(...args) as { n: number }).n; - const rows = await db.prepare(`SELECT i.repo, i.number, i.kind, i.title, r.score, r.breakdown, json_extract(p.view, '$.next') AS next, json_extract(p.view, '$.label') AS label, p.item_state + const rows = await db.prepare(`SELECT i.repo, i.number, i.kind, i.title, r.score, r.breakdown, ${jsonText(db, "p.view", "$.next")} AS next, ${jsonText(db, "p.view", "$.label")} AS label, p.item_state FROM items i JOIN item_rank r ON r.repo = i.repo AND r.number = i.number LEFT JOIN item_plans p ON p.repo = i.repo AND p.number = i.number WHERE ${where} ORDER BY r.score DESC, i.repo, i.number LIMIT ? OFFSET ?`).all(...args, limit, offset) as Row[]; const reader = await readerOf(db, req); diff --git a/src/dash/server/github-setup.ts b/src/dash/server/github-setup.ts index 85cbbc911..70f73102d 100644 --- a/src/dash/server/github-setup.ts +++ b/src/dash/server/github-setup.ts @@ -17,6 +17,7 @@ import { convertAndStore, DEFAULT_APP_NAME, publicBase } from "./github-app.ts"; import type { GithubUser, Provider, Tokens } from "./provider.ts"; import { esc, plainPage } from "./util.ts"; import type { Db } from "../../db/index.ts"; +import { ciEq } from "../../db/portable.ts"; export const SETUP_COOKIE = "__Host-craft_setup"; const LINK_TTL_MS = 7 * 86_400_000; @@ -49,16 +50,16 @@ export async function revokeLink(db: Db, operator: string, id: string): Promise< /** Links that can still be used, newest first. */ export async function openLinks(db: Db): Promise { - const rows = await db.prepare(`SELECT id, org, created_by, created_at, expires_at FROM github_setup_links WHERE revoked_at IS NULL AND used_at IS NULL AND expires_at > ? AND ${BY_OPERATOR} ORDER BY created_at DESC`) + const rows = await db.prepare(`SELECT id, org, created_by, created_at, expires_at FROM github_setup_links WHERE revoked_at IS NULL AND used_at IS NULL AND expires_at > ? AND ${byOperator(db)} ORDER BY created_at DESC`) .all(new Date().toISOString()) as LinkRow[]; return rows.map((l) => ({ id: l.id, org: l.org, createdBy: l.created_by, createdAt: l.created_at, expiresAt: l.expires_at })); } /** A link works only while its creator is an operator on the access list. */ -const BY_OPERATOR = "EXISTS (SELECT 1 FROM access a WHERE a.login = github_setup_links.created_by COLLATE NOCASE AND a.role = 'operator')"; +const byOperator = (db: Db): string => `EXISTS (SELECT 1 FROM access a WHERE ${ciEq(db, "a.login", "github_setup_links.created_by")} AND a.role = 'operator')`; const openLink = async (db: Db, where: "id" | "hash", value: string): Promise => - (await db.prepare(`SELECT * FROM github_setup_links WHERE ${where} = ? AND revoked_at IS NULL AND used_at IS NULL AND expires_at > ? AND ${BY_OPERATOR}`).get(value, new Date().toISOString()) as LinkRow | undefined) ?? null; + (await db.prepare(`SELECT * FROM github_setup_links WHERE ${where} = ? AND revoked_at IS NULL AND used_at IS NULL AND expires_at > ? AND ${byOperator(db)}`).get(value, new Date().toISOString()) as LinkRow | undefined) ?? null; // ---- The visitor's flow ----------------------------------------------------- diff --git a/src/github/user-lane.ts b/src/github/user-lane.ts index 5c61b8d05..3ceee5926 100644 --- a/src/github/user-lane.ts +++ b/src/github/user-lane.ts @@ -16,6 +16,7 @@ import { exec as defaultExec, type Exec } from "../fixup/git.ts"; import { Client, GithubError, Transient, type Querier } from "../mirror.ts"; import { slugOf } from "../owners.ts"; import type { Db } from "../db/index.ts"; +import { ciEq } from "../db/portable.ts"; export type ExecState = "pending" | "waiting-token" | "waiting-permission" | "done" | "failed"; export const WAITING: readonly ExecState[] = ["waiting-token", "waiting-permission"]; @@ -25,7 +26,7 @@ export const noWriteReason = (repo: string): string => `You have no write access /** Sets the state shown on the decision. Writes nothing when it is already that, so the planner is not woken for nothing. */ export async function setExecState(db: Db, id: string, state: ExecState, reason: string | null = null): Promise { - await db.prepare("UPDATE main.decisions SET exec_state = ?, exec_reason = ? WHERE id = ? AND exec_state IS NOT 'disputed' AND (exec_state IS NOT ? OR exec_reason IS NOT ?)").run(state, reason, id, state, reason); + await db.prepare("UPDATE main.decisions SET exec_state = ?, exec_reason = ? WHERE id = ? AND exec_state IS DISTINCT FROM 'disputed' AND (exec_state IS DISTINCT FROM ? OR exec_reason IS DISTINCT FROM ?)").run(state, reason, id, state, reason); } /** Decisions the pipeline applied are done. */ @@ -48,7 +49,7 @@ export async function initExecState(db: Db, id: string): Promise { /** Puts the waiting (and, for one decision, failed) decisions back to pending so the stages take them up again. Returns how many changed. */ export async function retryWaiting(db: Db, login?: string): Promise { const r = await db.prepare(`UPDATE main.decisions SET exec_state = 'pending', exec_reason = NULL - WHERE exec_state IN ('waiting-token', 'waiting-permission') AND applied_at IS NULL AND answer IS NOT NULL AND (? IS NULL OR answered_by = ? COLLATE NOCASE)`).run(login ?? null, login ?? null); + WHERE exec_state IN ('waiting-token', 'waiting-permission') AND applied_at IS NULL AND answer IS NOT NULL AND (CAST(? AS TEXT) IS NULL OR ${ciEq(db, "answered_by", "?")})`).run(login ?? null, login ?? null); return Number(r.changes); }