diff --git a/src/answers/hold.ts b/src/answers/hold.ts index 49bb6c5fb..7c16a4dda 100644 --- a/src/answers/hold.ts +++ b/src/answers/hold.ts @@ -109,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 NOT ${ciEq(db, "answered_by", "?")} + 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 }); 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,24 +455,24 @@ 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}))`; } /** @@ -491,7 +492,7 @@ export function needingSql(db: Db, 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 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; @@ -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 01e252e9a..b2c936c54 100644 --- a/src/dash/api/home.ts +++ b/src/dash/api/home.ts @@ -38,7 +38,7 @@ async function phases(db: Db, hidden: string[]): Promise { const params: Record = {}; - const hide = withoutHidden(hidden, params); + 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; 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 65f7d33c1..b9a49854d 100644 --- a/src/dash/api/items.ts +++ b/src/dash/api/items.ts @@ -24,6 +24,7 @@ import { ITEM_PHASES, PHASE_SQL, type ItemPhase, type ItemStatus, type ItemStatu import { mapSeq } from "../../async-seq.ts"; import type { Db, Dialect } from "../../db/index.ts"; import { commentMatchSql, commentRankOrder, itemMatchSql, parseSearch, searchParam, snippetSql } from "../../db/search.ts"; +import { indexedBy } from "../../db/portable.ts"; // Items matching the query bound as :q in their title, body or any comment. const hitIds = (d: Dialect): string => `hits AS ( @@ -231,7 +232,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) + @@ -328,7 +329,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/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 ba815fdee..a8450f506 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(); @@ -138,13 +142,15 @@ 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 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]; diff --git a/src/dash/api/now.ts b/src/dash/api/now.ts index 968fd7621..5835de72c 100644 --- a/src/dash/api/now.ts +++ b/src/dash/api/now.ts @@ -18,6 +18,7 @@ import { blankIfHidden, hiddenRepos } from "./visible.ts"; import { filtered, hiddenTest, isHiddenRepo, type HiddenRepos } from "../../hidden-sql.ts"; import { touchesHidden } from "../../agents/runs.ts"; import type { Db } from "../../db/index.ts"; +import { inList, inTuples } from "../../db/portable.ts"; const RECENT = 15; type Feed = { entries: NowEntry[]; also: string[]; nextCursor: string | null }; @@ -55,15 +56,15 @@ const groupBy = (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/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/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/stats.ts b/src/dash/api/stats.ts index 3f145babf..fbfbfe446 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, settledOn, 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); @@ -51,7 +52,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, @@ -74,8 +75,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/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/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/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/db/portable.ts b/src/db/portable.ts index 555cee7d1..bab98e803 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")` | @@ -21,6 +22,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` | @@ -61,6 +63,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})`; @@ -272,3 +283,8 @@ export function rowidOf(table: string): string { 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/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/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); } diff --git a/src/merge/batch-store.ts b/src/merge/batch-store.ts index 4056ad1f8..2d6e85004 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/test/api.test.ts b/test/api.test.ts index 1a71d6c81..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"); @@ -279,7 +279,7 @@ describe("api", () => { 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(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." };