{"draft":null,"from":3,"to":318,"files":[{"path":"server/src/issues/store.ts","added":1693,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues/store.ts\n@@ -0,0 +1,1693 @@\n+// Issues for the open server (abso-core issue 17): one store per project, in SQLite, holding current state:\n+// issues, comments, labels, asks with their answers and threads, claims, the versions out for each issue,\n+// drafts, and what each reader's news has shown. Ported from the platform's issues Worker, without its\n+// workflow and release stores, prose authorship records, attachments, copies and meaning search.\n+//\n+// Status comes from the work and nobody sets it: Done when a publish closed it (or someone marked it done),\n+// Blocked while an ask that isn't a review is open on it (or names it in `blocks`) or an issue it is blocked\n+// by is not done, In review while a review ask is open on it, In progress while a start note names it, and\n+// Open otherwise. An answer is kept in its writer's own words on the ask it answers.\n+//\n+// Watchers: who opened an issue, its Agent and any agent that claims it, its reviewer, whoever was named in\n+// Notify, and whoever comments. An edit tells them unless its writer says not to.\n+\n+import type {\n+\tActor,\n+\tAsk,\n+\tAskReply,\n+\tComment,\n+\tDraft,\n+\tDraftBody,\n+\tEdit,\n+\tIssuePage,\n+\tIssueRow,\n+\tLines,\n+\tNews,\n+\tProseAuthorship,\n+\tStatus,\n+} from \"../../../client/src/issues-wire.ts\";\n+import { unseenIn } from \"../../../worker/project/unseen.ts\";\n+\n+export type {\n+\tActor,\n+\tAsk,\n+\tClaim,\n+\tComment,\n+\tDraft,\n+\tDraftBody,\n+\tEdit,\n+\tIssuePage,\n+\tIssueRow,\n+\tLines,\n+\tNews,\n+\tStatus,\n+} from \"../../../client/src/issues-wire.ts\";\n+\n+/** The SQL a Durable Object's storage gives (ctx.storage.sql), and node:sqlite in tests. */\n+export interface Sql {\n+\texec(query: string, ...bindings: unknown[]): { toArray(): unknown[] };\n+}\n+\n+/** A plain sentence for the person or agent; the route answers with it and `status`. */\n+export class IssuesError extends Error {\n+\treadonly status: number;\n+\t/** Seconds until a refused write may be tried again (429), for Retry-After. */\n+\treadonly retryAfter: number | undefined;\n+\tconstructor(message: string, status = 400, retryAfter?: number) {\n+\t\tsuper(message);\n+\t\tthis.status = status;\n+\t\tthis.retryAfter = retryAfter;\n+\t}\n+}\n+\n+/**\n+ * A label: 1-40 characters of lower-case letters, digits, and - _ . : (so\n+ * \"friction\", \"good-first-issue\", \"area:client\"). Anything else is refused,\n+ * upper case included, rather than changed: the client and the\n+ * site lower-case what's typed before sending.\n+ */\n+export const LABEL = /^[a-z0-9][a-z0-9_.:-]{0,39}$/;\n+export const LABELS_PER_ISSUE = 20;\n+/** Distinct labels a project may hold, since GET labels lists every one. */\n+export const LABELS_PER_PROJECT = 200;\n+\n+/** Writes per writer (agent or person:<id>), since each can carry news. */\n+export const WRITES_PER_MINUTE = 100;\n+export const WRITES_PER_DAY = 1000;\n+\n+/** At most this many @names in one comment are told. */\n+export const MENTIONS_MAX = 20;\n+\n+/**\n+ * The agents a text names as @name, in order, each once: an @ at the start or after anything\n+ * but a name character, so an email address isn't one. A sentence's full stop or dash after the name isn't\n+ * part of it.\n+ */\n+export function mentionsIn(text: string): string[] {\n+\tconst names = new Set<string>();\n+\tfor (const m of text.matchAll(/(?:^|[^A-Za-z0-9._@-])@([A-Za-z0-9][A-Za-z0-9._-]{0,63})/g)) {\n+\t\tnames.add(m[1]!.replace(/[._-]+$/, \"\"));\n+\t\tif (names.size === MENTIONS_MAX) break;\n+\t}\n+\treturn [...names];\n+}\n+\n+const LIMITS = {\n+\ttitle: 200,\n+\tdescription: 20_000,\n+\ttext: 4_000,\n+\topen: 10_000,\n+\toptions: 10,\n+\tblocks: 50,\n+\tnames: 50,\n+\tdrafts: 100,\n+\tdraft: 30_000,\n+};\n+\n+/**\n+ * The tables the change count watches: what issue reads show. Not drafts (one person's), writes (the rate log),\n+ * search (kept from issues and comments) or meta. Fixed, since SCHEMA makes three triggers for each: a later\n+ * table appends its own three to SCHEMA instead.\n+ */\n+const COUNTED_TABLES = [\n+\t\"issues\",\n+\t\"comments\",\n+\t\"asks\",\n+\t\"claims\",\n+\t\"versions\",\n+\t\"watchers\",\n+\t\"blocked_by\",\n+\t\"edits\",\n+\t\"labels\",\n+\t\"ask_replies\",\n+] as const;\n+\n+/**\n+ * The tables, as add-only migrations: the IssueProject object runs each once, in order (index.ts), so an\n+ * older Worker still reads a newer database. Append; never edit or reorder.\n+ */\n+export const SCHEMA: readonly string[] = [\n+\t`CREATE TABLE IF NOT EXISTS issues (id INTEGER PRIMARY KEY, parent INTEGER, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',\n+\t\topened_by TEXT NOT NULL, opened_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, lines TEXT,\n+\t\tclosed_how TEXT, closed_by TEXT, closed_version INTEGER, closed_at INTEGER, agent TEXT)`,\n+\t\"CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY, issue INTEGER NOT NULL, by TEXT NOT NULL, kind TEXT NOT NULL, text TEXT NOT NULL, at INTEGER NOT NULL)\",\n+\t`CREATE TABLE IF NOT EXISTS asks (id INTEGER PRIMARY KEY, issue INTEGER, by TEXT NOT NULL, of TEXT NOT NULL, kind TEXT NOT NULL, question TEXT NOT NULL,\n+\t\treview INTEGER NOT NULL, due TEXT, recommendation TEXT, options TEXT NOT NULL, blocks TEXT NOT NULL, at INTEGER NOT NULL,\n+\t\tanswer_by TEXT, answer_words TEXT, answer_at INTEGER, seen_at INTEGER, outcome TEXT, ack_at INTEGER, ack_note TEXT, waiting_on TEXT)`,\n+\t\"CREATE TABLE IF NOT EXISTS claims (issue INTEGER NOT NULL, agent TEXT NOT NULL, change INTEGER NOT NULL, since INTEGER NOT NULL, PRIMARY KEY (issue, agent))\",\n+\t\"CREATE TABLE IF NOT EXISTS versions (issue INTEGER NOT NULL, version INTEGER NOT NULL, agent TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (issue, version))\",\n+\t\"CREATE TABLE IF NOT EXISTS watchers (issue INTEGER NOT NULL, who TEXT NOT NULL, since INTEGER NOT NULL, PRIMARY KEY (issue, who))\",\n+\t\"CREATE TABLE IF NOT EXISTS blocked_by (issue INTEGER NOT NULL, blocker INTEGER NOT NULL, PRIMARY KEY (issue, blocker))\",\n+\t\"CREATE TABLE IF NOT EXISTS edits (id INTEGER PRIMARY KEY, issue INTEGER NOT NULL, by TEXT NOT NULL, changes TEXT NOT NULL, notified TEXT NOT NULL, at INTEGER NOT NULL)\",\n+\t\"CREATE TABLE IF NOT EXISTS drafts (id INTEGER PRIMARY KEY, owner TEXT NOT NULL, body TEXT NOT NULL, saved_at INTEGER NOT NULL)\",\n+\t// Each writer's writes of the last day, for the limit.\n+\t\"CREATE TABLE IF NOT EXISTS writes (who TEXT NOT NULL, at INTEGER NOT NULL)\",\n+\t\"CREATE TABLE IF NOT EXISTS labels (issue INTEGER NOT NULL, label TEXT NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (issue, label))\",\n+\t// Ask threads: replies from either side while the ask is open or after. An ask's waiting_on is null while it\n+\t// waits on the one asked, and the asker's name after the one asked replies with a question.\n+\t\"CREATE TABLE IF NOT EXISTS ask_replies (id INTEGER PRIMARY KEY, ask INTEGER NOT NULL, by TEXT NOT NULL, text TEXT NOT NULL, question INTEGER NOT NULL DEFAULT 0, at INTEGER NOT NULL)\",\n+\t// A reader's news: read up to when. Not counted, since no issue read shows it.\n+\t\"CREATE TABLE IF NOT EXISTS news_read (who TEXT PRIMARY KEY, at INTEGER NOT NULL)\",\n+\t\"CREATE INDEX IF NOT EXISTS comments_issue ON comments (issue)\",\n+\t\"CREATE INDEX IF NOT EXISTS comments_at ON comments (at)\",\n+\t\"CREATE INDEX IF NOT EXISTS asks_issue ON asks (issue)\",\n+\t\"CREATE INDEX IF NOT EXISTS asks_open ON asks (answer_at)\",\n+\t\"CREATE INDEX IF NOT EXISTS issues_parent ON issues (parent)\",\n+\t\"CREATE INDEX IF NOT EXISTS issues_updated ON issues (updated_at)\",\n+\t\"CREATE INDEX IF NOT EXISTS edits_issue ON edits (issue)\",\n+\t\"CREATE INDEX IF NOT EXISTS drafts_owner ON drafts (owner)\",\n+\t\"CREATE INDEX IF NOT EXISTS writes_who ON writes (who, at)\",\n+\t\"CREATE INDEX IF NOT EXISTS labels_label ON labels (label)\",\n+\t\"CREATE INDEX IF NOT EXISTS ask_replies_ask ON ask_replies (ask)\",\n+\t\"CREATE INDEX IF NOT EXISTS ask_replies_at ON ask_replies (at)\",\n+\t// Search: every title, description and comment in a full-text index, kept in step by triggers.\n+\t\"CREATE VIRTUAL TABLE IF NOT EXISTS search USING fts5(issue UNINDEXED, comment UNINDEXED, field UNINDEXED, text, tokenize = 'porter unicode61')\",\n+\t`CREATE TRIGGER IF NOT EXISTS search_issue_in AFTER INSERT ON issues BEGIN\n+\t\tINSERT INTO search (issue, comment, field, text) VALUES (new.id, 0, 'title', new.title);\n+\t\tINSERT INTO search (issue, comment, field, text) SELECT new.id, 0, 'description', new.description WHERE new.description <> '';\n+\tEND`,\n+\t`CREATE TRIGGER IF NOT EXISTS search_issue_edit AFTER UPDATE OF title, description ON issues BEGIN\n+\t\tDELETE FROM search WHERE issue = old.id AND comment = 0;\n+\t\tINSERT INTO search (issue, comment, field, text) VALUES (new.id, 0, 'title', new.title);\n+\t\tINSERT INTO search (issue, comment, field, text) SELECT new.id, 0, 'description', new.description WHERE new.description <> '';\n+\tEND`,\n+\t\"CREATE TRIGGER IF NOT EXISTS search_issue_out AFTER DELETE ON issues BEGIN DELETE FROM search WHERE issue = old.id; END\",\n+\t\"CREATE TRIGGER IF NOT EXISTS search_comment_in AFTER INSERT ON comments BEGIN INSERT INTO search (issue, comment, field, text) VALUES (new.issue, new.id, 'comment', new.text); END\",\n+\t`CREATE TRIGGER IF NOT EXISTS search_comment_edit AFTER UPDATE OF text ON comments BEGIN\n+\t\tDELETE FROM search WHERE comment = old.id;\n+\t\tINSERT INTO search (issue, comment, field, text) VALUES (new.issue, new.id, 'comment', new.text);\n+\tEND`,\n+\t\"CREATE TRIGGER IF NOT EXISTS search_comment_out AFTER DELETE ON comments BEGIN DELETE FROM search WHERE comment = old.id; END\",\n+\t// The change count: one number that only grows, bumped by triggers on every table an issue read shows, so\n+\t// every write path moves it, the seen marks waiting writes included. A reader can cache issue reads by it.\n+\t\"CREATE TABLE IF NOT EXISTS change_count (id INTEGER PRIMARY KEY CHECK (id = 1), n INTEGER NOT NULL)\",\n+\t\"INSERT OR IGNORE INTO change_count (id, n) VALUES (1, 0)\",\n+\t...COUNTED_TABLES.flatMap((t) =>\n+\t\t([\"INSERT\", \"UPDATE\", \"DELETE\"] as const).map(\n+\t\t\t(op) =>\n+\t\t\t\t`CREATE TRIGGER IF NOT EXISTS changed_${t}_${op.toLowerCase()} AFTER ${op} ON ${t} BEGIN UPDATE change_count SET n = n + 1 WHERE id = 1; END`,\n+\t\t),\n+\t),\n+];\n+\n+/** How many news items one project gives a person's news, before the merge across projects. */\n+export const NEWS_MAX = 50;\n+/** How much of a comment, answer or reply a news item carries. */\n+const NEWS_TEXT_MAX = 280;\n+\n+/**\n+ * One thing for a person's news: an answer to their ask, a reply on an ask they're in, an\n+ * @mention of them, or a comment, edit or close on an issue they watch, by someone else.\n+ */\n+export interface NewsItem {\n+\tkind: \"answer\" | \"reply\" | \"mention\" | \"comment\" | \"edit\" | \"closed\";\n+\tissue: number | null;\n+\ttitle: string | null;\n+\task?: number;\n+\tby: string;\n+\ttext: string;\n+\tat: number;\n+\tread: boolean;\n+}\n+\n+/** One issue a search found: where the best match is, a snippet around it, and how well it matched. */\n+export interface SearchHit {\n+\tissue: { id: number; title: string; status: Status; updated: number; labels: string[] };\n+\t/** Where the best match is: the title, the description, or a comment (with its id). */\n+\twhere: \"title\" | \"description\" | \"comment\";\n+\tcomment?: number;\n+\t/** A few words around the match, with each matched span's [start, end) in `marks`. */\n+\tsnippet: string;\n+\tmarks: number[][];\n+\t/** FTS5's bm25, made positive: higher matches better. */\n+\tscore: number;\n+}\n+\n+/** A search hit as the client reads it: the issue's title and the matched text, each with who wrote it. */\n+export type AuthoredSearchHit = Omit<SearchHit, \"issue\"> & {\n+\tissue: SearchHit[\"issue\"] & { authorship: { title: ProseAuthorship } };\n+\tmatchedAuthorship: ProseAuthorship;\n+};\n+\n+type StoredAskReply = Omit<AskReply, \"authorship\">;\n+type StoredAsk = Omit<Ask, \"authorship\" | \"answer\" | \"ack\" | \"replies\"> & {\n+\tanswer: { by: string; words: string; at: number } | null;\n+\tack?: { at: number; note: string };\n+\treplies: StoredAskReply[];\n+};\n+\n+const UNKNOWN: ProseAuthorship = { kind: \"unknown\", actor: null, provenance: \"unknown\", authorField: null };\n+\n+/**\n+ * Who wrote a text, from the column that names its writer: an agent, or a person (person:<id>). This server\n+ * keeps no separate authorship records, so every text is its writer's own (\"native\").\n+ */\n+function authored(by: unknown, authorField: string): ProseAuthorship {\n+\tif (typeof by !== \"string\" || by === \"\") return UNKNOWN;\n+\treturn { kind: by.startsWith(\"person:\") ? \"human\" : \"agent\", actor: by, provenance: \"native\", authorField };\n+}\n+\n+/**\n+ * A person's words as an FTS5 query: each word quoted, so nothing they type\n+ * is query syntax, and the last one a prefix, so a search box finds as they\n+ * type. Undefined when there's no word in it.\n+ */\n+export function searchQuery(q: string): string | undefined {\n+\tconst words = q.match(/[\\p{L}\\p{N}_]+/gu)?.slice(0, 12);\n+\tif (!words || words.length === 0) return undefined;\n+\treturn words.map((w, i) => `\"${w}\"${i === words.length - 1 ? \"*\" : \"\"}`).join(\" \");\n+}\n+\n+type Row = Record<string, unknown>;\n+\n+/** How an actor is named in the store and on the pages: the agent's name, or person:<id>. */\n+export function who(actor: Actor): string {\n+\treturn \"agent\" in actor ? actor.agent : `person:${actor.person}`;\n+}\n+\n+/**\n+ * Words that reach agents on pages and in news: within `max`, with nothing a reader can't see (the engine's\n+ * own list, worker/project/unseen.ts), and on one line where `oneLine`.\n+ */\n+function text(value: unknown, what: string, max: number, required = true, oneLine = false): string {\n+\tif (value === undefined || value === null || value === \"\") {\n+\t\tif (required) throw new IssuesError(`${what} is missing`);\n+\t\treturn \"\";\n+\t}\n+\tif (typeof value !== \"string\") throw new IssuesError(`${what} is text`);\n+\tconst t = value.trim();\n+\tif (required && t === \"\") throw new IssuesError(`${what} is empty`);\n+\tif (t.length > max) throw new IssuesError(`${what} is ${t.length} characters; the most is ${max}`);\n+\tconst hidden = unseenIn(t);\n+\tif (hidden !== null)\n+\t\tthrow new IssuesError(`${what} holds ${hidden}, which a reader of the page can't see; take it out`);\n+\tif (oneLine && /[\\n\\t]/.test(t)) throw new IssuesError(`${what} is one line`);\n+\treturn t;\n+}\n+\n+function issueNumber(value: unknown, what = \"an issue number\"): number {\n+\tconst n = Number(value);\n+\tif (!Number.isInteger(n) || n < 1) throw new IssuesError(`${what} is a whole number from 1`);\n+\treturn n;\n+}\n+\n+/** A list of names (agents, or person:<id>), each once. */\n+function names(value: unknown, what: string): string[] {\n+\tif (value === undefined || value === null) return [];\n+\tif (!Array.isArray(value) || value.length > LIMITS.names)\n+\t\tthrow new IssuesError(`${what} is a list of up to ${LIMITS.names} names`);\n+\treturn [...new Set(value.map((v, i) => text(v, `${what}'s name ${i + 1}`, 100, true, true)))];\n+}\n+\n+/** Labels, checked as given (nothing is changed but surrounding spaces), each once, sorted. */\n+function labelsOf(value: unknown, what = \"labels\"): string[] {\n+\tif (value === undefined || value === null) return [];\n+\tif (!Array.isArray(value) || value.length > LABELS_PER_ISSUE)\n+\t\tthrow new IssuesError(`${what} is a list of up to ${LABELS_PER_ISSUE} labels`);\n+\tconst out = new Set<string>();\n+\tfor (const v of value) {\n+\t\tconst l = typeof v === \"string\" ? v.trim() : \"\";\n+\t\tif (!LABEL.test(l))\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`${JSON.stringify(v)} isn't a label: 1-40 lower-case letters, digits, and - _ . : (like friction or area:client)`,\n+\t\t\t);\n+\t\tout.add(l);\n+\t}\n+\treturn [...out].sort();\n+}\n+\n+/** A name, or null for none: \"\" and null clear it. */\n+function nameOrNone(value: unknown, what: string): string | null {\n+\treturn value === null || value === \"\" ? null : text(value, what, 100, true, true);\n+}\n+\n+function lines(value: unknown): Lines | null {\n+\tif (value === undefined || value === null) return null;\n+\tconst l = value as Partial<Lines>;\n+\tif (\n+\t\ttypeof l.file !== \"string\" ||\n+\t\tl.file === \"\" ||\n+\t\t!Number.isInteger(l.from) ||\n+\t\t!Number.isInteger(l.to) ||\n+\t\t!Number.isInteger(l.version) ||\n+\t\tl.from! < 1 ||\n+\t\tl.to! < l.from! ||\n+\t\tl.version! < 0\n+\t) {\n+\t\tthrow new IssuesError(\"lines are {file, from, to, version}: lines from-to of a file at a version\");\n+\t}\n+\treturn { file: text(l.file, \"the lines' file\", 1000, true, true), from: l.from!, to: l.to!, version: l.version! };\n+}\n+\n+const unique = (xs: readonly string[]): string[] => [...new Set(xs)];\n+\n+export class IssuesStore {\n+\tprivate readonly sql: Sql;\n+\tprivate readonly now: () => number;\n+\tprivate readonly atomic: (<T>(action: () => T) => T) | null;\n+\n+\t/** Over tables SCHEMA made (the object's migrations, or createTables in tests). `atomic` runs a transaction. */\n+\tconstructor(sql: Sql, now: () => number = Date.now, atomic?: <T>(action: () => T) => T) {\n+\t\tthis.sql = sql;\n+\t\tthis.now = now;\n+\t\tthis.atomic = atomic ?? null;\n+\t}\n+\n+\tprivate transaction<T>(action: () => T): T {\n+\t\treturn this.atomic ? this.atomic(action) : action();\n+\t}\n+\n+\tstatic createTables(sql: Sql): void {\n+\t\tfor (const s of SCHEMA) sql.exec(s);\n+\t}\n+\n+\t/**\n+\t * The change count: it grows with every write an issue read can show and never goes back, so a read cached\n+\t * under it is never older than its key.\n+\t */\n+\tchanges(): number {\n+\t\treturn (this.rows(\"SELECT n FROM change_count WHERE id = 1\")[0]?.n as number | undefined) ?? 0;\n+\t}\n+\n+\t/**\n+\t * A reader's news here, newest first, at most NEWS_MAX: answers to their asks, replies on asks they asked or\n+\t * were asked, comments naming them as @name (`names`: what they go by; an agent goes by its own name), and on\n+\t * issues they watch, others' comments, the edits that told them, and closes. Each is read when it is at or\n+\t * before their news_read mark. `before` pages back.\n+\t */\n+\tnewsFor(reader: Actor, names: readonly string[], before?: number): NewsItem[] {\n+\t\tconst me = who(reader);\n+\t\tconst until = before ?? Number.MAX_SAFE_INTEGER;\n+\t\tconst mark = (this.rows(\"SELECT at FROM news_read WHERE who = ?\", me)[0]?.at as number | undefined) ?? 0;\n+\t\tconst cut = (t: string) => (t.length > NEWS_TEXT_MAX ? `${t.slice(0, NEWS_TEXT_MAX - 1)}…` : t);\n+\t\tconst items: NewsItem[] = [];\n+\t\tconst add = (kind: NewsItem[\"kind\"], r: Row, text: string, ask?: number) =>\n+\t\t\titems.push({\n+\t\t\t\tkind,\n+\t\t\t\tissue: (r.issue as number | null) ?? null,\n+\t\t\t\ttitle: (r.title as string | null) ?? null,\n+\t\t\t\t...(ask !== undefined ? { ask } : {}),\n+\t\t\t\tby: r.by as string,\n+\t\t\t\ttext: cut(text),\n+\t\t\t\tat: r.at as number,\n+\t\t\t\tread: (r.at as number) <= mark,\n+\t\t\t});\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT a.id, a.issue, i.title, a.answer_by AS by, a.answer_words AS text, a.answer_at AS at FROM asks a\n+\t\t\tLEFT JOIN issues i ON i.id = a.issue\n+\t\t\tWHERE a.by = ? AND a.answer_at IS NOT NULL AND a.answer_at < ? AND a.answer_by <> ? AND (a.outcome IS NULL OR a.outcome <> 'withdrawn')\n+\t\t\tORDER BY a.answer_at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tme,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tadd(\"answer\", r, (r.text as string | null) ?? \"\", r.id as number);\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT r.ask, a.issue, i.title, r.by, r.text, r.at FROM ask_replies r JOIN asks a ON a.id = r.ask\n+\t\t\tLEFT JOIN issues i ON i.id = a.issue\n+\t\t\tWHERE (a.by = ? OR a.of = ?) AND r.by <> ? AND r.at < ? ORDER BY r.at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tme,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tadd(\"reply\", r, r.text as string, r.ask as number);\n+\t\tconst named = names.filter((n) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(n)).slice(0, 4);\n+\t\tconst mentioned = new Set<number>();\n+\t\tfor (const n of named)\n+\t\t\tfor (const r of this.rows(\n+\t\t\t\t`SELECT c.id, c.issue, i.title, c.by, c.text, c.at FROM comments c JOIN issues i ON i.id = c.issue\n+\t\t\t\tWHERE c.by <> ? AND c.at < ? AND instr(lower(c.text), ?) > 0 ORDER BY c.at DESC LIMIT ?`,\n+\t\t\t\tme,\n+\t\t\t\tuntil,\n+\t\t\t\t`@${n.toLowerCase()}`,\n+\t\t\t\tNEWS_MAX,\n+\t\t\t)) {\n+\t\t\t\tconst said = mentionsIn(r.text as string).map((m) => m.toLowerCase());\n+\t\t\t\tif (!said.includes(n.toLowerCase()) || mentioned.has(r.id as number)) continue;\n+\t\t\t\tmentioned.add(r.id as number);\n+\t\t\t\tadd(\"mention\", r, r.text as string);\n+\t\t\t}\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT c.id, c.issue, i.title, c.by, c.text, c.at FROM comments c JOIN watchers w ON w.issue = c.issue AND w.who = ?\n+\t\t\tJOIN issues i ON i.id = c.issue\n+\t\t\tWHERE c.by <> ? AND c.at >= w.since AND c.at < ? ORDER BY c.at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tif (!mentioned.has(r.id as number)) add(\"comment\", r, r.text as string);\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT e.issue, i.title, e.by, e.changes, e.at FROM edits e JOIN issues i ON i.id = e.issue\n+\t\t\tWHERE e.by <> ? AND e.at < ? AND EXISTS (SELECT 1 FROM json_each(e.notified) WHERE value = ?)\n+\t\t\tORDER BY e.at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tme,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tadd(\"edit\", r, Object.keys(JSON.parse(r.changes as string) as object).join(\", \"));\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT i.id AS issue, i.title, i.closed_by AS by, i.closed_how, i.closed_at AS at FROM issues i\n+\t\t\tJOIN watchers w ON w.issue = i.id AND w.who = ?\n+\t\t\tWHERE i.closed_at IS NOT NULL AND i.closed_at < ? AND i.closed_by <> ? ORDER BY i.closed_at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tme,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tadd(\"closed\", r, r.closed_how as string);\n+\t\treturn items.sort((x, y) => y.at - x.at).slice(0, NEWS_MAX);\n+\t}\n+\n+\t/** Marks the reader's news here read up to `at` (never back); answers the mark. */\n+\tmarkNewsRead(reader: Actor, at: number): { read: number } {\n+\t\tthis.sql.exec(\n+\t\t\t\"INSERT INTO news_read (who, at) VALUES (?, ?) ON CONFLICT (who) DO UPDATE SET at = MAX(at, excluded.at)\",\n+\t\t\twho(reader),\n+\t\t\tat,\n+\t\t);\n+\t\treturn { read: this.rows(\"SELECT at FROM news_read WHERE who = ?\", who(reader))[0]!.at as number };\n+\t}\n+\n+\tprivate rows(query: string, ...b: unknown[]): Row[] {\n+\t\treturn this.sql.exec(query, ...b).toArray() as Row[];\n+\t}\n+\n+\tprivate exists(id: number): Row {\n+\t\tconst row = this.rows(\"SELECT * FROM issues WHERE id = ?\", issueNumber(id))[0];\n+\t\tif (!row) throw new IssuesError(`there's no issue ${id}`, 404);\n+\t\treturn row;\n+\t}\n+\n+\tprivate touch(...ids: (number | null)[]): void {\n+\t\tconst at = this.now();\n+\t\tfor (const id of ids)\n+\t\t\tif (id !== null) this.sql.exec(\"UPDATE issues SET updated_at = MAX(updated_at, ?) WHERE id = ?\", at, id);\n+\t}\n+\n+\t/** Refuses labels that would take the project past LABELS_PER_PROJECT distinct ones. */\n+\tprivate roomForLabels(labels: readonly string[]): void {\n+\t\tconst inUse = new Set(this.rows(\"SELECT DISTINCT label FROM labels\").map((l) => l.label as string));\n+\t\tconst added = labels.filter((l) => !inUse.has(l));\n+\t\tif (added.length > 0 && inUse.size + added.length > LABELS_PER_PROJECT)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`this project has ${inUse.size} labels, and ${LABELS_PER_PROJECT} is the most; use one it has (abso issues --labels lists them)`,\n+\t\t\t);\n+\t}\n+\n+\t/** Attachments aren't kept on this server: a write that names any is refused before anything is written. */\n+\tprivate noAttachments(raw: unknown): void {\n+\t\tif (raw === undefined || raw === null || (Array.isArray(raw) && raw.length === 0)) return;\n+\t\tthrow new IssuesError(\"this server doesn't keep attachments; leave them off, or link the file instead\", 501);\n+\t}\n+\n+\t/** Adds watchers to an issue; each is kept once, from when they first watched. */\n+\tprivate watch(id: number, ...people: (string | null | undefined)[]): void {\n+\t\tconst at = this.now();\n+\t\tfor (const p of people)\n+\t\t\tif (p)\n+\t\t\t\tthis.sql.exec(\n+\t\t\t\t\t\"INSERT INTO watchers (issue, who, since) VALUES (?, ?, ?) ON CONFLICT (issue, who) DO NOTHING\",\n+\t\t\t\t\tid,\n+\t\t\t\t\tp,\n+\t\t\t\t\tat,\n+\t\t\t\t);\n+\t}\n+\n+\tprivate watchersOf(id: number): string[] {\n+\t\treturn this.rows(\"SELECT who FROM watchers WHERE issue = ? ORDER BY since, who\", id).map((w) => w.who as string);\n+\t}\n+\n+\t/** Blocked by, checked: issues that exist, not `id` itself, and none already waiting on `id` (that would wait forever). */\n+\tprivate blockersFor(id: number | null, value: unknown): number[] {\n+\t\tif (value === undefined || value === null) return [];\n+\t\tif (!Array.isArray(value) || value.length > LIMITS.blocks)\n+\t\t\tthrow new IssuesError(`blocked by is a list of up to ${LIMITS.blocks} issue numbers`);\n+\t\tconst ids = [...new Set(value.map((b) => issueNumber(b, \"an issue it's blocked by\")))];\n+\t\tfor (const b of ids) {\n+\t\t\tthis.exists(b);\n+\t\t\tif (b === id) throw new IssuesError(`issue ${id} can't be blocked by itself`);\n+\t\t\tif (id !== null && this.waitsOn(b, id))\n+\t\t\t\tthrow new IssuesError(`issue ${b} already waits on issue ${id}, so neither could start`);\n+\t\t}\n+\t\treturn ids;\n+\t}\n+\n+\t/** Whether `from` waits on `on`, through Blocked by. */\n+\tprivate waitsOn(from: number, on: number): boolean {\n+\t\tconst seen = new Set<number>();\n+\t\tconst next = [from];\n+\t\twhile (next.length > 0) {\n+\t\t\tconst at = next.pop()!;\n+\t\t\tif (at === on) return true;\n+\t\t\tif (seen.has(at)) continue;\n+\t\t\tseen.add(at);\n+\t\t\tfor (const b of this.rows(\"SELECT blocker FROM blocked_by WHERE issue = ?\", at)) next.push(b.blocker as number);\n+\t\t}\n+\t\treturn false;\n+\t}\n+\n+\t/** A parent, checked: an issue that exists and isn't `id` or under it. */\n+\tprivate parentFor(id: number | null, value: unknown): number | null {\n+\t\tif (value === undefined || value === null) return null;\n+\t\tconst parent = issueNumber(value, \"the parent\");\n+\t\tthis.exists(parent);\n+\t\tfor (\n+\t\t\tlet at: number | null = parent;\n+\t\t\tat !== null;\n+\t\t\tat = (this.rows(\"SELECT parent FROM issues WHERE id = ?\", at)[0]?.parent as number | null | undefined) ?? null\n+\t\t) {\n+\t\t\tif (at === id) throw new IssuesError(`issue ${parent} is issue ${id} or under it, so it can't be its parent`);\n+\t\t}\n+\t\treturn parent;\n+\t}\n+\n+\t/** Every row's status and joins at once: one query per table, not one per issue. */\n+\tprivate statuses(rows: Row[]): IssueRow[] {\n+\t\tif (rows.length === 0) return [];\n+\t\t// Open asks hold up their own issue and the ones they name in blocks.\n+\t\tconst held = new Map<number, { review: boolean; of: string }[]>();\n+\t\tfor (const a of this.rows(\n+\t\t\t\"SELECT issue, COALESCE(waiting_on, of) AS of, review, blocks FROM asks WHERE answer_at IS NULL\",\n+\t\t)) {\n+\t\t\tconst on = new Set<number>([\n+\t\t\t\t...(a.issue !== null ? [a.issue as number] : []),\n+\t\t\t\t...(JSON.parse(a.blocks as string) as number[]),\n+\t\t\t]);\n+\t\t\tfor (const id of on)\n+\t\t\t\theld.set(id, [...(held.get(id) ?? []), { review: a.review === 1 && id === a.issue, of: a.of as string }]);\n+\t\t}\n+\t\tconst claims = new Map<number, string[]>();\n+\t\tfor (const c of this.rows(\"SELECT issue, agent FROM claims ORDER BY since\"))\n+\t\t\tclaims.set(c.issue as number, [...(claims.get(c.issue as number) ?? []), c.agent as string]);\n+\t\tconst versions = new Map<number, number[]>();\n+\t\tfor (const v of this.rows(\"SELECT issue, version FROM versions ORDER BY version\"))\n+\t\t\tversions.set(v.issue as number, [...(versions.get(v.issue as number) ?? []), v.version as number]);\n+\t\tconst children = new Map<number, number>();\n+\t\tfor (const c of this.rows(\"SELECT parent, COUNT(*) AS n FROM issues WHERE parent IS NOT NULL GROUP BY parent\"))\n+\t\t\tchildren.set(c.parent as number, c.n as number);\n+\t\tconst labels = new Map<number, string[]>();\n+\t\tfor (const l of this.rows(\"SELECT issue, label FROM labels ORDER BY label\"))\n+\t\t\tlabels.set(l.issue as number, [...(labels.get(l.issue as number) ?? []), l.label as string]);\n+\t\t// Blocked by: each blocker, and whether it's Done yet.\n+\t\tconst blockers = new Map<number, { id: number; done: boolean }[]>();\n+\t\tfor (const b of this.rows(\n+\t\t\t\"SELECT blocked_by.issue, blocked_by.blocker, issues.closed_how FROM blocked_by LEFT JOIN issues ON issues.id = blocked_by.blocker ORDER BY blocked_by.blocker\",\n+\t\t)) {\n+\t\t\tblockers.set(b.issue as number, [\n+\t\t\t\t...(blockers.get(b.issue as number) ?? []),\n+\t\t\t\t{ id: b.blocker as number, done: b.closed_how === \"done\" },\n+\t\t\t]);\n+\t\t}\n+\t\tconst retitled = this.lastEditors(\"title\");\n+\t\treturn rows.map((r) => {\n+\t\t\tconst id = r.id as number;\n+\t\t\tconst asks = held.get(id) ?? [];\n+\t\t\tconst agents = claims.get(id) ?? [];\n+\t\t\tconst blockedBy = blockers.get(id) ?? [];\n+\t\t\tconst status: Status =\n+\t\t\t\tr.closed_how === \"done\"\n+\t\t\t\t\t? \"done\"\n+\t\t\t\t\t: r.closed_how === \"dropped\"\n+\t\t\t\t\t\t? \"dropped\"\n+\t\t\t\t\t\t: asks.some((a) => !a.review) || blockedBy.some((b) => !b.done)\n+\t\t\t\t\t\t\t? \"blocked\"\n+\t\t\t\t\t\t\t: asks.length > 0\n+\t\t\t\t\t\t\t\t? \"in review\"\n+\t\t\t\t\t\t\t\t: agents.length > 0\n+\t\t\t\t\t\t\t\t\t? \"in progress\"\n+\t\t\t\t\t\t\t\t\t: \"open\";\n+\t\t\treturn {\n+\t\t\t\tid,\n+\t\t\t\ttitle: r.title as string,\n+\t\t\t\tauthorship: { title: this.issueFieldAuthorship(r, retitled) },\n+\t\t\t\tparent: (r.parent as number | null) ?? null,\n+\t\t\t\tstatus,\n+\t\t\t\tagent: (r.agent as string | null | undefined) ?? null,\n+\t\t\t\tagents,\n+\t\t\t\tblockedBy: blockedBy.map((b) => b.id),\n+\t\t\t\tlabels: labels.get(id) ?? [],\n+\t\t\t\tversions: versions.get(id) ?? [],\n+\t\t\t\twaitingOn: r.closed_how ? [] : [...new Set(asks.map((a) => a.of))],\n+\t\t\t\topened: { by: r.opened_by as string, at: r.opened_at as number },\n+\t\t\t\tupdated: r.updated_at as number,\n+\t\t\t\tclosed: r.closed_how\n+\t\t\t\t\t? {\n+\t\t\t\t\t\t\thow: r.closed_how as \"done\" | \"dropped\",\n+\t\t\t\t\t\t\tby: r.closed_by as string,\n+\t\t\t\t\t\t\tversion: (r.closed_version as number | null) ?? null,\n+\t\t\t\t\t\t\tat: r.closed_at as number,\n+\t\t\t\t\t\t}\n+\t\t\t\t\t: null,\n+\t\t\t\tchildren: children.get(id) ?? 0,\n+\t\t\t};\n+\t\t});\n+\t}\n+\n+\t/** Who last edited `field` on each issue whose `field` was edited (or only issue `id`'s). */\n+\tprivate lastEditors(field: \"title\" | \"description\", id?: number): Map<number, string> {\n+\t\tconst edited = new Map<number, string>();\n+\t\tconst where = `json_type(changes, '$.${field}') IS NOT NULL${id === undefined ? \"\" : \" AND issue = ?\"}`;\n+\t\tfor (const e of this.rows(\n+\t\t\t`SELECT issue, by FROM edits WHERE ${where} ORDER BY id`,\n+\t\t\t...(id === undefined ? [] : [id]),\n+\t\t))\n+\t\t\tedited.set(e.issue as number, e.by as string);\n+\t\treturn edited;\n+\t}\n+\n+\t/** Who wrote an issue's title or description now: whoever last edited it, else whoever opened the issue. */\n+\tprivate issueFieldAuthorship(row: Row, edited: Map<number, string>): ProseAuthorship {\n+\t\tconst editor = edited.get(row.id as number);\n+\t\treturn editor === undefined ? authored(row.opened_by, \"issues.opened_by\") : authored(editor, \"edits.by\");\n+\t}\n+\n+\t/** An ask as the client reads it: each text with who wrote it. */\n+\tprivate authoredAsk(a: StoredAsk): Ask {\n+\t\tconst { ack, ...ask } = a;\n+\t\treturn {\n+\t\t\t...ask,\n+\t\t\tauthorship: { question: authored(a.by, \"asks.by\") },\n+\t\t\tanswer: a.answer ? { ...a.answer, authorship: authored(a.answer.by, \"asks.answer_by\") } : null,\n+\t\t\t...(ack\n+\t\t\t\t? { ack: { ...ack, authorship: { note: ack.note === \"\" ? UNKNOWN : authored(a.of, \"ask_replies.by\") } } }\n+\t\t\t\t: {}),\n+\t\t\treplies: a.replies.map((reply) => ({ ...reply, authorship: authored(reply.by, \"ask_replies.by\") })),\n+\t\t};\n+\t}\n+\n+\t// Reads ----------------------------------------------------------------------------------\n+\n+\t/**\n+\t * Issues, most recently updated first, filtered by status, agent, parent or\n+\t * labels (each one named). `open` leaves out done and dropped.\n+\t */\n+\tlist(\n+\t\tfilter: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},\n+\t): IssueRow[] {\n+\t\tconst wanted = filter.labels === undefined ? [] : labelsOf([...filter.labels], \"the labels to filter by\");\n+\t\tconst rows =\n+\t\t\tfilter.parent === undefined\n+\t\t\t\t? this.rows(\"SELECT * FROM issues ORDER BY updated_at DESC, id DESC\")\n+\t\t\t\t: this.rows(\"SELECT * FROM issues WHERE parent = ? ORDER BY updated_at DESC, id DESC\", filter.parent);\n+\t\treturn this.statuses(rows).filter(\n+\t\t\t(i) =>\n+\t\t\t\t(filter.status === undefined || i.status === filter.status) &&\n+\t\t\t\t(filter.agent === undefined || i.agent === filter.agent || i.agents.includes(filter.agent)) &&\n+\t\t\t\t(!filter.open || (i.status !== \"done\" && i.status !== \"dropped\")) &&\n+\t\t\t\twanted.every((l) => i.labels.includes(l)),\n+\t\t);\n+\t}\n+\n+\t/** Issues matching `q`, best first, one hit per issue at its best place. Drafts aren't searched. */\n+\tsearch(q: string, limit = 20): AuthoredSearchHit[] {\n+\t\tconst query = searchQuery(q);\n+\t\tif (query === undefined) return [];\n+\t\tconst rows = this.rows(\n+\t\t\t\"SELECT issue, comment, field, snippet(search, 3, char(1), char(2), '…', 14) AS snip, bm25(search) AS rank FROM search WHERE search MATCH ? ORDER BY rank LIMIT 500\",\n+\t\t\tquery,\n+\t\t);\n+\t\tconst best = new Map<number, Row>();\n+\t\tfor (const r of rows) if (!best.has(r.issue as number)) best.set(r.issue as number, r);\n+\t\tconst ids = [...best.keys()].slice(0, Math.max(1, Math.min(limit, 50)));\n+\t\tif (ids.length === 0) return [];\n+\t\tconst found = this.rows(`SELECT * FROM issues WHERE id IN (${ids.map(() => \"?\").join(\", \")})`, ...ids);\n+\t\tconst rowOf = new Map(found.map((r) => [r.id as number, r]));\n+\t\tconst issues = new Map(this.statuses(found).map((i) => [i.id, i]));\n+\t\treturn ids.flatMap((id) => {\n+\t\t\tconst r = best.get(id)!;\n+\t\t\tconst i = issues.get(id);\n+\t\t\tif (!i) return [];\n+\t\t\tconst { text, marks } = marked(r.snip as string);\n+\t\t\tconst where = r.field as SearchHit[\"where\"];\n+\t\t\tconst commentId = r.comment as number;\n+\t\t\tconst matchedAuthorship =\n+\t\t\t\twhere === \"comment\"\n+\t\t\t\t\t? authored(this.rows(\"SELECT by FROM comments WHERE id = ?\", commentId)[0]?.by, \"comments.by\")\n+\t\t\t\t\t: where === \"title\"\n+\t\t\t\t\t\t? i.authorship.title\n+\t\t\t\t\t\t: this.issueFieldAuthorship(rowOf.get(id)!, this.lastEditors(\"description\", id));\n+\t\t\treturn [\n+\t\t\t\t{\n+\t\t\t\t\tissue: {\n+\t\t\t\t\t\tid,\n+\t\t\t\t\t\ttitle: i.title,\n+\t\t\t\t\t\tstatus: i.status,\n+\t\t\t\t\t\tupdated: i.updated,\n+\t\t\t\t\t\tlabels: i.labels,\n+\t\t\t\t\t\tauthorship: i.authorship,\n+\t\t\t\t\t},\n+\t\t\t\t\twhere,\n+\t\t\t\t\t...(where === \"comment\" ? { comment: commentId } : {}),\n+\t\t\t\t\tsnippet: text,\n+\t\t\t\t\tmarks,\n+\t\t\t\t\tmatchedAuthorship,\n+\t\t\t\t\tscore: -(r.rank as number),\n+\t\t\t\t},\n+\t\t\t];\n+\t\t});\n+\t}\n+\n+\t/** Every label in use, with how many issues have it and how many of those are open (done and dropped aren't). */\n+\tlabelsInUse(): { label: string; open: number; total: number }[] {\n+\t\treturn this.rows(\n+\t\t\t\"SELECT label, COUNT(*) AS total, SUM(CASE WHEN issues.closed_how IS NULL THEN 1 ELSE 0 END) AS open FROM labels JOIN issues ON issues.id = labels.issue GROUP BY label ORDER BY label\",\n+\t\t).map((r) => ({ label: r.label as string, open: r.open as number, total: r.total as number }));\n+\t}\n+\n+\t/** An ask with its thread, oldest first. */\n+\tprivate withFiles(a: StoredAsk): StoredAsk {\n+\t\treturn { ...a, replies: this.repliesOf(a.id) };\n+\t}\n+\n+\t/** An ask's replies, oldest first. */\n+\tprivate repliesOf(ask: number): StoredAskReply[] {\n+\t\treturn this.rows(\"SELECT id, by, text, question, at FROM ask_replies WHERE ask = ? ORDER BY id\", ask).map((r) => ({\n+\t\t\tid: r.id as number,\n+\t\t\tby: r.by as string,\n+\t\t\ttext: r.text as string,\n+\t\t\tat: r.at as number,\n+\t\t\t...(r.question === 1 ? { question: true as const } : {}),\n+\t\t}));\n+\t}\n+\n+\tpage(id: number): IssuePage {\n+\t\tconst row = this.exists(id);\n+\t\tconst [issue] = this.statuses([row]);\n+\t\treturn {\n+\t\t\tissue: {\n+\t\t\t\t...issue!,\n+\t\t\t\tdescription: row.description as string,\n+\t\t\t\tauthorship: {\n+\t\t\t\t\ttitle: issue!.authorship.title,\n+\t\t\t\t\tdescription: this.issueFieldAuthorship(row, this.lastEditors(\"description\", id)),\n+\t\t\t\t},\n+\t\t\t\tlines: row.lines ? (JSON.parse(row.lines as string) as Lines) : null,\n+\t\t\t\twatchers: this.watchersOf(id),\n+\t\t\t},\n+\t\t\tcomments: this.rows(\"SELECT * FROM comments WHERE issue = ? ORDER BY id\", id).map((c) => ({\n+\t\t\t\tid: c.id as number,\n+\t\t\t\tby: c.by as string,\n+\t\t\t\tkind: c.kind as Comment[\"kind\"],\n+\t\t\t\ttext: c.text as string,\n+\t\t\t\tauthorship: authored(c.by, \"comments.by\"),\n+\t\t\t\tat: c.at as number,\n+\t\t\t})),\n+\t\t\tedits: this.rows(\"SELECT * FROM edits WHERE issue = ? ORDER BY id\", id).map((e) => ({\n+\t\t\t\tid: e.id as number,\n+\t\t\t\tby: e.by as string,\n+\t\t\t\tchanges: JSON.parse(e.changes as string) as Edit[\"changes\"],\n+\t\t\t\tnotified: JSON.parse(e.notified as string) as string[],\n+\t\t\t\tat: e.at as number,\n+\t\t\t})),\n+\t\t\tasks: this.rows(\"SELECT * FROM asks WHERE issue = ? ORDER BY id\", id).map((r) =>\n+\t\t\t\tthis.authoredAsk(this.withFiles(askOf(r))),\n+\t\t\t),\n+\t\t\tclaims: this.rows(\"SELECT agent, change, since FROM claims WHERE issue = ? ORDER BY since\", id).map((c) => ({\n+\t\t\t\tagent: c.agent as string,\n+\t\t\t\tchange: c.change as number,\n+\t\t\t\tsince: c.since as number,\n+\t\t\t})),\n+\t\t\tchildren: this.statuses(this.rows(\"SELECT * FROM issues WHERE parent = ? ORDER BY id\", id)),\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * Open asks of someone (an agent's name or person:<id>), soonest due first, then oldest; every open ask without `of`.\n+\t * When `reader` is the one they're asked of, each listed for the first time is marked seen now; the answer still\n+\t * says null for those, so the reader can tell what's new.\n+\t */\n+\twaiting(of?: string, reader?: string): (Ask & { title: string | null })[] {\n+\t\tconst select =\n+\t\t\t\"SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE answer_at IS NULL\";\n+\t\tconst rows =\n+\t\t\tof === undefined\n+\t\t\t\t? this.rows(`${select} ORDER BY due IS NULL, due, asks.id`)\n+\t\t\t\t: this.rows(`${select} AND COALESCE(waiting_on, of) = ? ORDER BY due IS NULL, due, asks.id`, of);\n+\t\tif (of !== undefined && reader === of)\n+\t\t\tthis.sql.exec(\n+\t\t\t\t\"UPDATE asks SET seen_at = ? WHERE of = ? AND answer_at IS NULL AND seen_at IS NULL\",\n+\t\t\t\tthis.now(),\n+\t\t\t\tof,\n+\t\t\t);\n+\t\treturn rows.map((r) => ({\n+\t\t\t...this.authoredAsk(this.withFiles(askOf(r))),\n+\t\t\ttitle: (r.title as string | null) ?? null,\n+\t\t}));\n+\t}\n+\n+\t/** Asks of someone that have been answered, newest first. */\n+\tanswered(of: string, limit = 50): (Ask & { title: string | null })[] {\n+\t\treturn this.rows(\n+\t\t\t\"SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE answer_at IS NOT NULL AND of = ? ORDER BY answer_at DESC LIMIT ?\",\n+\t\t\tof,\n+\t\t\tlimit,\n+\t\t).map((r) => ({\n+\t\t\t...this.authoredAsk(this.withFiles(askOf(r))),\n+\t\t\ttitle: (r.title as string | null) ?? null,\n+\t\t}));\n+\t}\n+\n+\t/** The asks someone sent: every open one, oldest first, then the latest answered or withdrawn. */\n+\tasked(by: string, answeredLimit = 10): (Ask & { title: string | null })[] {\n+\t\tconst select = \"SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE asks.by = ?\";\n+\t\treturn [\n+\t\t\t...this.rows(`${select} AND answer_at IS NULL ORDER BY asks.id`, by),\n+\t\t\t...this.rows(`${select} AND answer_at IS NOT NULL ORDER BY answer_at DESC LIMIT ?`, by, answeredLimit),\n+\t\t].map((r) => ({ ...this.authoredAsk(this.withFiles(askOf(r))), title: (r.title as string | null) ?? null }));\n+\t}\n+\n+\t/** One ask, open or closed, with its thread and its issue's title. */\n+\taskThread(id: number): Ask & { title: string | null } {\n+\t\tconst r = this.rows(\n+\t\t\t\"SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE asks.id = ?\",\n+\t\t\tissueNumber(id, \"an ask number\"),\n+\t\t)[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${id}`, 404);\n+\t\treturn { ...this.authoredAsk(this.withFiles(askOf(r))), title: (r.title as string | null) ?? null };\n+\t}\n+\n+\t// Writes ---------------------------------------------------------------------------------\n+\n+\t/**\n+\t * A new issue. Agent is who it's for, Blocked by the issues it waits on,\n+\t * and Notify who the writer tells. The writer, its Agent and Notify watch\n+\t * it; Agent and Notify hear it now, and the parent's agents hear it too.\n+\t */\n+\topen(actor: Actor, body: Parameters<IssuesStore[\"openRecord\"]>[1]): { id: number; news?: News } {\n+\t\treturn this.transaction(() => this.openRecord(actor, body));\n+\t}\n+\n+\tprivate openRecord(\n+\t\tactor: Actor,\n+\t\tbody: {\n+\t\t\ttitle?: unknown;\n+\t\t\tdescription?: unknown;\n+\t\t\tparent?: unknown;\n+\t\t\tlines?: unknown;\n+\t\t\tagent?: unknown;\n+\t\t\tblockedBy?: unknown;\n+\t\t\tnotify?: unknown;\n+\t\t\tlabels?: unknown;\n+\t\t\tattachments?: unknown;\n+\t\t},\n+\t): { id: number; news?: News } {\n+\t\tconst title = text(body.title, \"the title\", LIMITS.title, true, true);\n+\t\tthis.noAttachments(body.attachments);\n+\t\tconst description = text(body.description, \"the description\", LIMITS.description, false);\n+\t\tconst parent = this.parentFor(null, body.parent);\n+\t\tconst at_ = lines(body.lines);\n+\t\tconst agent = body.agent === undefined ? null : nameOrNone(body.agent, \"the Agent\");\n+\t\tconst blockedBy = this.blockersFor(null, body.blockedBy);\n+\t\tconst notify = names(body.notify, \"Notify\");\n+\t\tconst labels = labelsOf(body.labels);\n+\t\tthis.roomForLabels(labels);\n+\t\tconst open = this.rows(\"SELECT COUNT(*) AS n FROM issues WHERE closed_how IS NULL\")[0]!.n as number;\n+\t\tif (open >= LIMITS.open)\n+\t\t\tthrow new IssuesError(`this project has ${open} open issues, the most it can hold; close some first`);\n+\t\tconst at = this.now();\n+\t\tconst row = this.rows(\n+\t\t\t\"INSERT INTO issues (parent, title, description, opened_by, opened_at, updated_at, lines, agent) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id\",\n+\t\t\tparent,\n+\t\t\ttitle,\n+\t\t\tdescription,\n+\t\t\twho(actor),\n+\t\t\tat,\n+\t\t\tat,\n+\t\t\tat_ ? JSON.stringify(at_) : null,\n+\t\t\tagent,\n+\t\t)[0]!;\n+\t\tconst id = row.id as number;\n+\t\tfor (const b of blockedBy) this.sql.exec(\"INSERT INTO blocked_by (issue, blocker) VALUES (?, ?)\", id, b);\n+\t\tfor (const l of labels)\n+\t\t\tthis.sql.exec(\"INSERT INTO labels (issue, label, by, at) VALUES (?, ?, ?, ?)\", id, l, who(actor), at);\n+\t\tthis.watch(id, who(actor), agent, ...notify);\n+\t\tthis.touch(parent);\n+\t\tconst to = unique([...(agent !== null ? [agent] : []), ...notify]).filter((p) => p !== who(actor));\n+\t\tif (parent === null && to.length === 0) return { id };\n+\t\tconst detail = [\n+\t\t\tagent !== null ? `Agent ${agent}` : \"\",\n+\t\t\tblockedBy.length > 0 ? `blocked by ${blockedBy.join(\", \")}` : \"\",\n+\t\t].filter((d) => d !== \"\");\n+\t\treturn {\n+\t\t\tid,\n+\t\t\tnews: {\n+\t\t\t\tissue: parent,\n+\t\t\t\ttext: `${who(actor)} opened issue ${id}${parent !== null ? ` under issue ${parent}` : \"\"}: ${JSON.stringify(title)}${detail.length > 0 ? ` (${detail.join(\"; \")})` : \"\"}`,\n+\t\t\t\t...(to.length > 0 ? { to } : {}),\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * An edit: title, description, parent, Agent, Blocked by or labels, kept in\n+\t * the issue's activity. It tells the watchers unless `notify` is false;\n+\t * `also` adds people, who watch it from then on (they were named in Notify).\n+\t * Labels are `labels` (the whole set) or `addLabels` and `removeLabels`; an\n+\t * edit that only changes labels tells nobody unless `notify` is true, since\n+\t * agents sort issues by label all the time.\n+\t */\n+\tedit(\n+\t\tactor: Actor,\n+\t\tid: number,\n+\t\tbody: {\n+\t\t\ttitle?: unknown;\n+\t\t\tdescription?: unknown;\n+\t\t\tparent?: unknown;\n+\t\t\tagent?: unknown;\n+\t\t\tblockedBy?: unknown;\n+\t\t\tnotify?: unknown;\n+\t\t\talso?: unknown;\n+\t\t\tlabels?: unknown;\n+\t\t\taddLabels?: unknown;\n+\t\t\tremoveLabels?: unknown;\n+\t\t},\n+\t): { edit: number; notified: string[]; news?: News } {\n+\t\tconst row = this.exists(id);\n+\t\tconst changes: Edit[\"changes\"] = {};\n+\t\tconst sets: [string, unknown][] = [];\n+\t\tif (body.title !== undefined) {\n+\t\t\tconst title = text(body.title, \"the title\", LIMITS.title, true, true);\n+\t\t\tif (title !== row.title) (changes.title = { from: row.title, to: title }), sets.push([\"title\", title]);\n+\t\t}\n+\t\tif (body.description !== undefined) {\n+\t\t\tconst description = text(body.description, \"the description\", LIMITS.description, false);\n+\t\t\tif (description !== row.description)\n+\t\t\t\t(changes.description = { from: row.description, to: description }), sets.push([\"description\", description]);\n+\t\t}\n+\t\tif (body.parent !== undefined) {\n+\t\t\tconst parent = this.parentFor(id, body.parent);\n+\t\t\tif (parent !== ((row.parent as number | null) ?? null))\n+\t\t\t\t(changes.parent = { from: row.parent ?? null, to: parent }), sets.push([\"parent\", parent]);\n+\t\t}\n+\t\tif (body.agent !== undefined) {\n+\t\t\tconst agent = nameOrNone(body.agent, \"the Agent\");\n+\t\t\tif (agent !== ((row.agent as string | null | undefined) ?? null))\n+\t\t\t\t(changes.agent = { from: row.agent ?? null, to: agent }), sets.push([\"agent\", agent]);\n+\t\t}\n+\t\tlet blockedBy: number[] | undefined;\n+\t\tif (body.blockedBy !== undefined) {\n+\t\t\tblockedBy = this.blockersFor(id, body.blockedBy);\n+\t\t\tconst before = this.rows(\"SELECT blocker FROM blocked_by WHERE issue = ? ORDER BY blocker\", id).map(\n+\t\t\t\t(b) => b.blocker as number,\n+\t\t\t);\n+\t\t\tconst after = [...blockedBy].sort((a, b) => a - b);\n+\t\t\tif (before.join() !== after.join()) changes.blockedBy = { from: before, to: after };\n+\t\t\telse blockedBy = undefined;\n+\t\t}\n+\t\tlet labels: string[] | undefined;\n+\t\tif (body.labels !== undefined || body.addLabels !== undefined || body.removeLabels !== undefined) {\n+\t\t\tif (body.labels !== undefined && (body.addLabels !== undefined || body.removeLabels !== undefined))\n+\t\t\t\tthrow new IssuesError(\"labels is the whole set; addLabels and removeLabels change it; send one or the other\");\n+\t\t\tconst before = this.rows(\"SELECT label FROM labels WHERE issue = ? ORDER BY label\", id).map(\n+\t\t\t\t(l) => l.label as string,\n+\t\t\t);\n+\t\t\tconst drop = new Set(labelsOf(body.removeLabels, \"removeLabels\"));\n+\t\t\tconst after =\n+\t\t\t\tbody.labels !== undefined\n+\t\t\t\t\t? labelsOf(body.labels)\n+\t\t\t\t\t: labelsOf([...before.filter((l) => !drop.has(l)), ...labelsOf(body.addLabels, \"addLabels\")]);\n+\t\t\tif (before.join() !== after.join()) {\n+\t\t\t\tthis.roomForLabels(after);\n+\t\t\t\tchanges.labels = { from: before, to: after };\n+\t\t\t\tlabels = after;\n+\t\t\t}\n+\t\t}\n+\t\tif (body.notify !== undefined && typeof body.notify !== \"boolean\")\n+\t\t\tthrow new IssuesError(\"notify is true (tell the watchers, the default) or false (tell nobody)\");\n+\t\tconst also = names(body.also, \"who else to tell\");\n+\t\tif (Object.keys(changes).length === 0) throw new IssuesError(`that changes nothing on issue ${id}`);\n+\t\tconst labelsOnly = Object.keys(changes).every((k) => k === \"labels\");\n+\t\tconst e = this.transaction(() => {\n+\t\t\tfor (const [column, value] of sets) this.sql.exec(`UPDATE issues SET ${column} = ? WHERE id = ?`, value, id);\n+\t\t\tif (blockedBy !== undefined) {\n+\t\t\t\tthis.sql.exec(\"DELETE FROM blocked_by WHERE issue = ?\", id);\n+\t\t\t\tfor (const b of blockedBy) this.sql.exec(\"INSERT INTO blocked_by (issue, blocker) VALUES (?, ?)\", id, b);\n+\t\t\t}\n+\t\t\tif (labels !== undefined) {\n+\t\t\t\t// A label kept keeps who added it and when.\n+\t\t\t\tfor (const l of this.rows(\"SELECT label FROM labels WHERE issue = ?\", id))\n+\t\t\t\t\tif (!labels.includes(l.label as string))\n+\t\t\t\t\t\tthis.sql.exec(\"DELETE FROM labels WHERE issue = ? AND label = ?\", id, l.label);\n+\t\t\t\tfor (const l of labels)\n+\t\t\t\t\tthis.sql.exec(\n+\t\t\t\t\t\t\"INSERT OR IGNORE INTO labels (issue, label, by, at) VALUES (?, ?, ?, ?)\",\n+\t\t\t\t\t\tid,\n+\t\t\t\t\t\tl,\n+\t\t\t\t\t\twho(actor),\n+\t\t\t\t\t\tthis.now(),\n+\t\t\t\t\t);\n+\t\t\t}\n+\t\t\tthis.watch(id, (changes.agent?.to as string | null | undefined) ?? null, ...also);\n+\t\t\tconst notified =\n+\t\t\t\tbody.notify === false || (labelsOnly && body.notify !== true)\n+\t\t\t\t\t? []\n+\t\t\t\t\t: unique([...this.watchersOf(id), ...also]).filter((p) => p !== who(actor));\n+\t\t\tconst edit = this.rows(\n+\t\t\t\t\"INSERT INTO edits (issue, by, changes, notified, at) VALUES (?, ?, ?, ?, ?) RETURNING id\",\n+\t\t\t\tid,\n+\t\t\t\twho(actor),\n+\t\t\t\tJSON.stringify(changes),\n+\t\t\t\tJSON.stringify(notified),\n+\t\t\t\tthis.now(),\n+\t\t\t)[0]!.id as number;\n+\t\t\treturn { id: edit, notified };\n+\t\t});\n+\t\tconst notified = e.notified;\n+\t\tthis.touch(id, (row.parent as number | null) ?? null, (changes.parent?.to as number | null | undefined) ?? null);\n+\t\tif (notified.length === 0) return { edit: e.id as number, notified };\n+\t\tconst title = (changes.title?.to as string | undefined) ?? (row.title as string);\n+\t\tconst said = [\n+\t\t\tchanges.title ? `title was ${JSON.stringify(changes.title.from)}` : \"\",\n+\t\t\tchanges.description ? \"description changed\" : \"\",\n+\t\t\tchanges.parent ? (changes.parent.to === null ? \"no parent now\" : `parent is issue ${changes.parent.to}`) : \"\",\n+\t\t\tchanges.agent ? (changes.agent.to === null ? \"no Agent now\" : `Agent is ${changes.agent.to}`) : \"\",\n+\t\t\tchanges.blockedBy\n+\t\t\t\t? (changes.blockedBy.to as number[]).length === 0\n+\t\t\t\t\t? \"blocked by nothing now\"\n+\t\t\t\t\t: `blocked by ${(changes.blockedBy.to as number[]).join(\", \")}`\n+\t\t\t\t: \"\",\n+\t\t\tchanges.labels\n+\t\t\t\t? (changes.labels.to as string[]).length === 0\n+\t\t\t\t\t? \"no labels now\"\n+\t\t\t\t\t: `labels ${(changes.labels.to as string[]).join(\", \")}`\n+\t\t\t\t: \"\",\n+\t\t].filter((s) => s !== \"\");\n+\t\treturn {\n+\t\t\tedit: e.id as number,\n+\t\t\tnotified,\n+\t\t\tnews: {\n+\t\t\t\tissue: null,\n+\t\t\t\ttext: `${who(actor)} edited issue ${id} (${JSON.stringify(title)}): ${said.join(\"; \")}`,\n+\t\t\t\tto: notified,\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\tcomment(\n+\t\tactor: Actor,\n+\t\tid: number,\n+\t\tbody: { text?: unknown; objection?: unknown; attachments?: unknown },\n+\t): { id: number; news: News } {\n+\t\tconst row = this.exists(id);\n+\t\tconst t = text(body.text, \"the comment\", LIMITS.text);\n+\t\tthis.noAttachments(body.attachments);\n+\t\tconst kind = body.objection === true ? \"objection\" : \"comment\";\n+\t\tconst c = this.rows(\n+\t\t\t\"INSERT INTO comments (issue, by, kind, text, at) VALUES (?, ?, ?, ?, ?) RETURNING id\",\n+\t\t\tid,\n+\t\t\twho(actor),\n+\t\t\tkind,\n+\t\t\tt,\n+\t\t\tthis.now(),\n+\t\t)[0]!;\n+\t\tthis.watch(id, who(actor));\n+\t\tthis.touch(id);\n+\t\t// @name in the text tells that agent too; the project drops names that aren't its agents.\n+\t\tconst mentioned = mentionsIn(t).filter((name) => name !== who(actor));\n+\t\treturn {\n+\t\t\tid: c.id as number,\n+\t\t\tnews: {\n+\t\t\t\tissue: id,\n+\t\t\t\ttext: `${who(actor)} ${kind === \"objection\" ? \"objects\" : \"comments\"} on issue ${id} (${JSON.stringify(row.title)}): ${JSON.stringify(t)}`,\n+\t\t\t\t...(mentioned.length > 0 ? { to: mentioned } : {}),\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * An ask: a question or a task for someone, on an issue or on none. A\n+\t * review ask (`review`) puts its issue In review; any other holds it up\n+\t * (Blocked), and so do the issues it names in `blocks`.\n+\t */\n+\task(\n+\t\tactor: Actor,\n+\t\tbody: {\n+\t\t\tissue?: unknown;\n+\t\t\tof?: unknown;\n+\t\t\tquestion?: unknown;\n+\t\t\treview?: unknown;\n+\t\t\tkind?: unknown;\n+\t\t\tdue?: unknown;\n+\t\t\trecommendation?: unknown;\n+\t\t\toptions?: unknown;\n+\t\t\tblocks?: unknown;\n+\t\t\tattachments?: unknown;\n+\t\t},\n+\t): { id: number; news: News } {\n+\t\tconst issue = body.issue === undefined || body.issue === null ? null : issueNumber(body.issue);\n+\t\tconst row = issue === null ? undefined : this.exists(issue);\n+\t\tif (row?.closed_how) throw new IssuesError(`issue ${issue} is closed`);\n+\t\tconst of = text(body.of, \"who it asks\", 100, true, true);\n+\t\tconst question = text(body.question, \"the question\", LIMITS.text);\n+\t\tconst kind = body.kind === undefined || body.kind === null ? \"question\" : body.kind;\n+\t\tif (kind !== \"question\" && kind !== \"task\")\n+\t\t\tthrow new IssuesError('kind is \"question\", or \"task\" for something only they can do');\n+\t\tconst review = body.review === true;\n+\t\tif (review && issue === null) throw new IssuesError(\"a review ask is on an issue\");\n+\t\tlet due: string | null = null;\n+\t\tif (body.due !== undefined && body.due !== null && body.due !== \"\") {\n+\t\t\tif (typeof body.due !== \"string\" || !/^\\d{4}-\\d{2}-\\d{2}/.test(body.due) || Number.isNaN(Date.parse(body.due)))\n+\t\t\t\tthrow new IssuesError(\"due is a date, like 2026-10-14\");\n+\t\t\tdue = body.due;\n+\t\t}\n+\t\tlet recommendation: { text: string; by: string } | null = null;\n+\t\tif (body.recommendation !== undefined && body.recommendation !== null) {\n+\t\t\tconst r = body.recommendation as { text?: unknown; by?: unknown };\n+\t\t\trecommendation = {\n+\t\t\t\ttext: text(r.text, \"the recommendation\", LIMITS.text),\n+\t\t\t\tby: r.by === undefined ? who(actor) : text(r.by, \"who recommends it\", 100, true, true),\n+\t\t\t};\n+\t\t}\n+\t\tconst options = body.options === undefined || body.options === null ? [] : body.options;\n+\t\tif (!Array.isArray(options) || options.length > LIMITS.options)\n+\t\t\tthrow new IssuesError(`options are a list of up to ${LIMITS.options} choices`);\n+\t\tconst choices = options.map((o, i) => text(o, `option ${i + 1}`, 500, true, true));\n+\t\tconst blocks = body.blocks === undefined || body.blocks === null ? [] : body.blocks;\n+\t\tif (!Array.isArray(blocks) || blocks.length > LIMITS.blocks)\n+\t\t\tthrow new IssuesError(`blocks is a list of up to ${LIMITS.blocks} issue numbers`);\n+\t\tconst held = [...new Set(blocks.map((b) => issueNumber(b, \"an issue it blocks\")))].filter((b) => b !== issue);\n+\t\tfor (const b of held) this.exists(b);\n+\t\tthis.noAttachments(body.attachments);\n+\t\tconst a = this.rows(\n+\t\t\t\"INSERT INTO asks (issue, by, of, kind, question, review, due, recommendation, options, blocks, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id\",\n+\t\t\tissue,\n+\t\t\twho(actor),\n+\t\t\tof,\n+\t\t\tkind,\n+\t\t\tquestion,\n+\t\t\treview ? 1 : 0,\n+\t\t\tdue,\n+\t\t\trecommendation ? JSON.stringify(recommendation) : null,\n+\t\t\tJSON.stringify(choices),\n+\t\t\tJSON.stringify(held),\n+\t\t\tthis.now(),\n+\t\t)[0]!;\n+\t\tif (review && issue !== null) this.watch(issue, of);\n+\t\tthis.touch(issue, ...held);\n+\t\tconst what = review ? \"for a review\" : kind === \"task\" ? \"to do something\" : \"a question\";\n+\t\tconst where = issue === null ? \"\" : ` on issue ${issue} (${JSON.stringify(row!.title)})`;\n+\t\treturn {\n+\t\t\tid: a.id as number,\n+\t\t\t// An agent asked hears how to answer.\n+\t\t\tnews: {\n+\t\t\t\tissue,\n+\t\t\t\ttext: `${who(actor)} asks ${of} ${what}${where}: ${JSON.stringify(question)}${of.startsWith(\"person:\") ? \"\" : ` Answer: abso answer ${a.id} \"...\"`}`,\n+\t\t\t\tto: [of],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/** An answer, in the answerer's own words, kept on the ask. Only the one asked answers; a task is answered \"done\". */\n+\tanswer(\n+\t\tactor: Actor,\n+\t\taskId: number,\n+\t\tbody: {\n+\t\t\twords?: unknown;\n+\t\t\toption?: unknown;\n+\t\t\texpect?: unknown;\n+\t\t\tnote?: unknown;\n+\t\t\tdone?: unknown;\n+\t\t\tattachments?: unknown;\n+\t\t},\n+\t): { ask: Ask; news: News } {\n+\t\tconst r = this.rows(\"SELECT * FROM asks WHERE id = ?\", issueNumber(askId, \"an ask number\"))[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${askId}`, 404);\n+\t\tif (r.of !== who(actor)) throw new IssuesError(`ask ${askId} is for ${r.of as string}, not ${who(actor)}`, 403);\n+\t\tif (r.answer_at !== null && r.answer_at !== undefined)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\tr.outcome === \"withdrawn\"\n+\t\t\t\t\t? `ask ${askId} was withdrawn by ${r.answer_by as string}, who asked it; it needs no answer`\n+\t\t\t\t\t: `ask ${askId} is answered already`,\n+\t\t\t\t409,\n+\t\t\t);\n+\t\tconst words = this.answerWordsFor(r, body);\n+\t\tthis.noAttachments(body.attachments);\n+\t\tconst at = this.now();\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE asks SET answer_by = ?, answer_words = ?, answer_at = ? WHERE id = ?\",\n+\t\t\twho(actor),\n+\t\t\twords,\n+\t\t\tat,\n+\t\t\tr.id,\n+\t\t);\n+\t\tconst ask = this.authoredAsk(\n+\t\t\tthis.withFiles(askOf({ ...r, answer_by: who(actor), answer_words: words, answer_at: at })),\n+\t\t);\n+\t\tthis.touch(ask.issue, ...ask.blocks);\n+\t\treturn {\n+\t\t\task,\n+\t\t\tnews: {\n+\t\t\t\tissue: ask.issue,\n+\t\t\t\ttext: `${who(actor)} answered ${ask.by}'s ${ask.review ? \"review ask\" : ask.kind}${ask.issue !== null ? ` on issue ${ask.issue}` : \"\"}: ${JSON.stringify(words)}`,\n+\t\t\t\tto: [ask.by],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\tprivate answerWordsFor(\n+\t\tr: Row,\n+\t\tbody: { words?: unknown; option?: unknown; expect?: unknown; note?: unknown; done?: unknown },\n+\t): string {\n+\t\tconst askId = r.id as number;\n+\t\tconst options = JSON.parse(r.options as string) as string[];\n+\t\tif (body.option !== undefined && body.option !== null) {\n+\t\t\tconst pick = typeof body.option === \"number\" ? options[body.option] : options.find((o) => o === body.option);\n+\t\t\tif (pick === undefined)\n+\t\t\t\tthrow new IssuesError(`ask ${askId}'s options are: ${options.map((o) => JSON.stringify(o)).join(\", \")}`);\n+\t\t\tif (body.expect !== undefined && body.expect !== pick)\n+\t\t\t\tthrow new IssuesError(\n+\t\t\t\t\t`ask ${askId}'s option ${Number(body.option) + 1} is ${JSON.stringify(pick)}, not the one you picked; look again`,\n+\t\t\t\t\t409,\n+\t\t\t\t);\n+\t\t\tconst note = text(body.note, \"the note\", LIMITS.text, false);\n+\t\t\treturn note === \"\" ? pick : `${pick}\\n\\n${note}`;\n+\t\t}\n+\t\tif (body.done === true && r.kind === \"task\") {\n+\t\t\tconst note = text(body.note, \"the note\", LIMITS.text, false);\n+\t\t\treturn note === \"\" ? \"done\" : `done\\n\\n${note}`;\n+\t\t}\n+\t\treturn text(body.words, \"the answer\", LIMITS.text);\n+\t}\n+\n+\t/**\n+\t * The one asked says they have it and will answer later. The ask stays open and keeps\n+\t * blocking; it shows as acknowledged, and the asker hears it with the note. Acknowledging again updates\n+\t * the note and the time. abso answer closes it as before.\n+\t */\n+\tack(actor: Actor, askId: number, body: { note?: unknown }): { ask: Ask; news: News } {\n+\t\tconst r = this.rows(\"SELECT * FROM asks WHERE id = ?\", issueNumber(askId, \"an ask number\"))[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${askId}`, 404);\n+\t\tif (r.of !== who(actor)) throw new IssuesError(`ask ${askId} is for ${r.of as string}, not ${who(actor)}`, 403);\n+\t\tif (r.answer_at !== null && r.answer_at !== undefined)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\tr.outcome === \"withdrawn\"\n+\t\t\t\t\t? `ask ${askId} was withdrawn by ${r.answer_by as string}, who asked it; it needs no answer`\n+\t\t\t\t\t: `ask ${askId} is answered already`,\n+\t\t\t\t409,\n+\t\t\t);\n+\t\tconst note = text(body.note, \"the note\", LIMITS.text, false);\n+\t\tconst at = this.now();\n+\t\tthis.transaction(() => {\n+\t\t\tthis.sql.exec(\"UPDATE asks SET ack_at = ?, ack_note = ? WHERE id = ?\", at, note, r.id);\n+\t\t\t// The note is a reply in the thread.\n+\t\t\tif (note !== \"\")\n+\t\t\t\tthis.sql.exec(\n+\t\t\t\t\t\"INSERT INTO ask_replies (ask, by, text, question, at) VALUES (?, ?, ?, 0, ?)\",\n+\t\t\t\t\tr.id,\n+\t\t\t\t\twho(actor),\n+\t\t\t\t\tnote,\n+\t\t\t\t\tat,\n+\t\t\t\t);\n+\t\t});\n+\t\tconst ask = this.authoredAsk(this.withFiles(askOf({ ...r, ack_at: at, ack_note: note })));\n+\t\tthis.touch(ask.issue);\n+\t\treturn {\n+\t\t\task,\n+\t\t\tnews: {\n+\t\t\t\tissue: ask.issue,\n+\t\t\t\ttext: `${who(actor)} has your ${ask.review ? \"review ask\" : ask.kind} (ask ${ask.id})${ask.issue !== null ? ` on issue ${ask.issue}` : \"\"} and will answer${note !== \"\" ? `: ${JSON.stringify(note)}` : \".\"}`,\n+\t\t\t\tto: [ask.by],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * A reply on an ask's thread, from the one asked or the asker, open or closed. The other side\n+\t * hears it. Whose turn it is: a reply from the one asked marked as a question waits on the asker; the asker's\n+\t * next reply hands it back. Answering still closes it.\n+\t */\n+\treply(actor: Actor, askId: number, body: { text?: unknown; question?: unknown }): { ask: Ask; news: News } {\n+\t\tconst r = this.rows(\"SELECT * FROM asks WHERE id = ?\", issueNumber(askId, \"an ask number\"))[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${askId}`, 404);\n+\t\tconst me = who(actor);\n+\t\tif (me !== r.of && me !== r.by)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`ask ${askId} is between ${r.by as string} and ${r.of as string}; only they reply on it. abso comment says something on its issue`,\n+\t\t\t\t403,\n+\t\t\t);\n+\t\tconst words = text(body.text, \"the reply\", LIMITS.text);\n+\t\tconst question = body.question === true;\n+\t\tconst open = r.answer_at === null || r.answer_at === undefined;\n+\t\tlet waitingOn = (r.waiting_on as string | null) ?? null;\n+\t\tif (open) {\n+\t\t\tif (me === r.of && me !== r.by) {\n+\t\t\t\tif (question) waitingOn = r.by as string;\n+\t\t\t} else waitingOn = null;\n+\t\t}\n+\t\tconst at = this.now();\n+\t\tthis.transaction(() => {\n+\t\t\tthis.sql.exec(\n+\t\t\t\t\"INSERT INTO ask_replies (ask, by, text, question, at) VALUES (?, ?, ?, ?, ?)\",\n+\t\t\t\tr.id,\n+\t\t\t\tme,\n+\t\t\t\twords,\n+\t\t\t\tquestion ? 1 : 0,\n+\t\t\t\tat,\n+\t\t\t);\n+\t\t\tif (open) this.sql.exec(\"UPDATE asks SET waiting_on = ? WHERE id = ?\", waitingOn, r.id);\n+\t\t});\n+\t\tconst ask = this.authoredAsk(this.withFiles(askOf({ ...r, waiting_on: waitingOn })));\n+\t\tthis.touch(ask.issue);\n+\t\tconst other = me === ask.of ? ask.by : ask.of;\n+\t\tconst turn = open && (waitingOn ?? ask.of) === other ? \" It waits on you.\" : \"\";\n+\t\treturn {\n+\t\t\task,\n+\t\t\tnews: {\n+\t\t\t\tissue: ask.issue,\n+\t\t\t\ttext: `${me} replied on ask ${ask.id}${ask.issue !== null ? ` (issue ${ask.issue})` : \"\"}${question ? \" with a question\" : \"\"}: ${JSON.stringify(words)}${turn}${other.startsWith(\"person:\") ? \"\" : ` abso ask ${ask.id} shows the thread.`}`,\n+\t\t\t\tto: [other],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * The asker takes back an ask nobody needs answered any more. It closes as an answer does\n+\t * (answer_at set, so it leaves waiting and stops blocking), with the asker as answer_by, their note as\n+\t * answer_words, and outcome 'withdrawn'. The one asked hears it.\n+\t */\n+\twithdraw(actor: Actor, askId: number, body: { note?: unknown }): { ask: Ask; news: News } {\n+\t\tconst r = this.rows(\"SELECT * FROM asks WHERE id = ?\", issueNumber(askId, \"an ask number\"))[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${askId}`, 404);\n+\t\tif (r.by !== who(actor))\n+\t\t\tthrow new IssuesError(`ask ${askId} was asked by ${r.by as string}; only they can withdraw it`, 403);\n+\t\tif (r.answer_at !== null && r.answer_at !== undefined)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\tr.outcome === \"withdrawn\"\n+\t\t\t\t\t? `ask ${askId} is withdrawn already`\n+\t\t\t\t\t: `ask ${askId} is answered already, so there's nothing to withdraw`,\n+\t\t\t\t409,\n+\t\t\t);\n+\t\tconst note = text(body.note, \"the note\", LIMITS.text, false);\n+\t\tconst at = this.now();\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE asks SET answer_by = ?, answer_words = ?, answer_at = ?, outcome = 'withdrawn' WHERE id = ?\",\n+\t\t\twho(actor),\n+\t\t\tnote,\n+\t\t\tat,\n+\t\t\tr.id,\n+\t\t);\n+\t\tconst ask = this.authoredAsk(\n+\t\t\tthis.withFiles(askOf({ ...r, answer_by: who(actor), answer_words: note, answer_at: at, outcome: \"withdrawn\" })),\n+\t\t);\n+\t\tthis.touch(ask.issue, ...ask.blocks);\n+\t\treturn {\n+\t\t\task,\n+\t\t\tnews: {\n+\t\t\t\tissue: ask.issue,\n+\t\t\t\ttext: `${who(actor)} withdrew their ${ask.review ? \"review ask\" : ask.kind} of ${ask.of}${ask.issue !== null ? ` on issue ${ask.issue}` : \"\"}${note !== \"\" ? `: ${JSON.stringify(note)}` : \"\"}`,\n+\t\t\t\tto: [ask.of],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/** Dropped by hand; done comes only from a publish (the done hook). */\n+\tdrop(actor: Actor, id: number): { news: News } {\n+\t\tconst row = this.exists(id);\n+\t\tif (row.closed_how)\n+\t\t\tthrow new IssuesError(`issue ${id} is ${row.closed_how === \"done\" ? \"done\" : \"dropped\"} already`, 409);\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE issues SET closed_how = 'dropped', closed_by = ?, closed_at = ?, updated_at = ? WHERE id = ?\",\n+\t\t\twho(actor),\n+\t\t\tthis.now(),\n+\t\t\tthis.now(),\n+\t\t\tid,\n+\t\t);\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ?\", id);\n+\t\treturn { news: { issue: id, text: `${who(actor)} dropped issue ${id} (${JSON.stringify(row.title)})` } };\n+\t}\n+\n+\t/** A dropped issue opens again. A done issue stays done. */\n+\treopen(actor: Actor, id: number): { news: News } {\n+\t\tconst row = this.exists(id);\n+\t\tif (row.closed_how !== \"dropped\")\n+\t\t\tthrow new IssuesError(\n+\t\t\t\trow.closed_how === \"done\" ? `issue ${id} is done; it stays done` : `issue ${id} is open`,\n+\t\t\t\t409,\n+\t\t\t);\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE issues SET closed_how = NULL, closed_by = NULL, closed_version = NULL, closed_at = NULL, updated_at = ? WHERE id = ?\",\n+\t\t\tthis.now(),\n+\t\t\tid,\n+\t\t);\n+\t\tthis.touch(id);\n+\t\treturn { news: { issue: id, text: `${who(actor)} reopened issue ${id} (${JSON.stringify(row.title)})` } };\n+\t}\n+\n+\t/**\n+\t * Marked done by hand, by a person or an agent. `version`, when\n+\t * given, is the published version that did the work. A dropped issue is reopened first.\n+\t */\n+\tmarkDone(actor: Actor, id: number, version: number | null): { news: News } {\n+\t\tconst row = this.exists(id);\n+\t\tif (row.closed_how === \"dropped\")\n+\t\t\tthrow new IssuesError(`issue ${id} is dropped; reopen it before marking it done`, 409);\n+\t\tif (row.closed_how === \"done\") throw new IssuesError(`issue ${id} is done already`, 409);\n+\t\tif (version !== null && (!Number.isInteger(version) || version < 1))\n+\t\t\tthrow new IssuesError(\"version is a published version, 1 or more\");\n+\t\tconst at = this.now();\n+\t\tconst by = who(actor);\n+\t\tif (version !== null)\n+\t\t\tthis.sql.exec(\n+\t\t\t\t\"INSERT INTO versions (issue, version, agent, at) VALUES (?, ?, ?, ?) ON CONFLICT (issue, version) DO NOTHING\",\n+\t\t\t\tid,\n+\t\t\t\tversion,\n+\t\t\t\tby,\n+\t\t\t\tat,\n+\t\t\t);\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE issues SET closed_how = 'done', closed_by = ?, closed_version = ?, closed_at = ?, updated_at = ? WHERE id = ?\",\n+\t\t\tby,\n+\t\t\tversion,\n+\t\t\tat,\n+\t\t\tat,\n+\t\t\tid,\n+\t\t);\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ?\", id);\n+\t\tconst where = version === null ? \"by hand\" : `in version ${version}`;\n+\t\treturn {\n+\t\t\tnews: { issue: id, text: `${by} marked issue ${id} (${JSON.stringify(row.title)}) done ${where}` },\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * Refuses a write past the writer's limit: WRITES_PER_MINUTE a\n+\t * minute and WRITES_PER_DAY a day, opens, edits, comments, asks, answers and\n+\t * drops together. A 429 says when to try again.\n+\t */\n+\tcheckLimit(actor: Actor): void {\n+\t\tconst now = this.now();\n+\t\tthis.sql.exec(\"DELETE FROM writes WHERE who = ? AND at <= ?\", who(actor), now - 86_400_000);\n+\t\tconst times = this.rows(\"SELECT at FROM writes WHERE who = ? ORDER BY at\", who(actor)).map((w) => w.at as number);\n+\t\tconst minute = times.filter((t) => now - t < 60_000);\n+\t\tif (minute.length >= WRITES_PER_MINUTE)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`at most ${WRITES_PER_MINUTE} issue writes a minute; try again shortly`,\n+\t\t\t\t429,\n+\t\t\t\tMath.max(1, Math.ceil((minute[0]! + 60_000 - now) / 1000)),\n+\t\t\t);\n+\t\tif (times.length >= WRITES_PER_DAY)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`at most ${WRITES_PER_DAY} issue writes a day in a project`,\n+\t\t\t\t429,\n+\t\t\t\tMath.max(1, Math.ceil((times[0]! + 86_400_000 - now) / 1000)),\n+\t\t\t);\n+\t}\n+\n+\t/** Counts a write that went through. */\n+\twrote(actor: Actor): void {\n+\t\tthis.sql.exec(\"INSERT INTO writes (who, at) VALUES (?, ?)\", who(actor), this.now());\n+\t}\n+\n+\t// Drafts: a writer's own, with no number and no news ------------------------\n+\n+\t/** The actor's drafts, newest first. Nobody else's. */\n+\tdrafts(actor: Actor): Draft[] {\n+\t\treturn this.rows(\"SELECT * FROM drafts WHERE owner = ? ORDER BY saved_at DESC, id DESC\", who(actor)).map(asDraft);\n+\t}\n+\n+\t/**\n+\t * Saves a draft, new or (with `id`) over one of the actor's. Any field may\n+\t * be empty; what's there is checked as open would check it, but not whether\n+\t * the issues it names still exist (that waits for opening).\n+\t */\n+\tsaveDraft(\n+\t\tactor: Actor,\n+\t\tbody: {\n+\t\t\tid?: unknown;\n+\t\t\ttitle?: unknown;\n+\t\t\tdescription?: unknown;\n+\t\t\tparent?: unknown;\n+\t\t\tlines?: unknown;\n+\t\t\tagent?: unknown;\n+\t\t\tblockedBy?: unknown;\n+\t\t\tnotify?: unknown;\n+\t\t\tlabels?: unknown;\n+\t\t},\n+\t): { id: number } {\n+\t\tconst draft: DraftBody = {};\n+\t\tconst title = text(body.title, \"the title\", LIMITS.title, false, true);\n+\t\tif (title !== \"\") draft.title = title;\n+\t\tconst description = text(body.description, \"the description\", LIMITS.description, false);\n+\t\tif (description !== \"\") draft.description = description;\n+\t\tif (body.parent !== undefined && body.parent !== null) draft.parent = issueNumber(body.parent, \"the parent\");\n+\t\tconst l = lines(body.lines);\n+\t\tif (l !== null) draft.lines = l;\n+\t\tif (body.agent !== undefined && body.agent !== null && body.agent !== \"\")\n+\t\t\tdraft.agent = nameOrNone(body.agent, \"the Agent\");\n+\t\tif (body.blockedBy !== undefined && body.blockedBy !== null) {\n+\t\t\tif (!Array.isArray(body.blockedBy) || body.blockedBy.length > LIMITS.blocks)\n+\t\t\t\tthrow new IssuesError(`blocked by is a list of up to ${LIMITS.blocks} issue numbers`);\n+\t\t\tdraft.blockedBy = [...new Set(body.blockedBy.map((b) => issueNumber(b, \"an issue it's blocked by\")))];\n+\t\t}\n+\t\tconst notify = names(body.notify, \"Notify\");\n+\t\tif (notify.length > 0) draft.notify = notify;\n+\t\tconst labels = labelsOf(body.labels);\n+\t\tif (labels.length > 0) draft.labels = labels;\n+\t\tconst saved = JSON.stringify(draft);\n+\t\tif (saved.length > LIMITS.draft) throw new IssuesError(`a draft holds at most ${LIMITS.draft} characters`);\n+\t\tif (body.id !== undefined && body.id !== null) {\n+\t\t\tconst id = this.draftOf(actor, body.id).id as number;\n+\t\t\tthis.sql.exec(\"UPDATE drafts SET body = ?, saved_at = ? WHERE id = ?\", saved, this.now(), id);\n+\t\t\treturn { id };\n+\t\t}\n+\t\tconst n = this.rows(\"SELECT COUNT(*) AS n FROM drafts WHERE owner = ?\", who(actor))[0]!.n as number;\n+\t\tif (n >= LIMITS.drafts)\n+\t\t\tthrow new IssuesError(`you have ${n} drafts, the most there can be; open or delete some first`);\n+\t\treturn {\n+\t\t\tid: this.rows(\n+\t\t\t\t\"INSERT INTO drafts (owner, body, saved_at) VALUES (?, ?, ?) RETURNING id\",\n+\t\t\t\twho(actor),\n+\t\t\t\tsaved,\n+\t\t\t\tthis.now(),\n+\t\t\t)[0]!.id as number,\n+\t\t};\n+\t}\n+\n+\tdeleteDraft(actor: Actor, id: number): void {\n+\t\tthis.sql.exec(\"DELETE FROM drafts WHERE id = ?\", this.draftOf(actor, id).id);\n+\t}\n+\n+\t/** Opens a draft as an issue, with `body`'s fields over the draft's, and deletes the draft. The issue's news is the only news. */\n+\topenDraft(actor: Actor, id: number, body: Record<string, unknown> = {}): { id: number; news?: News } {\n+\t\tconst d = this.draftOf(actor, id);\n+\t\tconst opened = this.open(actor, { ...(JSON.parse(d.body as string) as DraftBody), ...body });\n+\t\tthis.sql.exec(\"DELETE FROM drafts WHERE id = ?\", d.id);\n+\t\treturn opened;\n+\t}\n+\n+\t/** One of the actor's drafts; another's is \"no such draft\", as if it weren't there. */\n+\tprivate draftOf(actor: Actor, id: unknown): Row {\n+\t\tconst row = this.rows(\n+\t\t\t\"SELECT * FROM drafts WHERE id = ? AND owner = ?\",\n+\t\t\tissueNumber(id, \"a draft number\"),\n+\t\t\twho(actor),\n+\t\t)[0];\n+\t\tif (!row) throw new IssuesError(`you have no draft ${String(id)}`, 404);\n+\t\treturn row;\n+\t}\n+\t// From the project: start notes and publish --done ----------------------------------------\n+\n+\t/** A start note names the issue (`change` is the note's log position). One that doesn't exist, or is closed, is ignored: the note stands either way. */\n+\tclaim(agent: string, id: number, change: number): void {\n+\t\tconst row = this.rows(\"SELECT closed_how FROM issues WHERE id = ?\", id)[0];\n+\t\tif (!row || row.closed_how) return;\n+\t\tthis.sql.exec(\n+\t\t\t\"INSERT INTO claims (issue, agent, change, since) VALUES (?, ?, ?, ?) ON CONFLICT (issue, agent) DO UPDATE SET change = excluded.change, since = excluded.since\",\n+\t\t\tid,\n+\t\t\tagent,\n+\t\t\tchange,\n+\t\t\tthis.now(),\n+\t\t);\n+\t\tthis.sql.exec(\"UPDATE issues SET agent = ? WHERE id = ? AND agent IS NULL\", agent, id);\n+\t\tthis.watch(id, agent);\n+\t\tthis.touch(id);\n+\t}\n+\n+\t/** The start note ended without finishing the issue. */\n+\tunclaim(agent: string, id: number): void {\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ? AND agent = ?\", id, agent);\n+\t\tthis.touch(id);\n+\t}\n+\n+\t/** publish --done finished it, with that version of shared: done, and the version is one out for it. */\n+\tdone(agent: string, id: number, version: number): { news?: News } {\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ? AND agent = ?\", id, agent);\n+\t\tconst row = this.rows(\"SELECT title, closed_how FROM issues WHERE id = ?\", id)[0];\n+\t\tif (!row) return {};\n+\t\tthis.sql.exec(\n+\t\t\t\"INSERT INTO versions (issue, version, agent, at) VALUES (?, ?, ?, ?) ON CONFLICT (issue, version) DO NOTHING\",\n+\t\t\tid,\n+\t\t\tversion,\n+\t\t\tagent,\n+\t\t\tthis.now(),\n+\t\t);\n+\t\tthis.touch(id);\n+\t\tif (row.closed_how) return {};\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE issues SET closed_how = 'done', closed_by = ?, closed_version = ?, closed_at = ? WHERE id = ?\",\n+\t\t\tagent,\n+\t\t\tversion,\n+\t\t\tthis.now(),\n+\t\t\tid,\n+\t\t);\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ?\", id);\n+\t\treturn {\n+\t\t\tnews: { issue: id, text: `${agent} finished issue ${id} (${JSON.stringify(row.title)}) in version ${version}` },\n+\t\t};\n+\t}\n+}\n+\n+function asDraft(d: Row): Draft {\n+\treturn {\n+\t\tid: d.id as number,\n+\t\tbody: JSON.parse(d.body as string) as DraftBody,\n+\t\tsaved: d.saved_at as number,\n+\t};\n+}\n+\n+/** A snippet with \\u0001 and \\u0002 around each match, as plain text and the matches' spans. */\n+function marked(snip: string): { text: string; marks: number[][] } {\n+\tlet text = \"\";\n+\tconst marks: number[][] = [];\n+\tlet open = -1;\n+\tfor (const ch of snip) {\n+\t\tif (ch === \"\\u0001\") open = text.length;\n+\t\telse if (ch === \"\\u0002\") {\n+\t\t\tif (open >= 0) marks.push([open, text.length]);\n+\t\t\topen = -1;\n+\t\t} else text += ch;\n+\t}\n+\treturn { text, marks };\n+}\n+\n+function askOf(r: Row): StoredAsk {\n+\treturn {\n+\t\tid: r.id as number,\n+\t\tissue: (r.issue as number | null) ?? null,\n+\t\tby: r.by as string,\n+\t\tof: r.of as string,\n+\t\tkind: r.kind as Ask[\"kind\"],\n+\t\tquestion: r.question as string,\n+\t\treview: r.review === 1,\n+\t\tdue: (r.due as string | null) ?? null,\n+\t\trecommendation: r.recommendation ? (JSON.parse(r.recommendation as string) as Ask[\"recommendation\"]) : null,\n+\t\toptions: JSON.parse(r.options as string) as string[],\n+\t\tblocks: JSON.parse(r.blocks as string) as number[],\n+\t\tat: r.at as number,\n+\t\tanswer:\n+\t\t\tr.answer_at !== null && r.answer_at !== undefined\n+\t\t\t\t? { by: r.answer_by as string, words: r.answer_words as string, at: r.answer_at as number }\n+\t\t\t\t: null,\n+\t\tseen: (r.seen_at as number | null | undefined) ?? null,\n+\t\twaitingOn:\n+\t\t\tr.answer_at !== null && r.answer_at !== undefined ? null : ((r.waiting_on as string | null) ?? (r.of as string)),\n+\t\treplies: [],\n+\t\t...(r.outcome === \"withdrawn\" ? { outcome: \"withdrawn\" as const } : {}),\n+\t\t...(typeof r.ack_at === \"number\" ? { ack: { at: r.ack_at, note: (r.ack_note as string | null) ?? \"\" } } : {}),\n+\t};\n+}"}],"unmatched":[]}