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
MCP
show on this site's /mcp
CLI
abso show 151 --json
JSON
/christopher/abso-core/versions/151?format=json

Open server: issues, asks and news, served at <server>/issues, and the client finds them there when no issues server is named

of shared·trials··Not checked

Version 150 · Files at version 151

16 files, 3709 lines added, 46 removed.

--- a/client/src/core.ts
+++ b/client/src/core.ts
@@ -107,6 +107,22 @@
107107}
108108
109109/**
110+ * A server's base: its origin and any path, without a trailing slash (https://x.example/issues), or undefined
111+ * for anything else, a query, a fragment or a user name included. Plain string work, as serverOrigin.
112+ */
113+export function serverBase(s: string): string | undefined {
114+ const m = /^(https?):\/\/([^/?#\\]+)((?:\/[^?#\\]*)?)$/i.exec(s.trim());
115+ if (!m || m[2]!.includes("@")) return undefined;
116+ return `${m[1]!.toLowerCase()}://${m[2]!.toLowerCase()}${m[3]!.replace(/\/+$/, "")}`;
117+}
119+/** The origin of a server given with or without a path (serverBase), or undefined. */
120+export function baseOrigin(s: string): string | undefined {
121+ const base = serverBase(s);
122+ return base === undefined ? undefined : serverOrigin(base.replace(/^(https?:\/\/[^/]+).*$/i, "$1"));
123+}
125+/**
110126 * This machine's servers, from ~/.abso/servers.json:
111127 * {"servers": {"<server>": {"issues": "<its Issues Worker>"}}}. Each server
112128 * named there, and each Issues Worker it names, may receive the token, and a
@@ -130,10 +146,10 @@
130146 if (o === undefined) continue;
131147 trusted.push(o);
132148 const i = (about as { issues?: unknown } | null)?.issues;
133− const io = typeof i === "string" ? serverOrigin(i) : undefined;
149+ const io = typeof i === "string" ? serverBase(i) : undefined;
134150 if (io !== undefined) {
135151 issues[o] = io;
136− trusted.push(io);
152+ trusted.push(baseOrigin(io)!);
137153 }
138154 }
139155 } catch {}
@@ -146,14 +162,24 @@
146162}
147163
148164/**
149− * The Issues Worker beside an avcs server (#54): this machine's servers.json
150− * first, then abso's own. ABSO_ISSUES_SERVER overrides both (issues.ts).
165+ * The Issues Worker beside an avcs server: this machine's servers.json
166+ * first, then abso's own, else the server's own /issues, where the open
167+ * server keeps them. ABSO_ISSUES_SERVER overrides all three (issues.ts).
151168 */
152169export function issuesServerFor(server: string, machine?: MachineServers): string | undefined {
153170 const o = serverOrigin(server);
154− return o === undefined ? undefined : (machine?.issues[o] ?? ISSUES_SERVERS[o]);
171+ return o === undefined ? undefined : (machine?.issues[o] ?? ISSUES_SERVERS[o] ?? `${o}/issues`);
155172}
156173
174+/**
175+ * Whether the token may go to an Issues Worker: as to its origin (tokenGoesTo), since it may sit at a path on
176+ * its server, as the open server's do at <server>/issues. A query, a fragment or a user name is refused.
177+ */
178+export function tokenGoesToIssues(server: string, trusted?: string): boolean {
179+ const o = baseOrigin(server);
180+ return o !== undefined && tokenGoesTo(o, trusted);
181+}
157183/** Whether the token may go to `server`: TOKEN_SERVERS, `trusted` (trustedList), or this machine. Plain string work: the mod has no URL. */
158184export function tokenGoesTo(server: string, trusted?: string): boolean {
159185 const origin = serverOrigin;
--- a/client/src/issues.ts
+++ b/client/src/issues.ts
@@ -23,7 +23,7 @@
2323import { bool, type Parsed, str, UsageError } from "./args.ts";
2424import { type Env, type Output, open, plural } from "./commands.ts";
2525import { type Config, readMachineServers, trustedServers } from "./config.ts";
26−import { issuesServerFor, tokenGoesTo } from "./core.ts";
26+import { issuesServerFor, tokenGoesToIssues } from "./core.ts";
2727import { fromEnv } from "./env-names.ts";
2828import { ignoredHere } from "./fetch.ts";
2929import { loadIgnore, relativeTo } from "./folder.ts";
@@ -41,7 +41,7 @@
4141 throw new UsageError(
4242 `${config.server} has no Issues Worker beside it that abso knows; ~/.abso/servers.json or ABSO_ISSUES_SERVER names one`,
4343 );
44− if (config.token !== undefined && !tokenGoesTo(server, trustedServers(env.env))) {
44+ if (config.token !== undefined && !tokenGoesToIssues(server, trustedServers(env.env))) {
4545 throw new UsageError(
4646 `the Issues Worker is ${server}, and abso sends your token only to its own servers and this machine. If ${server} is yours, name it in ~/.abso/servers.json or ABSO_TRUSTED_SERVERS.`,
4747 );
--- a/client/test/client.test.ts
+++ b/client/test/client.test.ts
@@ -1556,7 +1556,7 @@
15561556 assert.equal(tokenGoesTo("https://sneaky.example", trusted), false);
15571557 assert.equal(tokenGoesTo("https://evil.example", trusted), false);
15581558 assert.equal(issuesServerFor("https://abso.example", machine), "https://issues.abso.example");
1559− assert.equal(issuesServerFor("https://staging.abso.example", machine), undefined);
1559+ assert.equal(issuesServerFor("https://staging.abso.example", machine), "https://staging.abso.example/issues");
15601560 assert.deepEqual(machineServers("{not json"), { trusted: [], issues: {} });
15611561 assert.deepEqual(machineServers(undefined), { trusted: [], issues: {} });
15621562 assert.equal(trustedList("https://a.example", machine).split(",")[0], "https://a.example");
--- a/client/test/issues.test.ts
+++ b/client/test/issues.test.ts
@@ -13,7 +13,7 @@
1313import { join } from "node:path";
1414import { after, before, describe, it } from "node:test";
1515import { readConfig, readMachineServers } from "../src/config.ts";
16−import { issuesServerFor, tokenGoesTo } from "../src/core.ts";
16+import { issuesServerFor, tokenGoesTo, tokenGoesToIssues } from "../src/core.ts";
1717import { issuePage, searchLines } from "../src/issues.ts";
1818import type { IssuePage } from "../src/issues-wire.ts";
1919import { main } from "../src/main.ts";
@@ -176,16 +176,42 @@
176176 assert.equal(r.exit, 1, r.out);
177177 assert.match(r.out, /sends your token only to its own servers and this machine/);
178178 assert.equal(seen.length, before);
179− // A server with no Issues Worker beside it, and none named.
180− const { AVCS_ISSUES_SERVER: _, ...without } = ENV();
181− const none = await avcs(dave, ["waiting"], without);
182− assert.notEqual(none.exit, 0);
183− assert.match(
184− none.out,
185− /has no Issues Worker beside it that abso knows; ~\/\.abso\/servers\.json or ABSO_ISSUES_SERVER names one/,
186− );
187179 });
188180
181+ it("with no Issues Worker named, uses the server's own /issues, as the open server keeps them", () => {
182+ assert.equal(issuesServerFor("https://abso.example"), "https://abso.example/issues");
183+ assert.equal(issuesServerFor("https://Abso.Example/"), "https://abso.example/issues");
184+ assert.equal(issuesServerFor("http://localhost:8787"), "http://localhost:8787/issues");
185+ assert.equal(issuesServerFor("not a server"), undefined);
186+ // abso's hosted server keeps its own Issues Worker, and servers.json still comes first.
187+ assert.equal(issuesServerFor("https://api.abso.dev"), "https://issues.abso.dev");
188+ const machine = {
189+ trusted: [],
190+ issues: { "https://staging.abso.example": "https://issues-staging.abso.example" },
191+ };
192+ assert.equal(issuesServerFor("https://staging.abso.example", machine), "https://issues-staging.abso.example");
193+ // The token goes to <server>/issues exactly where it goes to <server>.
194+ assert.ok(tokenGoesToIssues("https://api.abso.dev/issues"));
195+ assert.ok(tokenGoesToIssues("http://localhost:8787/issues"));
196+ assert.ok(tokenGoesToIssues("https://mine.example/issues", "https://mine.example"));
197+ assert.equal(tokenGoesToIssues("https://evil.example/issues"), false);
198+ assert.equal(tokenGoesToIssues("https://api.abso.dev@evil.example/issues"), false);
199+ assert.equal(tokenGoesToIssues("https://api.abso.dev/issues?x=1"), false);
200+ assert.equal(tokenGoesToIssues("http://mine.example/issues", "http://mine.example"), false, "plain http only here");
201+ // The server itself still takes no path.
202+ assert.equal(tokenGoesTo("https://api.abso.dev/issues"), false);
203+ });
205+ it("calls <issues server>/p/<project>/... when the Issues Worker is at a path", async () => {
206+ const fay = await folder("fay");
207+ const before = seen.length;
208+ const env = { ...ENV(), AVCS_ISSUES_SERVER: `${issuesUrl}/issues` };
209+ const r = await main(["ask", "7"], { cwd: fay, env, write: () => {} });
210+ assert.equal(r.exit, 0, r.stdout + r.stderr);
211+ const { project } = readConfig(fay);
212+ assert.deepEqual(seen.slice(before), [`GET /issues/p/${project}/ask/7`]);
213+ });
189215 it("finds a server's Issues Worker in this machine's servers.json, and may send it the token", async () => {
190216 const dir = mkdtempSync(join(tmpdir(), "abso-servers-"));
191217 dirs.push(dir);
@@ -198,7 +224,7 @@
198224 assert.ok(seen.length > before, "the call went to the Issues Worker servers.json names");
199225 const machine = readMachineServers({ AVCS_SERVERS_FILE: file });
200226 assert.equal(issuesServerFor(fake.url, machine), issuesUrl);
201− assert.equal(issuesServerFor("https://abso.example", machine), undefined);
227+ assert.equal(issuesServerFor("https://abso.example", machine), "https://abso.example/issues");
202228 // abso's own server and its Issues Worker are built in.
203229 assert.ok(tokenGoesTo("https://api.abso.dev"));
204230 assert.ok(tokenGoesTo("https://issues.abso.dev"));
--- a/server/src/issues-entry.ts
+++ b/server/src/issues-entry.ts
@@ -1,27 +1 @@
1−// Where the router meets issues, asks and news (server/src/issues/, built alongside this file). Until that folder
2−// lands, this is a stand-in with the same exports, so the Worker builds and its tests run. When it lands, this file
3−// becomes one line:
4−//
5−// export { IssueProject, issuesFetch } from "./issues/index.ts";
6−//
7−// The agreed interface: issuesFetch(request, env, ctx, {project, rest, auth}), where rest is the path after
8−// /issues/p/<project> and auth is {kind: "token"} or {kind: "key", agent, role}. The router has checked auth before it
9−// calls. The issues code reaches the project through env.PROJECT and its RPC methods agents(project) and
10−// news(project, items) on ProjectObject.
11−
12−import { DurableObject } from "cloudflare:workers";
13−import type { Env } from "./env.ts";
14−import type { KeyRole } from "./keys.ts";
15−
16−export type IssuesAuth = { kind: "token" } | { kind: "key"; agent: string; role: KeyRole };
17−
18−export class IssueProject extends DurableObject<Env> {}
19−
20−export async function issuesFetch(
21− _request: Request,
22− _env: Env,
23− _ctx: ExecutionContext,
24− _where: { project: string; rest: string; auth: IssuesAuth },
25−): Promise<Response> {
26− return Response.json({ error: "issues aren't on this server yet" }, { status: 404 });
27−}
1+export { IssueProject, type IssuesAuth, issuesFetch } from "./issues/index.ts";
--- /dev/null
+++ b/server/src/issues/index.ts
@@ -0,0 +1,64 @@
1+// Issues, asks and news for the open server: one IssueProject Durable Object per project (bound as ISSUES_DO,
2+// named by the project's name), reached through issuesFetch from the Worker's /issues/p/:project/... routes.
3+// The logic is in serve.ts, store.ts and routes.ts, which run under node --test without Cloudflare's runtime.
4+//
5+// GET /issues/p/:project/issues[?status=&agent=&parent=&label=&open=1] issues, most recently updated first
6+// GET /issues/p/:project/issue/:n one issue with its comments, edits and asks
7+// GET /issues/p/:project/search?q=[&limit=] full-text search
8+// GET /issues/p/:project/labels | changes | waiting[?of=] | ask/:n | asked?by= | answered?of=
9+// GET /issues/p/:project/a/:agent/waiting | asked | drafts | news[?before=]
10+// POST /issues/p/:project/a/:agent/issue | ask | answer/:n | ack/:n | reply/:n | withdraw/:n
11+// POST /issues/p/:project/a/:agent/issue/:n/comment | edit | drop | reopen | done
12+// POST /issues/p/:project/a/:agent/draft | draft/:n/open | draft/:n/delete | news/read
14+import { DurableObject } from "cloudflare:workers";
15+import { type IssuesEnv, IssuesObject } from "./serve.ts";
16+import type { News } from "./store.ts";
18+export {
19+ type IssueNews,
20+ type IssuesAuth,
21+ type IssuesEnv,
22+ issuesFetch,
23+ type NamespaceLike,
24+ type ProjectHooks,
25+ type WaitUntil,
26+} from "./serve.ts";
28+/** One project's issues, in its own SQLite. */
29+export class IssueProject extends DurableObject<IssuesEnv> {
30+ private readonly issues: IssuesObject;
32+ constructor(ctx: DurableObjectState, env: IssuesEnv) {
33+ super(ctx, env);
34+ // The migrations are synchronous SQL, so they finish here, before the object takes any request.
35+ this.issues = new IssuesObject(
36+ { sql: ctx.storage.sql, transactionSync: (action) => ctx.storage.transactionSync(action) },
37+ env,
38+ );
39+ }
41+ async fetch(request: Request): Promise<Response> {
42+ return this.issues.fetch(request);
43+ }
45+ /** A start note names the issue; `change` is the note's log position. A missing or closed issue is ignored. */
46+ async claim(agent: string, issue: number, change: number): Promise<void> {
47+ this.issues.store.claim(agent, issue, change);
48+ }
50+ /** The start note ended without finishing the issue. */
51+ async unclaim(agent: string, issue: number): Promise<void> {
52+ this.issues.store.unclaim(agent, issue);
53+ }
55+ /** publish --done finished the issue in `version`: done, and its news for the project to deliver. */
56+ async done(agent: string, issue: number, version: number): Promise<{ news?: News }> {
57+ return this.issues.store.done(agent, issue, version);
58+ }
60+ /** How many schema migrations this object has run. */
61+ async schema(): Promise<{ migrations: number }> {
62+ return { migrations: this.issues.migrations() };
63+ }
64+}
--- /dev/null
+++ b/server/src/issues/routes.ts
@@ -0,0 +1,212 @@
1+// The issues routes, apart from the Durable Object so they run under node --test with a store on node:sqlite.
2+// Paths are the client's: /p/:project/<read> for reads, and /p/:project/a/:agent/<op> for an agent's writes and
3+// its own reads (waiting, asked, drafts, news). Who may call which path was decided before a request gets here.
4+
5+import { type Actor, IssuesError, type IssuesStore, who } from "./store.ts";
6+
7+/** The largest request body a write takes, in bytes: far above any text a write may hold. */
8+export const BODY_MAX = 1024 * 1024;
9+
10+export const json = (status: number, body: unknown): Response =>
11+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
13+/**
14+ * One request to a project's issues. `seatError` says why a new ask's `of` isn't an agent in the project, or null
15+ * when it is (or when the project can't say).
16+ */
17+export async function issuesRoute(
18+ store: IssuesStore,
19+ request: Request,
20+ seatError?: (of: string) => Promise<string | null>,
21+): Promise<Response> {
22+ try {
23+ return await route(store, request, seatError);
24+ } catch (e) {
25+ if (e instanceof IssuesError) {
26+ const answer = json(e.status, { error: e.message });
27+ if (e.retryAfter !== undefined) answer.headers.set("Retry-After", String(e.retryAfter));
28+ return answer;
29+ }
30+ throw e;
31+ }
32+}
34+async function route(
35+ store: IssuesStore,
36+ request: Request,
37+ seatError?: (of: string) => Promise<string | null>,
38+): Promise<Response> {
39+ const url = new URL(request.url);
40+ const m = /^\/p\/([^/]+)(?:\/a\/([^/]+))?\/(.+)$/.exec(url.pathname);
41+ if (!m) return json(404, { error: "no such issues route" });
42+ const agent = m[2] === undefined ? undefined : decodeURIComponent(m[2]);
43+ const rest = m[3]!;
44+ const q = url.searchParams;
45+ const actor: Actor | undefined = agent !== undefined ? { agent } : undefined;
46+ if (rest === "attachments" || rest.startsWith("attachments/"))
47+ return json(501, { error: "this server doesn't keep attachments" });
48+ // A reader sees only their own drafts.
49+ if (request.method === "GET" && rest === "drafts") {
50+ if (!actor) return json(403, { error: "drafts are an agent's: /a/:agent/drafts" });
51+ return json(200, { drafts: store.drafts(actor) });
52+ }
53+ if (request.method === "GET") {
54+ if (actor) {
55+ // An agent's own waiting list, which marks what it lists as seen.
56+ if (rest === "waiting") return json(200, { asks: store.waiting(who(actor), who(actor)) });
57+ // The asks an agent sent, open then the latest answered.
58+ if (rest === "asked") return json(200, { asks: store.asked(who(actor)) });
59+ // An agent's news here: answers, replies, @mentions, and changes on issues it watches, by others.
60+ if (rest === "news") {
61+ const before = q.get("before");
62+ return json(200, {
63+ news: store.newsFor(actor, [who(actor)], before === null ? undefined : Number(before) || undefined),
64+ });
65+ }
66+ return json(404, {
67+ error: "an agent's reads are waiting, asked, drafts and news; other reads have no /a/:agent/",
68+ });
69+ }
70+ if (rest === "issues") {
71+ const parent = q.get("parent");
72+ return json(200, {
73+ issues: store.list({
74+ ...(q.get("status") ? { status: q.get("status")! } : {}),
75+ ...(q.get("agent") ? { agent: q.get("agent")! } : {}),
76+ ...(parent ? { parent: Number(parent) } : {}),
77+ // ?label=a,b (or label repeated): issues with every one of them.
78+ ...(q.getAll("label").length > 0 ? { labels: q.getAll("label").flatMap((l) => l.split(",")) } : {}),
79+ open: q.get("open") === "1",
80+ }),
81+ });
82+ }
83+ if (rest === "labels") return json(200, { labels: store.labelsInUse() });
84+ // The change count: what a reader can cache issue reads under, cheap enough to ask every request.
85+ if (rest === "changes") return json(200, { changes: store.changes() });
86+ if (rest === "search") {
87+ const limit = Number(q.get("limit") ?? "20");
88+ return json(200, { hits: store.search((q.get("q") ?? "").slice(0, 200), Number.isInteger(limit) ? limit : 20) });
89+ }
90+ const one = /^issue\/(\d+)$/.exec(rest);
91+ if (one) return json(200, store.page(Number(one[1])));
92+ if (rest === "waiting") return json(200, { asks: store.waiting(q.get("of") ?? undefined) });
93+ const ask = /^ask\/(\d+)$/.exec(rest);
94+ if (ask) return json(200, { ask: store.askThread(Number(ask[1])) });
95+ if (rest === "asked") {
96+ const by = q.get("by");
97+ if (!by) return json(400, { error: "asked needs ?by=<agent>" });
98+ return json(200, { asks: store.asked(by) });
99+ }
100+ if (rest === "answered") {
101+ const of = q.get("of");
102+ if (!of) return json(400, { error: "answered needs ?of=<agent>" });
103+ return json(200, { asks: store.answered(of) });
104+ }
105+ return json(404, { error: "no such issues route" });
106+ }
107+ if (request.method !== "POST") return json(405, { error: "issues takes GET and POST" });
108+ if (!actor) return json(403, { error: "a write is an agent's: /p/:project/a/:agent/<op>" });
109+ let body: Record<string, unknown> = {};
110+ const raw = new TextDecoder().decode(await readCapped(request, BODY_MAX));
111+ if (raw.trim() !== "") {
112+ try {
113+ body = JSON.parse(raw) as Record<string, unknown>;
114+ } catch {
115+ return json(400, { error: "the body is JSON" });
116+ }
117+ if (typeof body !== "object" || body === null || Array.isArray(body))
118+ return json(400, { error: "the body is a JSON object" });
119+ }
120+ // Drafts and news marks make no news, so they don't count toward the writer's limit.
121+ if (rest === "draft") return json(200, { ok: true, ...store.saveDraft(actor, body) });
122+ const deleting = /^draft\/(\d+)\/delete$/.exec(rest);
123+ if (deleting) {
124+ store.deleteDraft(actor, Number(deleting[1]));
125+ return json(200, { ok: true });
126+ }
127+ if (rest === "news/read") {
128+ const at = body.at === undefined ? Date.now() : body.at;
129+ if (typeof at !== "number" || !Number.isFinite(at)) return json(400, { error: "at is a time in milliseconds" });
130+ return json(200, { ok: true, ...store.markNewsRead(actor, at) });
131+ }
132+ const write = writeFor(store, actor, rest, body);
133+ if (!write) return json(404, { error: "no such issues route" });
134+ // An ask goes to an agent in the project.
135+ if (rest === "ask" && seatError && typeof body.of === "string") {
136+ const refused = await seatError(body.of);
137+ if (refused) return json(400, { error: refused });
138+ }
139+ store.checkLimit(actor);
140+ const done = write();
141+ store.wrote(actor);
142+ // Every write answers the change count it made, for the next read.
143+ return json(200, { ok: true, ...done, changes: store.changes() });
144+}
146+/**
147+ * The body, read a chunk at a time and refused (413) the moment it passes `max`, so a body with no
148+ * Content-Length, or one that lies, never puts more than `max` in memory.
149+ */
150+export async function readCapped(request: Request, max: number): Promise<Uint8Array<ArrayBuffer>> {
151+ const declared = Number(request.headers.get("Content-Length") ?? "0");
152+ if (declared > max) throw new IssuesError(`the body is ${declared} bytes; the most is ${max}`, 413);
153+ if (!request.body) return new Uint8Array(0);
154+ const reader = request.body.getReader();
155+ const parts: Uint8Array[] = [];
156+ let size = 0;
157+ for (;;) {
158+ const { done, value } = await reader.read();
159+ if (done) break;
160+ size += value.length;
161+ if (size > max) {
162+ await reader.cancel();
163+ throw new IssuesError(`the body is over ${max} bytes, the most there can be`, 413);
164+ }
165+ parts.push(value);
166+ }
167+ const out = new Uint8Array(size);
168+ let at = 0;
169+ for (const part of parts) {
170+ out.set(part, at);
171+ at += part.length;
172+ }
173+ return out;
174+}
176+/** A write that can carry news, to run once the writer's limit allows it; undefined when no route matches. */
177+function writeFor(
178+ store: IssuesStore,
179+ actor: Actor,
180+ rest: string,
181+ body: Record<string, unknown>,
182+): (() => object) | undefined {
183+ if (rest === "issue") return () => store.open(actor, body);
184+ if (rest === "ask") return () => store.ask(actor, body);
185+ const on = /^issue\/(\d+)\/(comment|drop|edit|reopen|done)$/.exec(rest);
186+ if (on) {
187+ const id = Number(on[1]);
188+ return () => {
189+ if (on[2] === "comment") return store.comment(actor, id, body);
190+ if (on[2] === "edit") return store.edit(actor, id, body);
191+ if (on[2] === "reopen") return store.reopen(actor, id);
192+ if (on[2] === "done") {
193+ const version = body.version;
194+ if (version !== undefined && version !== null && typeof version !== "number")
195+ throw new IssuesError("version is a published version, 1 or more");
196+ return store.markDone(actor, id, typeof version === "number" ? version : null);
197+ }
198+ return store.drop(actor, id);
199+ };
200+ }
201+ const opening = /^draft\/(\d+)\/open$/.exec(rest);
202+ if (opening) return () => store.openDraft(actor, Number(opening[1]), body);
203+ const answer = /^answer\/(\d+)$/.exec(rest);
204+ if (answer) return () => store.answer(actor, Number(answer[1]), body);
205+ const ack = /^ack\/(\d+)$/.exec(rest);
206+ if (ack) return () => store.ack(actor, Number(ack[1]), body);
207+ const reply = /^reply\/(\d+)$/.exec(rest);
208+ if (reply) return () => store.reply(actor, Number(reply[1]), body);
209+ const withdraw = /^withdraw\/(\d+)$/.exec(rest);
210+ if (withdraw) return () => store.withdraw(actor, Number(withdraw[1]), body);
211+ return undefined;
212+}
--- /dev/null
+++ b/server/src/issues/seats.ts
@@ -0,0 +1,49 @@
1+// Asks go to seats: an ask to a name that isn't an agent in the project would
2+// wait on nobody, so it's refused, with the closest seat named. Seats are only
3+// ever this project's own.
4+
5+/** A name as people write it: lower case, letters and digits only ("abso - Cloud Infra Lead" → "absocloudinfralead"). */
6+function plain(name: string): string {
7+ return name.toLowerCase().replace(/[^a-z0-9]/g, "");
8+}
9+
10+/** Edits from a to b: insertions, deletions and substitutions. */
11+function distance(a: string, b: string): number {
12+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
13+ for (let i = 1; i <= a.length; i++) {
14+ const next = [i];
15+ for (let j = 1; j <= b.length; j++)
16+ next[j] = Math.min(row[j]! + 1, next[j - 1]! + 1, row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1));
17+ row = next;
18+ }
19+ return row[b.length]!;
20+}
22+/**
23+ * The seat a name most likely meant, or null. The same name written another way wins; then the longest seat
24+ * the name holds ("abso - Cloud Infra Lead" holds cloud), or that holds the name; then a near spelling.
25+ */
26+export function closestSeat(name: string, seats: readonly string[]): string | null {
27+ const n = plain(name);
28+ if (n === "") return null;
29+ const same = seats.find((s) => plain(s) === n);
30+ if (same) return same;
31+ const held = seats
32+ .filter((s) => plain(s).length >= 3 && (n.includes(plain(s)) || plain(s).includes(n)))
33+ .sort((a, b) => plain(b).length - plain(a).length);
34+ if (held[0]) return held[0];
35+ let best: string | null = null;
36+ let least = Math.max(2, Math.floor(n.length / 3)) + 1;
37+ for (const s of seats) {
38+ const d = distance(n, plain(s));
39+ if (d < least) [best, least] = [s, d];
40+ }
41+ return best;
42+}
44+/** Why an ask to `of` is refused, or null when `of` is a seat. */
45+export function seatRefusal(of: string, project: string, seats: readonly string[]): string | null {
46+ if (seats.includes(of)) return null;
47+ const near = closestSeat(of, seats);
48+ return `${JSON.stringify(of)} isn't an agent in ${project}, so nobody would hear the ask${near ? `; did you mean ${near}?` : "."} abso status lists the agents.`;
49+}
--- /dev/null
+++ b/server/src/issues/serve.ts
@@ -0,0 +1,200 @@
1+// How the open server's Worker reaches a project's issues, and what the IssueProject object does with a
2+// request, apart from Cloudflare's own types so both run under node --test.
3+//
4+// issuesFetch the Worker's entry for /issues/p/:project/...: the router has checked the token or key;
5+// this checks that a key acts only as its own agent (and a reader's only reads), hands the
6+// request to the project's IssueProject, and delivers a write's news to the project.
7+// IssuesObject one project's issues: migrations, the store, and its routes (routes.ts). An ask's `of` is
8+// checked against the project's agents.
9+//
10+// The project object (env.PROJECT, named by the project) is asked two things, both optional: agents(project)
11+// for the ask check, and news(project, items) to deliver a write's news as announcements. Without them the
12+// check is skipped and the news is dropped with a log line.
14+import type { News } from "../../../client/src/issues-wire.ts";
15+import { BODY_MAX, issuesRoute, json, readCapped } from "./routes.ts";
16+import { seatRefusal } from "./seats.ts";
17+import { IssuesError, IssuesStore, SCHEMA, type Sql } from "./store.ts";
19+/** A write's news for the project to deliver: the issue's claimers and those in `to` hear it, never `from`. */
20+export interface IssueNews extends News {
21+ /** The agent whose write it was. */
22+ from: string;
23+}
25+/** What issues asks of the project's own object. Each method is optional: an older project object may lack it. */
26+export interface ProjectHooks {
27+ /** The agents in the project, which an ask may go to. */
28+ agents?(project: string): Promise<string[]>;
29+ /** Deliver each item as an announcement from `from` to the issue's claimers and `to`. */
30+ news?(project: string, items: IssueNews[]): Promise<unknown>;
31+}
33+/** A Durable Object namespace as far as issues uses one; Cloudflare's DurableObjectNamespace fits it. */
34+export interface NamespaceLike {
35+ idFromName(name: string): unknown;
36+ get(id: never): object;
37+}
39+/** The bindings issues reads. */
40+export interface IssuesEnv {
41+ /** One IssueProject per project, named by the project's name. */
42+ ISSUES_DO: NamespaceLike;
43+ /** The project objects, named by the project's name; their stubs answer ProjectHooks. */
44+ PROJECT?: NamespaceLike;
45+}
47+/** How the router let the request in: the shared token acts as any agent; a key only as its own agent. */
48+export type IssuesAuth = { kind: "token" } | { kind: "key"; agent: string; role: string };
50+/** What issuesFetch needs from the Worker's context. */
51+export interface WaitUntil {
52+ waitUntil(promise: Promise<unknown>): void;
53+}
55+const PROJECT_NAME = /^[A-Za-z0-9._-]{1,64}$/;
56+const AGENT_NAME = /^[A-Za-z0-9._-]{1,64}$/;
58+function stubOf<T>(ns: NamespaceLike, name: string): T {
59+ const n = ns as unknown as { idFromName(name: string): unknown; get(id: unknown): T };
60+ return n.get(n.idFromName(name));
61+}
63+/** The project object's stub, as far as issues calls it; undefined when PROJECT isn't bound. */
64+function hooksOf(env: IssuesEnv, project: string): ProjectHooks | undefined {
65+ return env.PROJECT === undefined ? undefined : stubOf<ProjectHooks>(env.PROJECT, project);
66+}
68+/**
69+ * Whether an RPC call failed because the receiver has no such method. On an RPC stub every property reads as a
70+ * function, so only the call can tell: it fails with this error.
71+ */
72+export function missingMethod(e: unknown): boolean {
73+ const message = e instanceof Error ? e.message : String(e);
74+ return /does not implement (the )?method|is not a function/i.test(message);
75+}
77+/**
78+ * /issues/p/:project<rest> after the router's sign-in check. `rest` is the path after the project, like
79+ * /a/lead/ask or /issues.
80+ */
81+export async function issuesFetch(
82+ request: Request,
83+ env: IssuesEnv,
84+ ctx: WaitUntil,
85+ { project, rest, auth }: { project: string; rest: string; auth: IssuesAuth },
86+): Promise<Response> {
87+ if (!PROJECT_NAME.test(project)) return json(404, { error: "no such project" });
88+ if (!rest.startsWith("/")) return json(404, { error: "no such issues route" });
89+ const m = /^\/a\/([^/]+)\//.exec(rest);
90+ let agent: string | undefined;
91+ if (m) {
92+ try {
93+ agent = decodeURIComponent(m[1]!);
94+ } catch {
95+ return json(400, { error: "an agent's name is 1-64 of A-Z a-z 0-9 . _ -" });
96+ }
97+ if (!AGENT_NAME.test(agent)) return json(400, { error: "an agent's name is 1-64 of A-Z a-z 0-9 . _ -" });
98+ }
99+ const reading = request.method === "GET" || request.method === "HEAD";
100+ if (auth.kind === "key") {
101+ if (agent !== undefined && agent !== auth.agent)
102+ return json(403, { error: `this key is ${auth.agent}'s; it acts only as ${auth.agent}` });
103+ if (auth.role === "reader" && !reading) return json(403, { error: "a reader's key only reads issues" });
104+ }
105+ let body: Uint8Array<ArrayBuffer> | undefined;
106+ if (!reading) {
107+ try {
108+ body = await readCapped(request, BODY_MAX);
109+ } catch (e) {
110+ if (e instanceof IssuesError) return json(e.status, { error: e.message });
111+ throw e;
112+ }
113+ }
114+ // The object sees neither the token nor any header that could name a person.
115+ const headers = new Headers(request.headers);
116+ for (const h of ["Authorization", "X-Abso-User", "X-Avcs-User", "Cookie"]) headers.delete(h);
117+ const search = new URL(request.url).search;
118+ const forwarded = new Request(`https://issues.invalid/p/${encodeURIComponent(project)}${rest}${search}`, {
119+ method: request.method,
120+ headers,
121+ ...(body !== undefined ? { body } : {}),
122+ });
123+ const stub = stubOf<{ fetch(request: Request): Promise<Response> }>(env.ISSUES_DO, project);
124+ const answer = await stub.fetch(forwarded);
125+ if (!reading && agent !== undefined && answer.ok) ctx.waitUntil(tell(env, project, agent, answer.clone()));
126+ return answer;
127+}
129+/** A write's news to the project object, sent after the answer. A failed send is only logged; the write stands. */
130+async function tell(env: IssuesEnv, project: string, from: string, answer: Response): Promise<void> {
131+ try {
132+ const { news } = (await answer.json()) as { news?: News };
133+ if (!news || typeof news.text !== "string") return;
134+ const hooks = hooksOf(env, project);
135+ if (hooks === undefined) {
136+ console.log(`issues: news for ${project} dropped: PROJECT isn't bound`);
137+ return;
138+ }
139+ await hooks.news!(project, [{ from, ...news }]);
140+ } catch (err) {
141+ if (missingMethod(err)) console.log(`issues: news for ${project} dropped: the project object has no news method`);
142+ else console.error(`issues: news for ${project} not sent`, err);
143+ }
144+}
146+/** The storage an IssueProject object has: its SQL, and a synchronous transaction. */
147+export interface ObjectStorage {
148+ sql: Sql;
149+ transactionSync<T>(action: () => T): T;
150+}
152+/** One project's issues: the store over the object's SQLite, migrated, and the routes over it. */
153+export class IssuesObject {
154+ readonly store: IssuesStore;
155+ private readonly storage: ObjectStorage;
156+ private readonly env: IssuesEnv;
158+ constructor(storage: ObjectStorage, env: IssuesEnv, now: () => number = Date.now) {
159+ this.storage = storage;
160+ this.env = env;
161+ this.migrate();
162+ this.store = new IssuesStore(storage.sql, now, (action) => storage.transactionSync(action));
163+ }
165+ /** Runs each SCHEMA statement not yet run, once, in order, each in its own transaction. */
166+ private migrate(): void {
167+ const sql = this.storage.sql;
168+ sql.exec("CREATE TABLE IF NOT EXISTS migrations (n INTEGER PRIMARY KEY, at INTEGER NOT NULL)");
169+ const done = (sql.exec("SELECT COALESCE(MAX(n), 0) AS n FROM migrations").toArray()[0] as { n: number }).n;
170+ for (let n = done + 1; n <= SCHEMA.length; n++)
171+ this.storage.transactionSync(() => {
172+ sql.exec(SCHEMA[n - 1]!);
173+ sql.exec("INSERT INTO migrations (n, at) VALUES (?, ?)", n, Date.now());
174+ });
175+ }
177+ /** How many migrations this object has run. */
178+ migrations(): number {
179+ return (this.storage.sql.exec("SELECT COUNT(*) AS n FROM migrations").toArray()[0] as { n: number }).n;
180+ }
182+ async fetch(request: Request): Promise<Response> {
183+ const name = /^\/p\/([^/]+)\//.exec(new URL(request.url).pathname)?.[1];
184+ const project = name === undefined ? undefined : decodeURIComponent(name);
185+ const seatError = async (of: string): Promise<string | null> => {
186+ if (project === undefined) return null;
187+ const hooks = hooksOf(this.env, project);
188+ if (hooks === undefined) return null;
189+ let seats: string[];
190+ try {
191+ seats = await hooks.agents!(project);
192+ } catch (e) {
193+ if (missingMethod(e)) return null;
194+ throw e;
195+ }
196+ return Array.isArray(seats) ? seatRefusal(of, project, seats) : null;
197+ };
198+ return issuesRoute(this.store, request, seatError);
199+ }
200+}
--- /dev/null
+++ b/server/src/issues/store.ts
@@ -0,0 +1,1693 @@
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+ };
--- a/server/test/e2e-transcript.md
+++ b/server/test/e2e-transcript.md
@@ -128,5 +128,120 @@
128128- Per-agent keys (`AGENT_KEYS=on`, a local `KEY_HMAC_SECRET`): `POST /admin/agent-keys` without `x-abso-admin` is 403; with it, a writer key for `carol` is issued and listed. Carol's key syncs as carol; as `dave` it is 403 `that key is not for this agent`; on another project, 403 `that key is not for this project`.
129129- Blobs: a PUT whose bytes don't hash to the name is 400 `the bytes hash to …, not …`; the right hash is stored and read back; a name that isn't a SHA-256 is 400.
130130- `GET head` answers `{version, at}` from storage. `GET feed?from=<end>&wait=3` holds for 3 seconds, then answers with no events.
131−- `/issues/p/<project>/...` reaches the issues stand-in (404 `issues aren't on this server yet`) after auth.
131+- `/issues/p/<project>/...` reached the issues stand-in (404 `issues aren't on this server yet`) after auth, before the issues code landed; the run below is against the issues code itself.
132132- `POST git-remote` with Artifacts off: 501 `this server has no Artifacts binding, so no git remote`.
134+## Issues, asks and news, with no issues server named
136+Server: `http://127.0.0.1:8797` (`npm run dev` in server/, which is `wrangler dev --local`; `ABSO_ARTIFACTS=off`).
137+Token: an invented local test token in `server/.dev.vars`, given to the client as `ABSO_TOKEN`.
138+HOME and USERPROFILE: a new empty temporary folder, so no `~/.abso/servers.json`; `ABSO_ISSUES_SERVER` unset.
139+The client finds issues at `http://127.0.0.1:8797/issues`. Project: `e2e-issues-1791907724`. Run 2026-10-13T16:08Z.
141+```
142+(alice) $ abso init . --server http://127.0.0.1:8797 --project e2e-issues-1791907724 --agent alice
143+Created project e2e-issues-1791907724 at version 0 from 2 text files in <temp>\alice.
144+Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore.
145+No abso.json written: package.json gives no check or build to guess, so CI has nothing to run on each new version. To give it a check, push an abso.json like {"check": "npm test"} (abso ci --help says what it runs).
146+This folder is agent alice. Settings are in .abso/config.json.
147+Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\client\install-mod.ts installs it, and new chats load it. Anything else: abso record.
148+[exit 0]
149+```
151+```
152+(bob) $ abso join e2e-issues-1791907724 --agent bob --dir . --server http://127.0.0.1:8797
153+Joined e2e-issues-1791907724 as bob at version 0: wrote 2 files into <temp>\bob.
154+Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\client\install-mod.ts installs it, and new chats load it. Anything else: abso record.
155+[exit 0]
156+```
158+```
159+(alice) $ abso issue new "Sync is slow on big folders" --description "A pull of 5000 files takes a minute."
160+Opened issue 1. abso start "..." --issue 1 starts on it.
161+[exit 0]
162+```
164+```
165+(bob) $ abso issue 1 --comment "Seen it too: most of the minute is hashing."
166+Commented on issue 1. Its agents hear it.
167+[exit 0]
168+```
170+```
171+(alice) $ abso ask bob "Hash on the server or in the client?" --issue 1
172+Asked bob (ask 1). They hear it; abso waiting shows what's open.
173+[exit 0]
174+```
176+```
177+(alice) $ abso ask carol "Can you review the hashing?" --issue 1
178+abso ask: POST /a/alice/ask answered 400: "carol" isn't an agent in e2e-issues-1791907724, so nobody would hear the ask. abso status lists the agents.
179+[exit 1]
180+```
182+```
183+(bob) $ abso news
184+1 news item:
185+ alice (as claimed) told you, 16:08 UTC:
186+ alice asks bob a question on issue 1 ("Sync is slow on big folders"): "Hash on the server or in the client?" Answer: abso answer 1 "..."
187+[exit 0]
188+```
190+```
191+(bob) $ abso waiting --mine
192+1 open ask of bob, soonest due first:
193+ ask 1: alice, 16:08 UTC, asks bob a question on issue 1 ("Sync is slow on big folders") (new): "Hash on the server or in the client?"
194+abso ask <N> shows one with its thread; abso reply <N> "..." adds to it; abso answer <N> "..." answers one asked of you.
195+[exit 0]
196+```
198+```
199+(alice) $ abso issues
200+1 issue, most recently updated first:
201+ 1 blocked "Sync is slow on big folders" (waiting on bob; updated 16:08 UTC)
202+abso issue <N> shows one.
203+[exit 0]
204+```
206+```
207+(bob) $ abso answer 1 "In the client: the server never sees unchanged files."
208+Answered ask 1. alice hears it.
209+[exit 0]
210+```
212+```
213+(alice) $ abso news
214+1 news item:
215+ bob (as claimed) told you, 16:08 UTC:
216+ bob answered alice's question on issue 1: "In the client: the server never sees unchanged files."
217+[exit 0]
218+```
220+```
221+(alice) $ abso issue 1
222+Issue 1: "Sync is slow on big folders" [open]
223+Opened by alice, 16:08 UTC.
225+ A pull of 5000 files takes a minute.
227+Asks:
228+ ask 1: alice, 16:08 UTC, asks bob a question on issue 1 (answered by bob, 16:08 UTC): "Hash on the server or in the client?"
229+ answer: "In the client: the server never sees unchanged files."
231+Comments:
232+ bob, 16:08 UTC: "Seen it too: most of the minute is hashing."
234+Watchers: alice, bob.
236+abso start "..." --issue 1 starts on it; abso issue 1 --comment "..." comments; abso ask <who> "..." --issue 1 asks.
237+[exit 0]
238+```
240+```
241+(alice) $ abso waiting --asked
242+The latest answered:
243+ ask 1: alice, 16:08 UTC, asks bob a question on issue 1 ("Sync is slow on big folders") (answered by bob, 16:08 UTC): "Hash on the server or in the client?"
244+ answer: "In the client: the server never sees unchanged files."
245+abso ask <N> shows one with its whole thread.
246+[exit 0]
247+```
--- /dev/null
+++ b/server/test/issues/ask-threads.test.ts
@@ -0,0 +1,193 @@
1+// Ask threads: replies from either side, whose turn it is, the
2+// asks someone sent, one ask with its thread, and asks going only to seats.
3+
4+import assert from "node:assert/strict";
5+import { DatabaseSync } from "node:sqlite";
6+import { describe, it } from "node:test";
7+import { issuesRoute } from "../../src/issues/routes.ts";
8+import { closestSeat, seatRefusal } from "../../src/issues/seats.ts";
9+import { IssuesStore, type Sql } from "../../src/issues/store.ts";
11+function sql(): Sql {
12+ const db = new DatabaseSync(":memory:");
13+ return {
14+ exec: (q, ...b) => {
15+ if (/^\s*CREATE\b/i.test(q)) {
16+ db.exec(q);
17+ return { toArray: () => [] };
18+ }
19+ const rows = db.prepare(q).all(...(b as (string | number | null)[]));
20+ return { toArray: () => rows };
21+ },
22+ };
23+}
25+function store(): { s: IssuesStore; db: Sql; tick: (ms?: number) => void } {
26+ let t = Date.parse("2026-10-10T05:00:00Z");
27+ const db = sql();
28+ IssuesStore.createTables(db);
29+ return { s: new IssuesStore(db, () => t), db, tick: (ms = 1000) => void (t += ms) };
30+}
32+const desk = { agent: "desk" };
33+const fay = { agent: "fay" };
35+describe("ask threads", () => {
36+ it("replies from both sides, oldest first; a question back waits on the asker until they reply", () => {
37+ const { s, tick } = store();
38+ const id = s.open(desk, { title: "Sync is slow" }).id;
39+ const ask = s.ask(desk, { issue: id, of: "fay", question: "Which way?" });
40+ assert.equal(s.askThread(ask.id).waitingOn, "fay");
42+ tick();
43+ s.ack(fay, ask.id, { note: "ok, let me check" });
44+ tick();
45+ const back = s.reply(fay, ask.id, { text: "staging or live?", question: true });
46+ assert.equal(back.ask.waitingOn, "desk");
47+ assert.deepEqual(back.news.to, ["desk"]);
48+ assert.equal(
49+ back.news.text,
50+ `fay replied on ask ${ask.id} (issue ${id}) with a question: "staging or live?" It waits on you. abso ask ${ask.id} shows the thread.`,
51+ );
52+ assert.deepEqual(
53+ back.ask.replies!.map((r) => [r.by, r.text, r.question === true]),
54+ [
55+ ["fay", "ok, let me check", false],
56+ ["fay", "staging or live?", true],
57+ ],
58+ );
59+ // It's in the asker's waiting list now, not the one asked's, and the issue waits on the asker.
60+ assert.deepEqual(
61+ s.waiting("desk").map((a) => a.id),
62+ [ask.id],
63+ );
64+ assert.deepEqual(s.waiting("fay"), []);
65+ assert.deepEqual(s.page(id).issue.waitingOn, ["desk"]);
67+ tick();
68+ const handed = s.reply(desk, ask.id, { text: "live" });
69+ assert.equal(handed.ask.waitingOn, "fay");
70+ assert.deepEqual(handed.news.to, ["fay"]);
71+ assert.match(handed.news.text, /^desk replied on ask \d+ \(issue \d+\): "live" It waits on you\./);
72+ assert.deepEqual(
73+ s.waiting("fay").map((a) => a.id),
74+ [ask.id],
75+ );
77+ // A plain reply from the one asked leaves the turn where it is.
78+ assert.equal(s.reply(fay, ask.id, { text: "deploying" }).ask.waitingOn, "fay");
80+ // Answering closes it; a reply after still lands, and waits on nobody.
81+ s.answer(fay, ask.id, { words: "done on live" });
82+ const after = s.reply(desk, ask.id, { text: "thanks" });
83+ assert.equal(after.ask.waitingOn, null);
84+ assert.equal(after.ask.answer!.words, "done on live");
85+ assert.equal(after.ask.replies!.length, 5);
86+ assert.equal(s.page(id).asks[0]!.replies!.length, 5);
87+ assert.deepEqual(s.waiting("fay"), []);
88+ assert.deepEqual(s.waiting("desk"), []);
89+ });
91+ it("only the two reply, with words, on an ask that exists", () => {
92+ const { s } = store();
93+ const ask = s.ask(desk, { of: "fay", question: "Pick one" });
94+ assert.throws(
95+ () => s.reply({ agent: "eve" }, ask.id, { text: "me too" }),
96+ (e: { status?: number; message: string }) =>
97+ e.status === 403 && /between desk and fay; only they reply on it/.test(e.message),
98+ );
99+ assert.throws(
100+ () => s.reply(fay, 99, { text: "x" }),
101+ (e: { status?: number }) => e.status === 404,
102+ );
103+ assert.throws(() => s.reply(fay, ask.id, { text: "" }));
104+ assert.throws(() => s.reply(fay, ask.id, {}));
105+ });
107+ it("an ack with no note adds no reply; ack's note is the thread's first", () => {
108+ const { s } = store();
109+ const ask = s.ask(desk, { of: "fay", question: "Pick one" });
110+ assert.deepEqual(s.ack(fay, ask.id, {}).ask.replies, []);
111+ assert.equal(s.ack(fay, ask.id, { note: "soon" }).ask.replies![0]!.text, "soon");
112+ });
114+ it("asked lists what someone sent: open oldest first, then the latest answered", () => {
115+ const { s, tick } = store();
116+ const a = s.ask(desk, { of: "fay", question: "One" });
117+ tick();
118+ const b = s.ask(desk, { of: "fay", question: "Two" });
119+ tick();
120+ const c = s.ask(desk, { of: "fay", question: "Three" });
121+ s.ask(fay, { of: "desk", question: "Not desk's" });
122+ s.answer(fay, b.id, { words: "yes" });
123+ assert.deepEqual(
124+ s.asked("desk").map((x) => x.id),
125+ [a.id, c.id, b.id],
126+ );
127+ });
128+});
130+describe("ask thread routes", () => {
131+ const call = (
132+ s: IssuesStore,
133+ method: string,
134+ path: string,
135+ body?: unknown,
136+ seatError?: (of: string) => Promise<string | null>,
137+ ) =>
138+ issuesRoute(
139+ s,
140+ new Request(`https://issues.internal${path}`, {
141+ method,
142+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
143+ }),
144+ seatError,
145+ ).then(async (r) => ({ status: r.status, json: (await r.json()) as Record<string, any> }));
147+ it("POST a/<agent>/reply/N, GET ask/N, GET a/<agent>/asked and asked?by=", async () => {
148+ const { s } = store();
149+ const ask = s.ask(desk, { of: "fay", question: "Which way?" });
150+ const r = await call(s, "POST", `/p/web/a/fay/reply/${ask.id}`, { text: "live?", question: true });
151+ assert.equal(r.status, 200, JSON.stringify(r.json));
152+ assert.equal(r.json.ask.waitingOn, "desk");
153+ const one = await call(s, "GET", `/p/web/ask/${ask.id}`);
154+ assert.equal(one.json.ask.replies[0].text, "live?");
155+ assert.equal((await call(s, "GET", "/p/web/ask/99")).status, 404);
156+ const mine = await call(s, "GET", "/p/web/a/desk/asked");
157+ assert.deepEqual(
158+ mine.json.asks.map((a: { id: number }) => a.id),
159+ [ask.id],
160+ );
161+ assert.equal((await call(s, "GET", "/p/web/asked?by=desk")).json.asks.length, 1);
162+ assert.equal((await call(s, "GET", "/p/web/asked")).status, 400);
163+ });
165+ it("a new ask to a name that isn't a seat is refused, naming the closest seat", async () => {
166+ const { s } = store();
167+ const seats = ["cloud", "agentvcs", "pinch", "infra-ops"];
168+ const check = async (of: string) => (of.startsWith("person:") ? null : seatRefusal(of, "web", seats));
169+ const refused = await call(s, "POST", "/p/web/a/desk/ask", { of: "abso - Cloud Infra Lead", question: "Q" }, check);
170+ assert.equal(refused.status, 400);
171+ assert.equal(
172+ refused.json.error,
173+ '"abso - Cloud Infra Lead" isn\'t an agent in web, so nobody would hear the ask; did you mean cloud? abso status lists the agents.',
174+ );
175+ assert.deepEqual(s.asked("desk"), []);
176+ assert.equal((await call(s, "POST", "/p/web/a/desk/ask", { of: "cloud", question: "Q" }, check)).status, 200);
177+ });
179+ it("closestSeat: the same name written another way, a seat the name holds, then a near spelling", () => {
180+ const seats = ["cloud", "agentvcs", "pinch", "infra-ops", "security-2"];
181+ assert.equal(closestSeat("Agent VCS", seats), "agentvcs");
182+ assert.equal(closestSeat("abso - Cloud Infra Lead", seats), "cloud");
183+ assert.equal(closestSeat("Security 2", seats), "security-2");
184+ assert.equal(closestSeat("pnich", seats), "pinch");
185+ assert.equal(closestSeat("infraops", seats), "infra-ops");
186+ assert.equal(closestSeat("zzzzzz", seats), null);
187+ assert.equal(seatRefusal("pinch", "web", seats), null);
188+ assert.match(
189+ seatRefusal("nobody", "web", seats)!,
190+ /isn't an agent in web, so nobody would hear the ask\. abso status/,
191+ );
192+ });
193+});
--- /dev/null
+++ b/server/test/issues/changes.test.ts
@@ -0,0 +1,121 @@
1+// The change count: one number per project's issues that every write an issue read can
2+// show moves forward, kept by SQLite triggers, so a reader can cache issue reads under it.
3+
4+import assert from "node:assert/strict";
5+import { DatabaseSync } from "node:sqlite";
6+import { describe, it } from "node:test";
7+import { issuesRoute } from "../../src/issues/routes.ts";
8+import { IssuesStore, type Sql } from "../../src/issues/store.ts";
9+
10+function sql(): { sql: Sql; db: DatabaseSync } {
11+ const db = new DatabaseSync(":memory:");
12+ return {
13+ db,
14+ sql: {
15+ exec: (q, ...b) => {
16+ if (/^\s*CREATE\b/i.test(q)) {
17+ db.exec(q);
18+ return { toArray: () => [] };
19+ }
20+ const rows = db.prepare(q).all(...(b as (string | number | null)[]));
21+ return { toArray: () => rows };
22+ },
23+ },
24+ };
25+}
27+function store(): { s: IssuesStore; db: DatabaseSync; tick: () => void } {
28+ let t = Date.parse("2026-10-09T10:00:00Z");
29+ const { sql: q, db } = sql();
30+ IssuesStore.createTables(q);
31+ return { s: new IssuesStore(q, () => t), db, tick: () => void (t += 1000) };
32+}
34+const builder = { agent: "builder3" };
35+const christopher = { person: "u1" };
37+describe("issues: the change count", () => {
38+ it("is kept by a trigger on each counted table, for insert, update and delete", () => {
39+ const { db, s } = store();
40+ const triggers = db
41+ .prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'changed_%'")
42+ .all();
43+ assert.equal(triggers.length, 30, "three for each of the ten tables an issue read shows");
44+ assert.equal(s.changes(), 0);
45+ });
47+ it("moves forward on every write an issue read shows, and not on reads, drafts or a repeated waiting", () => {
48+ const { s, tick } = store();
49+ let last = s.changes();
50+ const moved = (what: string) => {
51+ const n = s.changes();
52+ assert.ok(n > last, `${what} moved the count (${last} to ${n})`);
53+ last = n;
54+ };
55+ const still = (what: string) => assert.equal(s.changes(), last, `${what} left the count alone`);
57+ const a = s.open(builder, { title: "Sign-in" }).id;
58+ moved("opening an issue");
59+ const b = s.open(builder, { title: "Logo", parent: a }).id;
60+ moved("opening a child");
61+ tick();
62+ s.comment(christopher, a, { text: "Looks right." });
63+ moved("a comment");
64+ const q = s.ask(builder, { issue: a, of: "security", question: "Is the cookie set right?", review: true });
65+ moved("an ask");
66+ s.waiting("security", "security");
67+ moved("waiting marking an ask seen");
68+ s.waiting("security", "security");
69+ still("a second waiting with nothing new");
70+ s.answer({ agent: "security" }, q.id, { words: "Yes." });
71+ moved("an answer");
72+ s.claim("builder3", b, 12);
73+ moved("a start note's claim");
74+ s.edit(christopher, b, { labels: ["design"] });
75+ moved("a label");
76+ s.edit(christopher, a, { blockedBy: [b] });
77+ moved("Blocked by");
78+ s.markDone(builder, b, 381);
79+ moved("done in a version");
80+ const c = s.open(builder, { title: "Footer" }).id;
81+ s.claim("builder3", c, 13);
82+ last = s.changes();
83+ s.unclaim("builder3", c);
84+ moved("an unclaim");
85+ s.drop(builder, c);
86+ moved("a drop");
87+ s.reopen(builder, c);
88+ moved("a reopen");
90+ s.page(a);
91+ s.list({});
92+ s.search("sign", 10);
93+ s.waiting();
94+ still("reads");
95+ s.saveDraft(builder, { title: "Mine for now" });
96+ s.wrote(builder);
97+ still("a draft and the rate log");
98+ });
100+ it("is a route, and every write answers the count it made", async () => {
101+ const { s } = store();
102+ const call = async (method: string, path: string, body?: unknown) => {
103+ const r = await issuesRoute(
104+ s,
105+ new Request(`https://issues.internal${path}`, {
106+ method,
107+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
108+ }),
109+ );
110+ return { status: r.status, json: (await r.json()) as Record<string, unknown> };
111+ };
112+ assert.deepEqual((await call("GET", "/p/web/changes")).json, { changes: 0 });
113+ const opened = await call("POST", "/p/web/a/builder3/issue", { title: "Sign-in" });
114+ assert.equal(opened.status, 200);
115+ const after = (await call("GET", "/p/web/changes")).json.changes as number;
116+ assert.ok(after > 0);
117+ assert.equal(opened.json.changes, after, "the write's answer is the count a read after it sees");
118+ const commented = await call("POST", "/p/web/a/builder3/issue/1/comment", { text: "More." });
119+ assert.ok((commented.json.changes as number) > after);
120+ });
121+});
--- /dev/null
+++ b/server/test/issues/issues.test.ts
@@ -0,0 +1,630 @@
1+// Issues: the store and its routes, on node:sqlite as a Durable Object's SQLite.
2+
3+import assert from "node:assert/strict";
4+import { DatabaseSync } from "node:sqlite";
5+import { describe, it } from "node:test";
6+import { issuesRoute } from "../../src/issues/routes.ts";
7+import { IssuesStore, type Sql, WRITES_PER_MINUTE } from "../../src/issues/store.ts";
8+
9+function sql(): Sql {
10+ const db = new DatabaseSync(":memory:");
11+ return {
12+ exec: (q, ...b) => {
13+ // Like ctx.storage.sql.exec: the statement runs at once; rows come from toArray.
14+ if (/^\s*CREATE\b/i.test(q)) {
15+ db.exec(q);
16+ return { toArray: () => [] };
17+ }
18+ const rows = db.prepare(q).all(...(b as (string | number | null)[]));
19+ return { toArray: () => rows };
20+ },
21+ };
22+}
24+function store(): { s: IssuesStore; tick: (ms?: number) => void } {
25+ let t = Date.parse("2026-10-07T20:00:00Z");
26+ const db = sql();
27+ IssuesStore.createTables(db);
28+ return { s: new IssuesStore(db, () => t), tick: (ms = 1000) => void (t += ms) };
29+}
31+const builder = { agent: "builder3" };
32+const christopher = { person: "u1" };
34+describe("issues: statuses come from the work", () => {
35+ it("open, in progress, in review, blocked, done and dropped, and a dropped issue can be reopened", () => {
36+ const { s, tick } = store();
37+ const a = s.open(builder, { title: "Sign-in page", description: "Pages for sign-in" }).id;
38+ const b = s.open(builder, { title: "Logo", parent: a }).id;
39+ assert.equal(s.page(a).issue.status, "open");
40+ assert.equal(s.page(a).issue.children, 1);
42+ tick();
43+ s.claim("builder3", a, 4400);
44+ assert.equal(s.page(a).issue.status, "in progress");
45+ assert.deepEqual(s.page(a).issue.agents, ["builder3"]);
47+ tick();
48+ const review = s.ask(builder, { issue: a, of: "security", question: "Is the cookie set right?", review: true });
49+ assert.equal(s.page(a).issue.status, "in review");
50+ assert.deepEqual(s.page(a).issue.waitingOn, ["security"]);
51+ assert.deepEqual(review.news.to, ["security"]);
52+ assert.ok(review.news.text.endsWith(`: "Is the cookie set right?" Answer: abso answer ${review.id} "..."`));
54+ // A question that isn't a review blocks, and outranks the review; it can hold up other issues too.
55+ const q = s.ask(builder, {
56+ issue: a,
57+ of: "person:u1",
58+ question: "Take abso.dev?",
59+ options: ["Yes", "No"],
60+ blocks: [b],
61+ due: "2026-10-09",
62+ });
63+ assert.equal(s.page(a).issue.status, "blocked");
64+ assert.equal(s.page(b).issue.status, "blocked", "an ask holds up the issues it names in blocks");
65+ assert.deepEqual(s.page(a).issue.waitingOn, ["security", "person:u1"]);
66+ assert.ok(q.news.text.endsWith('"Take abso.dev?"'), "a person answers elsewhere, so no command");
68+ tick();
69+ const answered = s.answer(christopher, q.id, { option: "Yes", note: "Renew it for two years." });
70+ assert.equal(answered.ask.answer?.words, "Yes\n\nRenew it for two years.", "kept in the person's own words");
71+ assert.equal(s.page(b).issue.status, "open");
72+ assert.equal(s.page(a).issue.status, "in review");
73+ s.answer({ agent: "security" }, review.id, { words: "Looks right." });
74+ assert.equal(s.page(a).issue.status, "in progress");
76+ tick();
77+ const done = s.done("builder3", a, 13);
78+ assert.match(done.news!.text, /^builder3 finished issue 1 \("Sign-in page"\) in version 13$/);
79+ const page = s.page(a);
80+ assert.equal(page.issue.status, "done");
81+ assert.deepEqual(page.issue.closed, { how: "done", by: "builder3", version: 13, at: page.issue.closed!.at });
82+ assert.deepEqual(page.issue.versions, [13]);
83+ assert.deepEqual(page.claims, []);
85+ s.drop(builder, b);
86+ assert.equal(s.page(b).issue.status, "dropped");
87+ assert.throws(() => s.drop(builder, b), /dropped already/);
88+ assert.throws(() => s.markDone(builder, b, null), /reopen it/);
89+ const reopened = s.reopen(builder, b);
90+ assert.match(reopened.news.text, /reopened issue/);
91+ assert.equal(s.page(b).issue.status, "open");
92+ assert.throws(() => s.reopen(builder, b), /is open/);
93+ const marked = s.markDone(builder, b, 381);
94+ assert.match(marked.news.text, /done in version 381/);
95+ assert.equal(s.page(b).issue.status, "done");
96+ assert.deepEqual(s.page(b).issue.versions, [381]);
97+ assert.throws(() => s.reopen(builder, b), /stays done/);
98+ assert.throws(() => s.markDone(builder, b, null), /done already/);
99+ assert.deepEqual(
100+ s.list({ open: true }).map((i) => i.id),
101+ [],
102+ );
103+ });
105+ it("a start note that ends without --done takes the claim back and leaves the issue open", () => {
106+ const { s } = store();
107+ const id = s.open(builder, { title: "x" }).id;
108+ s.claim("builder3", id, 10);
109+ s.unclaim("builder3", id);
110+ assert.equal(s.page(id).issue.status, "open");
111+ // Hooks for an issue that doesn't exist are ignored: the start note stands either way.
112+ s.claim("builder3", 99, 10);
113+ s.unclaim("builder3", 99);
114+ assert.deepEqual(s.done("builder3", 99, 3), {});
115+ });
117+ it("lists by status and agent, most recently updated first", () => {
118+ const { s, tick } = store();
119+ const one = s.open(builder, { title: "one" }).id;
120+ tick();
121+ const two = s.open(builder, { title: "two" }).id;
122+ tick();
123+ s.comment({ agent: "engine" }, one, { text: "on it soon" });
124+ assert.deepEqual(
125+ s.list().map((i) => i.id),
126+ [one, two],
127+ );
128+ s.claim("engine", two, 5);
129+ assert.deepEqual(
130+ s.list({ agent: "engine" }).map((i) => i.id),
131+ [two],
132+ );
133+ assert.deepEqual(
134+ s.list({ status: "open" }).map((i) => i.id),
135+ [one],
136+ );
137+ });
138+});
140+describe("issues: the asker withdraws an ask", () => {
141+ it("closes like an answer: off the waiting list, no longer blocking, kept with the note, and the one asked hears it", () => {
142+ const { s } = store();
143+ const id = s.open(builder, { title: "How judges see abso" }).id;
144+ const ask = s.ask(builder, { of: "person:u1", question: "A, B or C?", issue: id, options: ["A", "B", "C"] });
145+ assert.equal(s.page(id).issue.status, "blocked");
146+ const r = s.withdraw(builder, ask.id, { note: "Overtaken by tonight's rulings" });
147+ assert.equal(r.ask.outcome, "withdrawn");
148+ assert.deepEqual(r.ask.answer && { by: r.ask.answer.by, words: r.ask.answer.words }, {
149+ by: "builder3",
150+ words: "Overtaken by tonight's rulings",
151+ });
152+ assert.deepEqual(r.news.to, ["person:u1"]);
153+ assert.match(r.news.text, /^builder3 withdrew their question of person:u1 on issue \d+: "Overtaken/);
154+ assert.deepEqual(s.waiting("person:u1"), []);
155+ assert.equal(s.page(id).issue.status, "open");
156+ assert.equal(s.page(id).asks[0]!.outcome, "withdrawn");
157+ assert.equal(s.answered("person:u1")[0]!.outcome, "withdrawn");
158+ });
160+ it("only the asker withdraws, only while unanswered, and once; then it can't be answered", () => {
161+ const { s } = store();
162+ const ask = s.ask(builder, { of: "person:u1", question: "Pick one" });
163+ assert.throws(() => s.withdraw(christopher, ask.id, {}), /asked by builder3; only they can withdraw it/);
164+ assert.throws(() => s.withdraw(builder, 99, {}), /there's no ask 99/);
165+ const r = s.withdraw(builder, ask.id, {});
166+ assert.equal(r.ask.answer!.words, "");
167+ assert.equal(r.news.text, "builder3 withdrew their question of person:u1", "no note, so nothing after it");
168+ assert.throws(() => s.withdraw(builder, ask.id, {}), /withdrawn already/);
169+ assert.throws(
170+ () => s.answer(christopher, ask.id, { words: "A" }),
171+ (e: { status?: number; message: string }) => e.status === 409 && /withdrawn by builder3/.test(e.message),
172+ );
173+ const answered = s.ask(builder, { of: "person:u1", question: "Another" });
174+ s.answer(christopher, answered.id, { words: "Yes" });
175+ assert.throws(() => s.withdraw(builder, answered.id, {}), /answered already, so there's nothing to withdraw/);
176+ assert.equal(s.answered("person:u1").find((a) => a.id === answered.id)!.outcome, undefined);
177+ });
178+});
180+describe("issues: the one asked acknowledges an ask", () => {
181+ it("stays open and blocking, shows the ack and its note, and the asker hears it; an answer closes it", () => {
182+ const { s } = store();
183+ const id = s.open(builder, { title: "Which deploy first" }).id;
184+ const ask = s.ask(builder, { of: "person:u1", question: "A or B?", issue: id });
185+ const r = s.ack(christopher, ask.id, { note: "after the review" });
186+ assert.equal(r.ask.ack!.note, "after the review");
187+ assert.equal(r.ask.answer, null);
188+ assert.deepEqual(r.news.to, ["builder3"]);
189+ assert.equal(
190+ r.news.text,
191+ `person:u1 has your question (ask ${ask.id}) on issue ${id} and will answer: "after the review"`,
192+ );
193+ assert.equal(s.page(id).issue.status, "blocked");
194+ assert.equal(s.page(id).asks[0]!.ack!.note, "after the review");
195+ assert.deepEqual(
196+ s.waiting("person:u1").map((a) => a.id),
197+ [ask.id],
198+ );
199+ // Again, with no note: the note and time update.
200+ const again = s.ack(christopher, ask.id, {});
201+ assert.equal(again.ask.ack!.note, "");
202+ assert.equal(again.news.text, `person:u1 has your question (ask ${ask.id}) on issue ${id} and will answer.`);
203+ s.answer(christopher, ask.id, { words: "A" });
204+ assert.equal(s.page(id).issue.status, "open");
205+ assert.deepEqual(s.waiting("person:u1"), []);
206+ });
208+ it("only the one asked acknowledges, and only while it's open", () => {
209+ const { s } = store();
210+ const ask = s.ask(builder, { of: "person:u1", question: "Pick one" });
211+ assert.throws(
212+ () => s.ack(builder, ask.id, {}),
213+ (e: { status?: number; message: string }) => e.status === 403 && /is for person:u1, not builder3/.test(e.message),
214+ );
215+ assert.throws(
216+ () => s.ack(christopher, 99, {}),
217+ (e: { status?: number }) => e.status === 404,
218+ );
219+ s.answer(christopher, ask.id, { words: "A" });
220+ assert.throws(
221+ () => s.ack(christopher, ask.id, {}),
222+ (e: { status?: number; message: string }) => e.status === 409 && /answered already/.test(e.message),
223+ );
224+ const gone = s.ask(builder, { of: "person:u1", question: "Another" });
225+ s.withdraw(builder, gone.id, {});
226+ assert.throws(
227+ () => s.ack(christopher, gone.id, {}),
228+ (e: { status?: number; message: string }) => e.status === 409 && /withdrawn by builder3/.test(e.message),
229+ );
230+ });
231+});
233+describe("issues: asks and answers", () => {
234+ it("an ask on no issue, a task answered done, and waiting sorted by due date", () => {
235+ const { s } = store();
236+ const id = s.open(builder, { title: "Sign-in" }).id;
237+ const later = s.ask(builder, {
238+ of: "person:u1",
239+ question: "Does the avcs command become abso?",
240+ due: "2026-10-20",
241+ recommendation: { text: "Yes, with avcs kept as an alias" },
242+ });
243+ const sooner = s.ask(builder, {
244+ of: "person:u1",
245+ kind: "task",
246+ question: "Upload the sign-in logo",
247+ due: "2026-10-08",
248+ blocks: [id],
249+ });
250+ const none = s.ask(builder, { of: "person:u1", question: "Anything else?" });
251+ const waiting = s.waiting("person:u1");
252+ assert.deepEqual(
253+ waiting.map((a) => a.id),
254+ [sooner.id, later.id, none.id],
255+ );
256+ assert.equal(waiting[1]!.issue, null);
257+ assert.equal(waiting[1]!.title, null);
258+ assert.deepEqual(waiting[1]!.recommendation, { text: "Yes, with avcs kept as an alias", by: "builder3" });
259+ assert.equal(s.page(id).issue.status, "blocked");
260+ s.answer(christopher, sooner.id, { done: true });
261+ assert.equal(s.answered("person:u1")[0]!.answer!.words, "done");
262+ assert.equal(s.page(id).issue.status, "open");
263+ assert.deepEqual(
264+ s.waiting("person:u1").map((a) => a.id),
265+ [later.id, none.id],
266+ );
267+ });
269+ it("only the one asked answers, once, from its options", () => {
270+ const { s } = store();
271+ const ask = s.ask(builder, { of: "person:u1", question: "Pick one", options: ["A", "B"] });
272+ assert.throws(() => s.answer({ person: "u2" }, ask.id, { words: "A" }), /is for person:u1, not person:u2/);
273+ assert.throws(() => s.answer(christopher, ask.id, { option: "C" }), /options are: "A", "B"/);
274+ // The page sends the option's text as it showed it: an index that names another is refused.
275+ assert.throws(
276+ () => s.answer(christopher, ask.id, { option: 1, expect: "A" }),
277+ (e: { status?: number; message: string }) =>
278+ e.status === 409 && /option 2 is "B", not the one you picked/.test(e.message),
279+ );
280+ s.answer(christopher, ask.id, { option: 1, expect: "B" });
281+ assert.throws(() => s.answer(christopher, ask.id, { words: "A" }), /answered already/);
282+ assert.equal(s.answered("person:u1")[0]!.answer!.words, "B");
283+ });
285+ it("checks its input", () => {
286+ const { s } = store();
287+ assert.throws(() => s.open(builder, { title: "" }), /the title is missing/);
288+ assert.throws(() => s.open(builder, { title: "x".repeat(201) }), /201 characters; the most is 200/);
289+ assert.throws(() => s.open(builder, { title: "x", parent: 7 }), /there's no issue 7/);
290+ assert.throws(
291+ () => s.open(builder, { title: "x", lines: { file: "a.ts", from: 3, to: 1, version: 2 } }),
292+ /lines are/,
293+ );
294+ assert.throws(() => s.ask(builder, { of: "x", question: "q", review: true }), /a review ask is on an issue/);
295+ assert.throws(() => s.ask(builder, { of: "x", question: "q", due: "soon" }), /due is a date/);
296+ assert.throws(() => s.ask(builder, { of: "x", question: "q", kind: "chore" }), /kind is "question", or "task"/);
297+ });
298+});
300+describe("issues: routes", () => {
301+ const call = (s: IssuesStore, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) =>
302+ issuesRoute(
303+ s,
304+ new Request(`https://issues.internal${path}`, {
305+ method,
306+ headers,
307+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
308+ }),
309+ ).then(async (r) => ({ status: r.status, json: (await r.json()) as Record<string, any> }));
311+ it("agents write under /a/:agent/, a write naming nobody is refused, and everyone reads", async () => {
312+ const { s } = store();
313+ const opened = await call(s, "POST", "/p/web/a/builder3/issue", { title: "Sign-in", description: "d" });
314+ assert.equal(opened.status, 200);
315+ assert.equal(opened.json.id, 1);
316+ assert.equal((await call(s, "POST", "/p/web/a/fe/issue/1/comment", { text: "nice" })).status, 200);
317+ assert.equal((await call(s, "POST", "/p/web/issue/1/comment", { text: "who am I" })).status, 403);
318+ assert.equal(
319+ (await call(s, "POST", "/p/web/issue/1/comment", { text: "a person?" }, { "X-Avcs-User": "u1" })).status,
320+ 403,
321+ "no header makes a person here",
322+ );
323+ const asked = await call(s, "POST", "/p/web/a/builder3/ask", { issue: 1, of: "fe", question: "OK?" });
324+ assert.equal(asked.json.news.to[0], "fe");
325+ assert.equal((await call(s, "POST", `/p/web/a/fe/answer/${asked.json.id}`, { words: "OK" })).status, 200);
327+ const list = await call(s, "GET", "/p/web/issues?open=1");
328+ assert.deepEqual(
329+ list.json.issues.map((i: { id: number; status: string }) => [i.id, i.status]),
330+ [[1, "open"]],
331+ );
332+ const page = await call(s, "GET", "/p/web/issue/1");
333+ assert.deepEqual(
334+ page.json.comments.map((c: { by: string }) => c.by),
335+ ["fe"],
336+ );
337+ assert.equal(page.json.asks[0].answer.words, "OK");
338+ assert.equal((await call(s, "GET", "/p/web/issue/9")).status, 404);
339+ assert.equal((await call(s, "GET", "/p/web/answered")).status, 400);
340+ assert.equal((await call(s, "POST", "/p/web/a/builder3/issue", "not an object")).status, 400);
341+ });
342+});
344+describe("issues: edits, watchers, Blocked by and drafts", () => {
345+ it("an edit tells the watchers by default, adds people, or tells nobody", () => {
346+ const { s, tick } = store();
347+ const a = s.open(christopher, { title: "Accounts" }).id;
348+ const b = s.open(christopher, { title: "Sign-in", agent: "fe", notify: ["design"] });
349+ assert.deepEqual(b.news, {
350+ issue: null,
351+ text: 'person:u1 opened issue 2: "Sign-in" (Agent fe)',
352+ to: ["fe", "design"],
353+ });
354+ s.comment(builder, b.id, { text: "on it soon" });
355+ s.claim("engine", b.id, 40);
356+ tick();
357+ // Issue 1 opened before issue 2, then put under it.
358+ const moved = s.edit(christopher, b.id, { parent: a, title: "Sign-in flow" });
359+ assert.deepEqual(moved.notified, ["builder3", "design", "engine", "fe"]);
360+ assert.equal(moved.news!.text, 'person:u1 edited issue 2 ("Sign-in flow"): title was "Sign-in"; parent is issue 1');
361+ const page = s.page(b.id);
362+ assert.equal(page.issue.parent, a);
363+ assert.deepEqual(page.issue.watchers, ["builder3", "design", "engine", "fe", "person:u1"]);
364+ assert.deepEqual(page.edits[0]!.changes, {
365+ title: { from: "Sign-in", to: "Sign-in flow" },
366+ parent: { from: null, to: 1 },
367+ });
368+ const quiet = s.edit(builder, b.id, { description: "typo", notify: false });
369+ assert.deepEqual(quiet, { edit: 2, notified: [] });
370+ const more = s.edit(builder, b.id, { agent: "web", also: ["person:u2"] });
371+ assert.ok(
372+ more.notified.includes("person:u2") && more.notified.includes("web") && !more.notified.includes("builder3"),
373+ );
374+ assert.equal(s.page(b.id).issue.agent, "web");
375+ assert.throws(() => s.edit(builder, b.id, { agent: "web" }), /that changes nothing on issue 2/);
376+ assert.throws(() => s.edit(builder, a, { parent: b.id }), /issue 2 is issue 1 or under it/);
377+ assert.throws(() => s.edit(builder, a, { notify: "no", title: "A" }), /notify is true/);
378+ });
380+ it("Blocked by holds an issue Blocked until each is Done, and refuses a loop", () => {
381+ const { s } = store();
382+ const a = s.open(builder, { title: "Schema" }).id;
383+ const b = s.open(builder, { title: "Pages", blockedBy: [a] }).id;
384+ assert.equal(s.page(b).issue.status, "blocked");
385+ assert.deepEqual(s.page(b).issue.blockedBy, [a]);
386+ assert.throws(() => s.edit(builder, a, { blockedBy: [b] }), /issue 2 already waits on issue 1/);
387+ assert.throws(() => s.edit(builder, a, { blockedBy: [a] }), /can't be blocked by itself/);
388+ s.done("engine", a, 12);
389+ assert.equal(s.page(b).issue.status, "open");
390+ const c = s.open(builder, { title: "Docs" }).id;
391+ s.edit(builder, c, { blockedBy: [b] });
392+ assert.equal(s.page(c).issue.status, "blocked");
393+ s.edit(builder, c, { blockedBy: [] });
394+ assert.equal(s.page(c).issue.status, "open");
395+ });
397+ it("the first start note sets the Agent when none was set, and the claimer watches", () => {
398+ const { s } = store();
399+ const id = s.open(builder, { title: "x" }).id;
400+ s.claim("engine", id, 3);
401+ s.claim("fe", id, 4);
402+ assert.equal(s.page(id).issue.agent, "engine");
403+ assert.deepEqual(
404+ s.list({ agent: "engine" }).map((i) => i.id),
405+ [id],
406+ );
407+ assert.ok(s.page(id).issue.watchers.includes("fe"));
408+ });
410+ it("drafts are their writer's alone, have no number, make no news, and open as issues", () => {
411+ const { s } = store();
412+ const d = s.saveDraft(christopher, { title: "Half a thought" }).id;
413+ s.saveDraft(christopher, { id: d, title: "A whole thought", agent: "fe" });
414+ assert.deepEqual(
415+ s.drafts(christopher).map((x) => x.body),
416+ [{ title: "A whole thought", agent: "fe" }],
417+ );
418+ assert.deepEqual(s.drafts({ person: "u2" }), []);
419+ assert.throws(() => s.deleteDraft({ person: "u2" }, d), /you have no draft/);
420+ assert.deepEqual(s.list(), []);
421+ assert.deepEqual(s.drafts(christopher)[0]!.id, d);
422+ s.saveDraft(christopher, {});
423+ const opened = s.openDraft(christopher, d, { description: "added when opening" });
424+ assert.equal(opened.id, 1);
425+ assert.deepEqual(opened.news!.to, ["fe"]);
426+ assert.equal(s.page(1).issue.description, "added when opening");
427+ assert.equal(s.drafts(christopher).length, 1);
428+ assert.throws(() => s.openDraft(christopher, s.drafts(christopher)[0]!.id), /the title is missing/);
429+ });
431+ it("refuses words a reader can't see, and titles over more than one line", () => {
432+ const { s } = store();
433+ assert.throws(
434+ () => s.open(builder, { title: "fine\u{E0041}" }),
435+ /a tag character \(U\+E0000-E007F\) at character 5/,
436+ );
437+ assert.throws(() => s.open(builder, { title: "one\ntwo" }), /the title is one line/);
438+ assert.throws(() => s.open(builder, { title: "x", description: "a\u202Eb" }), /bidirectional/);
439+ const id = s.open(builder, { title: "x", description: "two\nlines\tand a tab" }).id;
440+ assert.throws(() => s.comment(builder, id, { text: "hi\u200B" }), /zero-width/);
441+ assert.throws(() => s.edit(builder, id, { title: "a\nb" }), /one line/);
442+ assert.throws(() => s.open(builder, { title: "x", notify: ["fe\nengine"] }), /one line/);
443+ });
445+ it("routes: edit, and drafts read and written by their writer", async () => {
446+ const { s } = store();
447+ const call = (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) =>
448+ issuesRoute(
449+ s,
450+ new Request(`https://issues.internal${path}`, {
451+ method,
452+ headers,
453+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
454+ }),
455+ ).then(async (r) => ({ status: r.status, json: (await r.json()) as Record<string, any> }));
456+ const title400 = await call("POST", "/p/web/a/fe/issue", { title: "x\u{E0001}" });
457+ assert.equal(title400.status, 400);
458+ assert.match(title400.json.error, /tag character/);
459+ assert.equal((await call("POST", "/p/web/a/fe/issue", { title: "a\nb" })).status, 400);
460+ await call("POST", "/p/web/a/fe/issue", { title: "Sign-in" });
461+ const edited = await call("POST", "/p/web/a/lead/issue/1/edit", { title: "Sign-in flow" });
462+ assert.equal(edited.status, 200);
463+ assert.deepEqual(edited.json.notified, ["fe"]);
464+ const saved = await call("POST", "/p/web/a/lead/draft", { title: "Later" });
465+ assert.equal((await call("GET", "/p/web/a/lead/drafts", undefined)).json.drafts[0].body.title, "Later");
466+ assert.deepEqual((await call("GET", "/p/web/a/fe/drafts")).json.drafts, []);
467+ // A read naming nobody sees no one's drafts.
468+ assert.equal((await call("GET", "/p/web/drafts")).status, 403);
469+ assert.equal((await call("POST", `/p/web/a/fe/draft/${saved.json.id}/delete`)).status, 404);
470+ assert.equal((await call("POST", `/p/web/a/lead/draft/${saved.json.id}/open`, {})).json.id, 2);
471+ assert.deepEqual((await call("GET", "/p/web/a/lead/drafts", undefined)).json.drafts, []);
472+ });
473+});
475+describe("issues: each writer's limit", () => {
476+ it("one write past the per-minute limit gets 429 with Retry-After; another writer isn't affected", async () => {
477+ const { s, tick } = store();
478+ const call = (path: string, body: unknown, agent: string) =>
479+ issuesRoute(
480+ s,
481+ new Request(`https://issues.internal${path.replace("/p/web/", `/p/web/a/${agent}/`)}`, {
482+ method: "POST",
483+ body: JSON.stringify(body),
484+ }),
485+ );
486+ assert.equal((await call("/p/web/issue", { title: "One" }, "u1")).status, 200);
487+ for (let i = 0; i < WRITES_PER_MINUTE - 1; i++)
488+ assert.equal((await call("/p/web/issue/1/comment", { text: `c${i}` }, "u1")).status, 200);
489+ // A refused write doesn't count, and drafts make no news, so they don't either.
490+ assert.equal((await call("/p/web/draft", { title: "later" }, "u1")).status, 200);
491+ const over = await call("/p/web/issue/1/comment", { text: "over limit" }, "u1");
492+ assert.equal(over.status, 429);
493+ assert.match(
494+ ((await over.json()) as { error: string }).error,
495+ new RegExp(`at most ${WRITES_PER_MINUTE} issue writes a minute`),
496+ );
497+ assert.equal(over.headers.get("Retry-After"), "60");
498+ assert.equal((await call("/p/web/issue/1/comment", { text: "mine" }, "u2")).status, 200);
499+ tick(60_000);
500+ assert.equal((await call("/p/web/issue/1/comment", { text: "a minute on" }, "u1")).status, 200);
501+ });
502+});
504+describe("issues: labels", () => {
505+ it("set on open, changed by edit, filtered by, and listed with counts", () => {
506+ const { s } = store();
507+ const a = s.open(builder, { title: "Sync is slow", labels: ["friction", "client", "friction"] }).id;
508+ const b = s.open(builder, { title: "Blame past a reformat", labels: ["friction", "engine"] }).id;
509+ s.open(builder, { title: "Logo" });
510+ assert.deepEqual(s.page(a).issue.labels, ["client", "friction"]);
511+ assert.deepEqual(
512+ s.list({ labels: ["friction"] }).map((i) => i.id),
513+ [b, a],
514+ );
515+ assert.deepEqual(
516+ s.list({ labels: ["friction", "client"] }).map((i) => i.id),
517+ [a],
518+ );
519+ // A label-only edit tells nobody unless asked; it's in the activity.
520+ const quiet = s.edit(christopher, a, { addLabels: ["good-first-issue"], removeLabels: ["client"] });
521+ assert.deepEqual(quiet.notified, []);
522+ assert.deepEqual(s.page(a).issue.labels, ["friction", "good-first-issue"]);
523+ assert.deepEqual(s.page(a).edits.at(-1)!.changes.labels, {
524+ from: ["client", "friction"],
525+ to: ["friction", "good-first-issue"],
526+ });
527+ const told = s.edit(christopher, a, { labels: ["friction"], notify: true });
528+ assert.match(told.news!.text, /labels friction$/);
529+ s.drop(builder, b);
530+ assert.deepEqual(s.labelsInUse(), [
531+ { label: "engine", open: 0, total: 1 },
532+ { label: "friction", open: 1, total: 2 },
533+ ]);
534+ assert.throws(() => s.edit(builder, a, { addLabels: ["friction"] }), /changes nothing/);
535+ assert.throws(() => s.open(builder, { title: "x", labels: ["two words"] }), /isn't a label/);
536+ // Sent straight to the Worker, upper case and a zero-width are refused, not changed.
537+ assert.throws(
538+ () => s.open(builder, { title: "x", labels: ["Friction"] }),
539+ (e: { status?: number }) => e.status === 400,
540+ );
541+ assert.throws(
542+ () => s.open(builder, { title: "x", labels: ["fric​tion"] }),
543+ (e: { status?: number }) => e.status === 400,
544+ );
545+ assert.throws(() => s.open(builder, { title: "x", labels: ["x".repeat(41)] }), /isn't a label/);
546+ assert.throws(() => s.edit(builder, a, { labels: [], addLabels: ["x"] }), /one or the other/);
547+ assert.throws(() => s.list({ labels: ["Bad Label"] }), /isn't a label/);
548+ });
550+ it("routes: ?label= filters, GET labels lists, and drafts keep labels", async () => {
551+ const { s } = store();
552+ const call = (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) =>
553+ issuesRoute(
554+ s,
555+ new Request(`https://issues.internal${path}`, {
556+ method,
557+ headers,
558+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
559+ }),
560+ ).then(async (r) => ({ status: r.status, json: (await r.json()) as Record<string, any> }));
561+ await call("POST", "/p/web/a/fe/issue", { title: "One", labels: ["friction"] });
562+ await call("POST", "/p/web/a/fe/issue", { title: "Two", labels: ["friction", "client"] });
563+ const both = await call("GET", "/p/web/issues?label=friction,client");
564+ assert.deepEqual(
565+ both.json.issues.map((i: { title: string }) => i.title),
566+ ["Two"],
567+ );
568+ assert.equal((await call("GET", "/p/web/issues?label=friction&label=client")).json.issues.length, 1);
569+ assert.equal((await call("GET", "/p/web/issues?label=Not%20one")).status, 400);
570+ assert.deepEqual((await call("GET", "/p/web/labels")).json.labels, [
571+ { label: "client", open: 1, total: 1 },
572+ { label: "friction", open: 2, total: 2 },
573+ ]);
574+ const edited = await call("POST", "/p/web/a/fe/issue/1/edit", { addLabels: ["client"] });
575+ assert.equal(edited.status, 200);
576+ const d = await call("POST", "/p/web/a/fe/draft", { title: "Later", labels: ["friction"] });
577+ const opened = await call("POST", `/p/web/a/fe/draft/${d.json.id}/open`, {});
578+ assert.deepEqual((await call("GET", `/p/web/issue/${opened.json.id}`)).json.issue.labels, ["friction"]);
579+ });
580+});
582+describe("issues: a project's labels are capped", () => {
583+ it("a new label past 200 distinct ones is refused; one in use still goes on", () => {
584+ const { s } = store();
585+ const ids: number[] = [];
586+ for (let i = 0; i < 10; i++)
587+ ids.push(s.open(builder, { title: `t${i}`, labels: Array.from({ length: 20 }, (_, j) => `l${i * 20 + j}`) }).id);
588+ assert.equal(s.labelsInUse().length, 200);
589+ assert.throws(
590+ () => s.open(builder, { title: "one more", labels: ["l-new"] }),
591+ /this project has 200 labels, and 200 is the most/,
592+ );
593+ assert.throws(
594+ () => s.edit(builder, s.open(builder, { title: "room" }).id, { addLabels: ["l-new"] }),
595+ /200 is the most/,
596+ );
597+ assert.equal(s.edit(builder, ids[1]!, { addLabels: ["l0"], removeLabels: ["l20"] }).notified.length, 0);
598+ });
599+});
601+describe("issues: when an ask was first listed to its reader", () => {
602+ const get = (s: IssuesStore, path: string, headers: Record<string, string> = {}) =>
603+ issuesRoute(s, new Request(`https://issues.internal${path}`, { headers }));
605+ it("an agent's own waiting marks what it lists as seen, and says null for what it saw first just now", async () => {
606+ const { s, tick } = store();
607+ const id = s.ask(builder, { of: "security", question: "Is the cookie set right?" }).id;
608+ const read = async (path: string) =>
609+ ((await (await get(s, path)).json()) as { asks: { id: number; seen: number | null }[] }).asks;
610+ assert.deepEqual(await read("/p/abso/waiting?of=security"), [{ ...s.waiting("security")[0]!, seen: null }]);
611+ assert.equal(s.waiting("security")[0]!.seen, null, "a read of someone else's list marks nothing");
612+ tick();
613+ const first = await read("/p/abso/a/security/waiting");
614+ assert.equal(first[0]!.seen, null);
615+ const at = s.waiting("security")[0]!.seen;
616+ assert.equal(at, Date.parse("2026-10-07T20:00:01Z"));
617+ tick();
618+ assert.equal((await read("/p/abso/a/security/waiting"))[0]!.seen, at, "the first time stays");
619+ assert.equal(first[0]!.id, id);
620+ });
622+ it("another agent's read of the list marks nothing", async () => {
623+ const { s } = store();
624+ s.ask(builder, { of: "security", question: "Take abso.dev?" });
625+ await get(s, "/p/abso/a/fe/waiting");
626+ assert.equal(s.waiting("security")[0]!.seen, null);
627+ await get(s, "/p/abso/a/security/waiting");
628+ assert.notEqual(s.waiting("security")[0]!.seen, null);
629+ });
630+});
--- /dev/null
+++ b/server/test/issues/news.test.ts
@@ -0,0 +1,144 @@
1+// A reader's news (a person's or an agent's): answers to their asks, replies on asks
2+// they're in, @name mentions, and comments, edits and closes on issues they
3+// watch, by others, newest first, each read or not.
4+
5+import assert from "node:assert/strict";
6+import { DatabaseSync } from "node:sqlite";
7+import { describe, it } from "node:test";
8+import { IssuesStore, NEWS_MAX, type Sql } from "../../src/issues/store.ts";
9+
10+function sql(): Sql {
11+ const db = new DatabaseSync(":memory:");
12+ return {
13+ exec: (q, ...b) => {
14+ if (/^\s*(CREATE|ALTER)\b/i.test(q)) {
15+ db.exec(q);
16+ return { toArray: () => [] };
17+ }
18+ const rows = db.prepare(q).all(...(b as (string | number | null)[]));
19+ return { toArray: () => rows };
20+ },
21+ };
22+}
24+function store(): { s: IssuesStore; db: Sql; tick: () => number } {
25+ const db = sql();
26+ IssuesStore.createTables(db);
27+ let at = Date.parse("2026-10-10T03:00:00Z");
28+ return { s: new IssuesStore(db, () => at), db, tick: () => (at += 1000) };
29+}
31+const ann = { person: "acct_ann" };
32+const fay = { agent: "fay" };
34+describe("a reader's news", () => {
35+ it("gathers answers, replies, mentions and watched changes by others, newest first", () => {
36+ const { s, tick } = store();
37+ const id = s.open(ann, { title: "Sync is slow" }).id;
38+ const other = s.open(fay, { title: "Not watched" }).id;
39+ tick();
40+ const ask = s.ask(ann, { issue: id, of: "fay", question: "Which way?" });
41+ tick();
42+ s.reply(fay, ask.id, { text: "staging or live?", question: true });
43+ tick();
44+ s.answer(fay, ask.id, { words: "live" });
45+ tick();
46+ s.comment(fay, id, { text: "a comment on a watched issue" });
47+ tick();
48+ s.comment(fay, other, { text: "cc @ann, have a look" });
49+ tick();
50+ s.comment(fay, other, { text: "no name here, and an email ann@x.dev isn't one" });
51+ tick();
52+ s.edit(fay, id, { title: "Sync is slow on big projects" });
53+ tick();
54+ s.markDone(fay, id, 12);
55+ tick();
56+ s.comment(ann, id, { text: "my own comment isn't news" });
58+ const news = s.newsFor({ person: "acct_ann" }, ["ann"]);
59+ assert.deepEqual(
60+ news.map((n) => [n.kind, n.issue]),
61+ [
62+ ["closed", id],
63+ ["edit", id],
64+ ["mention", other],
65+ ["comment", id],
66+ ["answer", id],
67+ ["reply", id],
68+ ],
69+ );
70+ assert.equal(news.find((n) => n.kind === "answer")!.text, "live");
71+ assert.equal(news.find((n) => n.kind === "answer")!.ask, ask.id);
72+ assert.equal(news.find((n) => n.kind === "edit")!.text, "title");
73+ assert.ok(news.every((n) => !n.read && n.by === "fay"));
74+ assert.deepEqual(
75+ s
76+ .newsFor({ person: "acct_ann" }, [])
77+ .map((n) => n.kind)
78+ .includes("mention"),
79+ false,
80+ "no names, no mentions",
81+ );
82+ });
84+ it("marks read up to a time, never back, per person", () => {
85+ const { s, tick } = store();
86+ const id = s.open(ann, { title: "One" }).id;
87+ tick();
88+ s.comment(fay, id, { text: "first" });
89+ const mark = tick();
90+ tick();
91+ s.comment(fay, id, { text: "second" });
92+ assert.equal(s.markNewsRead({ person: "acct_ann" }, mark).read, mark);
93+ assert.equal(s.markNewsRead({ person: "acct_ann" }, 0).read, mark, "a mark never goes back");
94+ assert.deepEqual(
95+ s.newsFor({ person: "acct_ann" }, []).map((n) => [n.text, n.read]),
96+ [
97+ ["second", false],
98+ ["first", true],
99+ ],
100+ );
101+ assert.ok(s.newsFor({ person: "acct_bo" }, []).every((n) => !n.read));
102+ });
104+ it("pages back with before, keeps at most NEWS_MAX and cuts long text", () => {
105+ const { s, tick } = store();
106+ const id = s.open(ann, { title: "Busy" }).id;
107+ for (let i = 0; i < NEWS_MAX + 5; i++) {
108+ tick();
109+ s.comment(fay, id, { text: i === 0 ? "x".repeat(400) : `comment ${i}` });
110+ }
111+ const first = s.newsFor({ person: "acct_ann" }, []);
112+ assert.equal(first.length, NEWS_MAX);
113+ const older = s.newsFor({ person: "acct_ann" }, [], first.at(-1)!.at);
114+ assert.equal(older.length, 5);
115+ assert.equal(older.at(-1)!.text.length, 280);
116+ });
118+ it("doesn't move the change count", () => {
119+ const { s } = store();
120+ s.open(ann, { title: "One" });
121+ const before = s.changes();
122+ s.markNewsRead({ person: "acct_ann" }, 5);
123+ assert.equal(s.changes(), before);
124+ });
126+ it("is an agent's too: answers to its asks and @mentions of its name", () => {
127+ const { s, tick } = store();
128+ const lead = { agent: "lead" };
129+ const id = s.open(fay, { title: "Sync is slow" }).id;
130+ tick();
131+ const ask = s.ask(lead, { issue: id, of: "fay", question: "Which way?" });
132+ tick();
133+ s.answer(fay, ask.id, { words: "live" });
134+ tick();
135+ s.comment(fay, id, { text: "@lead it's done" });
136+ assert.deepEqual(
137+ s.newsFor(lead, ["lead"]).map((n) => [n.kind, n.by, n.text]),
138+ [
139+ ["mention", "fay", "@lead it's done"],
140+ ["answer", "fay", "live"],
141+ ],
142+ );
143+ });
144+});
--- /dev/null
+++ b/server/test/issues/serve.test.ts
@@ -0,0 +1,216 @@
1+// The Worker's way into issues: a key acts only as its own agent, a reader's key only reads, an ask goes only to
2+// the project's agents, and a write's news reaches the project object. Each IssueProject is an IssuesObject over
3+// node:sqlite, reached through fake namespaces shaped like Cloudflare's.
4+
5+import assert from "node:assert/strict";
6+import { DatabaseSync } from "node:sqlite";
7+import { describe, it } from "node:test";
8+import {
9+ type IssueNews,
10+ type IssuesAuth,
11+ type IssuesEnv,
12+ IssuesObject,
13+ issuesFetch,
14+ type ProjectHooks,
15+} from "../../src/issues/serve.ts";
16+import { SCHEMA } from "../../src/issues/store.ts";
18+function storage() {
19+ const db = new DatabaseSync(":memory:");
20+ return {
21+ sql: {
22+ exec: (q: string, ...b: unknown[]) => {
23+ if (/^\s*CREATE\b/i.test(q)) {
24+ db.exec(q);
25+ return { toArray: () => [] };
26+ }
27+ const rows = db.prepare(q).all(...(b as (string | number | null)[]));
28+ return { toArray: () => rows };
29+ },
30+ },
31+ transactionSync: <T>(action: () => T): T => {
32+ db.exec("SAVEPOINT t");
33+ try {
34+ const out = action();
35+ db.exec("RELEASE t");
36+ return out;
37+ } catch (e) {
38+ db.exec("ROLLBACK TO t");
39+ db.exec("RELEASE t");
40+ throw e;
41+ }
42+ },
43+ };
44+}
46+/** A namespace like Cloudflare's: idFromName gives the name back, get gives one object per name. */
47+function namespace<T extends object>(make: (name: string) => T) {
48+ const made = new Map<string, T>();
49+ return {
50+ idFromName: (name: string) => name,
51+ get: (id: never) => {
52+ const name = id as unknown as string;
53+ if (!made.has(name)) made.set(name, make(name));
54+ return made.get(name)!;
55+ },
56+ };
57+}
59+function world(hooks?: ProjectHooks) {
60+ const env: IssuesEnv = { ISSUES_DO: namespace(() => new IssuesObject(storage(), env)) };
61+ if (hooks) env.PROJECT = namespace(() => hooks);
62+ const waits: Promise<unknown>[] = [];
63+ const ctx = { waitUntil: (p: Promise<unknown>) => void waits.push(p) };
64+ const call = async (auth: IssuesAuth, method: string, rest: string, body?: unknown, project = "web") => {
65+ const r = await issuesFetch(
66+ new Request(`https://abso.example/issues/p/${project}${rest}`, {
67+ method,
68+ headers: { Authorization: "Bearer secret" },
69+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
70+ }),
71+ env,
72+ ctx,
73+ { project, rest: rest.replace(/\?.*$/, ""), auth },
74+ );
75+ await Promise.all(waits.splice(0));
76+ return { status: r.status, json: (await r.json()) as Record<string, any> };
77+ };
78+ return { env, call };
79+}
81+const token: IssuesAuth = { kind: "token" };
82+const leadKey: IssuesAuth = { kind: "key", agent: "lead", role: "writer" };
83+const readerKey: IssuesAuth = { kind: "key", agent: "watcher", role: "reader" };
85+describe("issuesFetch: who may do what", () => {
86+ it("the token acts as any agent; a key only as its own", async () => {
87+ const { call } = world();
88+ assert.equal((await call(token, "POST", "/a/fay/issue", { title: "Sync is slow" })).status, 200);
89+ assert.equal((await call(leadKey, "POST", "/a/lead/issue", { title: "Logo" })).status, 200);
90+ const other = await call(leadKey, "POST", "/a/fay/issue/1/comment", { text: "as fay" });
91+ assert.equal(other.status, 403);
92+ assert.match(other.json.error, /this key is lead's/);
93+ assert.equal((await call(leadKey, "GET", "/a/fay/waiting")).status, 403, "nor reads another's own list");
94+ assert.equal((await call(leadKey, "GET", "/issues")).json.issues.length, 2);
95+ });
97+ it("a reader's key reads and never writes", async () => {
98+ const { call } = world();
99+ await call(token, "POST", "/a/fay/issue", { title: "Sync is slow" });
100+ assert.equal((await call(readerKey, "GET", "/issue/1")).status, 200);
101+ assert.equal((await call(readerKey, "GET", "/search?q=sync")).json.hits.length, 1);
102+ const refused = await call(readerKey, "POST", "/a/watcher/issue/1/comment", { text: "hi" });
103+ assert.equal(refused.status, 403);
104+ assert.match(refused.json.error, /only reads/);
105+ });
107+ it("refuses a bad project or agent name, and an empty rest", async () => {
108+ const { call } = world();
109+ assert.equal((await call(token, "GET", "/issues", undefined, "no/such")).status, 404);
110+ assert.equal((await call(token, "POST", "/a/person:u1/issue", { title: "x" })).status, 400);
111+ assert.equal((await call(token, "GET", "")).status, 404);
112+ });
114+ it("each project has its own issues", async () => {
115+ const { call } = world();
116+ await call(token, "POST", "/a/fay/issue", { title: "Web's" });
117+ assert.equal((await call(token, "GET", "/issues", undefined, "other")).json.issues.length, 0);
118+ });
120+ it("attachments are 501, and a write naming one is refused before anything is written", async () => {
121+ const { call } = world();
122+ assert.equal((await call(token, "POST", "/a/fay/attachments")).status, 501);
123+ const named = await call(token, "POST", "/a/fay/issue", { title: "x", attachments: ["a0123456789ab"] });
124+ assert.equal(named.status, 501);
125+ assert.equal((await call(token, "GET", "/issues")).json.issues.length, 0);
126+ });
127+});
129+describe("issuesFetch: the project object", () => {
130+ it("an ask goes only to the project's agents", async () => {
131+ const { call } = world({ agents: async () => ["lead", "fay", "cloud"] });
132+ const refused = await call(token, "POST", "/a/lead/ask", { of: "Cloud Lead", question: "Which region?" });
133+ assert.equal(refused.status, 400);
134+ assert.match(refused.json.error, /isn't an agent in web, so nobody would hear the ask; did you mean cloud\?/);
135+ assert.equal((await call(token, "POST", "/a/lead/ask", { of: "cloud", question: "Which region?" })).status, 200);
136+ });
138+ it("without agents (or without PROJECT) the ask check is skipped", async () => {
139+ for (const hooks of [{}, undefined]) {
140+ const { call } = world(hooks);
141+ assert.equal((await call(token, "POST", "/a/lead/ask", { of: "anyone", question: "Q" })).status, 200);
142+ }
143+ });
145+ it("a write's news goes to the project from its writer; reads and refusals send none", async () => {
146+ const told: { project: string; items: IssueNews[] }[] = [];
147+ const { call } = world({
148+ news: async (project, items) => {
149+ told.push({ project, items });
150+ return [];
151+ },
152+ });
153+ await call(token, "POST", "/a/lead/issue", { title: "Sync is slow" });
154+ assert.equal(told.length, 0, "an issue for nobody in particular tells nobody");
155+ const asked = await call(token, "POST", "/a/lead/ask", { issue: 1, of: "fay", question: "Which way?" });
156+ assert.equal(told.length, 1);
157+ assert.equal(told[0]!.project, "web");
158+ assert.deepEqual(told[0]!.items, [
159+ {
160+ from: "lead",
161+ issue: 1,
162+ text: `lead asks fay a question on issue 1 ("Sync is slow"): "Which way?" Answer: abso answer ${asked.json.id} "..."`,
163+ to: ["fay"],
164+ },
165+ ]);
166+ await call(token, "GET", "/issue/1");
167+ await call(token, "POST", "/a/lead/answer/1", { words: "not mine to answer" });
168+ assert.equal(told.length, 1);
169+ });
171+ it("news with no news method on the project is dropped, and the write stands", async () => {
172+ const { call } = world({ agents: async () => ["lead", "fay"] });
173+ const asked = await call(token, "POST", "/a/lead/ask", { of: "fay", question: "Which way?" });
174+ assert.equal(asked.status, 200);
175+ assert.equal((await call(token, "GET", "/a/fay/waiting")).json.asks.length, 1);
176+ });
178+ it("an agent reads its news and marks it read", async () => {
179+ const { call } = world();
180+ await call(token, "POST", "/a/fay/issue", { title: "Sync is slow" });
181+ await call(token, "POST", "/a/lead/ask", { issue: 1, of: "fay", question: "Which way?" });
182+ await call(token, "POST", "/a/fay/answer/1", { words: "live" });
183+ const news = await call(leadKey, "GET", "/a/lead/news");
184+ assert.deepEqual(
185+ news.json.news.map((n: { kind: string; text: string; read: boolean }) => [n.kind, n.text, n.read]),
186+ [["answer", "live", false]],
187+ );
188+ const marked = await call(leadKey, "POST", "/a/lead/news/read", {});
189+ assert.equal(marked.status, 200);
190+ assert.equal((await call(leadKey, "GET", "/a/lead/news")).json.news[0].read, true);
191+ });
192+});
194+describe("IssuesObject", () => {
195+ it("runs every migration once, and again runs none", () => {
196+ const s = storage();
197+ const env: IssuesEnv = { ISSUES_DO: namespace(() => ({})) };
198+ assert.equal(new IssuesObject(s, env).migrations(), SCHEMA.length);
199+ assert.equal(new IssuesObject(s, env).migrations(), SCHEMA.length);
200+ });
202+ it("names who wrote each text: the opener, then whoever last edited it", async () => {
203+ const { call } = world();
204+ await call(token, "POST", "/a/fay/issue", { title: "Sync", description: "slow" });
205+ await call(token, "POST", "/a/lead/issue/1/edit", { title: "Sync is slow" });
206+ await call(token, "POST", "/a/lead/issue/1/comment", { text: "seen it" });
207+ const page = (await call(token, "GET", "/issue/1")).json;
208+ assert.deepEqual(page.issue.authorship, {
209+ title: { kind: "agent", actor: "lead", provenance: "native", authorField: "edits.by" },
210+ description: { kind: "agent", actor: "fay", provenance: "native", authorField: "issues.opened_by" },
211+ });
212+ assert.equal(page.comments[0].authorship.actor, "lead");
213+ const hit = (await call(token, "GET", "/search?q=slow")).json.hits[0];
214+ assert.equal(hit.issue.authorship.title.actor, "lead");
215+ });
216+});