Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed

Versions 68 to 318

Compare

+1693 −0 in 1 place
new file, 1,693 lines
1+// Issues for the open server (abso-core issue 17): one store per project, in SQLite, holding current state:
2+// issues, comments, labels, asks with their answers and threads, claims, the versions out for each issue,
3+// drafts, and what each reader's news has shown. Ported from the platform's issues Worker, without its
4+// workflow and release stores, prose authorship records, attachments, copies and meaning search.
5+//
6+// Status comes from the work and nobody sets it: Done when a publish closed it (or someone marked it done),
7+// Blocked while an ask that isn't a review is open on it (or names it in `blocks`) or an issue it is blocked
8+// by is not done, In review while a review ask is open on it, In progress while a start note names it, and
9+// Open otherwise. An answer is kept in its writer's own words on the ask it answers.
10+//
11+// Watchers: who opened an issue, its Agent and any agent that claims it, its reviewer, whoever was named in
12+// Notify, and whoever comments. An edit tells them unless its writer says not to.
14+import type {
15+ Actor,
16+ Ask,
17+ AskReply,
18+ Comment,
19+ Draft,
20+ DraftBody,
21+ Edit,
22+ IssuePage,
23+ IssueRow,
24+ Lines,
25+ News,
26+ ProseAuthorship,
27+ Status,
28+} from "../../../client/src/issues-wire.ts";
29+import { unseenIn } from "../../../worker/project/unseen.ts";
31+export type {
32+ Actor,
33+ Ask,
34+ Claim,
35+ Comment,
36+ Draft,
37+ DraftBody,
38+ Edit,
39+ IssuePage,
40+ IssueRow,
41+ Lines,
42+ News,
43+ Status,
44+} from "../../../client/src/issues-wire.ts";
46+/** The SQL a Durable Object's storage gives (ctx.storage.sql), and node:sqlite in tests. */
47+export interface Sql {
48+ exec(query: string, ...bindings: unknown[]): { toArray(): unknown[] };
49+}
51+/** A plain sentence for the person or agent; the route answers with it and `status`. */
52+export class IssuesError extends Error {
53+ readonly status: number;
54+ /** Seconds until a refused write may be tried again (429), for Retry-After. */
55+ readonly retryAfter: number | undefined;
56+ constructor(message: string, status = 400, retryAfter?: number) {
57+ super(message);
58+ this.status = status;
59+ this.retryAfter = retryAfter;
60+ }
61+}
63+/**
64+ * A label: 1-40 characters of lower-case letters, digits, and - _ . : (so
65+ * "friction", "good-first-issue", "area:client"). Anything else is refused,
66+ * upper case included, rather than changed: the client and the
67+ * site lower-case what's typed before sending.
68+ */
69+export const LABEL = /^[a-z0-9][a-z0-9_.:-]{0,39}$/;
70+export const LABELS_PER_ISSUE = 20;
71+/** Distinct labels a project may hold, since GET labels lists every one. */
72+export const LABELS_PER_PROJECT = 200;
74+/** Writes per writer (agent or person:<id>), since each can carry news. */
75+export const WRITES_PER_MINUTE = 100;
76+export const WRITES_PER_DAY = 1000;
78+/** At most this many @names in one comment are told. */
79+export const MENTIONS_MAX = 20;
81+/**
82+ * The agents a text names as @name, in order, each once: an @ at the start or after anything
83+ * but a name character, so an email address isn't one. A sentence's full stop or dash after the name isn't
84+ * part of it.
85+ */
86+export function mentionsIn(text: string): string[] {
87+ const names = new Set<string>();
88+ for (const m of text.matchAll(/(?:^|[^A-Za-z0-9._@-])@([A-Za-z0-9][A-Za-z0-9._-]{0,63})/g)) {
89+ names.add(m[1]!.replace(/[._-]+$/, ""));
90+ if (names.size === MENTIONS_MAX) break;
91+ }
92+ return [...names];
93+}
95+const LIMITS = {
96+ title: 200,
97+ description: 20_000,
98+ text: 4_000,
99+ open: 10_000,
100+ options: 10,
101+ blocks: 50,
102+ names: 50,
103+ drafts: 100,
104+ draft: 30_000,
105+};
107+/**
108+ * The tables the change count watches: what issue reads show. Not drafts (one person's), writes (the rate log),
109+ * search (kept from issues and comments) or meta. Fixed, since SCHEMA makes three triggers for each: a later
110+ * table appends its own three to SCHEMA instead.
111+ */
112+const COUNTED_TABLES = [
113+ "issues",
114+ "comments",
115+ "asks",
116+ "claims",
117+ "versions",
118+ "watchers",
119+ "blocked_by",
120+ "edits",
121+ "labels",
122+ "ask_replies",
123+] as const;
125+/**
126+ * The tables, as add-only migrations: the IssueProject object runs each once, in order (index.ts), so an
127+ * older Worker still reads a newer database. Append; never edit or reorder.
128+ */
129+export const SCHEMA: readonly string[] = [
130+ `CREATE TABLE IF NOT EXISTS issues (id INTEGER PRIMARY KEY, parent INTEGER, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',
131+ opened_by TEXT NOT NULL, opened_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, lines TEXT,
132+ closed_how TEXT, closed_by TEXT, closed_version INTEGER, closed_at INTEGER, agent TEXT)`,
133+ "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)",
134+ `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,
135+ review INTEGER NOT NULL, due TEXT, recommendation TEXT, options TEXT NOT NULL, blocks TEXT NOT NULL, at INTEGER NOT NULL,
136+ answer_by TEXT, answer_words TEXT, answer_at INTEGER, seen_at INTEGER, outcome TEXT, ack_at INTEGER, ack_note TEXT, waiting_on TEXT)`,
137+ "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))",
138+ "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))",
139+ "CREATE TABLE IF NOT EXISTS watchers (issue INTEGER NOT NULL, who TEXT NOT NULL, since INTEGER NOT NULL, PRIMARY KEY (issue, who))",
140+ "CREATE TABLE IF NOT EXISTS blocked_by (issue INTEGER NOT NULL, blocker INTEGER NOT NULL, PRIMARY KEY (issue, blocker))",
141+ "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)",
142+ "CREATE TABLE IF NOT EXISTS drafts (id INTEGER PRIMARY KEY, owner TEXT NOT NULL, body TEXT NOT NULL, saved_at INTEGER NOT NULL)",
143+ // Each writer's writes of the last day, for the limit.
144+ "CREATE TABLE IF NOT EXISTS writes (who TEXT NOT NULL, at INTEGER NOT NULL)",
145+ "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))",
146+ // Ask threads: replies from either side while the ask is open or after. An ask's waiting_on is null while it
147+ // waits on the one asked, and the asker's name after the one asked replies with a question.
148+ "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)",
149+ // A reader's news: read up to when. Not counted, since no issue read shows it.
150+ "CREATE TABLE IF NOT EXISTS news_read (who TEXT PRIMARY KEY, at INTEGER NOT NULL)",
151+ "CREATE INDEX IF NOT EXISTS comments_issue ON comments (issue)",
152+ "CREATE INDEX IF NOT EXISTS comments_at ON comments (at)",
153+ "CREATE INDEX IF NOT EXISTS asks_issue ON asks (issue)",
154+ "CREATE INDEX IF NOT EXISTS asks_open ON asks (answer_at)",
155+ "CREATE INDEX IF NOT EXISTS issues_parent ON issues (parent)",
156+ "CREATE INDEX IF NOT EXISTS issues_updated ON issues (updated_at)",
157+ "CREATE INDEX IF NOT EXISTS edits_issue ON edits (issue)",
158+ "CREATE INDEX IF NOT EXISTS drafts_owner ON drafts (owner)",
159+ "CREATE INDEX IF NOT EXISTS writes_who ON writes (who, at)",
160+ "CREATE INDEX IF NOT EXISTS labels_label ON labels (label)",
161+ "CREATE INDEX IF NOT EXISTS ask_replies_ask ON ask_replies (ask)",
162+ "CREATE INDEX IF NOT EXISTS ask_replies_at ON ask_replies (at)",
163+ // Search: every title, description and comment in a full-text index, kept in step by triggers.
164+ "CREATE VIRTUAL TABLE IF NOT EXISTS search USING fts5(issue UNINDEXED, comment UNINDEXED, field UNINDEXED, text, tokenize = 'porter unicode61')",
165+ `CREATE TRIGGER IF NOT EXISTS search_issue_in AFTER INSERT ON issues BEGIN
166+ INSERT INTO search (issue, comment, field, text) VALUES (new.id, 0, 'title', new.title);
167+ INSERT INTO search (issue, comment, field, text) SELECT new.id, 0, 'description', new.description WHERE new.description <> '';
168+ END`,
169+ `CREATE TRIGGER IF NOT EXISTS search_issue_edit AFTER UPDATE OF title, description ON issues BEGIN
170+ DELETE FROM search WHERE issue = old.id AND comment = 0;
171+ INSERT INTO search (issue, comment, field, text) VALUES (new.id, 0, 'title', new.title);
172+ INSERT INTO search (issue, comment, field, text) SELECT new.id, 0, 'description', new.description WHERE new.description <> '';
173+ END`,
174+ "CREATE TRIGGER IF NOT EXISTS search_issue_out AFTER DELETE ON issues BEGIN DELETE FROM search WHERE issue = old.id; END",
175+ "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",
176+ `CREATE TRIGGER IF NOT EXISTS search_comment_edit AFTER UPDATE OF text ON comments BEGIN
177+ DELETE FROM search WHERE comment = old.id;
178+ INSERT INTO search (issue, comment, field, text) VALUES (new.issue, new.id, 'comment', new.text);
179+ END`,
180+ "CREATE TRIGGER IF NOT EXISTS search_comment_out AFTER DELETE ON comments BEGIN DELETE FROM search WHERE comment = old.id; END",
181+ // The change count: one number that only grows, bumped by triggers on every table an issue read shows, so
182+ // every write path moves it, the seen marks waiting writes included. A reader can cache issue reads by it.
183+ "CREATE TABLE IF NOT EXISTS change_count (id INTEGER PRIMARY KEY CHECK (id = 1), n INTEGER NOT NULL)",
184+ "INSERT OR IGNORE INTO change_count (id, n) VALUES (1, 0)",
185+ ...COUNTED_TABLES.flatMap((t) =>
186+ (["INSERT", "UPDATE", "DELETE"] as const).map(
187+ (op) =>
188+ `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`,
189+ ),
190+ ),
191+];
193+/** How many news items one project gives a person's news, before the merge across projects. */
194+export const NEWS_MAX = 50;
195+/** How much of a comment, answer or reply a news item carries. */
196+const NEWS_TEXT_MAX = 280;
198+/**
199+ * One thing for a person's news: an answer to their ask, a reply on an ask they're in, an
200+ * @mention of them, or a comment, edit or close on an issue they watch, by someone else.
201+ */
202+export interface NewsItem {
203+ kind: "answer" | "reply" | "mention" | "comment" | "edit" | "closed";
204+ issue: number | null;
205+ title: string | null;
206+ ask?: number;
207+ by: string;
208+ text: string;
209+ at: number;
210+ read: boolean;
211+}
213+/** One issue a search found: where the best match is, a snippet around it, and how well it matched. */
214+export interface SearchHit {
215+ issue: { id: number; title: string; status: Status; updated: number; labels: string[] };
216+ /** Where the best match is: the title, the description, or a comment (with its id). */
217+ where: "title" | "description" | "comment";
218+ comment?: number;
219+ /** A few words around the match, with each matched span's [start, end) in `marks`. */
220+ snippet: string;
221+ marks: number[][];
222+ /** FTS5's bm25, made positive: higher matches better. */
223+ score: number;
224+}
226+/** A search hit as the client reads it: the issue's title and the matched text, each with who wrote it. */
227+export type AuthoredSearchHit = Omit<SearchHit, "issue"> & {
228+ issue: SearchHit["issue"] & { authorship: { title: ProseAuthorship } };
229+ matchedAuthorship: ProseAuthorship;
230+};
232+type StoredAskReply = Omit<AskReply, "authorship">;
233+type StoredAsk = Omit<Ask, "authorship" | "answer" | "ack" | "replies"> & {
234+ answer: { by: string; words: string; at: number } | null;
235+ ack?: { at: number; note: string };
236+ replies: StoredAskReply[];
237+};
239+const UNKNOWN: ProseAuthorship = { kind: "unknown", actor: null, provenance: "unknown", authorField: null };
241+/**
242+ * Who wrote a text, from the column that names its writer: an agent, or a person (person:<id>). This server
243+ * keeps no separate authorship records, so every text is its writer's own ("native").
244+ */
245+function authored(by: unknown, authorField: string): ProseAuthorship {
246+ if (typeof by !== "string" || by === "") return UNKNOWN;
247+ return { kind: by.startsWith("person:") ? "human" : "agent", actor: by, provenance: "native", authorField };
248+}
250+/**
251+ * A person's words as an FTS5 query: each word quoted, so nothing they type
252+ * is query syntax, and the last one a prefix, so a search box finds as they
253+ * type. Undefined when there's no word in it.
254+ */
255+export function searchQuery(q: string): string | undefined {
256+ const words = q.match(/[\p{L}\p{N}_]+/gu)?.slice(0, 12);
257+ if (!words || words.length === 0) return undefined;
258+ return words.map((w, i) => `"${w}"${i === words.length - 1 ? "*" : ""}`).join(" ");
259+}
261+type Row = Record<string, unknown>;
263+/** How an actor is named in the store and on the pages: the agent's name, or person:<id>. */
264+export function who(actor: Actor): string {
265+ return "agent" in actor ? actor.agent : `person:${actor.person}`;
266+}
268+/**
269+ * Words that reach agents on pages and in news: within `max`, with nothing a reader can't see (the engine's
270+ * own list, worker/project/unseen.ts), and on one line where `oneLine`.
271+ */
272+function text(value: unknown, what: string, max: number, required = true, oneLine = false): string {
273+ if (value === undefined || value === null || value === "") {
274+ if (required) throw new IssuesError(`${what} is missing`);
275+ return "";
276+ }
277+ if (typeof value !== "string") throw new IssuesError(`${what} is text`);
278+ const t = value.trim();
279+ if (required && t === "") throw new IssuesError(`${what} is empty`);
280+ if (t.length > max) throw new IssuesError(`${what} is ${t.length} characters; the most is ${max}`);
281+ const hidden = unseenIn(t);
282+ if (hidden !== null)
283+ throw new IssuesError(`${what} holds ${hidden}, which a reader of the page can't see; take it out`);
284+ if (oneLine && /[\n\t]/.test(t)) throw new IssuesError(`${what} is one line`);
285+ return t;
286+}
288+function issueNumber(value: unknown, what = "an issue number"): number {
289+ const n = Number(value);
290+ if (!Number.isInteger(n) || n < 1) throw new IssuesError(`${what} is a whole number from 1`);
291+ return n;
292+}
294+/** A list of names (agents, or person:<id>), each once. */
295+function names(value: unknown, what: string): string[] {
296+ if (value === undefined || value === null) return [];
297+ if (!Array.isArray(value) || value.length > LIMITS.names)
298+ throw new IssuesError(`${what} is a list of up to ${LIMITS.names} names`);
299+ return [...new Set(value.map((v, i) => text(v, `${what}'s name ${i + 1}`, 100, true, true)))];
300+}
302+/** Labels, checked as given (nothing is changed but surrounding spaces), each once, sorted. */
303+function labelsOf(value: unknown, what = "labels"): string[] {
304+ if (value === undefined || value === null) return [];
305+ if (!Array.isArray(value) || value.length > LABELS_PER_ISSUE)
306+ throw new IssuesError(`${what} is a list of up to ${LABELS_PER_ISSUE} labels`);
307+ const out = new Set<string>();
308+ for (const v of value) {
309+ const l = typeof v === "string" ? v.trim() : "";
310+ if (!LABEL.test(l))
311+ throw new IssuesError(
312+ `${JSON.stringify(v)} isn't a label: 1-40 lower-case letters, digits, and - _ . : (like friction or area:client)`,
313+ );
314+ out.add(l);
315+ }
316+ return [...out].sort();
317+}
319+/** A name, or null for none: "" and null clear it. */
320+function nameOrNone(value: unknown, what: string): string | null {
321+ return value === null || value === "" ? null : text(value, what, 100, true, true);
322+}
324+function lines(value: unknown): Lines | null {
325+ if (value === undefined || value === null) return null;
326+ const l = value as Partial<Lines>;
327+ if (
328+ typeof l.file !== "string" ||
329+ l.file === "" ||
330+ !Number.isInteger(l.from) ||
331+ !Number.isInteger(l.to) ||
332+ !Number.isInteger(l.version) ||
333+ l.from! < 1 ||
334+ l.to! < l.from! ||
335+ l.version! < 0
336+ ) {
337+ throw new IssuesError("lines are {file, from, to, version}: lines from-to of a file at a version");
338+ }
339+ return { file: text(l.file, "the lines' file", 1000, true, true), from: l.from!, to: l.to!, version: l.version! };
340+}
342+const unique = (xs: readonly string[]): string[] => [...new Set(xs)];
344+export class IssuesStore {
345+ private readonly sql: Sql;
346+ private readonly now: () => number;
347+ private readonly atomic: (<T>(action: () => T) => T) | null;
349+ /** Over tables SCHEMA made (the object's migrations, or createTables in tests). `atomic` runs a transaction. */
350+ constructor(sql: Sql, now: () => number = Date.now, atomic?: <T>(action: () => T) => T) {
351+ this.sql = sql;
352+ this.now = now;
353+ this.atomic = atomic ?? null;
354+ }
356+ private transaction<T>(action: () => T): T {
357+ return this.atomic ? this.atomic(action) : action();
358+ }
360+ static createTables(sql: Sql): void {
361+ for (const s of SCHEMA) sql.exec(s);
362+ }
364+ /**
365+ * The change count: it grows with every write an issue read can show and never goes back, so a read cached
366+ * under it is never older than its key.
367+ */
368+ changes(): number {
369+ return (this.rows("SELECT n FROM change_count WHERE id = 1")[0]?.n as number | undefined) ?? 0;
370+ }
372+ /**
373+ * A reader's news here, newest first, at most NEWS_MAX: answers to their asks, replies on asks they asked or
374+ * were asked, comments naming them as @name (`names`: what they go by; an agent goes by its own name), and on
375+ * issues they watch, others' comments, the edits that told them, and closes. Each is read when it is at or
376+ * before their news_read mark. `before` pages back.
377+ */
378+ newsFor(reader: Actor, names: readonly string[], before?: number): NewsItem[] {
379+ const me = who(reader);
380+ const until = before ?? Number.MAX_SAFE_INTEGER;
381+ const mark = (this.rows("SELECT at FROM news_read WHERE who = ?", me)[0]?.at as number | undefined) ?? 0;
382+ const cut = (t: string) => (t.length > NEWS_TEXT_MAX ? `${t.slice(0, NEWS_TEXT_MAX - 1)}…` : t);
383+ const items: NewsItem[] = [];
384+ const add = (kind: NewsItem["kind"], r: Row, text: string, ask?: number) =>
385+ items.push({
386+ kind,
387+ issue: (r.issue as number | null) ?? null,
388+ title: (r.title as string | null) ?? null,
389+ ...(ask !== undefined ? { ask } : {}),
390+ by: r.by as string,
391+ text: cut(text),
392+ at: r.at as number,
393+ read: (r.at as number) <= mark,
394+ });
395+ for (const r of this.rows(
396+ `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
397+ LEFT JOIN issues i ON i.id = a.issue
398+ WHERE 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')
399+ ORDER BY a.answer_at DESC LIMIT ?`,
400+ me,
401+ until,
402+ me,
403+ NEWS_MAX,
404+ ))
405+ add("answer", r, (r.text as string | null) ?? "", r.id as number);
406+ for (const r of this.rows(
407+ `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
408+ LEFT JOIN issues i ON i.id = a.issue
409+ WHERE (a.by = ? OR a.of = ?) AND r.by <> ? AND r.at < ? ORDER BY r.at DESC LIMIT ?`,
410+ me,
411+ me,
412+ me,
413+ until,
414+ NEWS_MAX,
415+ ))
416+ add("reply", r, r.text as string, r.ask as number);
417+ const named = names.filter((n) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(n)).slice(0, 4);
418+ const mentioned = new Set<number>();
419+ for (const n of named)
420+ for (const r of this.rows(
421+ `SELECT c.id, c.issue, i.title, c.by, c.text, c.at FROM comments c JOIN issues i ON i.id = c.issue
422+ WHERE c.by <> ? AND c.at < ? AND instr(lower(c.text), ?) > 0 ORDER BY c.at DESC LIMIT ?`,
423+ me,
424+ until,
425+ `@${n.toLowerCase()}`,
426+ NEWS_MAX,
427+ )) {
428+ const said = mentionsIn(r.text as string).map((m) => m.toLowerCase());
429+ if (!said.includes(n.toLowerCase()) || mentioned.has(r.id as number)) continue;
430+ mentioned.add(r.id as number);
431+ add("mention", r, r.text as string);
432+ }
433+ for (const r of this.rows(
434+ `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 = ?
435+ JOIN issues i ON i.id = c.issue
436+ WHERE c.by <> ? AND c.at >= w.since AND c.at < ? ORDER BY c.at DESC LIMIT ?`,
437+ me,
438+ me,
439+ until,
440+ NEWS_MAX,
441+ ))
442+ if (!mentioned.has(r.id as number)) add("comment", r, r.text as string);
443+ for (const r of this.rows(
444+ `SELECT e.issue, i.title, e.by, e.changes, e.at FROM edits e JOIN issues i ON i.id = e.issue
445+ WHERE e.by <> ? AND e.at < ? AND EXISTS (SELECT 1 FROM json_each(e.notified) WHERE value = ?)
446+ ORDER BY e.at DESC LIMIT ?`,
447+ me,
448+ until,
449+ me,
450+ NEWS_MAX,
451+ ))
452+ add("edit", r, Object.keys(JSON.parse(r.changes as string) as object).join(", "));
453+ for (const r of this.rows(
454+ `SELECT i.id AS issue, i.title, i.closed_by AS by, i.closed_how, i.closed_at AS at FROM issues i
455+ JOIN watchers w ON w.issue = i.id AND w.who = ?
456+ WHERE i.closed_at IS NOT NULL AND i.closed_at < ? AND i.closed_by <> ? ORDER BY i.closed_at DESC LIMIT ?`,
457+ me,
458+ until,
459+ me,
460+ NEWS_MAX,
461+ ))
462+ add("closed", r, r.closed_how as string);
463+ return items.sort((x, y) => y.at - x.at).slice(0, NEWS_MAX);
464+ }
466+ /** Marks the reader's news here read up to `at` (never back); answers the mark. */
467+ markNewsRead(reader: Actor, at: number): { read: number } {
468+ this.sql.exec(
469+ "INSERT INTO news_read (who, at) VALUES (?, ?) ON CONFLICT (who) DO UPDATE SET at = MAX(at, excluded.at)",
470+ who(reader),
471+ at,
472+ );
473+ return { read: this.rows("SELECT at FROM news_read WHERE who = ?", who(reader))[0]!.at as number };
474+ }
476+ private rows(query: string, ...b: unknown[]): Row[] {
477+ return this.sql.exec(query, ...b).toArray() as Row[];
478+ }
480+ private exists(id: number): Row {
481+ const row = this.rows("SELECT * FROM issues WHERE id = ?", issueNumber(id))[0];
482+ if (!row) throw new IssuesError(`there's no issue ${id}`, 404);
483+ return row;
484+ }
486+ private touch(...ids: (number | null)[]): void {
487+ const at = this.now();
488+ for (const id of ids)
489+ if (id !== null) this.sql.exec("UPDATE issues SET updated_at = MAX(updated_at, ?) WHERE id = ?", at, id);
490+ }
492+ /** Refuses labels that would take the project past LABELS_PER_PROJECT distinct ones. */
493+ private roomForLabels(labels: readonly string[]): void {
494+ const inUse = new Set(this.rows("SELECT DISTINCT label FROM labels").map((l) => l.label as string));
495+ const added = labels.filter((l) => !inUse.has(l));
496+ if (added.length > 0 && inUse.size + added.length > LABELS_PER_PROJECT)
497+ throw new IssuesError(
498+ `this project has ${inUse.size} labels, and ${LABELS_PER_PROJECT} is the most; use one it has (abso issues --labels lists them)`,
499+ );
500+ }
502+ /** Attachments aren't kept on this server: a write that names any is refused before anything is written. */
503+ private noAttachments(raw: unknown): void {
504+ if (raw === undefined || raw === null || (Array.isArray(raw) && raw.length === 0)) return;
505+ throw new IssuesError("this server doesn't keep attachments; leave them off, or link the file instead", 501);
506+ }
508+ /** Adds watchers to an issue; each is kept once, from when they first watched. */
509+ private watch(id: number, ...people: (string | null | undefined)[]): void {
510+ const at = this.now();
511+ for (const p of people)
512+ if (p)
513+ this.sql.exec(
514+ "INSERT INTO watchers (issue, who, since) VALUES (?, ?, ?) ON CONFLICT (issue, who) DO NOTHING",
515+ id,
516+ p,
517+ at,
518+ );
519+ }
521+ private watchersOf(id: number): string[] {
522+ return this.rows("SELECT who FROM watchers WHERE issue = ? ORDER BY since, who", id).map((w) => w.who as string);
523+ }
525+ /** Blocked by, checked: issues that exist, not `id` itself, and none already waiting on `id` (that would wait forever). */
526+ private blockersFor(id: number | null, value: unknown): number[] {
527+ if (value === undefined || value === null) return [];
528+ if (!Array.isArray(value) || value.length > LIMITS.blocks)
529+ throw new IssuesError(`blocked by is a list of up to ${LIMITS.blocks} issue numbers`);
530+ const ids = [...new Set(value.map((b) => issueNumber(b, "an issue it's blocked by")))];
531+ for (const b of ids) {
532+ this.exists(b);
533+ if (b === id) throw new IssuesError(`issue ${id} can't be blocked by itself`);
534+ if (id !== null && this.waitsOn(b, id))
535+ throw new IssuesError(`issue ${b} already waits on issue ${id}, so neither could start`);
536+ }
537+ return ids;
538+ }
540+ /** Whether `from` waits on `on`, through Blocked by. */
541+ private waitsOn(from: number, on: number): boolean {
542+ const seen = new Set<number>();
543+ const next = [from];
544+ while (next.length > 0) {
545+ const at = next.pop()!;
546+ if (at === on) return true;
547+ if (seen.has(at)) continue;
548+ seen.add(at);
549+ for (const b of this.rows("SELECT blocker FROM blocked_by WHERE issue = ?", at)) next.push(b.blocker as number);
550+ }
551+ return false;
552+ }
554+ /** A parent, checked: an issue that exists and isn't `id` or under it. */
555+ private parentFor(id: number | null, value: unknown): number | null {
556+ if (value === undefined || value === null) return null;
557+ const parent = issueNumber(value, "the parent");
558+ this.exists(parent);
559+ for (
560+ let at: number | null = parent;
561+ at !== null;
562+ at = (this.rows("SELECT parent FROM issues WHERE id = ?", at)[0]?.parent as number | null | undefined) ?? null
563+ ) {
564+ if (at === id) throw new IssuesError(`issue ${parent} is issue ${id} or under it, so it can't be its parent`);
565+ }
566+ return parent;
567+ }
569+ /** Every row's status and joins at once: one query per table, not one per issue. */
570+ private statuses(rows: Row[]): IssueRow[] {
571+ if (rows.length === 0) return [];
572+ // Open asks hold up their own issue and the ones they name in blocks.
573+ const held = new Map<number, { review: boolean; of: string }[]>();
574+ for (const a of this.rows(
575+ "SELECT issue, COALESCE(waiting_on, of) AS of, review, blocks FROM asks WHERE answer_at IS NULL",
576+ )) {
577+ const on = new Set<number>([
578+ ...(a.issue !== null ? [a.issue as number] : []),
579+ ...(JSON.parse(a.blocks as string) as number[]),
580+ ]);
581+ for (const id of on)
582+ held.set(id, [...(held.get(id) ?? []), { review: a.review === 1 && id === a.issue, of: a.of as string }]);
583+ }
584+ const claims = new Map<number, string[]>();
585+ for (const c of this.rows("SELECT issue, agent FROM claims ORDER BY since"))
586+ claims.set(c.issue as number, [...(claims.get(c.issue as number) ?? []), c.agent as string]);
587+ const versions = new Map<number, number[]>();
588+ for (const v of this.rows("SELECT issue, version FROM versions ORDER BY version"))
589+ versions.set(v.issue as number, [...(versions.get(v.issue as number) ?? []), v.version as number]);
590+ const children = new Map<number, number>();
591+ for (const c of this.rows("SELECT parent, COUNT(*) AS n FROM issues WHERE parent IS NOT NULL GROUP BY parent"))
592+ children.set(c.parent as number, c.n as number);
593+ const labels = new Map<number, string[]>();
594+ for (const l of this.rows("SELECT issue, label FROM labels ORDER BY label"))
595+ labels.set(l.issue as number, [...(labels.get(l.issue as number) ?? []), l.label as string]);
596+ // Blocked by: each blocker, and whether it's Done yet.
597+ const blockers = new Map<number, { id: number; done: boolean }[]>();
598+ for (const b of this.rows(
599+ "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",
600+ )) {
601+ blockers.set(b.issue as number, [
602+ ...(blockers.get(b.issue as number) ?? []),
603+ { id: b.blocker as number, done: b.closed_how === "done" },
604+ ]);
605+ }
606+ const retitled = this.lastEditors("title");
607+ return rows.map((r) => {
608+ const id = r.id as number;
609+ const asks = held.get(id) ?? [];
610+ const agents = claims.get(id) ?? [];
611+ const blockedBy = blockers.get(id) ?? [];
612+ const status: Status =
613+ r.closed_how === "done"
614+ ? "done"
615+ : r.closed_how === "dropped"
616+ ? "dropped"
617+ : asks.some((a) => !a.review) || blockedBy.some((b) => !b.done)
618+ ? "blocked"
619+ : asks.length > 0
620+ ? "in review"
621+ : agents.length > 0
622+ ? "in progress"
623+ : "open";
624+ return {
625+ id,
626+ title: r.title as string,
627+ authorship: { title: this.issueFieldAuthorship(r, retitled) },
628+ parent: (r.parent as number | null) ?? null,
629+ status,
630+ agent: (r.agent as string | null | undefined) ?? null,
631+ agents,
632+ blockedBy: blockedBy.map((b) => b.id),
633+ labels: labels.get(id) ?? [],
634+ versions: versions.get(id) ?? [],
635+ waitingOn: r.closed_how ? [] : [...new Set(asks.map((a) => a.of))],
636+ opened: { by: r.opened_by as string, at: r.opened_at as number },
637+ updated: r.updated_at as number,
638+ closed: r.closed_how
639+ ? {
640+ how: r.closed_how as "done" | "dropped",
641+ by: r.closed_by as string,
642+ version: (r.closed_version as number | null) ?? null,
643+ at: r.closed_at as number,
644+ }
645+ : null,
646+ children: children.get(id) ?? 0,
647+ };
648+ });
649+ }
651+ /** Who last edited `field` on each issue whose `field` was edited (or only issue `id`'s). */
652+ private lastEditors(field: "title" | "description", id?: number): Map<number, string> {
653+ const edited = new Map<number, string>();
654+ const where = `json_type(changes, '$.${field}') IS NOT NULL${id === undefined ? "" : " AND issue = ?"}`;
655+ for (const e of this.rows(
656+ `SELECT issue, by FROM edits WHERE ${where} ORDER BY id`,
657+ ...(id === undefined ? [] : [id]),
658+ ))
659+ edited.set(e.issue as number, e.by as string);
660+ return edited;
661+ }
663+ /** Who wrote an issue's title or description now: whoever last edited it, else whoever opened the issue. */
664+ private issueFieldAuthorship(row: Row, edited: Map<number, string>): ProseAuthorship {
665+ const editor = edited.get(row.id as number);
666+ return editor === undefined ? authored(row.opened_by, "issues.opened_by") : authored(editor, "edits.by");
667+ }
669+ /** An ask as the client reads it: each text with who wrote it. */
670+ private authoredAsk(a: StoredAsk): Ask {
671+ const { ack, ...ask } = a;
672+ return {
673+ ...ask,
674+ authorship: { question: authored(a.by, "asks.by") },
675+ answer: a.answer ? { ...a.answer, authorship: authored(a.answer.by, "asks.answer_by") } : null,
676+ ...(ack
677+ ? { ack: { ...ack, authorship: { note: ack.note === "" ? UNKNOWN : authored(a.of, "ask_replies.by") } } }
678+ : {}),
679+ replies: a.replies.map((reply) => ({ ...reply, authorship: authored(reply.by, "ask_replies.by") })),
680+ };
681+ }
683+ // Reads ----------------------------------------------------------------------------------
685+ /**
686+ * Issues, most recently updated first, filtered by status, agent, parent or
687+ * labels (each one named). `open` leaves out done and dropped.
688+ */
689+ list(
690+ filter: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},
691+ ): IssueRow[] {
692+ const wanted = filter.labels === undefined ? [] : labelsOf([...filter.labels], "the labels to filter by");
693+ const rows =
694+ filter.parent === undefined
695+ ? this.rows("SELECT * FROM issues ORDER BY updated_at DESC, id DESC")
696+ : this.rows("SELECT * FROM issues WHERE parent = ? ORDER BY updated_at DESC, id DESC", filter.parent);
697+ return this.statuses(rows).filter(
698+ (i) =>
699+ (filter.status === undefined || i.status === filter.status) &&
700+ (filter.agent === undefined || i.agent === filter.agent || i.agents.includes(filter.agent)) &&
701+ (!filter.open || (i.status !== "done" && i.status !== "dropped")) &&
702+ wanted.every((l) => i.labels.includes(l)),
703+ );
704+ }
706+ /** Issues matching `q`, best first, one hit per issue at its best place. Drafts aren't searched. */
707+ search(q: string, limit = 20): AuthoredSearchHit[] {
708+ const query = searchQuery(q);
709+ if (query === undefined) return [];
710+ const rows = this.rows(
711+ "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",
712+ query,
713+ );
714+ const best = new Map<number, Row>();
715+ for (const r of rows) if (!best.has(r.issue as number)) best.set(r.issue as number, r);
716+ const ids = [...best.keys()].slice(0, Math.max(1, Math.min(limit, 50)));
717+ if (ids.length === 0) return [];
718+ const found = this.rows(`SELECT * FROM issues WHERE id IN (${ids.map(() => "?").join(", ")})`, ...ids);
719+ const rowOf = new Map(found.map((r) => [r.id as number, r]));
720+ const issues = new Map(this.statuses(found).map((i) => [i.id, i]));
721+ return ids.flatMap((id) => {
722+ const r = best.get(id)!;
723+ const i = issues.get(id);
724+ if (!i) return [];
725+ const { text, marks } = marked(r.snip as string);
726+ const where = r.field as SearchHit["where"];
727+ const commentId = r.comment as number;
728+ const matchedAuthorship =
729+ where === "comment"
730+ ? authored(this.rows("SELECT by FROM comments WHERE id = ?", commentId)[0]?.by, "comments.by")
731+ : where === "title"
732+ ? i.authorship.title
733+ : this.issueFieldAuthorship(rowOf.get(id)!, this.lastEditors("description", id));
734+ return [
735+ {
736+ issue: {
737+ id,
738+ title: i.title,
739+ status: i.status,
740+ updated: i.updated,
741+ labels: i.labels,
742+ authorship: i.authorship,
743+ },
744+ where,
745+ ...(where === "comment" ? { comment: commentId } : {}),
746+ snippet: text,
747+ marks,
748+ matchedAuthorship,
749+ score: -(r.rank as number),
750+ },
751+ ];
752+ });
753+ }
755+ /** Every label in use, with how many issues have it and how many of those are open (done and dropped aren't). */
756+ labelsInUse(): { label: string; open: number; total: number }[] {
757+ return this.rows(
758+ "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",
759+ ).map((r) => ({ label: r.label as string, open: r.open as number, total: r.total as number }));
760+ }
762+ /** An ask with its thread, oldest first. */
763+ private withFiles(a: StoredAsk): StoredAsk {
764+ return { ...a, replies: this.repliesOf(a.id) };
765+ }
767+ /** An ask's replies, oldest first. */
768+ private repliesOf(ask: number): StoredAskReply[] {
769+ return this.rows("SELECT id, by, text, question, at FROM ask_replies WHERE ask = ? ORDER BY id", ask).map((r) => ({
770+ id: r.id as number,
771+ by: r.by as string,
772+ text: r.text as string,
773+ at: r.at as number,
774+ ...(r.question === 1 ? { question: true as const } : {}),
775+ }));
776+ }
778+ page(id: number): IssuePage {
779+ const row = this.exists(id);
780+ const [issue] = this.statuses([row]);
781+ return {
782+ issue: {
783+ ...issue!,
784+ description: row.description as string,
785+ authorship: {
786+ title: issue!.authorship.title,
787+ description: this.issueFieldAuthorship(row, this.lastEditors("description", id)),
788+ },
789+ lines: row.lines ? (JSON.parse(row.lines as string) as Lines) : null,
790+ watchers: this.watchersOf(id),
791+ },
792+ comments: this.rows("SELECT * FROM comments WHERE issue = ? ORDER BY id", id).map((c) => ({
793+ id: c.id as number,
794+ by: c.by as string,
795+ kind: c.kind as Comment["kind"],
796+ text: c.text as string,
797+ authorship: authored(c.by, "comments.by"),
798+ at: c.at as number,
799+ })),
800+ edits: this.rows("SELECT * FROM edits WHERE issue = ? ORDER BY id", id).map((e) => ({
801+ id: e.id as number,
802+ by: e.by as string,
803+ changes: JSON.parse(e.changes as string) as Edit["changes"],
804+ notified: JSON.parse(e.notified as string) as string[],
805+ at: e.at as number,
806+ })),
807+ asks: this.rows("SELECT * FROM asks WHERE issue = ? ORDER BY id", id).map((r) =>
808+ this.authoredAsk(this.withFiles(askOf(r))),
809+ ),
810+ claims: this.rows("SELECT agent, change, since FROM claims WHERE issue = ? ORDER BY since", id).map((c) => ({
811+ agent: c.agent as string,
812+ change: c.change as number,
813+ since: c.since as number,
814+ })),
815+ children: this.statuses(this.rows("SELECT * FROM issues WHERE parent = ? ORDER BY id", id)),
816+ };
817+ }
819+ /**
820+ * Open asks of someone (an agent's name or person:<id>), soonest due first, then oldest; every open ask without `of`.
821+ * When `reader` is the one they're asked of, each listed for the first time is marked seen now; the answer still
822+ * says null for those, so the reader can tell what's new.
823+ */
824+ waiting(of?: string, reader?: string): (Ask & { title: string | null })[] {
825+ const select =
826+ "SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE answer_at IS NULL";
827+ const rows =
828+ of === undefined
829+ ? this.rows(`${select} ORDER BY due IS NULL, due, asks.id`)
830+ : this.rows(`${select} AND COALESCE(waiting_on, of) = ? ORDER BY due IS NULL, due, asks.id`, of);
831+ if (of !== undefined && reader === of)
832+ this.sql.exec(
833+ "UPDATE asks SET seen_at = ? WHERE of = ? AND answer_at IS NULL AND seen_at IS NULL",
834+ this.now(),
835+ of,
836+ );
837+ return rows.map((r) => ({
838+ ...this.authoredAsk(this.withFiles(askOf(r))),
839+ title: (r.title as string | null) ?? null,
840+ }));
841+ }
843+ /** Asks of someone that have been answered, newest first. */
844+ answered(of: string, limit = 50): (Ask & { title: string | null })[] {
845+ return this.rows(
846+ "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 ?",
847+ of,
848+ limit,
849+ ).map((r) => ({
850+ ...this.authoredAsk(this.withFiles(askOf(r))),
851+ title: (r.title as string | null) ?? null,
852+ }));
853+ }
855+ /** The asks someone sent: every open one, oldest first, then the latest answered or withdrawn. */
856+ asked(by: string, answeredLimit = 10): (Ask & { title: string | null })[] {
857+ const select = "SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE asks.by = ?";
858+ return [
859+ ...this.rows(`${select} AND answer_at IS NULL ORDER BY asks.id`, by),
860+ ...this.rows(`${select} AND answer_at IS NOT NULL ORDER BY answer_at DESC LIMIT ?`, by, answeredLimit),
861+ ].map((r) => ({ ...this.authoredAsk(this.withFiles(askOf(r))), title: (r.title as string | null) ?? null }));
862+ }
864+ /** One ask, open or closed, with its thread and its issue's title. */
865+ askThread(id: number): Ask & { title: string | null } {
866+ const r = this.rows(
867+ "SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE asks.id = ?",
868+ issueNumber(id, "an ask number"),
869+ )[0];
870+ if (!r) throw new IssuesError(`there's no ask ${id}`, 404);
871+ return { ...this.authoredAsk(this.withFiles(askOf(r))), title: (r.title as string | null) ?? null };
872+ }
874+ // Writes ---------------------------------------------------------------------------------
876+ /**
877+ * A new issue. Agent is who it's for, Blocked by the issues it waits on,
878+ * and Notify who the writer tells. The writer, its Agent and Notify watch
879+ * it; Agent and Notify hear it now, and the parent's agents hear it too.
880+ */
881+ open(actor: Actor, body: Parameters<IssuesStore["openRecord"]>[1]): { id: number; news?: News } {
882+ return this.transaction(() => this.openRecord(actor, body));
883+ }
885+ private openRecord(
886+ actor: Actor,
887+ body: {
888+ title?: unknown;
889+ description?: unknown;
890+ parent?: unknown;
891+ lines?: unknown;
892+ agent?: unknown;
893+ blockedBy?: unknown;
894+ notify?: unknown;
895+ labels?: unknown;
896+ attachments?: unknown;
897+ },
898+ ): { id: number; news?: News } {
899+ const title = text(body.title, "the title", LIMITS.title, true, true);
900+ this.noAttachments(body.attachments);
901+ const description = text(body.description, "the description", LIMITS.description, false);
902+ const parent = this.parentFor(null, body.parent);
903+ const at_ = lines(body.lines);
904+ const agent = body.agent === undefined ? null : nameOrNone(body.agent, "the Agent");
905+ const blockedBy = this.blockersFor(null, body.blockedBy);
906+ const notify = names(body.notify, "Notify");
907+ const labels = labelsOf(body.labels);
908+ this.roomForLabels(labels);
909+ const open = this.rows("SELECT COUNT(*) AS n FROM issues WHERE closed_how IS NULL")[0]!.n as number;
910+ if (open >= LIMITS.open)
911+ throw new IssuesError(`this project has ${open} open issues, the most it can hold; close some first`);
912+ const at = this.now();
913+ const row = this.rows(
914+ "INSERT INTO issues (parent, title, description, opened_by, opened_at, updated_at, lines, agent) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
915+ parent,
916+ title,
917+ description,
918+ who(actor),
919+ at,
920+ at,
921+ at_ ? JSON.stringify(at_) : null,
922+ agent,
923+ )[0]!;
924+ const id = row.id as number;
925+ for (const b of blockedBy) this.sql.exec("INSERT INTO blocked_by (issue, blocker) VALUES (?, ?)", id, b);
926+ for (const l of labels)
927+ this.sql.exec("INSERT INTO labels (issue, label, by, at) VALUES (?, ?, ?, ?)", id, l, who(actor), at);
928+ this.watch(id, who(actor), agent, ...notify);
929+ this.touch(parent);
930+ const to = unique([...(agent !== null ? [agent] : []), ...notify]).filter((p) => p !== who(actor));
931+ if (parent === null && to.length === 0) return { id };
932+ const detail = [
933+ agent !== null ? `Agent ${agent}` : "",
934+ blockedBy.length > 0 ? `blocked by ${blockedBy.join(", ")}` : "",
935+ ].filter((d) => d !== "");
936+ return {
937+ id,
938+ news: {
939+ issue: parent,
940+ text: `${who(actor)} opened issue ${id}${parent !== null ? ` under issue ${parent}` : ""}: ${JSON.stringify(title)}${detail.length > 0 ? ` (${detail.join("; ")})` : ""}`,
941+ ...(to.length > 0 ? { to } : {}),
942+ },
943+ };
944+ }
946+ /**
947+ * An edit: title, description, parent, Agent, Blocked by or labels, kept in
948+ * the issue's activity. It tells the watchers unless `notify` is false;
949+ * `also` adds people, who watch it from then on (they were named in Notify).
950+ * Labels are `labels` (the whole set) or `addLabels` and `removeLabels`; an
951+ * edit that only changes labels tells nobody unless `notify` is true, since
952+ * agents sort issues by label all the time.
953+ */
954+ edit(
955+ actor: Actor,
956+ id: number,
957+ body: {
958+ title?: unknown;
959+ description?: unknown;
960+ parent?: unknown;
961+ agent?: unknown;
962+ blockedBy?: unknown;
963+ notify?: unknown;
964+ also?: unknown;
965+ labels?: unknown;
966+ addLabels?: unknown;
967+ removeLabels?: unknown;
968+ },
969+ ): { edit: number; notified: string[]; news?: News } {
970+ const row = this.exists(id);
971+ const changes: Edit["changes"] = {};
972+ const sets: [string, unknown][] = [];
973+ if (body.title !== undefined) {
974+ const title = text(body.title, "the title", LIMITS.title, true, true);
975+ if (title !== row.title) (changes.title = { from: row.title, to: title }), sets.push(["title", title]);
976+ }
977+ if (body.description !== undefined) {
978+ const description = text(body.description, "the description", LIMITS.description, false);
979+ if (description !== row.description)
980+ (changes.description = { from: row.description, to: description }), sets.push(["description", description]);
981+ }
982+ if (body.parent !== undefined) {
983+ const parent = this.parentFor(id, body.parent);
984+ if (parent !== ((row.parent as number | null) ?? null))
985+ (changes.parent = { from: row.parent ?? null, to: parent }), sets.push(["parent", parent]);
986+ }
987+ if (body.agent !== undefined) {
988+ const agent = nameOrNone(body.agent, "the Agent");
989+ if (agent !== ((row.agent as string | null | undefined) ?? null))
990+ (changes.agent = { from: row.agent ?? null, to: agent }), sets.push(["agent", agent]);
991+ }
992+ let blockedBy: number[] | undefined;
993+ if (body.blockedBy !== undefined) {
994+ blockedBy = this.blockersFor(id, body.blockedBy);
995+ const before = this.rows("SELECT blocker FROM blocked_by WHERE issue = ? ORDER BY blocker", id).map(
996+ (b) => b.blocker as number,
997+ );
998+ const after = [...blockedBy].sort((a, b) => a - b);
999+ if (before.join() !== after.join()) changes.blockedBy = { from: before, to: after };
1000+ else blockedBy = undefined;
1001+ }
1002+ let labels: string[] | undefined;
1003+ if (body.labels !== undefined || body.addLabels !== undefined || body.removeLabels !== undefined) {
1004+ if (body.labels !== undefined && (body.addLabels !== undefined || body.removeLabels !== undefined))
1005+ throw new IssuesError("labels is the whole set; addLabels and removeLabels change it; send one or the other");
1006+ const before = this.rows("SELECT label FROM labels WHERE issue = ? ORDER BY label", id).map(
1007+ (l) => l.label as string,
1008+ );
1009+ const drop = new Set(labelsOf(body.removeLabels, "removeLabels"));
1010+ const after =
1011+ body.labels !== undefined
1012+ ? labelsOf(body.labels)
1013+ : labelsOf([...before.filter((l) => !drop.has(l)), ...labelsOf(body.addLabels, "addLabels")]);
1014+ if (before.join() !== after.join()) {
1015+ this.roomForLabels(after);
1016+ changes.labels = { from: before, to: after };
1017+ labels = after;
1018+ }
1019+ }
1020+ if (body.notify !== undefined && typeof body.notify !== "boolean")
1021+ throw new IssuesError("notify is true (tell the watchers, the default) or false (tell nobody)");
1022+ const also = names(body.also, "who else to tell");
1023+ if (Object.keys(changes).length === 0) throw new IssuesError(`that changes nothing on issue ${id}`);
1024+ const labelsOnly = Object.keys(changes).every((k) => k === "labels");
1025+ const e = this.transaction(() => {
1026+ for (const [column, value] of sets) this.sql.exec(`UPDATE issues SET ${column} = ? WHERE id = ?`, value, id);
1027+ if (blockedBy !== undefined) {
1028+ this.sql.exec("DELETE FROM blocked_by WHERE issue = ?", id);
1029+ for (const b of blockedBy) this.sql.exec("INSERT INTO blocked_by (issue, blocker) VALUES (?, ?)", id, b);
1030+ }
1031+ if (labels !== undefined) {
1032+ // A label kept keeps who added it and when.
1033+ for (const l of this.rows("SELECT label FROM labels WHERE issue = ?", id))
1034+ if (!labels.includes(l.label as string))
1035+ this.sql.exec("DELETE FROM labels WHERE issue = ? AND label = ?", id, l.label);
1036+ for (const l of labels)
1037+ this.sql.exec(
1038+ "INSERT OR IGNORE INTO labels (issue, label, by, at) VALUES (?, ?, ?, ?)",
1039+ id,
1040+ l,
1041+ who(actor),
1042+ this.now(),
1043+ );
1044+ }
1045+ this.watch(id, (changes.agent?.to as string | null | undefined) ?? null, ...also);
1046+ const notified =
1047+ body.notify === false || (labelsOnly && body.notify !== true)
1048+ ? []
1049+ : unique([...this.watchersOf(id), ...also]).filter((p) => p !== who(actor));
1050+ const edit = this.rows(
1051+ "INSERT INTO edits (issue, by, changes, notified, at) VALUES (?, ?, ?, ?, ?) RETURNING id",
1052+ id,
1053+ who(actor),
1054+ JSON.stringify(changes),
1055+ JSON.stringify(notified),
1056+ this.now(),
1057+ )[0]!.id as number;
1058+ return { id: edit, notified };
1059+ });
1060+ const notified = e.notified;
1061+ this.touch(id, (row.parent as number | null) ?? null, (changes.parent?.to as number | null | undefined) ?? null);
1062+ if (notified.length === 0) return { edit: e.id as number, notified };
1063+ const title = (changes.title?.to as string | undefined) ?? (row.title as string);
1064+ const said = [
1065+ changes.title ? `title was ${JSON.stringify(changes.title.from)}` : "",
1066+ changes.description ? "description changed" : "",
1067+ changes.parent ? (changes.parent.to === null ? "no parent now" : `parent is issue ${changes.parent.to}`) : "",
1068+ changes.agent ? (changes.agent.to === null ? "no Agent now" : `Agent is ${changes.agent.to}`) : "",
1069+ changes.blockedBy
1070+ ? (changes.blockedBy.to as number[]).length === 0
1071+ ? "blocked by nothing now"
1072+ : `blocked by ${(changes.blockedBy.to as number[]).join(", ")}`
1073+ : "",
1074+ changes.labels
1075+ ? (changes.labels.to as string[]).length === 0
1076+ ? "no labels now"
1077+ : `labels ${(changes.labels.to as string[]).join(", ")}`
1078+ : "",
1079+ ].filter((s) => s !== "");
1080+ return {
1081+ edit: e.id as number,
1082+ notified,
1083+ news: {
1084+ issue: null,
1085+ text: `${who(actor)} edited issue ${id} (${JSON.stringify(title)}): ${said.join("; ")}`,
1086+ to: notified,
1087+ },
1088+ };
1089+ }
1091+ comment(
1092+ actor: Actor,
1093+ id: number,
1094+ body: { text?: unknown; objection?: unknown; attachments?: unknown },
1095+ ): { id: number; news: News } {
1096+ const row = this.exists(id);
1097+ const t = text(body.text, "the comment", LIMITS.text);
1098+ this.noAttachments(body.attachments);
1099+ const kind = body.objection === true ? "objection" : "comment";
1100+ const c = this.rows(
1101+ "INSERT INTO comments (issue, by, kind, text, at) VALUES (?, ?, ?, ?, ?) RETURNING id",
1102+ id,
1103+ who(actor),
1104+ kind,
1105+ t,
1106+ this.now(),
1107+ )[0]!;
1108+ this.watch(id, who(actor));
1109+ this.touch(id);
1110+ // @name in the text tells that agent too; the project drops names that aren't its agents.
1111+ const mentioned = mentionsIn(t).filter((name) => name !== who(actor));
1112+ return {
1113+ id: c.id as number,
1114+ news: {
1115+ issue: id,
1116+ text: `${who(actor)} ${kind === "objection" ? "objects" : "comments"} on issue ${id} (${JSON.stringify(row.title)}): ${JSON.stringify(t)}`,
1117+ ...(mentioned.length > 0 ? { to: mentioned } : {}),
1118+ },
1119+ };
1120+ }
1122+ /**
1123+ * An ask: a question or a task for someone, on an issue or on none. A
1124+ * review ask (`review`) puts its issue In review; any other holds it up
1125+ * (Blocked), and so do the issues it names in `blocks`.
1126+ */
1127+ ask(
1128+ actor: Actor,
1129+ body: {
1130+ issue?: unknown;
1131+ of?: unknown;
1132+ question?: unknown;
1133+ review?: unknown;
1134+ kind?: unknown;
1135+ due?: unknown;
1136+ recommendation?: unknown;
1137+ options?: unknown;
1138+ blocks?: unknown;
1139+ attachments?: unknown;
1140+ },
1141+ ): { id: number; news: News } {
1142+ const issue = body.issue === undefined || body.issue === null ? null : issueNumber(body.issue);
1143+ const row = issue === null ? undefined : this.exists(issue);
1144+ if (row?.closed_how) throw new IssuesError(`issue ${issue} is closed`);
1145+ const of = text(body.of, "who it asks", 100, true, true);
1146+ const question = text(body.question, "the question", LIMITS.text);
1147+ const kind = body.kind === undefined || body.kind === null ? "question" : body.kind;
1148+ if (kind !== "question" && kind !== "task")
1149+ throw new IssuesError('kind is "question", or "task" for something only they can do');
1150+ const review = body.review === true;
1151+ if (review && issue === null) throw new IssuesError("a review ask is on an issue");
1152+ let due: string | null = null;
1153+ if (body.due !== undefined && body.due !== null && body.due !== "") {
1154+ if (typeof body.due !== "string" || !/^\d{4}-\d{2}-\d{2}/.test(body.due) || Number.isNaN(Date.parse(body.due)))
1155+ throw new IssuesError("due is a date, like 2026-10-14");
1156+ due = body.due;
1157+ }
1158+ let recommendation: { text: string; by: string } | null = null;
1159+ if (body.recommendation !== undefined && body.recommendation !== null) {
1160+ const r = body.recommendation as { text?: unknown; by?: unknown };
1161+ recommendation = {
1162+ text: text(r.text, "the recommendation", LIMITS.text),
1163+ by: r.by === undefined ? who(actor) : text(r.by, "who recommends it", 100, true, true),
1164+ };
1165+ }
1166+ const options = body.options === undefined || body.options === null ? [] : body.options;
1167+ if (!Array.isArray(options) || options.length > LIMITS.options)
1168+ throw new IssuesError(`options are a list of up to ${LIMITS.options} choices`);
1169+ const choices = options.map((o, i) => text(o, `option ${i + 1}`, 500, true, true));
1170+ const blocks = body.blocks === undefined || body.blocks === null ? [] : body.blocks;
1171+ if (!Array.isArray(blocks) || blocks.length > LIMITS.blocks)
1172+ throw new IssuesError(`blocks is a list of up to ${LIMITS.blocks} issue numbers`);
1173+ const held = [...new Set(blocks.map((b) => issueNumber(b, "an issue it blocks")))].filter((b) => b !== issue);
1174+ for (const b of held) this.exists(b);
1175+ this.noAttachments(body.attachments);
1176+ const a = this.rows(
1177+ "INSERT INTO asks (issue, by, of, kind, question, review, due, recommendation, options, blocks, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
1178+ issue,
1179+ who(actor),
1180+ of,
1181+ kind,
1182+ question,
1183+ review ? 1 : 0,
1184+ due,
1185+ recommendation ? JSON.stringify(recommendation) : null,
1186+ JSON.stringify(choices),
1187+ JSON.stringify(held),
1188+ this.now(),
1189+ )[0]!;
1190+ if (review && issue !== null) this.watch(issue, of);
1191+ this.touch(issue, ...held);
1192+ const what = review ? "for a review" : kind === "task" ? "to do something" : "a question";
1193+ const where = issue === null ? "" : ` on issue ${issue} (${JSON.stringify(row!.title)})`;
1194+ return {
1195+ id: a.id as number,
1196+ // An agent asked hears how to answer.
1197+ news: {
1198+ issue,
1199+ text: `${who(actor)} asks ${of} ${what}${where}: ${JSON.stringify(question)}${of.startsWith("person:") ? "" : ` Answer: abso answer ${a.id} "..."`}`,
1200+ to: [of],
1201+ },
1202+ };
1203+ }
1205+ /** An answer, in the answerer's own words, kept on the ask. Only the one asked answers; a task is answered "done". */
1206+ answer(
1207+ actor: Actor,
1208+ askId: number,
1209+ body: {
1210+ words?: unknown;
1211+ option?: unknown;
1212+ expect?: unknown;
1213+ note?: unknown;
1214+ done?: unknown;
1215+ attachments?: unknown;
1216+ },
1217+ ): { ask: Ask; news: News } {
1218+ const r = this.rows("SELECT * FROM asks WHERE id = ?", issueNumber(askId, "an ask number"))[0];
1219+ if (!r) throw new IssuesError(`there's no ask ${askId}`, 404);
1220+ if (r.of !== who(actor)) throw new IssuesError(`ask ${askId} is for ${r.of as string}, not ${who(actor)}`, 403);
1221+ if (r.answer_at !== null && r.answer_at !== undefined)
1222+ throw new IssuesError(
1223+ r.outcome === "withdrawn"
1224+ ? `ask ${askId} was withdrawn by ${r.answer_by as string}, who asked it; it needs no answer`
1225+ : `ask ${askId} is answered already`,
1226+ 409,
1227+ );
1228+ const words = this.answerWordsFor(r, body);
1229+ this.noAttachments(body.attachments);
1230+ const at = this.now();
1231+ this.sql.exec(
1232+ "UPDATE asks SET answer_by = ?, answer_words = ?, answer_at = ? WHERE id = ?",
1233+ who(actor),
1234+ words,
1235+ at,
1236+ r.id,
1237+ );
1238+ const ask = this.authoredAsk(
1239+ this.withFiles(askOf({ ...r, answer_by: who(actor), answer_words: words, answer_at: at })),
1240+ );
1241+ this.touch(ask.issue, ...ask.blocks);
1242+ return {
1243+ ask,
1244+ news: {
1245+ issue: ask.issue,
1246+ text: `${who(actor)} answered ${ask.by}'s ${ask.review ? "review ask" : ask.kind}${ask.issue !== null ? ` on issue ${ask.issue}` : ""}: ${JSON.stringify(words)}`,
1247+ to: [ask.by],
1248+ },
1249+ };
1250+ }
1252+ private answerWordsFor(
1253+ r: Row,
1254+ body: { words?: unknown; option?: unknown; expect?: unknown; note?: unknown; done?: unknown },
1255+ ): string {
1256+ const askId = r.id as number;
1257+ const options = JSON.parse(r.options as string) as string[];
1258+ if (body.option !== undefined && body.option !== null) {
1259+ const pick = typeof body.option === "number" ? options[body.option] : options.find((o) => o === body.option);
1260+ if (pick === undefined)
1261+ throw new IssuesError(`ask ${askId}'s options are: ${options.map((o) => JSON.stringify(o)).join(", ")}`);
1262+ if (body.expect !== undefined && body.expect !== pick)
1263+ throw new IssuesError(
1264+ `ask ${askId}'s option ${Number(body.option) + 1} is ${JSON.stringify(pick)}, not the one you picked; look again`,
1265+ 409,
1266+ );
1267+ const note = text(body.note, "the note", LIMITS.text, false);
1268+ return note === "" ? pick : `${pick}\n\n${note}`;
1269+ }
1270+ if (body.done === true && r.kind === "task") {
1271+ const note = text(body.note, "the note", LIMITS.text, false);
1272+ return note === "" ? "done" : `done\n\n${note}`;
1273+ }
1274+ return text(body.words, "the answer", LIMITS.text);
1275+ }
1277+ /**
1278+ * The one asked says they have it and will answer later. The ask stays open and keeps
1279+ * blocking; it shows as acknowledged, and the asker hears it with the note. Acknowledging again updates
1280+ * the note and the time. abso answer closes it as before.
1281+ */
1282+ ack(actor: Actor, askId: number, body: { note?: unknown }): { ask: Ask; news: News } {
1283+ const r = this.rows("SELECT * FROM asks WHERE id = ?", issueNumber(askId, "an ask number"))[0];
1284+ if (!r) throw new IssuesError(`there's no ask ${askId}`, 404);
1285+ if (r.of !== who(actor)) throw new IssuesError(`ask ${askId} is for ${r.of as string}, not ${who(actor)}`, 403);
1286+ if (r.answer_at !== null && r.answer_at !== undefined)
1287+ throw new IssuesError(
1288+ r.outcome === "withdrawn"
1289+ ? `ask ${askId} was withdrawn by ${r.answer_by as string}, who asked it; it needs no answer`
1290+ : `ask ${askId} is answered already`,
1291+ 409,
1292+ );
1293+ const note = text(body.note, "the note", LIMITS.text, false);
1294+ const at = this.now();
1295+ this.transaction(() => {
1296+ this.sql.exec("UPDATE asks SET ack_at = ?, ack_note = ? WHERE id = ?", at, note, r.id);
1297+ // The note is a reply in the thread.
1298+ if (note !== "")
1299+ this.sql.exec(
1300+ "INSERT INTO ask_replies (ask, by, text, question, at) VALUES (?, ?, ?, 0, ?)",
1301+ r.id,
1302+ who(actor),
1303+ note,
1304+ at,
1305+ );
1306+ });
1307+ const ask = this.authoredAsk(this.withFiles(askOf({ ...r, ack_at: at, ack_note: note })));
1308+ this.touch(ask.issue);
1309+ return {
1310+ ask,
1311+ news: {
1312+ issue: ask.issue,
1313+ text: `${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)}` : "."}`,
1314+ to: [ask.by],
1315+ },
1316+ };
1317+ }
1319+ /**
1320+ * A reply on an ask's thread, from the one asked or the asker, open or closed. The other side
1321+ * hears it. Whose turn it is: a reply from the one asked marked as a question waits on the asker; the asker's
1322+ * next reply hands it back. Answering still closes it.
1323+ */
1324+ reply(actor: Actor, askId: number, body: { text?: unknown; question?: unknown }): { ask: Ask; news: News } {
1325+ const r = this.rows("SELECT * FROM asks WHERE id = ?", issueNumber(askId, "an ask number"))[0];
1326+ if (!r) throw new IssuesError(`there's no ask ${askId}`, 404);
1327+ const me = who(actor);
1328+ if (me !== r.of && me !== r.by)
1329+ throw new IssuesError(
1330+ `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`,
1331+ 403,
1332+ );
1333+ const words = text(body.text, "the reply", LIMITS.text);
1334+ const question = body.question === true;
1335+ const open = r.answer_at === null || r.answer_at === undefined;
1336+ let waitingOn = (r.waiting_on as string | null) ?? null;
1337+ if (open) {
1338+ if (me === r.of && me !== r.by) {
1339+ if (question) waitingOn = r.by as string;
1340+ } else waitingOn = null;
1341+ }
1342+ const at = this.now();
1343+ this.transaction(() => {
1344+ this.sql.exec(
1345+ "INSERT INTO ask_replies (ask, by, text, question, at) VALUES (?, ?, ?, ?, ?)",
1346+ r.id,
1347+ me,
1348+ words,
1349+ question ? 1 : 0,
1350+ at,
1351+ );
1352+ if (open) this.sql.exec("UPDATE asks SET waiting_on = ? WHERE id = ?", waitingOn, r.id);
1353+ });
1354+ const ask = this.authoredAsk(this.withFiles(askOf({ ...r, waiting_on: waitingOn })));
1355+ this.touch(ask.issue);
1356+ const other = me === ask.of ? ask.by : ask.of;
1357+ const turn = open && (waitingOn ?? ask.of) === other ? " It waits on you." : "";
1358+ return {
1359+ ask,
1360+ news: {
1361+ issue: ask.issue,
1362+ text: `${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.`}`,
1363+ to: [other],
1364+ },
1365+ };
1366+ }
1368+ /**
1369+ * The asker takes back an ask nobody needs answered any more. It closes as an answer does
1370+ * (answer_at set, so it leaves waiting and stops blocking), with the asker as answer_by, their note as
1371+ * answer_words, and outcome 'withdrawn'. The one asked hears it.
1372+ */
1373+ withdraw(actor: Actor, askId: number, body: { note?: unknown }): { ask: Ask; news: News } {
1374+ const r = this.rows("SELECT * FROM asks WHERE id = ?", issueNumber(askId, "an ask number"))[0];
1375+ if (!r) throw new IssuesError(`there's no ask ${askId}`, 404);
1376+ if (r.by !== who(actor))
1377+ throw new IssuesError(`ask ${askId} was asked by ${r.by as string}; only they can withdraw it`, 403);
1378+ if (r.answer_at !== null && r.answer_at !== undefined)
1379+ throw new IssuesError(
1380+ r.outcome === "withdrawn"
1381+ ? `ask ${askId} is withdrawn already`
1382+ : `ask ${askId} is answered already, so there's nothing to withdraw`,
1383+ 409,
1384+ );
1385+ const note = text(body.note, "the note", LIMITS.text, false);
1386+ const at = this.now();
1387+ this.sql.exec(
1388+ "UPDATE asks SET answer_by = ?, answer_words = ?, answer_at = ?, outcome = 'withdrawn' WHERE id = ?",
1389+ who(actor),
1390+ note,
1391+ at,
1392+ r.id,
1393+ );
1394+ const ask = this.authoredAsk(
1395+ this.withFiles(askOf({ ...r, answer_by: who(actor), answer_words: note, answer_at: at, outcome: "withdrawn" })),
1396+ );
1397+ this.touch(ask.issue, ...ask.blocks);
1398+ return {
1399+ ask,
1400+ news: {
1401+ issue: ask.issue,
1402+ text: `${who(actor)} withdrew their ${ask.review ? "review ask" : ask.kind} of ${ask.of}${ask.issue !== null ? ` on issue ${ask.issue}` : ""}${note !== "" ? `: ${JSON.stringify(note)}` : ""}`,
1403+ to: [ask.of],
1404+ },
1405+ };
1406+ }
1408+ /** Dropped by hand; done comes only from a publish (the done hook). */
1409+ drop(actor: Actor, id: number): { news: News } {
1410+ const row = this.exists(id);
1411+ if (row.closed_how)
1412+ throw new IssuesError(`issue ${id} is ${row.closed_how === "done" ? "done" : "dropped"} already`, 409);
1413+ this.sql.exec(
1414+ "UPDATE issues SET closed_how = 'dropped', closed_by = ?, closed_at = ?, updated_at = ? WHERE id = ?",
1415+ who(actor),
1416+ this.now(),
1417+ this.now(),
1418+ id,
1419+ );
1420+ this.sql.exec("DELETE FROM claims WHERE issue = ?", id);
1421+ return { news: { issue: id, text: `${who(actor)} dropped issue ${id} (${JSON.stringify(row.title)})` } };
1422+ }
1424+ /** A dropped issue opens again. A done issue stays done. */
1425+ reopen(actor: Actor, id: number): { news: News } {
1426+ const row = this.exists(id);
1427+ if (row.closed_how !== "dropped")
1428+ throw new IssuesError(
1429+ row.closed_how === "done" ? `issue ${id} is done; it stays done` : `issue ${id} is open`,
1430+ 409,
1431+ );
1432+ this.sql.exec(
1433+ "UPDATE issues SET closed_how = NULL, closed_by = NULL, closed_version = NULL, closed_at = NULL, updated_at = ? WHERE id = ?",
1434+ this.now(),
1435+ id,
1436+ );
1437+ this.touch(id);
1438+ return { news: { issue: id, text: `${who(actor)} reopened issue ${id} (${JSON.stringify(row.title)})` } };
1439+ }
1441+ /**
1442+ * Marked done by hand, by a person or an agent. `version`, when
1443+ * given, is the published version that did the work. A dropped issue is reopened first.
1444+ */
1445+ markDone(actor: Actor, id: number, version: number | null): { news: News } {
1446+ const row = this.exists(id);
1447+ if (row.closed_how === "dropped")
1448+ throw new IssuesError(`issue ${id} is dropped; reopen it before marking it done`, 409);
1449+ if (row.closed_how === "done") throw new IssuesError(`issue ${id} is done already`, 409);
1450+ if (version !== null && (!Number.isInteger(version) || version < 1))
1451+ throw new IssuesError("version is a published version, 1 or more");
1452+ const at = this.now();
1453+ const by = who(actor);
1454+ if (version !== null)
1455+ this.sql.exec(
1456+ "INSERT INTO versions (issue, version, agent, at) VALUES (?, ?, ?, ?) ON CONFLICT (issue, version) DO NOTHING",
1457+ id,
1458+ version,
1459+ by,
1460+ at,
1461+ );
1462+ this.sql.exec(
1463+ "UPDATE issues SET closed_how = 'done', closed_by = ?, closed_version = ?, closed_at = ?, updated_at = ? WHERE id = ?",
1464+ by,
1465+ version,
1466+ at,
1467+ at,
1468+ id,
1469+ );
1470+ this.sql.exec("DELETE FROM claims WHERE issue = ?", id);
1471+ const where = version === null ? "by hand" : `in version ${version}`;
1472+ return {
1473+ news: { issue: id, text: `${by} marked issue ${id} (${JSON.stringify(row.title)}) done ${where}` },
1474+ };
1475+ }
1477+ /**
1478+ * Refuses a write past the writer's limit: WRITES_PER_MINUTE a
1479+ * minute and WRITES_PER_DAY a day, opens, edits, comments, asks, answers and
1480+ * drops together. A 429 says when to try again.
1481+ */
1482+ checkLimit(actor: Actor): void {
1483+ const now = this.now();
1484+ this.sql.exec("DELETE FROM writes WHERE who = ? AND at <= ?", who(actor), now - 86_400_000);
1485+ const times = this.rows("SELECT at FROM writes WHERE who = ? ORDER BY at", who(actor)).map((w) => w.at as number);
1486+ const minute = times.filter((t) => now - t < 60_000);
1487+ if (minute.length >= WRITES_PER_MINUTE)
1488+ throw new IssuesError(
1489+ `at most ${WRITES_PER_MINUTE} issue writes a minute; try again shortly`,
1490+ 429,
1491+ Math.max(1, Math.ceil((minute[0]! + 60_000 - now) / 1000)),
1492+ );
1493+ if (times.length >= WRITES_PER_DAY)
1494+ throw new IssuesError(
1495+ `at most ${WRITES_PER_DAY} issue writes a day in a project`,
1496+ 429,
1497+ Math.max(1, Math.ceil((times[0]! + 86_400_000 - now) / 1000)),
1498+ );
1499+ }
1501+ /** Counts a write that went through. */
1502+ wrote(actor: Actor): void {
1503+ this.sql.exec("INSERT INTO writes (who, at) VALUES (?, ?)", who(actor), this.now());
1504+ }
1506+ // Drafts: a writer's own, with no number and no news ------------------------
1508+ /** The actor's drafts, newest first. Nobody else's. */
1509+ drafts(actor: Actor): Draft[] {
1510+ return this.rows("SELECT * FROM drafts WHERE owner = ? ORDER BY saved_at DESC, id DESC", who(actor)).map(asDraft);
1511+ }
1513+ /**
1514+ * Saves a draft, new or (with `id`) over one of the actor's. Any field may
1515+ * be empty; what's there is checked as open would check it, but not whether
1516+ * the issues it names still exist (that waits for opening).
1517+ */
1518+ saveDraft(
1519+ actor: Actor,
1520+ body: {
1521+ id?: unknown;
1522+ title?: unknown;
1523+ description?: unknown;
1524+ parent?: unknown;
1525+ lines?: unknown;
1526+ agent?: unknown;
1527+ blockedBy?: unknown;
1528+ notify?: unknown;
1529+ labels?: unknown;
1530+ },
1531+ ): { id: number } {
1532+ const draft: DraftBody = {};
1533+ const title = text(body.title, "the title", LIMITS.title, false, true);
1534+ if (title !== "") draft.title = title;
1535+ const description = text(body.description, "the description", LIMITS.description, false);
1536+ if (description !== "") draft.description = description;
1537+ if (body.parent !== undefined && body.parent !== null) draft.parent = issueNumber(body.parent, "the parent");
1538+ const l = lines(body.lines);
1539+ if (l !== null) draft.lines = l;
1540+ if (body.agent !== undefined && body.agent !== null && body.agent !== "")
1541+ draft.agent = nameOrNone(body.agent, "the Agent");
1542+ if (body.blockedBy !== undefined && body.blockedBy !== null) {
1543+ if (!Array.isArray(body.blockedBy) || body.blockedBy.length > LIMITS.blocks)
1544+ throw new IssuesError(`blocked by is a list of up to ${LIMITS.blocks} issue numbers`);
1545+ draft.blockedBy = [...new Set(body.blockedBy.map((b) => issueNumber(b, "an issue it's blocked by")))];
1546+ }
1547+ const notify = names(body.notify, "Notify");
1548+ if (notify.length > 0) draft.notify = notify;
1549+ const labels = labelsOf(body.labels);
1550+ if (labels.length > 0) draft.labels = labels;
1551+ const saved = JSON.stringify(draft);
1552+ if (saved.length > LIMITS.draft) throw new IssuesError(`a draft holds at most ${LIMITS.draft} characters`);
1553+ if (body.id !== undefined && body.id !== null) {
1554+ const id = this.draftOf(actor, body.id).id as number;
1555+ this.sql.exec("UPDATE drafts SET body = ?, saved_at = ? WHERE id = ?", saved, this.now(), id);
1556+ return { id };
1557+ }
1558+ const n = this.rows("SELECT COUNT(*) AS n FROM drafts WHERE owner = ?", who(actor))[0]!.n as number;
1559+ if (n >= LIMITS.drafts)
1560+ throw new IssuesError(`you have ${n} drafts, the most there can be; open or delete some first`);
1561+ return {
1562+ id: this.rows(
1563+ "INSERT INTO drafts (owner, body, saved_at) VALUES (?, ?, ?) RETURNING id",
1564+ who(actor),
1565+ saved,
1566+ this.now(),
1567+ )[0]!.id as number,
1568+ };
1569+ }
1571+ deleteDraft(actor: Actor, id: number): void {
1572+ this.sql.exec("DELETE FROM drafts WHERE id = ?", this.draftOf(actor, id).id);
1573+ }
1575+ /** 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. */
1576+ openDraft(actor: Actor, id: number, body: Record<string, unknown> = {}): { id: number; news?: News } {
1577+ const d = this.draftOf(actor, id);
1578+ const opened = this.open(actor, { ...(JSON.parse(d.body as string) as DraftBody), ...body });
1579+ this.sql.exec("DELETE FROM drafts WHERE id = ?", d.id);
1580+ return opened;
1581+ }
1583+ /** One of the actor's drafts; another's is "no such draft", as if it weren't there. */
1584+ private draftOf(actor: Actor, id: unknown): Row {
1585+ const row = this.rows(
1586+ "SELECT * FROM drafts WHERE id = ? AND owner = ?",
1587+ issueNumber(id, "a draft number"),
1588+ who(actor),
1589+ )[0];
1590+ if (!row) throw new IssuesError(`you have no draft ${String(id)}`, 404);
1591+ return row;
1592+ }
1593+ // From the project: start notes and publish --done ----------------------------------------
1595+ /** 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. */
1596+ claim(agent: string, id: number, change: number): void {
1597+ const row = this.rows("SELECT closed_how FROM issues WHERE id = ?", id)[0];
1598+ if (!row || row.closed_how) return;
1599+ this.sql.exec(
1600+ "INSERT INTO claims (issue, agent, change, since) VALUES (?, ?, ?, ?) ON CONFLICT (issue, agent) DO UPDATE SET change = excluded.change, since = excluded.since",
1601+ id,
1602+ agent,
1603+ change,
1604+ this.now(),
1605+ );
1606+ this.sql.exec("UPDATE issues SET agent = ? WHERE id = ? AND agent IS NULL", agent, id);
1607+ this.watch(id, agent);
1608+ this.touch(id);
1609+ }
1611+ /** The start note ended without finishing the issue. */
1612+ unclaim(agent: string, id: number): void {
1613+ this.sql.exec("DELETE FROM claims WHERE issue = ? AND agent = ?", id, agent);
1614+ this.touch(id);
1615+ }
1617+ /** publish --done finished it, with that version of shared: done, and the version is one out for it. */
1618+ done(agent: string, id: number, version: number): { news?: News } {
1619+ this.sql.exec("DELETE FROM claims WHERE issue = ? AND agent = ?", id, agent);
1620+ const row = this.rows("SELECT title, closed_how FROM issues WHERE id = ?", id)[0];
1621+ if (!row) return {};
1622+ this.sql.exec(
1623+ "INSERT INTO versions (issue, version, agent, at) VALUES (?, ?, ?, ?) ON CONFLICT (issue, version) DO NOTHING",
1624+ id,
1625+ version,
1626+ agent,
1627+ this.now(),
1628+ );
1629+ this.touch(id);
1630+ if (row.closed_how) return {};
1631+ this.sql.exec(
1632+ "UPDATE issues SET closed_how = 'done', closed_by = ?, closed_version = ?, closed_at = ? WHERE id = ?",
1633+ agent,
1634+ version,
1635+ this.now(),
1636+ id,
1637+ );
1638+ this.sql.exec("DELETE FROM claims WHERE issue = ?", id);
1639+ return {
1640+ news: { issue: id, text: `${agent} finished issue ${id} (${JSON.stringify(row.title)}) in version ${version}` },
1641+ };
1642+ }
1645+function asDraft(d: Row): Draft {
1646+ return {
1647+ id: d.id as number,
1648+ body: JSON.parse(d.body as string) as DraftBody,
1649+ saved: d.saved_at as number,
1650+ };
1653+/** A snippet with \u0001 and \u0002 around each match, as plain text and the matches' spans. */
1654+function marked(snip: string): { text: string; marks: number[][] } {
1655+ let text = "";
1656+ const marks: number[][] = [];
1657+ let open = -1;
1658+ for (const ch of snip) {
1659+ if (ch === "\u0001") open = text.length;
1660+ else if (ch === "\u0002") {
1661+ if (open >= 0) marks.push([open, text.length]);
1662+ open = -1;
1663+ } else text += ch;
1664+ }
1665+ return { text, marks };
1668+function askOf(r: Row): StoredAsk {
1669+ return {
1670+ id: r.id as number,
1671+ issue: (r.issue as number | null) ?? null,
1672+ by: r.by as string,
1673+ of: r.of as string,
1674+ kind: r.kind as Ask["kind"],
1675+ question: r.question as string,
1676+ review: r.review === 1,
1677+ due: (r.due as string | null) ?? null,
1678+ recommendation: r.recommendation ? (JSON.parse(r.recommendation as string) as Ask["recommendation"]) : null,
1679+ options: JSON.parse(r.options as string) as string[],
1680+ blocks: JSON.parse(r.blocks as string) as number[],
1681+ at: r.at as number,
1682+ answer:
1683+ r.answer_at !== null && r.answer_at !== undefined
1684+ ? { by: r.answer_by as string, words: r.answer_words as string, at: r.answer_at as number }
1685+ : null,
1686+ seen: (r.seen_at as number | null | undefined) ?? null,
1687+ waitingOn:
1688+ r.answer_at !== null && r.answer_at !== undefined ? null : ((r.waiting_on as string | null) ?? (r.of as string)),
1689+ replies: [],
1690+ ...(r.outcome === "withdrawn" ? { outcome: "withdrawn" as const } : {}),
1691+ ...(typeof r.ack_at === "number" ? { ack: { at: r.ack_at, note: (r.ack_note as string | null) ?? "" } } : {}),
1692+ };
MCP
compare on this site's /mcp
CLI
abso diff 68 318 server/src/issues/store.ts --json
JSON
/christopher/abso-core/compare/68..318?file=server%2Fsrc%2Fissues%2Fstore.ts&format=json