{"issue":{"id":17,"title":"Open server: run abso on your own Cloudflare account","authorship":{"title":{"kind":"unknown","actor":null,"provenance":"unknown","authorField":null},"description":{"kind":"unknown","actor":null,"provenance":"unknown","authorField":null}},"parent":null,"status":"in progress","agent":"review","agents":["trials"],"blockedBy":[],"labels":[],"versions":[],"waitingOn":[],"opened":{"by":"review","at":1791906426237,"atIso":"2026-10-13T15:47:06.237Z"},"updated":1791908913797,"closed":null,"children":0,"description":"## What Christopher asked for\n\nChristopher, 2026-10-13: \"I don't think anyone would expect me to make the ENTIRE platform MIT licensed, but I do want anyone to be able to run abso servers that do most of the core things including running in cloudflare stuff for now\". Issues, asks and news belong in it. Agent VCS owns the split and reviews it.\n\nThis is also what the Cloudflare competition needs: an MIT repository, built on Workers and Artifacts, with instructions for running it. abso-core today has the client, the engine and the project logic, but no server that runs on Cloudflare.\n\n## The shape\n\nA new top-level `server/` folder in abso-core: one Worker that anyone deploys to their own Cloudflare account with `npx wrangler deploy`.\n\n**In it:**\n- The Worker entry: routes `/p/<project>/...` and `/p/<project>/a/<agent>/<op>` to a project Durable Object, using the existing `answer()` in `worker/project/http.ts`.\n- `ProjectObject`, one per project (SQLite): the append-only log, the blob store, and the engine (`Project`) loaded from them.\n- Cloudflare Artifacts: each project's shared is pushed out to its own Artifacts repo after a push, and plain-git pushes to that repo come back in.\n- Issues, asks, answers and the news feed: an `IssueProject` Durable Object per project, served from the same Worker under `/issues`.\n- Sign-in: one shared token (`ABSO_TOKEN`), with optional per-agent keys.\n\n**Left in the closed platform:** accounts and browser sign-in, boxes, CI and containers, pipelines and deploys, R2 version copies, the edge cache, meaning search, attachments, releases, the website, and ops.\n\n## Steps\n\n1. The project server: router, `ProjectObject`, blobs, the Artifacts push-out and intake, shared token. Proven with the stock client against `wrangler dev`: two agents join, edit and push, and a collision is held.\n2. Issues, asks and news in the same Worker. The client finds them at `<server>/issues` when no other issues server is set.\n3. README: run your own, step by step.\n4. A real deploy on a Cloudflare account, and a measured run with many projects and agents at once to show it scales out.\n\nLater: the platform's own Worker builds on `server/` instead of keeping a second copy of the core path. Offline-first (abso issue 617) comes after the split.","lines":null,"watchers":["review","trials","speed"]},"comments":[{"id":139,"by":"review","kind":"comment","text":"Christopher, 10:50 AM CT 2026-10-13: OK to prove the open server with a real deploy on their Cloudflare account, as a separate Worker (working name `abso-open`), after Agent VCS reviews the code. The scale run goes there too. Nothing touches prod or staging.","authorship":{"kind":"unknown","actor":null,"provenance":"unknown","authorField":null},"at":1791907018432,"atIso":"2026-10-13T15:56:58.432Z"},{"id":140,"by":"speed","kind":"comment","text":"## Step 1 draft is recorded (agent speed, not pushed)\n\n`server/` in abso-core: the Worker, `ProjectObject` (log, blobs, engine), the Artifacts push-out and plain-git intake, the shared token with optional per-agent keys, and the issues hook-up through `server/src/issues-entry.ts` (a stand-in until the issues builder's folder lands).\n\nProven against `wrangler dev --local` with the stock client: init, two agents join, edit and push, and a third change collides on line four and is held with the collision named. The transcript is `server/test/e2e-transcript.md`. Artifacts was not exercised locally. Waiting on Agent VCS's review before pushing.","authorship":{"kind":"unknown","actor":null,"provenance":"unknown","authorField":null},"at":1791907457918,"atIso":"2026-10-13T16:04:17.918Z"},{"id":141,"by":"speed","kind":"comment","text":"## Step 1 landed in version 150\n\n`server/` in abso-core is a Worker anyone can deploy with `cd server && npx wrangler deploy`. It has:\n\n- a router for the core project routes;\n- `ProjectObject`, holding each project's log, blobs and engine in SQLite;\n- shared pushed out to an Artifacts repo `abso-<project>`, and plain-git pushes taken back in;\n- the shared token (`ABSO_TOKEN`), with optional per-agent keys;\n- the issues hook-up, `server/src/issues-entry.ts`, which is a stand-in until the issues folder lands. Then it becomes one line: `export { IssueProject, issuesFetch, type IssuesAuth } from \"./issues/index.ts\";`.\n\nThe stock client was proven against `wrangler dev --local`: two agents join, edit and push, and a collision on the same line is held. The transcript is `server/test/e2e-transcript.md`.\n\n### Known gaps\n\n- Artifacts never ran locally: `--local` still binds it, so local runs set `ABSO_ARTIFACTS=off`. Push-out, plain-git intake and `git-remote` are untested apart from a unit test of the commit they write.\n- It's unconfirmed whether Artifacts takes repo names with capitals or \".\", which project names may have.\n- New project names aren't held to the platform's lowercase rule.\n- `abso key` wasn't run through the client; curl exercised the same routes.\n- Wrangler resolved to 4.150.0 under `^4.147.0`.\n- Keep `wrangler dev --local`: without it, the Artifacts binding makes wrangler connect to the signed-in account.","authorship":{"kind":"unknown","actor":null,"provenance":"unknown","authorField":null},"at":1791907531410,"atIso":"2026-10-13T16:05:31.410Z"},{"id":142,"by":"trials","kind":"comment","text":"## Issues, asks and news landed in version 151\n\n`server/src/issues/` is a trimmed port of the platform's issues Worker, now MIT. It has one `IssueProject` Durable Object per project, served from the same Worker under `/issues/p/<project>/...`. `server/src/issues-entry.ts` is now the one line that exports it.\n\n**Kept:** issues, comments, labels, parents, blocked by, watchers, edits, drafts, asks, answers, acks, replies, withdraw, waiting, asked, answered, claims and versions. Also the change count, full-text search (FTS5), the per-writer rate limit, and each reader's news feed, now for agents too: `GET /a/<agent>/news` and `POST /a/<agent>/news/read`.\n\n**Cut:** the workflow and release stores, the prose authorship records, meaning search, copies and export, seen and read marks, the edge cache, svg, `/admin`, and the website's person routes. Attachments answer 501. Authorship on each text now comes from the column that names its writer.\n\n**Access rules:** the shared token acts as any agent. A key acts only as its own agent, and a reader's key only reads. An ask goes only to an agent in the project. A write's news goes through `ProjectObject.news()` to the issue's claimers and the agents it names.\n\n**Client:** with no issues server named in `~/.abso/servers.json`, `ABSO_ISSUES_SERVER` or the built-in map, the client uses `<server origin>/issues`. Prod is unchanged: `api.abso.dev` still goes to `issues.abso.dev`. The token goes to an issues server at a path exactly as it goes to that server's origin.\n\n**Checks:** `npx biome ci .` and `npm run check` pass: 1,077 tests, 1,075 passed, 0 failed, 2 skipped. That includes 50 issues tests and the server typecheck.\n\n**End to end:** the stock client ran against `wrangler dev --local` with Artifacts off, an invented token, an empty HOME and no issues server named. Agent alice opened an issue and bob commented on it. An ask from alice to carol was refused, because carol isn't an agent in the project. Alice's ask to bob reached bob as news and in `waiting`. Bob answered, and alice heard the answer as news. The transcript is appended to `server/test/e2e-transcript.md`.\n\n### Known gaps\n\n- **Staging fallback:** staging is unchanged on machines whose `servers.json` names its issues server. A machine that names none now tries `<staging server>/issues` and gets a 404, where before it said there was no Issues Worker.\n- **No people:** the open server has no signed-in people, so an ask to `person:<id>` is refused by the agent check.\n- **Attachments:** not kept. An upload, or a write that names an attachment, answers 501.\n- **Claims and done:** `claim`, `unclaim` and `done` are wired up by the project object. What `done` returns is ignored for now.\n- **Cut for now:** meaning search, copies and export, and seen marks. Authorship comes from the writer columns, not the platform's prose records.","authorship":{"kind":"unknown","actor":null,"provenance":"unknown","authorField":null},"at":1791907852355,"atIso":"2026-10-13T16:10:52.355Z"},{"id":143,"by":"review","kind":"comment","text":"## Deployed: abso-open on Christopher's Cloudflare account\n\nVersion 151 is deployed as the Worker `abso-open` at https://abso-open.chrisazy.workers.dev, by Agent VCS with Christopher's authorization. Its shared token is set; without it every call answers 401.\n\n**End to end with the stock client against the real deployment (project `demo1`):**\n- `init` by alice, `join` by bob, and both push (versions 1 and 2).\n- Both change line 4: alice's push is version 3, and bob's is held, naming the collision.\n- Alice opens issue 1 and asks bob; bob sees the ask in `waiting`.\n- **Artifacts:** shared reached the repo `abso-demo1`. A plain `git clone` shows version 3 (`abso-version: 3`, author alice) about a minute after the push, with both agents' lines in `hello.txt`.\n\nNext: the scale run (many projects and agents at once) with a harness in `server/scale/`.","authorship":{"kind":"unknown","actor":null,"provenance":"unknown","authorField":null},"at":1791908166975,"atIso":"2026-10-13T16:16:06.975Z"},{"id":144,"by":"speed","kind":"comment","text":"## Scale ramp on abso-open (version 152)\n\nThe scale harness is `server/scale/scale.mjs` (README beside it). It plays agents over HTTP the way the client does: sync, starting, record, publish and news, plus init with one blob per project. Results are in `server/scale/results/scale-mv6vzxzj-*.json`.\n\nSettings: 3 rounds per agent, overlap 0.2 (a fifth of rounds edit one of the first 3 lines of a shared hot file), 800 requests in flight. Artifacts lag was timed on 5 sampled projects per stage.\n\n| Stage (projects × agents) | Agents | Pushes | Pushes/s | Push p50 | Push p95 | Held (still held after one retry) | Errors | Artifacts lag p50 |\n|---|---|---|---|---|---|---|---|---|\n| 1 × 1 | 1 | 3 | 1.1 | 137 ms | 177 ms | 0 | 0 | 65 s |\n| 10 × 5 | 50 | 150 | 39.9 | 205 ms | 389 ms | 4 (0) | 0 | 65 s |\n| 50 × 10 | 500 | 1,456 | 190 | 231 ms | 405 ms | 113 (44) | 0 | 62 s |\n| 100 × 10 | 1,000 | 2,921 | 279 | 375 ms | 548 ms | 258 (79) | 0 | 55 s |\n| 200 × 20 | 4,000 | 11,073 | 419 | 372 ms | 579 ms | 1,983 (926) | 1 (a 502 on publish) | 41 s |\n\nWhat it shows:\n\n- **Throughput:** total pushes a second grew with the number of projects, from 40 to 419. Every sampled project reached Artifacts.\n- **Latency:** push latency rose from about 200 ms to about 370 ms between 10 and 100 projects, then stayed flat at 200 × 20.\n- **The harness was the ceiling at 200 × 20:** 1,926 requests a second is close to 800 requests in flight divided by the latency. That stage measures this machine's limit, not the server's.\n- **Pulls are the slow operation:** sync p50 was 1.4 s at 50 × 10, and p95 up to 4 s.\n- **Held pushes are contention by design:** 20 agents a project on 3 hot lines.\n- **Artifacts lag** (41 to 65 s) is mostly the server's push out, which runs at most once a minute per project.","authorship":{"kind":"unknown","actor":null,"provenance":"unknown","authorField":null},"at":1791908913797,"atIso":"2026-10-13T16:28:33.797Z"}],"edits":[],"asks":[],"claims":[{"agent":"trials","change":1799,"since":1791906498134}],"children":[],"publicProjects":[],"fileRefs":{},"parent":null,"change":{"id":1799,"agent":"trials","title":"Open server: issues, asks and news","kind":"note","note":{"text":"Open server: issues, asks and news","files":[]},"issue":17,"draft":null,"time":1791906497794,"timeIso":"2026-10-13T15:48:17.794Z","open":false,"versions":[{"version":151,"draft":null,"message":"Open server: issues, asks and news, served at <server>/issues, and the client finds them there when no issues server is named","time":1791907770251,"timeIso":"2026-10-13T16:09:30.251Z","files":["client/src/core.ts","client/src/issues.ts","client/test/client.test.ts","client/test/issues.test.ts","server/src/issues-entry.ts","server/src/issues/index.ts","server/src/issues/routes.ts","server/src/issues/seats.ts","server/src/issues/serve.ts","server/src/issues/store.ts","server/test/e2e-transcript.md","server/test/issues/ask-threads.test.ts","server/test/issues/changes.test.ts","server/test/issues/issues.test.ts","server/test/issues/news.test.ts","server/test/issues/serve.test.ts"]}],"files":["client/src/core.ts","client/src/issues.ts","client/test/client.test.ts","client/test/issues.test.ts","server/src/issues-entry.ts","server/src/issues/index.ts","server/src/issues/routes.ts","server/src/issues/seats.ts","server/src/issues/serve.ts","server/src/issues/store.ts","server/test/e2e-transcript.md","server/test/issues/ask-threads.test.ts","server/test/issues/changes.test.ts","server/test/issues/issues.test.ts","server/test/issues/news.test.ts","server/test/issues/serve.test.ts"],"settled":[],"refusals":[],"notes":[],"reviewers":[]},"detail":{"diff":{"from":150,"to":151,"files":[{"path":"client/src/core.ts","added":31,"removed":5,"diff":"--- a/client/src/core.ts\n+++ b/client/src/core.ts\n@@ -107,6 +107,22 @@\n }\n \n /**\n+ * A server's base: its origin and any path, without a trailing slash (https://x.example/issues), or undefined\n+ * for anything else, a query, a fragment or a user name included. Plain string work, as serverOrigin.\n+ */\n+export function serverBase(s: string): string | undefined {\n+\tconst m = /^(https?):\\/\\/([^/?#\\\\]+)((?:\\/[^?#\\\\]*)?)$/i.exec(s.trim());\n+\tif (!m || m[2]!.includes(\"@\")) return undefined;\n+\treturn `${m[1]!.toLowerCase()}://${m[2]!.toLowerCase()}${m[3]!.replace(/\\/+$/, \"\")}`;\n+}\n+\n+/** The origin of a server given with or without a path (serverBase), or undefined. */\n+export function baseOrigin(s: string): string | undefined {\n+\tconst base = serverBase(s);\n+\treturn base === undefined ? undefined : serverOrigin(base.replace(/^(https?:\\/\\/[^/]+).*$/i, \"$1\"));\n+}\n+\n+/**\n  * This machine's servers, from ~/.abso/servers.json:\n  * {\"servers\": {\"<server>\": {\"issues\": \"<its Issues Worker>\"}}}. Each server\n  * named there, and each Issues Worker it names, may receive the token, and a\n@@ -130,10 +146,10 @@\n \t\t\t\tif (o === undefined) continue;\n \t\t\t\ttrusted.push(o);\n \t\t\t\tconst i = (about as { issues?: unknown } | null)?.issues;\n-\t\t\t\tconst io = typeof i === \"string\" ? serverOrigin(i) : undefined;\n+\t\t\t\tconst io = typeof i === \"string\" ? serverBase(i) : undefined;\n \t\t\t\tif (io !== undefined) {\n \t\t\t\t\tissues[o] = io;\n-\t\t\t\t\ttrusted.push(io);\n+\t\t\t\t\ttrusted.push(baseOrigin(io)!);\n \t\t\t\t}\n \t\t\t}\n \t} catch {}\n@@ -146,14 +162,24 @@\n }\n \n /**\n- * The Issues Worker beside an avcs server (#54): this machine's servers.json\n- * first, then abso's own. ABSO_ISSUES_SERVER overrides both (issues.ts).\n+ * The Issues Worker beside an avcs server: this machine's servers.json\n+ * first, then abso's own, else the server's own /issues, where the open\n+ * server keeps them. ABSO_ISSUES_SERVER overrides all three (issues.ts).\n  */\n export function issuesServerFor(server: string, machine?: MachineServers): string | undefined {\n \tconst o = serverOrigin(server);\n-\treturn o === undefined ? undefined : (machine?.issues[o] ?? ISSUES_SERVERS[o]);\n+\treturn o === undefined ? undefined : (machine?.issues[o] ?? ISSUES_SERVERS[o] ?? `${o}/issues`);\n }\n \n+/**\n+ * Whether the token may go to an Issues Worker: as to its origin (tokenGoesTo), since it may sit at a path on\n+ * its server, as the open server's do at <server>/issues. A query, a fragment or a user name is refused.\n+ */\n+export function tokenGoesToIssues(server: string, trusted?: string): boolean {\n+\tconst o = baseOrigin(server);\n+\treturn o !== undefined && tokenGoesTo(o, trusted);\n+}\n+\n /** Whether the token may go to `server`: TOKEN_SERVERS, `trusted` (trustedList), or this machine. Plain string work: the mod has no URL. */\n export function tokenGoesTo(server: string, trusted?: string): boolean {\n \tconst origin = serverOrigin;"},{"path":"client/src/issues.ts","added":2,"removed":2,"diff":"--- a/client/src/issues.ts\n+++ b/client/src/issues.ts\n@@ -23,7 +23,7 @@\n import { bool, type Parsed, str, UsageError } from \"./args.ts\";\n import { type Env, type Output, open, plural } from \"./commands.ts\";\n import { type Config, readMachineServers, trustedServers } from \"./config.ts\";\n-import { issuesServerFor, tokenGoesTo } from \"./core.ts\";\n+import { issuesServerFor, tokenGoesToIssues } from \"./core.ts\";\n import { fromEnv } from \"./env-names.ts\";\n import { ignoredHere } from \"./fetch.ts\";\n import { loadIgnore, relativeTo } from \"./folder.ts\";\n@@ -41,7 +41,7 @@\n \t\tthrow new UsageError(\n \t\t\t`${config.server} has no Issues Worker beside it that abso knows; ~/.abso/servers.json or ABSO_ISSUES_SERVER names one`,\n \t\t);\n-\tif (config.token !== undefined && !tokenGoesTo(server, trustedServers(env.env))) {\n+\tif (config.token !== undefined && !tokenGoesToIssues(server, trustedServers(env.env))) {\n \t\tthrow new UsageError(\n \t\t\t`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.`,\n \t\t);"},{"path":"client/test/client.test.ts","added":1,"removed":1,"diff":"--- a/client/test/client.test.ts\n+++ b/client/test/client.test.ts\n@@ -1556,7 +1556,7 @@\n \t\tassert.equal(tokenGoesTo(\"https://sneaky.example\", trusted), false);\n \t\tassert.equal(tokenGoesTo(\"https://evil.example\", trusted), false);\n \t\tassert.equal(issuesServerFor(\"https://abso.example\", machine), \"https://issues.abso.example\");\n-\t\tassert.equal(issuesServerFor(\"https://staging.abso.example\", machine), undefined);\n+\t\tassert.equal(issuesServerFor(\"https://staging.abso.example\", machine), \"https://staging.abso.example/issues\");\n \t\tassert.deepEqual(machineServers(\"{not json\"), { trusted: [], issues: {} });\n \t\tassert.deepEqual(machineServers(undefined), { trusted: [], issues: {} });\n \t\tassert.equal(trustedList(\"https://a.example\", machine).split(\",\")[0], \"https://a.example\");"},{"path":"client/test/issues.test.ts","added":36,"removed":10,"diff":"--- a/client/test/issues.test.ts\n+++ b/client/test/issues.test.ts\n@@ -13,7 +13,7 @@\n import { join } from \"node:path\";\n import { after, before, describe, it } from \"node:test\";\n import { readConfig, readMachineServers } from \"../src/config.ts\";\n-import { issuesServerFor, tokenGoesTo } from \"../src/core.ts\";\n+import { issuesServerFor, tokenGoesTo, tokenGoesToIssues } from \"../src/core.ts\";\n import { issuePage, searchLines } from \"../src/issues.ts\";\n import type { IssuePage } from \"../src/issues-wire.ts\";\n import { main } from \"../src/main.ts\";\n@@ -176,16 +176,42 @@\n \t\tassert.equal(r.exit, 1, r.out);\n \t\tassert.match(r.out, /sends your token only to its own servers and this machine/);\n \t\tassert.equal(seen.length, before);\n-\t\t// A server with no Issues Worker beside it, and none named.\n-\t\tconst { AVCS_ISSUES_SERVER: _, ...without } = ENV();\n-\t\tconst none = await avcs(dave, [\"waiting\"], without);\n-\t\tassert.notEqual(none.exit, 0);\n-\t\tassert.match(\n-\t\t\tnone.out,\n-\t\t\t/has no Issues Worker beside it that abso knows; ~\\/\\.abso\\/servers\\.json or ABSO_ISSUES_SERVER names one/,\n-\t\t);\n \t});\n \n+\tit(\"with no Issues Worker named, uses the server's own /issues, as the open server keeps them\", () => {\n+\t\tassert.equal(issuesServerFor(\"https://abso.example\"), \"https://abso.example/issues\");\n+\t\tassert.equal(issuesServerFor(\"https://Abso.Example/\"), \"https://abso.example/issues\");\n+\t\tassert.equal(issuesServerFor(\"http://localhost:8787\"), \"http://localhost:8787/issues\");\n+\t\tassert.equal(issuesServerFor(\"not a server\"), undefined);\n+\t\t// abso's hosted server keeps its own Issues Worker, and servers.json still comes first.\n+\t\tassert.equal(issuesServerFor(\"https://api.abso.dev\"), \"https://issues.abso.dev\");\n+\t\tconst machine = {\n+\t\t\ttrusted: [],\n+\t\t\tissues: { \"https://staging.abso.example\": \"https://issues-staging.abso.example\" },\n+\t\t};\n+\t\tassert.equal(issuesServerFor(\"https://staging.abso.example\", machine), \"https://issues-staging.abso.example\");\n+\t\t// The token goes to <server>/issues exactly where it goes to <server>.\n+\t\tassert.ok(tokenGoesToIssues(\"https://api.abso.dev/issues\"));\n+\t\tassert.ok(tokenGoesToIssues(\"http://localhost:8787/issues\"));\n+\t\tassert.ok(tokenGoesToIssues(\"https://mine.example/issues\", \"https://mine.example\"));\n+\t\tassert.equal(tokenGoesToIssues(\"https://evil.example/issues\"), false);\n+\t\tassert.equal(tokenGoesToIssues(\"https://api.abso.dev@evil.example/issues\"), false);\n+\t\tassert.equal(tokenGoesToIssues(\"https://api.abso.dev/issues?x=1\"), false);\n+\t\tassert.equal(tokenGoesToIssues(\"http://mine.example/issues\", \"http://mine.example\"), false, \"plain http only here\");\n+\t\t// The server itself still takes no path.\n+\t\tassert.equal(tokenGoesTo(\"https://api.abso.dev/issues\"), false);\n+\t});\n+\n+\tit(\"calls <issues server>/p/<project>/... when the Issues Worker is at a path\", async () => {\n+\t\tconst fay = await folder(\"fay\");\n+\t\tconst before = seen.length;\n+\t\tconst env = { ...ENV(), AVCS_ISSUES_SERVER: `${issuesUrl}/issues` };\n+\t\tconst r = await main([\"ask\", \"7\"], { cwd: fay, env, write: () => {} });\n+\t\tassert.equal(r.exit, 0, r.stdout + r.stderr);\n+\t\tconst { project } = readConfig(fay);\n+\t\tassert.deepEqual(seen.slice(before), [`GET /issues/p/${project}/ask/7`]);\n+\t});\n+\n \tit(\"finds a server's Issues Worker in this machine's servers.json, and may send it the token\", async () => {\n \t\tconst dir = mkdtempSync(join(tmpdir(), \"abso-servers-\"));\n \t\tdirs.push(dir);\n@@ -198,7 +224,7 @@\n \t\tassert.ok(seen.length > before, \"the call went to the Issues Worker servers.json names\");\n \t\tconst machine = readMachineServers({ AVCS_SERVERS_FILE: file });\n \t\tassert.equal(issuesServerFor(fake.url, machine), issuesUrl);\n-\t\tassert.equal(issuesServerFor(\"https://abso.example\", machine), undefined);\n+\t\tassert.equal(issuesServerFor(\"https://abso.example\", machine), \"https://abso.example/issues\");\n \t\t// abso's own server and its Issues Worker are built in.\n \t\tassert.ok(tokenGoesTo(\"https://api.abso.dev\"));\n \t\tassert.ok(tokenGoesTo(\"https://issues.abso.dev\"));"},{"path":"server/src/issues-entry.ts","added":1,"removed":27,"diff":"--- a/server/src/issues-entry.ts\n+++ b/server/src/issues-entry.ts\n@@ -1,27 +1 @@\n-// Where the router meets issues, asks and news (server/src/issues/, built alongside this file). Until that folder\n-// lands, this is a stand-in with the same exports, so the Worker builds and its tests run. When it lands, this file\n-// becomes one line:\n-//\n-//   export { IssueProject, issuesFetch } from \"./issues/index.ts\";\n-//\n-// The agreed interface: issuesFetch(request, env, ctx, {project, rest, auth}), where rest is the path after\n-// /issues/p/<project> and auth is {kind: \"token\"} or {kind: \"key\", agent, role}. The router has checked auth before it\n-// calls. The issues code reaches the project through env.PROJECT and its RPC methods agents(project) and\n-// news(project, items) on ProjectObject.\n-\n-import { DurableObject } from \"cloudflare:workers\";\n-import type { Env } from \"./env.ts\";\n-import type { KeyRole } from \"./keys.ts\";\n-\n-export type IssuesAuth = { kind: \"token\" } | { kind: \"key\"; agent: string; role: KeyRole };\n-\n-export class IssueProject extends DurableObject<Env> {}\n-\n-export async function issuesFetch(\n-\t_request: Request,\n-\t_env: Env,\n-\t_ctx: ExecutionContext,\n-\t_where: { project: string; rest: string; auth: IssuesAuth },\n-): Promise<Response> {\n-\treturn Response.json({ error: \"issues aren't on this server yet\" }, { status: 404 });\n-}\n+export { IssueProject, type IssuesAuth, issuesFetch } from \"./issues/index.ts\";"},{"path":"server/src/issues/index.ts","added":64,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues/index.ts\n@@ -0,0 +1,64 @@\n+// Issues, asks and news for the open server: one IssueProject Durable Object per project (bound as ISSUES_DO,\n+// named by the project's name), reached through issuesFetch from the Worker's /issues/p/:project/... routes.\n+// The logic is in serve.ts, store.ts and routes.ts, which run under node --test without Cloudflare's runtime.\n+//\n+//   GET  /issues/p/:project/issues[?status=&agent=&parent=&label=&open=1]   issues, most recently updated first\n+//   GET  /issues/p/:project/issue/:n                                        one issue with its comments, edits and asks\n+//   GET  /issues/p/:project/search?q=[&limit=]                               full-text search\n+//   GET  /issues/p/:project/labels | changes | waiting[?of=] | ask/:n | asked?by= | answered?of=\n+//   GET  /issues/p/:project/a/:agent/waiting | asked | drafts | news[?before=]\n+//   POST /issues/p/:project/a/:agent/issue | ask | answer/:n | ack/:n | reply/:n | withdraw/:n\n+//   POST /issues/p/:project/a/:agent/issue/:n/comment | edit | drop | reopen | done\n+//   POST /issues/p/:project/a/:agent/draft | draft/:n/open | draft/:n/delete | news/read\n+\n+import { DurableObject } from \"cloudflare:workers\";\n+import { type IssuesEnv, IssuesObject } from \"./serve.ts\";\n+import type { News } from \"./store.ts\";\n+\n+export {\n+\ttype IssueNews,\n+\ttype IssuesAuth,\n+\ttype IssuesEnv,\n+\tissuesFetch,\n+\ttype NamespaceLike,\n+\ttype ProjectHooks,\n+\ttype WaitUntil,\n+} from \"./serve.ts\";\n+\n+/** One project's issues, in its own SQLite. */\n+export class IssueProject extends DurableObject<IssuesEnv> {\n+\tprivate readonly issues: IssuesObject;\n+\n+\tconstructor(ctx: DurableObjectState, env: IssuesEnv) {\n+\t\tsuper(ctx, env);\n+\t\t// The migrations are synchronous SQL, so they finish here, before the object takes any request.\n+\t\tthis.issues = new IssuesObject(\n+\t\t\t{ sql: ctx.storage.sql, transactionSync: (action) => ctx.storage.transactionSync(action) },\n+\t\t\tenv,\n+\t\t);\n+\t}\n+\n+\tasync fetch(request: Request): Promise<Response> {\n+\t\treturn this.issues.fetch(request);\n+\t}\n+\n+\t/** A start note names the issue; `change` is the note's log position. A missing or closed issue is ignored. */\n+\tasync claim(agent: string, issue: number, change: number): Promise<void> {\n+\t\tthis.issues.store.claim(agent, issue, change);\n+\t}\n+\n+\t/** The start note ended without finishing the issue. */\n+\tasync unclaim(agent: string, issue: number): Promise<void> {\n+\t\tthis.issues.store.unclaim(agent, issue);\n+\t}\n+\n+\t/** publish --done finished the issue in `version`: done, and its news for the project to deliver. */\n+\tasync done(agent: string, issue: number, version: number): Promise<{ news?: News }> {\n+\t\treturn this.issues.store.done(agent, issue, version);\n+\t}\n+\n+\t/** How many schema migrations this object has run. */\n+\tasync schema(): Promise<{ migrations: number }> {\n+\t\treturn { migrations: this.issues.migrations() };\n+\t}\n+}"},{"path":"server/src/issues/routes.ts","added":212,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues/routes.ts\n@@ -0,0 +1,212 @@\n+// The issues routes, apart from the Durable Object so they run under node --test with a store on node:sqlite.\n+// Paths are the client's: /p/:project/<read> for reads, and /p/:project/a/:agent/<op> for an agent's writes and\n+// its own reads (waiting, asked, drafts, news). Who may call which path was decided before a request gets here.\n+\n+import { type Actor, IssuesError, type IssuesStore, who } from \"./store.ts\";\n+\n+/** The largest request body a write takes, in bytes: far above any text a write may hold. */\n+export const BODY_MAX = 1024 * 1024;\n+\n+export const json = (status: number, body: unknown): Response =>\n+\tnew Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } });\n+\n+/**\n+ * One request to a project's issues. `seatError` says why a new ask's `of` isn't an agent in the project, or null\n+ * when it is (or when the project can't say).\n+ */\n+export async function issuesRoute(\n+\tstore: IssuesStore,\n+\trequest: Request,\n+\tseatError?: (of: string) => Promise<string | null>,\n+): Promise<Response> {\n+\ttry {\n+\t\treturn await route(store, request, seatError);\n+\t} catch (e) {\n+\t\tif (e instanceof IssuesError) {\n+\t\t\tconst answer = json(e.status, { error: e.message });\n+\t\t\tif (e.retryAfter !== undefined) answer.headers.set(\"Retry-After\", String(e.retryAfter));\n+\t\t\treturn answer;\n+\t\t}\n+\t\tthrow e;\n+\t}\n+}\n+\n+async function route(\n+\tstore: IssuesStore,\n+\trequest: Request,\n+\tseatError?: (of: string) => Promise<string | null>,\n+): Promise<Response> {\n+\tconst url = new URL(request.url);\n+\tconst m = /^\\/p\\/([^/]+)(?:\\/a\\/([^/]+))?\\/(.+)$/.exec(url.pathname);\n+\tif (!m) return json(404, { error: \"no such issues route\" });\n+\tconst agent = m[2] === undefined ? undefined : decodeURIComponent(m[2]);\n+\tconst rest = m[3]!;\n+\tconst q = url.searchParams;\n+\tconst actor: Actor | undefined = agent !== undefined ? { agent } : undefined;\n+\tif (rest === \"attachments\" || rest.startsWith(\"attachments/\"))\n+\t\treturn json(501, { error: \"this server doesn't keep attachments\" });\n+\t// A reader sees only their own drafts.\n+\tif (request.method === \"GET\" && rest === \"drafts\") {\n+\t\tif (!actor) return json(403, { error: \"drafts are an agent's: /a/:agent/drafts\" });\n+\t\treturn json(200, { drafts: store.drafts(actor) });\n+\t}\n+\tif (request.method === \"GET\") {\n+\t\tif (actor) {\n+\t\t\t// An agent's own waiting list, which marks what it lists as seen.\n+\t\t\tif (rest === \"waiting\") return json(200, { asks: store.waiting(who(actor), who(actor)) });\n+\t\t\t// The asks an agent sent, open then the latest answered.\n+\t\t\tif (rest === \"asked\") return json(200, { asks: store.asked(who(actor)) });\n+\t\t\t// An agent's news here: answers, replies, @mentions, and changes on issues it watches, by others.\n+\t\t\tif (rest === \"news\") {\n+\t\t\t\tconst before = q.get(\"before\");\n+\t\t\t\treturn json(200, {\n+\t\t\t\t\tnews: store.newsFor(actor, [who(actor)], before === null ? undefined : Number(before) || undefined),\n+\t\t\t\t});\n+\t\t\t}\n+\t\t\treturn json(404, {\n+\t\t\t\terror: \"an agent's reads are waiting, asked, drafts and news; other reads have no /a/:agent/\",\n+\t\t\t});\n+\t\t}\n+\t\tif (rest === \"issues\") {\n+\t\t\tconst parent = q.get(\"parent\");\n+\t\t\treturn json(200, {\n+\t\t\t\tissues: store.list({\n+\t\t\t\t\t...(q.get(\"status\") ? { status: q.get(\"status\")! } : {}),\n+\t\t\t\t\t...(q.get(\"agent\") ? { agent: q.get(\"agent\")! } : {}),\n+\t\t\t\t\t...(parent ? { parent: Number(parent) } : {}),\n+\t\t\t\t\t// ?label=a,b (or label repeated): issues with every one of them.\n+\t\t\t\t\t...(q.getAll(\"label\").length > 0 ? { labels: q.getAll(\"label\").flatMap((l) => l.split(\",\")) } : {}),\n+\t\t\t\t\topen: q.get(\"open\") === \"1\",\n+\t\t\t\t}),\n+\t\t\t});\n+\t\t}\n+\t\tif (rest === \"labels\") return json(200, { labels: store.labelsInUse() });\n+\t\t// The change count: what a reader can cache issue reads under, cheap enough to ask every request.\n+\t\tif (rest === \"changes\") return json(200, { changes: store.changes() });\n+\t\tif (rest === \"search\") {\n+\t\t\tconst limit = Number(q.get(\"limit\") ?? \"20\");\n+\t\t\treturn json(200, { hits: store.search((q.get(\"q\") ?? \"\").slice(0, 200), Number.isInteger(limit) ? limit : 20) });\n+\t\t}\n+\t\tconst one = /^issue\\/(\\d+)$/.exec(rest);\n+\t\tif (one) return json(200, store.page(Number(one[1])));\n+\t\tif (rest === \"waiting\") return json(200, { asks: store.waiting(q.get(\"of\") ?? undefined) });\n+\t\tconst ask = /^ask\\/(\\d+)$/.exec(rest);\n+\t\tif (ask) return json(200, { ask: store.askThread(Number(ask[1])) });\n+\t\tif (rest === \"asked\") {\n+\t\t\tconst by = q.get(\"by\");\n+\t\t\tif (!by) return json(400, { error: \"asked needs ?by=<agent>\" });\n+\t\t\treturn json(200, { asks: store.asked(by) });\n+\t\t}\n+\t\tif (rest === \"answered\") {\n+\t\t\tconst of = q.get(\"of\");\n+\t\t\tif (!of) return json(400, { error: \"answered needs ?of=<agent>\" });\n+\t\t\treturn json(200, { asks: store.answered(of) });\n+\t\t}\n+\t\treturn json(404, { error: \"no such issues route\" });\n+\t}\n+\tif (request.method !== \"POST\") return json(405, { error: \"issues takes GET and POST\" });\n+\tif (!actor) return json(403, { error: \"a write is an agent's: /p/:project/a/:agent/<op>\" });\n+\tlet body: Record<string, unknown> = {};\n+\tconst raw = new TextDecoder().decode(await readCapped(request, BODY_MAX));\n+\tif (raw.trim() !== \"\") {\n+\t\ttry {\n+\t\t\tbody = JSON.parse(raw) as Record<string, unknown>;\n+\t\t} catch {\n+\t\t\treturn json(400, { error: \"the body is JSON\" });\n+\t\t}\n+\t\tif (typeof body !== \"object\" || body === null || Array.isArray(body))\n+\t\t\treturn json(400, { error: \"the body is a JSON object\" });\n+\t}\n+\t// Drafts and news marks make no news, so they don't count toward the writer's limit.\n+\tif (rest === \"draft\") return json(200, { ok: true, ...store.saveDraft(actor, body) });\n+\tconst deleting = /^draft\\/(\\d+)\\/delete$/.exec(rest);\n+\tif (deleting) {\n+\t\tstore.deleteDraft(actor, Number(deleting[1]));\n+\t\treturn json(200, { ok: true });\n+\t}\n+\tif (rest === \"news/read\") {\n+\t\tconst at = body.at === undefined ? Date.now() : body.at;\n+\t\tif (typeof at !== \"number\" || !Number.isFinite(at)) return json(400, { error: \"at is a time in milliseconds\" });\n+\t\treturn json(200, { ok: true, ...store.markNewsRead(actor, at) });\n+\t}\n+\tconst write = writeFor(store, actor, rest, body);\n+\tif (!write) return json(404, { error: \"no such issues route\" });\n+\t// An ask goes to an agent in the project.\n+\tif (rest === \"ask\" && seatError && typeof body.of === \"string\") {\n+\t\tconst refused = await seatError(body.of);\n+\t\tif (refused) return json(400, { error: refused });\n+\t}\n+\tstore.checkLimit(actor);\n+\tconst done = write();\n+\tstore.wrote(actor);\n+\t// Every write answers the change count it made, for the next read.\n+\treturn json(200, { ok: true, ...done, changes: store.changes() });\n+}\n+\n+/**\n+ * The body, read a chunk at a time and refused (413) the moment it passes `max`, so a body with no\n+ * Content-Length, or one that lies, never puts more than `max` in memory.\n+ */\n+export async function readCapped(request: Request, max: number): Promise<Uint8Array<ArrayBuffer>> {\n+\tconst declared = Number(request.headers.get(\"Content-Length\") ?? \"0\");\n+\tif (declared > max) throw new IssuesError(`the body is ${declared} bytes; the most is ${max}`, 413);\n+\tif (!request.body) return new Uint8Array(0);\n+\tconst reader = request.body.getReader();\n+\tconst parts: Uint8Array[] = [];\n+\tlet size = 0;\n+\tfor (;;) {\n+\t\tconst { done, value } = await reader.read();\n+\t\tif (done) break;\n+\t\tsize += value.length;\n+\t\tif (size > max) {\n+\t\t\tawait reader.cancel();\n+\t\t\tthrow new IssuesError(`the body is over ${max} bytes, the most there can be`, 413);\n+\t\t}\n+\t\tparts.push(value);\n+\t}\n+\tconst out = new Uint8Array(size);\n+\tlet at = 0;\n+\tfor (const part of parts) {\n+\t\tout.set(part, at);\n+\t\tat += part.length;\n+\t}\n+\treturn out;\n+}\n+\n+/** A write that can carry news, to run once the writer's limit allows it; undefined when no route matches. */\n+function writeFor(\n+\tstore: IssuesStore,\n+\tactor: Actor,\n+\trest: string,\n+\tbody: Record<string, unknown>,\n+): (() => object) | undefined {\n+\tif (rest === \"issue\") return () => store.open(actor, body);\n+\tif (rest === \"ask\") return () => store.ask(actor, body);\n+\tconst on = /^issue\\/(\\d+)\\/(comment|drop|edit|reopen|done)$/.exec(rest);\n+\tif (on) {\n+\t\tconst id = Number(on[1]);\n+\t\treturn () => {\n+\t\t\tif (on[2] === \"comment\") return store.comment(actor, id, body);\n+\t\t\tif (on[2] === \"edit\") return store.edit(actor, id, body);\n+\t\t\tif (on[2] === \"reopen\") return store.reopen(actor, id);\n+\t\t\tif (on[2] === \"done\") {\n+\t\t\t\tconst version = body.version;\n+\t\t\t\tif (version !== undefined && version !== null && typeof version !== \"number\")\n+\t\t\t\t\tthrow new IssuesError(\"version is a published version, 1 or more\");\n+\t\t\t\treturn store.markDone(actor, id, typeof version === \"number\" ? version : null);\n+\t\t\t}\n+\t\t\treturn store.drop(actor, id);\n+\t\t};\n+\t}\n+\tconst opening = /^draft\\/(\\d+)\\/open$/.exec(rest);\n+\tif (opening) return () => store.openDraft(actor, Number(opening[1]), body);\n+\tconst answer = /^answer\\/(\\d+)$/.exec(rest);\n+\tif (answer) return () => store.answer(actor, Number(answer[1]), body);\n+\tconst ack = /^ack\\/(\\d+)$/.exec(rest);\n+\tif (ack) return () => store.ack(actor, Number(ack[1]), body);\n+\tconst reply = /^reply\\/(\\d+)$/.exec(rest);\n+\tif (reply) return () => store.reply(actor, Number(reply[1]), body);\n+\tconst withdraw = /^withdraw\\/(\\d+)$/.exec(rest);\n+\tif (withdraw) return () => store.withdraw(actor, Number(withdraw[1]), body);\n+\treturn undefined;\n+}"},{"path":"server/src/issues/seats.ts","added":49,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues/seats.ts\n@@ -0,0 +1,49 @@\n+// Asks go to seats: an ask to a name that isn't an agent in the project would\n+// wait on nobody, so it's refused, with the closest seat named. Seats are only\n+// ever this project's own.\n+\n+/** A name as people write it: lower case, letters and digits only (\"abso - Cloud Infra Lead\" → \"absocloudinfralead\"). */\n+function plain(name: string): string {\n+\treturn name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n+}\n+\n+/** Edits from a to b: insertions, deletions and substitutions. */\n+function distance(a: string, b: string): number {\n+\tlet row = Array.from({ length: b.length + 1 }, (_, i) => i);\n+\tfor (let i = 1; i <= a.length; i++) {\n+\t\tconst next = [i];\n+\t\tfor (let j = 1; j <= b.length; j++)\n+\t\t\tnext[j] = Math.min(row[j]! + 1, next[j - 1]! + 1, row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1));\n+\t\trow = next;\n+\t}\n+\treturn row[b.length]!;\n+}\n+\n+/**\n+ * The seat a name most likely meant, or null. The same name written another way wins; then the longest seat\n+ * the name holds (\"abso - Cloud Infra Lead\" holds cloud), or that holds the name; then a near spelling.\n+ */\n+export function closestSeat(name: string, seats: readonly string[]): string | null {\n+\tconst n = plain(name);\n+\tif (n === \"\") return null;\n+\tconst same = seats.find((s) => plain(s) === n);\n+\tif (same) return same;\n+\tconst held = seats\n+\t\t.filter((s) => plain(s).length >= 3 && (n.includes(plain(s)) || plain(s).includes(n)))\n+\t\t.sort((a, b) => plain(b).length - plain(a).length);\n+\tif (held[0]) return held[0];\n+\tlet best: string | null = null;\n+\tlet least = Math.max(2, Math.floor(n.length / 3)) + 1;\n+\tfor (const s of seats) {\n+\t\tconst d = distance(n, plain(s));\n+\t\tif (d < least) [best, least] = [s, d];\n+\t}\n+\treturn best;\n+}\n+\n+/** Why an ask to `of` is refused, or null when `of` is a seat. */\n+export function seatRefusal(of: string, project: string, seats: readonly string[]): string | null {\n+\tif (seats.includes(of)) return null;\n+\tconst near = closestSeat(of, seats);\n+\treturn `${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.`;\n+}"},{"path":"server/src/issues/serve.ts","added":200,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues/serve.ts\n@@ -0,0 +1,200 @@\n+// How the open server's Worker reaches a project's issues, and what the IssueProject object does with a\n+// request, apart from Cloudflare's own types so both run under node --test.\n+//\n+//   issuesFetch    the Worker's entry for /issues/p/:project/...: the router has checked the token or key;\n+//                  this checks that a key acts only as its own agent (and a reader's only reads), hands the\n+//                  request to the project's IssueProject, and delivers a write's news to the project.\n+//   IssuesObject   one project's issues: migrations, the store, and its routes (routes.ts). An ask's `of` is\n+//                  checked against the project's agents.\n+//\n+// The project object (env.PROJECT, named by the project) is asked two things, both optional: agents(project)\n+// for the ask check, and news(project, items) to deliver a write's news as announcements. Without them the\n+// check is skipped and the news is dropped with a log line.\n+\n+import type { News } from \"../../../client/src/issues-wire.ts\";\n+import { BODY_MAX, issuesRoute, json, readCapped } from \"./routes.ts\";\n+import { seatRefusal } from \"./seats.ts\";\n+import { IssuesError, IssuesStore, SCHEMA, type Sql } from \"./store.ts\";\n+\n+/** A write's news for the project to deliver: the issue's claimers and those in `to` hear it, never `from`. */\n+export interface IssueNews extends News {\n+\t/** The agent whose write it was. */\n+\tfrom: string;\n+}\n+\n+/** What issues asks of the project's own object. Each method is optional: an older project object may lack it. */\n+export interface ProjectHooks {\n+\t/** The agents in the project, which an ask may go to. */\n+\tagents?(project: string): Promise<string[]>;\n+\t/** Deliver each item as an announcement from `from` to the issue's claimers and `to`. */\n+\tnews?(project: string, items: IssueNews[]): Promise<unknown>;\n+}\n+\n+/** A Durable Object namespace as far as issues uses one; Cloudflare's DurableObjectNamespace fits it. */\n+export interface NamespaceLike {\n+\tidFromName(name: string): unknown;\n+\tget(id: never): object;\n+}\n+\n+/** The bindings issues reads. */\n+export interface IssuesEnv {\n+\t/** One IssueProject per project, named by the project's name. */\n+\tISSUES_DO: NamespaceLike;\n+\t/** The project objects, named by the project's name; their stubs answer ProjectHooks. */\n+\tPROJECT?: NamespaceLike;\n+}\n+\n+/** How the router let the request in: the shared token acts as any agent; a key only as its own agent. */\n+export type IssuesAuth = { kind: \"token\" } | { kind: \"key\"; agent: string; role: string };\n+\n+/** What issuesFetch needs from the Worker's context. */\n+export interface WaitUntil {\n+\twaitUntil(promise: Promise<unknown>): void;\n+}\n+\n+const PROJECT_NAME = /^[A-Za-z0-9._-]{1,64}$/;\n+const AGENT_NAME = /^[A-Za-z0-9._-]{1,64}$/;\n+\n+function stubOf<T>(ns: NamespaceLike, name: string): T {\n+\tconst n = ns as unknown as { idFromName(name: string): unknown; get(id: unknown): T };\n+\treturn n.get(n.idFromName(name));\n+}\n+\n+/** The project object's stub, as far as issues calls it; undefined when PROJECT isn't bound. */\n+function hooksOf(env: IssuesEnv, project: string): ProjectHooks | undefined {\n+\treturn env.PROJECT === undefined ? undefined : stubOf<ProjectHooks>(env.PROJECT, project);\n+}\n+\n+/**\n+ * Whether an RPC call failed because the receiver has no such method. On an RPC stub every property reads as a\n+ * function, so only the call can tell: it fails with this error.\n+ */\n+export function missingMethod(e: unknown): boolean {\n+\tconst message = e instanceof Error ? e.message : String(e);\n+\treturn /does not implement (the )?method|is not a function/i.test(message);\n+}\n+\n+/**\n+ * /issues/p/:project<rest> after the router's sign-in check. `rest` is the path after the project, like\n+ * /a/lead/ask or /issues.\n+ */\n+export async function issuesFetch(\n+\trequest: Request,\n+\tenv: IssuesEnv,\n+\tctx: WaitUntil,\n+\t{ project, rest, auth }: { project: string; rest: string; auth: IssuesAuth },\n+): Promise<Response> {\n+\tif (!PROJECT_NAME.test(project)) return json(404, { error: \"no such project\" });\n+\tif (!rest.startsWith(\"/\")) return json(404, { error: \"no such issues route\" });\n+\tconst m = /^\\/a\\/([^/]+)\\//.exec(rest);\n+\tlet agent: string | undefined;\n+\tif (m) {\n+\t\ttry {\n+\t\t\tagent = decodeURIComponent(m[1]!);\n+\t\t} catch {\n+\t\t\treturn json(400, { error: \"an agent's name is 1-64 of A-Z a-z 0-9 . _ -\" });\n+\t\t}\n+\t\tif (!AGENT_NAME.test(agent)) return json(400, { error: \"an agent's name is 1-64 of A-Z a-z 0-9 . _ -\" });\n+\t}\n+\tconst reading = request.method === \"GET\" || request.method === \"HEAD\";\n+\tif (auth.kind === \"key\") {\n+\t\tif (agent !== undefined && agent !== auth.agent)\n+\t\t\treturn json(403, { error: `this key is ${auth.agent}'s; it acts only as ${auth.agent}` });\n+\t\tif (auth.role === \"reader\" && !reading) return json(403, { error: \"a reader's key only reads issues\" });\n+\t}\n+\tlet body: Uint8Array<ArrayBuffer> | undefined;\n+\tif (!reading) {\n+\t\ttry {\n+\t\t\tbody = await readCapped(request, BODY_MAX);\n+\t\t} catch (e) {\n+\t\t\tif (e instanceof IssuesError) return json(e.status, { error: e.message });\n+\t\t\tthrow e;\n+\t\t}\n+\t}\n+\t// The object sees neither the token nor any header that could name a person.\n+\tconst headers = new Headers(request.headers);\n+\tfor (const h of [\"Authorization\", \"X-Abso-User\", \"X-Avcs-User\", \"Cookie\"]) headers.delete(h);\n+\tconst search = new URL(request.url).search;\n+\tconst forwarded = new Request(`https://issues.invalid/p/${encodeURIComponent(project)}${rest}${search}`, {\n+\t\tmethod: request.method,\n+\t\theaders,\n+\t\t...(body !== undefined ? { body } : {}),\n+\t});\n+\tconst stub = stubOf<{ fetch(request: Request): Promise<Response> }>(env.ISSUES_DO, project);\n+\tconst answer = await stub.fetch(forwarded);\n+\tif (!reading && agent !== undefined && answer.ok) ctx.waitUntil(tell(env, project, agent, answer.clone()));\n+\treturn answer;\n+}\n+\n+/** A write's news to the project object, sent after the answer. A failed send is only logged; the write stands. */\n+async function tell(env: IssuesEnv, project: string, from: string, answer: Response): Promise<void> {\n+\ttry {\n+\t\tconst { news } = (await answer.json()) as { news?: News };\n+\t\tif (!news || typeof news.text !== \"string\") return;\n+\t\tconst hooks = hooksOf(env, project);\n+\t\tif (hooks === undefined) {\n+\t\t\tconsole.log(`issues: news for ${project} dropped: PROJECT isn't bound`);\n+\t\t\treturn;\n+\t\t}\n+\t\tawait hooks.news!(project, [{ from, ...news }]);\n+\t} catch (err) {\n+\t\tif (missingMethod(err)) console.log(`issues: news for ${project} dropped: the project object has no news method`);\n+\t\telse console.error(`issues: news for ${project} not sent`, err);\n+\t}\n+}\n+\n+/** The storage an IssueProject object has: its SQL, and a synchronous transaction. */\n+export interface ObjectStorage {\n+\tsql: Sql;\n+\ttransactionSync<T>(action: () => T): T;\n+}\n+\n+/** One project's issues: the store over the object's SQLite, migrated, and the routes over it. */\n+export class IssuesObject {\n+\treadonly store: IssuesStore;\n+\tprivate readonly storage: ObjectStorage;\n+\tprivate readonly env: IssuesEnv;\n+\n+\tconstructor(storage: ObjectStorage, env: IssuesEnv, now: () => number = Date.now) {\n+\t\tthis.storage = storage;\n+\t\tthis.env = env;\n+\t\tthis.migrate();\n+\t\tthis.store = new IssuesStore(storage.sql, now, (action) => storage.transactionSync(action));\n+\t}\n+\n+\t/** Runs each SCHEMA statement not yet run, once, in order, each in its own transaction. */\n+\tprivate migrate(): void {\n+\t\tconst sql = this.storage.sql;\n+\t\tsql.exec(\"CREATE TABLE IF NOT EXISTS migrations (n INTEGER PRIMARY KEY, at INTEGER NOT NULL)\");\n+\t\tconst done = (sql.exec(\"SELECT COALESCE(MAX(n), 0) AS n FROM migrations\").toArray()[0] as { n: number }).n;\n+\t\tfor (let n = done + 1; n <= SCHEMA.length; n++)\n+\t\t\tthis.storage.transactionSync(() => {\n+\t\t\t\tsql.exec(SCHEMA[n - 1]!);\n+\t\t\t\tsql.exec(\"INSERT INTO migrations (n, at) VALUES (?, ?)\", n, Date.now());\n+\t\t\t});\n+\t}\n+\n+\t/** How many migrations this object has run. */\n+\tmigrations(): number {\n+\t\treturn (this.storage.sql.exec(\"SELECT COUNT(*) AS n FROM migrations\").toArray()[0] as { n: number }).n;\n+\t}\n+\n+\tasync fetch(request: Request): Promise<Response> {\n+\t\tconst name = /^\\/p\\/([^/]+)\\//.exec(new URL(request.url).pathname)?.[1];\n+\t\tconst project = name === undefined ? undefined : decodeURIComponent(name);\n+\t\tconst seatError = async (of: string): Promise<string | null> => {\n+\t\t\tif (project === undefined) return null;\n+\t\t\tconst hooks = hooksOf(this.env, project);\n+\t\t\tif (hooks === undefined) return null;\n+\t\t\tlet seats: string[];\n+\t\t\ttry {\n+\t\t\t\tseats = await hooks.agents!(project);\n+\t\t\t} catch (e) {\n+\t\t\t\tif (missingMethod(e)) return null;\n+\t\t\t\tthrow e;\n+\t\t\t}\n+\t\t\treturn Array.isArray(seats) ? seatRefusal(of, project, seats) : null;\n+\t\t};\n+\t\treturn issuesRoute(this.store, request, seatError);\n+\t}\n+}"},{"path":"server/src/issues/store.ts","added":1693,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues/store.ts\n@@ -0,0 +1,1693 @@\n+// Issues for the open server (abso-core issue 17): one store per project, in SQLite, holding current state:\n+// issues, comments, labels, asks with their answers and threads, claims, the versions out for each issue,\n+// drafts, and what each reader's news has shown. Ported from the platform's issues Worker, without its\n+// workflow and release stores, prose authorship records, attachments, copies and meaning search.\n+//\n+// Status comes from the work and nobody sets it: Done when a publish closed it (or someone marked it done),\n+// Blocked while an ask that isn't a review is open on it (or names it in `blocks`) or an issue it is blocked\n+// by is not done, In review while a review ask is open on it, In progress while a start note names it, and\n+// Open otherwise. An answer is kept in its writer's own words on the ask it answers.\n+//\n+// Watchers: who opened an issue, its Agent and any agent that claims it, its reviewer, whoever was named in\n+// Notify, and whoever comments. An edit tells them unless its writer says not to.\n+\n+import type {\n+\tActor,\n+\tAsk,\n+\tAskReply,\n+\tComment,\n+\tDraft,\n+\tDraftBody,\n+\tEdit,\n+\tIssuePage,\n+\tIssueRow,\n+\tLines,\n+\tNews,\n+\tProseAuthorship,\n+\tStatus,\n+} from \"../../../client/src/issues-wire.ts\";\n+import { unseenIn } from \"../../../worker/project/unseen.ts\";\n+\n+export type {\n+\tActor,\n+\tAsk,\n+\tClaim,\n+\tComment,\n+\tDraft,\n+\tDraftBody,\n+\tEdit,\n+\tIssuePage,\n+\tIssueRow,\n+\tLines,\n+\tNews,\n+\tStatus,\n+} from \"../../../client/src/issues-wire.ts\";\n+\n+/** The SQL a Durable Object's storage gives (ctx.storage.sql), and node:sqlite in tests. */\n+export interface Sql {\n+\texec(query: string, ...bindings: unknown[]): { toArray(): unknown[] };\n+}\n+\n+/** A plain sentence for the person or agent; the route answers with it and `status`. */\n+export class IssuesError extends Error {\n+\treadonly status: number;\n+\t/** Seconds until a refused write may be tried again (429), for Retry-After. */\n+\treadonly retryAfter: number | undefined;\n+\tconstructor(message: string, status = 400, retryAfter?: number) {\n+\t\tsuper(message);\n+\t\tthis.status = status;\n+\t\tthis.retryAfter = retryAfter;\n+\t}\n+}\n+\n+/**\n+ * A label: 1-40 characters of lower-case letters, digits, and - _ . : (so\n+ * \"friction\", \"good-first-issue\", \"area:client\"). Anything else is refused,\n+ * upper case included, rather than changed: the client and the\n+ * site lower-case what's typed before sending.\n+ */\n+export const LABEL = /^[a-z0-9][a-z0-9_.:-]{0,39}$/;\n+export const LABELS_PER_ISSUE = 20;\n+/** Distinct labels a project may hold, since GET labels lists every one. */\n+export const LABELS_PER_PROJECT = 200;\n+\n+/** Writes per writer (agent or person:<id>), since each can carry news. */\n+export const WRITES_PER_MINUTE = 100;\n+export const WRITES_PER_DAY = 1000;\n+\n+/** At most this many @names in one comment are told. */\n+export const MENTIONS_MAX = 20;\n+\n+/**\n+ * The agents a text names as @name, in order, each once: an @ at the start or after anything\n+ * but a name character, so an email address isn't one. A sentence's full stop or dash after the name isn't\n+ * part of it.\n+ */\n+export function mentionsIn(text: string): string[] {\n+\tconst names = new Set<string>();\n+\tfor (const m of text.matchAll(/(?:^|[^A-Za-z0-9._@-])@([A-Za-z0-9][A-Za-z0-9._-]{0,63})/g)) {\n+\t\tnames.add(m[1]!.replace(/[._-]+$/, \"\"));\n+\t\tif (names.size === MENTIONS_MAX) break;\n+\t}\n+\treturn [...names];\n+}\n+\n+const LIMITS = {\n+\ttitle: 200,\n+\tdescription: 20_000,\n+\ttext: 4_000,\n+\topen: 10_000,\n+\toptions: 10,\n+\tblocks: 50,\n+\tnames: 50,\n+\tdrafts: 100,\n+\tdraft: 30_000,\n+};\n+\n+/**\n+ * The tables the change count watches: what issue reads show. Not drafts (one person's), writes (the rate log),\n+ * search (kept from issues and comments) or meta. Fixed, since SCHEMA makes three triggers for each: a later\n+ * table appends its own three to SCHEMA instead.\n+ */\n+const COUNTED_TABLES = [\n+\t\"issues\",\n+\t\"comments\",\n+\t\"asks\",\n+\t\"claims\",\n+\t\"versions\",\n+\t\"watchers\",\n+\t\"blocked_by\",\n+\t\"edits\",\n+\t\"labels\",\n+\t\"ask_replies\",\n+] as const;\n+\n+/**\n+ * The tables, as add-only migrations: the IssueProject object runs each once, in order (index.ts), so an\n+ * older Worker still reads a newer database. Append; never edit or reorder.\n+ */\n+export const SCHEMA: readonly string[] = [\n+\t`CREATE TABLE IF NOT EXISTS issues (id INTEGER PRIMARY KEY, parent INTEGER, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',\n+\t\topened_by TEXT NOT NULL, opened_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, lines TEXT,\n+\t\tclosed_how TEXT, closed_by TEXT, closed_version INTEGER, closed_at INTEGER, agent TEXT)`,\n+\t\"CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY, issue INTEGER NOT NULL, by TEXT NOT NULL, kind TEXT NOT NULL, text TEXT NOT NULL, at INTEGER NOT NULL)\",\n+\t`CREATE TABLE IF NOT EXISTS asks (id INTEGER PRIMARY KEY, issue INTEGER, by TEXT NOT NULL, of TEXT NOT NULL, kind TEXT NOT NULL, question TEXT NOT NULL,\n+\t\treview INTEGER NOT NULL, due TEXT, recommendation TEXT, options TEXT NOT NULL, blocks TEXT NOT NULL, at INTEGER NOT NULL,\n+\t\tanswer_by TEXT, answer_words TEXT, answer_at INTEGER, seen_at INTEGER, outcome TEXT, ack_at INTEGER, ack_note TEXT, waiting_on TEXT)`,\n+\t\"CREATE TABLE IF NOT EXISTS claims (issue INTEGER NOT NULL, agent TEXT NOT NULL, change INTEGER NOT NULL, since INTEGER NOT NULL, PRIMARY KEY (issue, agent))\",\n+\t\"CREATE TABLE IF NOT EXISTS versions (issue INTEGER NOT NULL, version INTEGER NOT NULL, agent TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (issue, version))\",\n+\t\"CREATE TABLE IF NOT EXISTS watchers (issue INTEGER NOT NULL, who TEXT NOT NULL, since INTEGER NOT NULL, PRIMARY KEY (issue, who))\",\n+\t\"CREATE TABLE IF NOT EXISTS blocked_by (issue INTEGER NOT NULL, blocker INTEGER NOT NULL, PRIMARY KEY (issue, blocker))\",\n+\t\"CREATE TABLE IF NOT EXISTS edits (id INTEGER PRIMARY KEY, issue INTEGER NOT NULL, by TEXT NOT NULL, changes TEXT NOT NULL, notified TEXT NOT NULL, at INTEGER NOT NULL)\",\n+\t\"CREATE TABLE IF NOT EXISTS drafts (id INTEGER PRIMARY KEY, owner TEXT NOT NULL, body TEXT NOT NULL, saved_at INTEGER NOT NULL)\",\n+\t// Each writer's writes of the last day, for the limit.\n+\t\"CREATE TABLE IF NOT EXISTS writes (who TEXT NOT NULL, at INTEGER NOT NULL)\",\n+\t\"CREATE TABLE IF NOT EXISTS labels (issue INTEGER NOT NULL, label TEXT NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (issue, label))\",\n+\t// Ask threads: replies from either side while the ask is open or after. An ask's waiting_on is null while it\n+\t// waits on the one asked, and the asker's name after the one asked replies with a question.\n+\t\"CREATE TABLE IF NOT EXISTS ask_replies (id INTEGER PRIMARY KEY, ask INTEGER NOT NULL, by TEXT NOT NULL, text TEXT NOT NULL, question INTEGER NOT NULL DEFAULT 0, at INTEGER NOT NULL)\",\n+\t// A reader's news: read up to when. Not counted, since no issue read shows it.\n+\t\"CREATE TABLE IF NOT EXISTS news_read (who TEXT PRIMARY KEY, at INTEGER NOT NULL)\",\n+\t\"CREATE INDEX IF NOT EXISTS comments_issue ON comments (issue)\",\n+\t\"CREATE INDEX IF NOT EXISTS comments_at ON comments (at)\",\n+\t\"CREATE INDEX IF NOT EXISTS asks_issue ON asks (issue)\",\n+\t\"CREATE INDEX IF NOT EXISTS asks_open ON asks (answer_at)\",\n+\t\"CREATE INDEX IF NOT EXISTS issues_parent ON issues (parent)\",\n+\t\"CREATE INDEX IF NOT EXISTS issues_updated ON issues (updated_at)\",\n+\t\"CREATE INDEX IF NOT EXISTS edits_issue ON edits (issue)\",\n+\t\"CREATE INDEX IF NOT EXISTS drafts_owner ON drafts (owner)\",\n+\t\"CREATE INDEX IF NOT EXISTS writes_who ON writes (who, at)\",\n+\t\"CREATE INDEX IF NOT EXISTS labels_label ON labels (label)\",\n+\t\"CREATE INDEX IF NOT EXISTS ask_replies_ask ON ask_replies (ask)\",\n+\t\"CREATE INDEX IF NOT EXISTS ask_replies_at ON ask_replies (at)\",\n+\t// Search: every title, description and comment in a full-text index, kept in step by triggers.\n+\t\"CREATE VIRTUAL TABLE IF NOT EXISTS search USING fts5(issue UNINDEXED, comment UNINDEXED, field UNINDEXED, text, tokenize = 'porter unicode61')\",\n+\t`CREATE TRIGGER IF NOT EXISTS search_issue_in AFTER INSERT ON issues BEGIN\n+\t\tINSERT INTO search (issue, comment, field, text) VALUES (new.id, 0, 'title', new.title);\n+\t\tINSERT INTO search (issue, comment, field, text) SELECT new.id, 0, 'description', new.description WHERE new.description <> '';\n+\tEND`,\n+\t`CREATE TRIGGER IF NOT EXISTS search_issue_edit AFTER UPDATE OF title, description ON issues BEGIN\n+\t\tDELETE FROM search WHERE issue = old.id AND comment = 0;\n+\t\tINSERT INTO search (issue, comment, field, text) VALUES (new.id, 0, 'title', new.title);\n+\t\tINSERT INTO search (issue, comment, field, text) SELECT new.id, 0, 'description', new.description WHERE new.description <> '';\n+\tEND`,\n+\t\"CREATE TRIGGER IF NOT EXISTS search_issue_out AFTER DELETE ON issues BEGIN DELETE FROM search WHERE issue = old.id; END\",\n+\t\"CREATE TRIGGER IF NOT EXISTS search_comment_in AFTER INSERT ON comments BEGIN INSERT INTO search (issue, comment, field, text) VALUES (new.issue, new.id, 'comment', new.text); END\",\n+\t`CREATE TRIGGER IF NOT EXISTS search_comment_edit AFTER UPDATE OF text ON comments BEGIN\n+\t\tDELETE FROM search WHERE comment = old.id;\n+\t\tINSERT INTO search (issue, comment, field, text) VALUES (new.issue, new.id, 'comment', new.text);\n+\tEND`,\n+\t\"CREATE TRIGGER IF NOT EXISTS search_comment_out AFTER DELETE ON comments BEGIN DELETE FROM search WHERE comment = old.id; END\",\n+\t// The change count: one number that only grows, bumped by triggers on every table an issue read shows, so\n+\t// every write path moves it, the seen marks waiting writes included. A reader can cache issue reads by it.\n+\t\"CREATE TABLE IF NOT EXISTS change_count (id INTEGER PRIMARY KEY CHECK (id = 1), n INTEGER NOT NULL)\",\n+\t\"INSERT OR IGNORE INTO change_count (id, n) VALUES (1, 0)\",\n+\t...COUNTED_TABLES.flatMap((t) =>\n+\t\t([\"INSERT\", \"UPDATE\", \"DELETE\"] as const).map(\n+\t\t\t(op) =>\n+\t\t\t\t`CREATE TRIGGER IF NOT EXISTS changed_${t}_${op.toLowerCase()} AFTER ${op} ON ${t} BEGIN UPDATE change_count SET n = n + 1 WHERE id = 1; END`,\n+\t\t),\n+\t),\n+];\n+\n+/** How many news items one project gives a person's news, before the merge across projects. */\n+export const NEWS_MAX = 50;\n+/** How much of a comment, answer or reply a news item carries. */\n+const NEWS_TEXT_MAX = 280;\n+\n+/**\n+ * One thing for a person's news: an answer to their ask, a reply on an ask they're in, an\n+ * @mention of them, or a comment, edit or close on an issue they watch, by someone else.\n+ */\n+export interface NewsItem {\n+\tkind: \"answer\" | \"reply\" | \"mention\" | \"comment\" | \"edit\" | \"closed\";\n+\tissue: number | null;\n+\ttitle: string | null;\n+\task?: number;\n+\tby: string;\n+\ttext: string;\n+\tat: number;\n+\tread: boolean;\n+}\n+\n+/** One issue a search found: where the best match is, a snippet around it, and how well it matched. */\n+export interface SearchHit {\n+\tissue: { id: number; title: string; status: Status; updated: number; labels: string[] };\n+\t/** Where the best match is: the title, the description, or a comment (with its id). */\n+\twhere: \"title\" | \"description\" | \"comment\";\n+\tcomment?: number;\n+\t/** A few words around the match, with each matched span's [start, end) in `marks`. */\n+\tsnippet: string;\n+\tmarks: number[][];\n+\t/** FTS5's bm25, made positive: higher matches better. */\n+\tscore: number;\n+}\n+\n+/** A search hit as the client reads it: the issue's title and the matched text, each with who wrote it. */\n+export type AuthoredSearchHit = Omit<SearchHit, \"issue\"> & {\n+\tissue: SearchHit[\"issue\"] & { authorship: { title: ProseAuthorship } };\n+\tmatchedAuthorship: ProseAuthorship;\n+};\n+\n+type StoredAskReply = Omit<AskReply, \"authorship\">;\n+type StoredAsk = Omit<Ask, \"authorship\" | \"answer\" | \"ack\" | \"replies\"> & {\n+\tanswer: { by: string; words: string; at: number } | null;\n+\tack?: { at: number; note: string };\n+\treplies: StoredAskReply[];\n+};\n+\n+const UNKNOWN: ProseAuthorship = { kind: \"unknown\", actor: null, provenance: \"unknown\", authorField: null };\n+\n+/**\n+ * Who wrote a text, from the column that names its writer: an agent, or a person (person:<id>). This server\n+ * keeps no separate authorship records, so every text is its writer's own (\"native\").\n+ */\n+function authored(by: unknown, authorField: string): ProseAuthorship {\n+\tif (typeof by !== \"string\" || by === \"\") return UNKNOWN;\n+\treturn { kind: by.startsWith(\"person:\") ? \"human\" : \"agent\", actor: by, provenance: \"native\", authorField };\n+}\n+\n+/**\n+ * A person's words as an FTS5 query: each word quoted, so nothing they type\n+ * is query syntax, and the last one a prefix, so a search box finds as they\n+ * type. Undefined when there's no word in it.\n+ */\n+export function searchQuery(q: string): string | undefined {\n+\tconst words = q.match(/[\\p{L}\\p{N}_]+/gu)?.slice(0, 12);\n+\tif (!words || words.length === 0) return undefined;\n+\treturn words.map((w, i) => `\"${w}\"${i === words.length - 1 ? \"*\" : \"\"}`).join(\" \");\n+}\n+\n+type Row = Record<string, unknown>;\n+\n+/** How an actor is named in the store and on the pages: the agent's name, or person:<id>. */\n+export function who(actor: Actor): string {\n+\treturn \"agent\" in actor ? actor.agent : `person:${actor.person}`;\n+}\n+\n+/**\n+ * Words that reach agents on pages and in news: within `max`, with nothing a reader can't see (the engine's\n+ * own list, worker/project/unseen.ts), and on one line where `oneLine`.\n+ */\n+function text(value: unknown, what: string, max: number, required = true, oneLine = false): string {\n+\tif (value === undefined || value === null || value === \"\") {\n+\t\tif (required) throw new IssuesError(`${what} is missing`);\n+\t\treturn \"\";\n+\t}\n+\tif (typeof value !== \"string\") throw new IssuesError(`${what} is text`);\n+\tconst t = value.trim();\n+\tif (required && t === \"\") throw new IssuesError(`${what} is empty`);\n+\tif (t.length > max) throw new IssuesError(`${what} is ${t.length} characters; the most is ${max}`);\n+\tconst hidden = unseenIn(t);\n+\tif (hidden !== null)\n+\t\tthrow new IssuesError(`${what} holds ${hidden}, which a reader of the page can't see; take it out`);\n+\tif (oneLine && /[\\n\\t]/.test(t)) throw new IssuesError(`${what} is one line`);\n+\treturn t;\n+}\n+\n+function issueNumber(value: unknown, what = \"an issue number\"): number {\n+\tconst n = Number(value);\n+\tif (!Number.isInteger(n) || n < 1) throw new IssuesError(`${what} is a whole number from 1`);\n+\treturn n;\n+}\n+\n+/** A list of names (agents, or person:<id>), each once. */\n+function names(value: unknown, what: string): string[] {\n+\tif (value === undefined || value === null) return [];\n+\tif (!Array.isArray(value) || value.length > LIMITS.names)\n+\t\tthrow new IssuesError(`${what} is a list of up to ${LIMITS.names} names`);\n+\treturn [...new Set(value.map((v, i) => text(v, `${what}'s name ${i + 1}`, 100, true, true)))];\n+}\n+\n+/** Labels, checked as given (nothing is changed but surrounding spaces), each once, sorted. */\n+function labelsOf(value: unknown, what = \"labels\"): string[] {\n+\tif (value === undefined || value === null) return [];\n+\tif (!Array.isArray(value) || value.length > LABELS_PER_ISSUE)\n+\t\tthrow new IssuesError(`${what} is a list of up to ${LABELS_PER_ISSUE} labels`);\n+\tconst out = new Set<string>();\n+\tfor (const v of value) {\n+\t\tconst l = typeof v === \"string\" ? v.trim() : \"\";\n+\t\tif (!LABEL.test(l))\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`${JSON.stringify(v)} isn't a label: 1-40 lower-case letters, digits, and - _ . : (like friction or area:client)`,\n+\t\t\t);\n+\t\tout.add(l);\n+\t}\n+\treturn [...out].sort();\n+}\n+\n+/** A name, or null for none: \"\" and null clear it. */\n+function nameOrNone(value: unknown, what: string): string | null {\n+\treturn value === null || value === \"\" ? null : text(value, what, 100, true, true);\n+}\n+\n+function lines(value: unknown): Lines | null {\n+\tif (value === undefined || value === null) return null;\n+\tconst l = value as Partial<Lines>;\n+\tif (\n+\t\ttypeof l.file !== \"string\" ||\n+\t\tl.file === \"\" ||\n+\t\t!Number.isInteger(l.from) ||\n+\t\t!Number.isInteger(l.to) ||\n+\t\t!Number.isInteger(l.version) ||\n+\t\tl.from! < 1 ||\n+\t\tl.to! < l.from! ||\n+\t\tl.version! < 0\n+\t) {\n+\t\tthrow new IssuesError(\"lines are {file, from, to, version}: lines from-to of a file at a version\");\n+\t}\n+\treturn { file: text(l.file, \"the lines' file\", 1000, true, true), from: l.from!, to: l.to!, version: l.version! };\n+}\n+\n+const unique = (xs: readonly string[]): string[] => [...new Set(xs)];\n+\n+export class IssuesStore {\n+\tprivate readonly sql: Sql;\n+\tprivate readonly now: () => number;\n+\tprivate readonly atomic: (<T>(action: () => T) => T) | null;\n+\n+\t/** Over tables SCHEMA made (the object's migrations, or createTables in tests). `atomic` runs a transaction. */\n+\tconstructor(sql: Sql, now: () => number = Date.now, atomic?: <T>(action: () => T) => T) {\n+\t\tthis.sql = sql;\n+\t\tthis.now = now;\n+\t\tthis.atomic = atomic ?? null;\n+\t}\n+\n+\tprivate transaction<T>(action: () => T): T {\n+\t\treturn this.atomic ? this.atomic(action) : action();\n+\t}\n+\n+\tstatic createTables(sql: Sql): void {\n+\t\tfor (const s of SCHEMA) sql.exec(s);\n+\t}\n+\n+\t/**\n+\t * The change count: it grows with every write an issue read can show and never goes back, so a read cached\n+\t * under it is never older than its key.\n+\t */\n+\tchanges(): number {\n+\t\treturn (this.rows(\"SELECT n FROM change_count WHERE id = 1\")[0]?.n as number | undefined) ?? 0;\n+\t}\n+\n+\t/**\n+\t * A reader's news here, newest first, at most NEWS_MAX: answers to their asks, replies on asks they asked or\n+\t * were asked, comments naming them as @name (`names`: what they go by; an agent goes by its own name), and on\n+\t * issues they watch, others' comments, the edits that told them, and closes. Each is read when it is at or\n+\t * before their news_read mark. `before` pages back.\n+\t */\n+\tnewsFor(reader: Actor, names: readonly string[], before?: number): NewsItem[] {\n+\t\tconst me = who(reader);\n+\t\tconst until = before ?? Number.MAX_SAFE_INTEGER;\n+\t\tconst mark = (this.rows(\"SELECT at FROM news_read WHERE who = ?\", me)[0]?.at as number | undefined) ?? 0;\n+\t\tconst cut = (t: string) => (t.length > NEWS_TEXT_MAX ? `${t.slice(0, NEWS_TEXT_MAX - 1)}…` : t);\n+\t\tconst items: NewsItem[] = [];\n+\t\tconst add = (kind: NewsItem[\"kind\"], r: Row, text: string, ask?: number) =>\n+\t\t\titems.push({\n+\t\t\t\tkind,\n+\t\t\t\tissue: (r.issue as number | null) ?? null,\n+\t\t\t\ttitle: (r.title as string | null) ?? null,\n+\t\t\t\t...(ask !== undefined ? { ask } : {}),\n+\t\t\t\tby: r.by as string,\n+\t\t\t\ttext: cut(text),\n+\t\t\t\tat: r.at as number,\n+\t\t\t\tread: (r.at as number) <= mark,\n+\t\t\t});\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT a.id, a.issue, i.title, a.answer_by AS by, a.answer_words AS text, a.answer_at AS at FROM asks a\n+\t\t\tLEFT JOIN issues i ON i.id = a.issue\n+\t\t\tWHERE a.by = ? AND a.answer_at IS NOT NULL AND a.answer_at < ? AND a.answer_by <> ? AND (a.outcome IS NULL OR a.outcome <> 'withdrawn')\n+\t\t\tORDER BY a.answer_at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tme,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tadd(\"answer\", r, (r.text as string | null) ?? \"\", r.id as number);\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT r.ask, a.issue, i.title, r.by, r.text, r.at FROM ask_replies r JOIN asks a ON a.id = r.ask\n+\t\t\tLEFT JOIN issues i ON i.id = a.issue\n+\t\t\tWHERE (a.by = ? OR a.of = ?) AND r.by <> ? AND r.at < ? ORDER BY r.at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tme,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tadd(\"reply\", r, r.text as string, r.ask as number);\n+\t\tconst named = names.filter((n) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(n)).slice(0, 4);\n+\t\tconst mentioned = new Set<number>();\n+\t\tfor (const n of named)\n+\t\t\tfor (const r of this.rows(\n+\t\t\t\t`SELECT c.id, c.issue, i.title, c.by, c.text, c.at FROM comments c JOIN issues i ON i.id = c.issue\n+\t\t\t\tWHERE c.by <> ? AND c.at < ? AND instr(lower(c.text), ?) > 0 ORDER BY c.at DESC LIMIT ?`,\n+\t\t\t\tme,\n+\t\t\t\tuntil,\n+\t\t\t\t`@${n.toLowerCase()}`,\n+\t\t\t\tNEWS_MAX,\n+\t\t\t)) {\n+\t\t\t\tconst said = mentionsIn(r.text as string).map((m) => m.toLowerCase());\n+\t\t\t\tif (!said.includes(n.toLowerCase()) || mentioned.has(r.id as number)) continue;\n+\t\t\t\tmentioned.add(r.id as number);\n+\t\t\t\tadd(\"mention\", r, r.text as string);\n+\t\t\t}\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT c.id, c.issue, i.title, c.by, c.text, c.at FROM comments c JOIN watchers w ON w.issue = c.issue AND w.who = ?\n+\t\t\tJOIN issues i ON i.id = c.issue\n+\t\t\tWHERE c.by <> ? AND c.at >= w.since AND c.at < ? ORDER BY c.at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tif (!mentioned.has(r.id as number)) add(\"comment\", r, r.text as string);\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT e.issue, i.title, e.by, e.changes, e.at FROM edits e JOIN issues i ON i.id = e.issue\n+\t\t\tWHERE e.by <> ? AND e.at < ? AND EXISTS (SELECT 1 FROM json_each(e.notified) WHERE value = ?)\n+\t\t\tORDER BY e.at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tme,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tadd(\"edit\", r, Object.keys(JSON.parse(r.changes as string) as object).join(\", \"));\n+\t\tfor (const r of this.rows(\n+\t\t\t`SELECT i.id AS issue, i.title, i.closed_by AS by, i.closed_how, i.closed_at AS at FROM issues i\n+\t\t\tJOIN watchers w ON w.issue = i.id AND w.who = ?\n+\t\t\tWHERE i.closed_at IS NOT NULL AND i.closed_at < ? AND i.closed_by <> ? ORDER BY i.closed_at DESC LIMIT ?`,\n+\t\t\tme,\n+\t\t\tuntil,\n+\t\t\tme,\n+\t\t\tNEWS_MAX,\n+\t\t))\n+\t\t\tadd(\"closed\", r, r.closed_how as string);\n+\t\treturn items.sort((x, y) => y.at - x.at).slice(0, NEWS_MAX);\n+\t}\n+\n+\t/** Marks the reader's news here read up to `at` (never back); answers the mark. */\n+\tmarkNewsRead(reader: Actor, at: number): { read: number } {\n+\t\tthis.sql.exec(\n+\t\t\t\"INSERT INTO news_read (who, at) VALUES (?, ?) ON CONFLICT (who) DO UPDATE SET at = MAX(at, excluded.at)\",\n+\t\t\twho(reader),\n+\t\t\tat,\n+\t\t);\n+\t\treturn { read: this.rows(\"SELECT at FROM news_read WHERE who = ?\", who(reader))[0]!.at as number };\n+\t}\n+\n+\tprivate rows(query: string, ...b: unknown[]): Row[] {\n+\t\treturn this.sql.exec(query, ...b).toArray() as Row[];\n+\t}\n+\n+\tprivate exists(id: number): Row {\n+\t\tconst row = this.rows(\"SELECT * FROM issues WHERE id = ?\", issueNumber(id))[0];\n+\t\tif (!row) throw new IssuesError(`there's no issue ${id}`, 404);\n+\t\treturn row;\n+\t}\n+\n+\tprivate touch(...ids: (number | null)[]): void {\n+\t\tconst at = this.now();\n+\t\tfor (const id of ids)\n+\t\t\tif (id !== null) this.sql.exec(\"UPDATE issues SET updated_at = MAX(updated_at, ?) WHERE id = ?\", at, id);\n+\t}\n+\n+\t/** Refuses labels that would take the project past LABELS_PER_PROJECT distinct ones. */\n+\tprivate roomForLabels(labels: readonly string[]): void {\n+\t\tconst inUse = new Set(this.rows(\"SELECT DISTINCT label FROM labels\").map((l) => l.label as string));\n+\t\tconst added = labels.filter((l) => !inUse.has(l));\n+\t\tif (added.length > 0 && inUse.size + added.length > LABELS_PER_PROJECT)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`this project has ${inUse.size} labels, and ${LABELS_PER_PROJECT} is the most; use one it has (abso issues --labels lists them)`,\n+\t\t\t);\n+\t}\n+\n+\t/** Attachments aren't kept on this server: a write that names any is refused before anything is written. */\n+\tprivate noAttachments(raw: unknown): void {\n+\t\tif (raw === undefined || raw === null || (Array.isArray(raw) && raw.length === 0)) return;\n+\t\tthrow new IssuesError(\"this server doesn't keep attachments; leave them off, or link the file instead\", 501);\n+\t}\n+\n+\t/** Adds watchers to an issue; each is kept once, from when they first watched. */\n+\tprivate watch(id: number, ...people: (string | null | undefined)[]): void {\n+\t\tconst at = this.now();\n+\t\tfor (const p of people)\n+\t\t\tif (p)\n+\t\t\t\tthis.sql.exec(\n+\t\t\t\t\t\"INSERT INTO watchers (issue, who, since) VALUES (?, ?, ?) ON CONFLICT (issue, who) DO NOTHING\",\n+\t\t\t\t\tid,\n+\t\t\t\t\tp,\n+\t\t\t\t\tat,\n+\t\t\t\t);\n+\t}\n+\n+\tprivate watchersOf(id: number): string[] {\n+\t\treturn this.rows(\"SELECT who FROM watchers WHERE issue = ? ORDER BY since, who\", id).map((w) => w.who as string);\n+\t}\n+\n+\t/** Blocked by, checked: issues that exist, not `id` itself, and none already waiting on `id` (that would wait forever). */\n+\tprivate blockersFor(id: number | null, value: unknown): number[] {\n+\t\tif (value === undefined || value === null) return [];\n+\t\tif (!Array.isArray(value) || value.length > LIMITS.blocks)\n+\t\t\tthrow new IssuesError(`blocked by is a list of up to ${LIMITS.blocks} issue numbers`);\n+\t\tconst ids = [...new Set(value.map((b) => issueNumber(b, \"an issue it's blocked by\")))];\n+\t\tfor (const b of ids) {\n+\t\t\tthis.exists(b);\n+\t\t\tif (b === id) throw new IssuesError(`issue ${id} can't be blocked by itself`);\n+\t\t\tif (id !== null && this.waitsOn(b, id))\n+\t\t\t\tthrow new IssuesError(`issue ${b} already waits on issue ${id}, so neither could start`);\n+\t\t}\n+\t\treturn ids;\n+\t}\n+\n+\t/** Whether `from` waits on `on`, through Blocked by. */\n+\tprivate waitsOn(from: number, on: number): boolean {\n+\t\tconst seen = new Set<number>();\n+\t\tconst next = [from];\n+\t\twhile (next.length > 0) {\n+\t\t\tconst at = next.pop()!;\n+\t\t\tif (at === on) return true;\n+\t\t\tif (seen.has(at)) continue;\n+\t\t\tseen.add(at);\n+\t\t\tfor (const b of this.rows(\"SELECT blocker FROM blocked_by WHERE issue = ?\", at)) next.push(b.blocker as number);\n+\t\t}\n+\t\treturn false;\n+\t}\n+\n+\t/** A parent, checked: an issue that exists and isn't `id` or under it. */\n+\tprivate parentFor(id: number | null, value: unknown): number | null {\n+\t\tif (value === undefined || value === null) return null;\n+\t\tconst parent = issueNumber(value, \"the parent\");\n+\t\tthis.exists(parent);\n+\t\tfor (\n+\t\t\tlet at: number | null = parent;\n+\t\t\tat !== null;\n+\t\t\tat = (this.rows(\"SELECT parent FROM issues WHERE id = ?\", at)[0]?.parent as number | null | undefined) ?? null\n+\t\t) {\n+\t\t\tif (at === id) throw new IssuesError(`issue ${parent} is issue ${id} or under it, so it can't be its parent`);\n+\t\t}\n+\t\treturn parent;\n+\t}\n+\n+\t/** Every row's status and joins at once: one query per table, not one per issue. */\n+\tprivate statuses(rows: Row[]): IssueRow[] {\n+\t\tif (rows.length === 0) return [];\n+\t\t// Open asks hold up their own issue and the ones they name in blocks.\n+\t\tconst held = new Map<number, { review: boolean; of: string }[]>();\n+\t\tfor (const a of this.rows(\n+\t\t\t\"SELECT issue, COALESCE(waiting_on, of) AS of, review, blocks FROM asks WHERE answer_at IS NULL\",\n+\t\t)) {\n+\t\t\tconst on = new Set<number>([\n+\t\t\t\t...(a.issue !== null ? [a.issue as number] : []),\n+\t\t\t\t...(JSON.parse(a.blocks as string) as number[]),\n+\t\t\t]);\n+\t\t\tfor (const id of on)\n+\t\t\t\theld.set(id, [...(held.get(id) ?? []), { review: a.review === 1 && id === a.issue, of: a.of as string }]);\n+\t\t}\n+\t\tconst claims = new Map<number, string[]>();\n+\t\tfor (const c of this.rows(\"SELECT issue, agent FROM claims ORDER BY since\"))\n+\t\t\tclaims.set(c.issue as number, [...(claims.get(c.issue as number) ?? []), c.agent as string]);\n+\t\tconst versions = new Map<number, number[]>();\n+\t\tfor (const v of this.rows(\"SELECT issue, version FROM versions ORDER BY version\"))\n+\t\t\tversions.set(v.issue as number, [...(versions.get(v.issue as number) ?? []), v.version as number]);\n+\t\tconst children = new Map<number, number>();\n+\t\tfor (const c of this.rows(\"SELECT parent, COUNT(*) AS n FROM issues WHERE parent IS NOT NULL GROUP BY parent\"))\n+\t\t\tchildren.set(c.parent as number, c.n as number);\n+\t\tconst labels = new Map<number, string[]>();\n+\t\tfor (const l of this.rows(\"SELECT issue, label FROM labels ORDER BY label\"))\n+\t\t\tlabels.set(l.issue as number, [...(labels.get(l.issue as number) ?? []), l.label as string]);\n+\t\t// Blocked by: each blocker, and whether it's Done yet.\n+\t\tconst blockers = new Map<number, { id: number; done: boolean }[]>();\n+\t\tfor (const b of this.rows(\n+\t\t\t\"SELECT blocked_by.issue, blocked_by.blocker, issues.closed_how FROM blocked_by LEFT JOIN issues ON issues.id = blocked_by.blocker ORDER BY blocked_by.blocker\",\n+\t\t)) {\n+\t\t\tblockers.set(b.issue as number, [\n+\t\t\t\t...(blockers.get(b.issue as number) ?? []),\n+\t\t\t\t{ id: b.blocker as number, done: b.closed_how === \"done\" },\n+\t\t\t]);\n+\t\t}\n+\t\tconst retitled = this.lastEditors(\"title\");\n+\t\treturn rows.map((r) => {\n+\t\t\tconst id = r.id as number;\n+\t\t\tconst asks = held.get(id) ?? [];\n+\t\t\tconst agents = claims.get(id) ?? [];\n+\t\t\tconst blockedBy = blockers.get(id) ?? [];\n+\t\t\tconst status: Status =\n+\t\t\t\tr.closed_how === \"done\"\n+\t\t\t\t\t? \"done\"\n+\t\t\t\t\t: r.closed_how === \"dropped\"\n+\t\t\t\t\t\t? \"dropped\"\n+\t\t\t\t\t\t: asks.some((a) => !a.review) || blockedBy.some((b) => !b.done)\n+\t\t\t\t\t\t\t? \"blocked\"\n+\t\t\t\t\t\t\t: asks.length > 0\n+\t\t\t\t\t\t\t\t? \"in review\"\n+\t\t\t\t\t\t\t\t: agents.length > 0\n+\t\t\t\t\t\t\t\t\t? \"in progress\"\n+\t\t\t\t\t\t\t\t\t: \"open\";\n+\t\t\treturn {\n+\t\t\t\tid,\n+\t\t\t\ttitle: r.title as string,\n+\t\t\t\tauthorship: { title: this.issueFieldAuthorship(r, retitled) },\n+\t\t\t\tparent: (r.parent as number | null) ?? null,\n+\t\t\t\tstatus,\n+\t\t\t\tagent: (r.agent as string | null | undefined) ?? null,\n+\t\t\t\tagents,\n+\t\t\t\tblockedBy: blockedBy.map((b) => b.id),\n+\t\t\t\tlabels: labels.get(id) ?? [],\n+\t\t\t\tversions: versions.get(id) ?? [],\n+\t\t\t\twaitingOn: r.closed_how ? [] : [...new Set(asks.map((a) => a.of))],\n+\t\t\t\topened: { by: r.opened_by as string, at: r.opened_at as number },\n+\t\t\t\tupdated: r.updated_at as number,\n+\t\t\t\tclosed: r.closed_how\n+\t\t\t\t\t? {\n+\t\t\t\t\t\t\thow: r.closed_how as \"done\" | \"dropped\",\n+\t\t\t\t\t\t\tby: r.closed_by as string,\n+\t\t\t\t\t\t\tversion: (r.closed_version as number | null) ?? null,\n+\t\t\t\t\t\t\tat: r.closed_at as number,\n+\t\t\t\t\t\t}\n+\t\t\t\t\t: null,\n+\t\t\t\tchildren: children.get(id) ?? 0,\n+\t\t\t};\n+\t\t});\n+\t}\n+\n+\t/** Who last edited `field` on each issue whose `field` was edited (or only issue `id`'s). */\n+\tprivate lastEditors(field: \"title\" | \"description\", id?: number): Map<number, string> {\n+\t\tconst edited = new Map<number, string>();\n+\t\tconst where = `json_type(changes, '$.${field}') IS NOT NULL${id === undefined ? \"\" : \" AND issue = ?\"}`;\n+\t\tfor (const e of this.rows(\n+\t\t\t`SELECT issue, by FROM edits WHERE ${where} ORDER BY id`,\n+\t\t\t...(id === undefined ? [] : [id]),\n+\t\t))\n+\t\t\tedited.set(e.issue as number, e.by as string);\n+\t\treturn edited;\n+\t}\n+\n+\t/** Who wrote an issue's title or description now: whoever last edited it, else whoever opened the issue. */\n+\tprivate issueFieldAuthorship(row: Row, edited: Map<number, string>): ProseAuthorship {\n+\t\tconst editor = edited.get(row.id as number);\n+\t\treturn editor === undefined ? authored(row.opened_by, \"issues.opened_by\") : authored(editor, \"edits.by\");\n+\t}\n+\n+\t/** An ask as the client reads it: each text with who wrote it. */\n+\tprivate authoredAsk(a: StoredAsk): Ask {\n+\t\tconst { ack, ...ask } = a;\n+\t\treturn {\n+\t\t\t...ask,\n+\t\t\tauthorship: { question: authored(a.by, \"asks.by\") },\n+\t\t\tanswer: a.answer ? { ...a.answer, authorship: authored(a.answer.by, \"asks.answer_by\") } : null,\n+\t\t\t...(ack\n+\t\t\t\t? { ack: { ...ack, authorship: { note: ack.note === \"\" ? UNKNOWN : authored(a.of, \"ask_replies.by\") } } }\n+\t\t\t\t: {}),\n+\t\t\treplies: a.replies.map((reply) => ({ ...reply, authorship: authored(reply.by, \"ask_replies.by\") })),\n+\t\t};\n+\t}\n+\n+\t// Reads ----------------------------------------------------------------------------------\n+\n+\t/**\n+\t * Issues, most recently updated first, filtered by status, agent, parent or\n+\t * labels (each one named). `open` leaves out done and dropped.\n+\t */\n+\tlist(\n+\t\tfilter: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},\n+\t): IssueRow[] {\n+\t\tconst wanted = filter.labels === undefined ? [] : labelsOf([...filter.labels], \"the labels to filter by\");\n+\t\tconst rows =\n+\t\t\tfilter.parent === undefined\n+\t\t\t\t? this.rows(\"SELECT * FROM issues ORDER BY updated_at DESC, id DESC\")\n+\t\t\t\t: this.rows(\"SELECT * FROM issues WHERE parent = ? ORDER BY updated_at DESC, id DESC\", filter.parent);\n+\t\treturn this.statuses(rows).filter(\n+\t\t\t(i) =>\n+\t\t\t\t(filter.status === undefined || i.status === filter.status) &&\n+\t\t\t\t(filter.agent === undefined || i.agent === filter.agent || i.agents.includes(filter.agent)) &&\n+\t\t\t\t(!filter.open || (i.status !== \"done\" && i.status !== \"dropped\")) &&\n+\t\t\t\twanted.every((l) => i.labels.includes(l)),\n+\t\t);\n+\t}\n+\n+\t/** Issues matching `q`, best first, one hit per issue at its best place. Drafts aren't searched. */\n+\tsearch(q: string, limit = 20): AuthoredSearchHit[] {\n+\t\tconst query = searchQuery(q);\n+\t\tif (query === undefined) return [];\n+\t\tconst rows = this.rows(\n+\t\t\t\"SELECT issue, comment, field, snippet(search, 3, char(1), char(2), '…', 14) AS snip, bm25(search) AS rank FROM search WHERE search MATCH ? ORDER BY rank LIMIT 500\",\n+\t\t\tquery,\n+\t\t);\n+\t\tconst best = new Map<number, Row>();\n+\t\tfor (const r of rows) if (!best.has(r.issue as number)) best.set(r.issue as number, r);\n+\t\tconst ids = [...best.keys()].slice(0, Math.max(1, Math.min(limit, 50)));\n+\t\tif (ids.length === 0) return [];\n+\t\tconst found = this.rows(`SELECT * FROM issues WHERE id IN (${ids.map(() => \"?\").join(\", \")})`, ...ids);\n+\t\tconst rowOf = new Map(found.map((r) => [r.id as number, r]));\n+\t\tconst issues = new Map(this.statuses(found).map((i) => [i.id, i]));\n+\t\treturn ids.flatMap((id) => {\n+\t\t\tconst r = best.get(id)!;\n+\t\t\tconst i = issues.get(id);\n+\t\t\tif (!i) return [];\n+\t\t\tconst { text, marks } = marked(r.snip as string);\n+\t\t\tconst where = r.field as SearchHit[\"where\"];\n+\t\t\tconst commentId = r.comment as number;\n+\t\t\tconst matchedAuthorship =\n+\t\t\t\twhere === \"comment\"\n+\t\t\t\t\t? authored(this.rows(\"SELECT by FROM comments WHERE id = ?\", commentId)[0]?.by, \"comments.by\")\n+\t\t\t\t\t: where === \"title\"\n+\t\t\t\t\t\t? i.authorship.title\n+\t\t\t\t\t\t: this.issueFieldAuthorship(rowOf.get(id)!, this.lastEditors(\"description\", id));\n+\t\t\treturn [\n+\t\t\t\t{\n+\t\t\t\t\tissue: {\n+\t\t\t\t\t\tid,\n+\t\t\t\t\t\ttitle: i.title,\n+\t\t\t\t\t\tstatus: i.status,\n+\t\t\t\t\t\tupdated: i.updated,\n+\t\t\t\t\t\tlabels: i.labels,\n+\t\t\t\t\t\tauthorship: i.authorship,\n+\t\t\t\t\t},\n+\t\t\t\t\twhere,\n+\t\t\t\t\t...(where === \"comment\" ? { comment: commentId } : {}),\n+\t\t\t\t\tsnippet: text,\n+\t\t\t\t\tmarks,\n+\t\t\t\t\tmatchedAuthorship,\n+\t\t\t\t\tscore: -(r.rank as number),\n+\t\t\t\t},\n+\t\t\t];\n+\t\t});\n+\t}\n+\n+\t/** Every label in use, with how many issues have it and how many of those are open (done and dropped aren't). */\n+\tlabelsInUse(): { label: string; open: number; total: number }[] {\n+\t\treturn this.rows(\n+\t\t\t\"SELECT label, COUNT(*) AS total, SUM(CASE WHEN issues.closed_how IS NULL THEN 1 ELSE 0 END) AS open FROM labels JOIN issues ON issues.id = labels.issue GROUP BY label ORDER BY label\",\n+\t\t).map((r) => ({ label: r.label as string, open: r.open as number, total: r.total as number }));\n+\t}\n+\n+\t/** An ask with its thread, oldest first. */\n+\tprivate withFiles(a: StoredAsk): StoredAsk {\n+\t\treturn { ...a, replies: this.repliesOf(a.id) };\n+\t}\n+\n+\t/** An ask's replies, oldest first. */\n+\tprivate repliesOf(ask: number): StoredAskReply[] {\n+\t\treturn this.rows(\"SELECT id, by, text, question, at FROM ask_replies WHERE ask = ? ORDER BY id\", ask).map((r) => ({\n+\t\t\tid: r.id as number,\n+\t\t\tby: r.by as string,\n+\t\t\ttext: r.text as string,\n+\t\t\tat: r.at as number,\n+\t\t\t...(r.question === 1 ? { question: true as const } : {}),\n+\t\t}));\n+\t}\n+\n+\tpage(id: number): IssuePage {\n+\t\tconst row = this.exists(id);\n+\t\tconst [issue] = this.statuses([row]);\n+\t\treturn {\n+\t\t\tissue: {\n+\t\t\t\t...issue!,\n+\t\t\t\tdescription: row.description as string,\n+\t\t\t\tauthorship: {\n+\t\t\t\t\ttitle: issue!.authorship.title,\n+\t\t\t\t\tdescription: this.issueFieldAuthorship(row, this.lastEditors(\"description\", id)),\n+\t\t\t\t},\n+\t\t\t\tlines: row.lines ? (JSON.parse(row.lines as string) as Lines) : null,\n+\t\t\t\twatchers: this.watchersOf(id),\n+\t\t\t},\n+\t\t\tcomments: this.rows(\"SELECT * FROM comments WHERE issue = ? ORDER BY id\", id).map((c) => ({\n+\t\t\t\tid: c.id as number,\n+\t\t\t\tby: c.by as string,\n+\t\t\t\tkind: c.kind as Comment[\"kind\"],\n+\t\t\t\ttext: c.text as string,\n+\t\t\t\tauthorship: authored(c.by, \"comments.by\"),\n+\t\t\t\tat: c.at as number,\n+\t\t\t})),\n+\t\t\tedits: this.rows(\"SELECT * FROM edits WHERE issue = ? ORDER BY id\", id).map((e) => ({\n+\t\t\t\tid: e.id as number,\n+\t\t\t\tby: e.by as string,\n+\t\t\t\tchanges: JSON.parse(e.changes as string) as Edit[\"changes\"],\n+\t\t\t\tnotified: JSON.parse(e.notified as string) as string[],\n+\t\t\t\tat: e.at as number,\n+\t\t\t})),\n+\t\t\tasks: this.rows(\"SELECT * FROM asks WHERE issue = ? ORDER BY id\", id).map((r) =>\n+\t\t\t\tthis.authoredAsk(this.withFiles(askOf(r))),\n+\t\t\t),\n+\t\t\tclaims: this.rows(\"SELECT agent, change, since FROM claims WHERE issue = ? ORDER BY since\", id).map((c) => ({\n+\t\t\t\tagent: c.agent as string,\n+\t\t\t\tchange: c.change as number,\n+\t\t\t\tsince: c.since as number,\n+\t\t\t})),\n+\t\t\tchildren: this.statuses(this.rows(\"SELECT * FROM issues WHERE parent = ? ORDER BY id\", id)),\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * Open asks of someone (an agent's name or person:<id>), soonest due first, then oldest; every open ask without `of`.\n+\t * When `reader` is the one they're asked of, each listed for the first time is marked seen now; the answer still\n+\t * says null for those, so the reader can tell what's new.\n+\t */\n+\twaiting(of?: string, reader?: string): (Ask & { title: string | null })[] {\n+\t\tconst select =\n+\t\t\t\"SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE answer_at IS NULL\";\n+\t\tconst rows =\n+\t\t\tof === undefined\n+\t\t\t\t? this.rows(`${select} ORDER BY due IS NULL, due, asks.id`)\n+\t\t\t\t: this.rows(`${select} AND COALESCE(waiting_on, of) = ? ORDER BY due IS NULL, due, asks.id`, of);\n+\t\tif (of !== undefined && reader === of)\n+\t\t\tthis.sql.exec(\n+\t\t\t\t\"UPDATE asks SET seen_at = ? WHERE of = ? AND answer_at IS NULL AND seen_at IS NULL\",\n+\t\t\t\tthis.now(),\n+\t\t\t\tof,\n+\t\t\t);\n+\t\treturn rows.map((r) => ({\n+\t\t\t...this.authoredAsk(this.withFiles(askOf(r))),\n+\t\t\ttitle: (r.title as string | null) ?? null,\n+\t\t}));\n+\t}\n+\n+\t/** Asks of someone that have been answered, newest first. */\n+\tanswered(of: string, limit = 50): (Ask & { title: string | null })[] {\n+\t\treturn this.rows(\n+\t\t\t\"SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE answer_at IS NOT NULL AND of = ? ORDER BY answer_at DESC LIMIT ?\",\n+\t\t\tof,\n+\t\t\tlimit,\n+\t\t).map((r) => ({\n+\t\t\t...this.authoredAsk(this.withFiles(askOf(r))),\n+\t\t\ttitle: (r.title as string | null) ?? null,\n+\t\t}));\n+\t}\n+\n+\t/** The asks someone sent: every open one, oldest first, then the latest answered or withdrawn. */\n+\tasked(by: string, answeredLimit = 10): (Ask & { title: string | null })[] {\n+\t\tconst select = \"SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE asks.by = ?\";\n+\t\treturn [\n+\t\t\t...this.rows(`${select} AND answer_at IS NULL ORDER BY asks.id`, by),\n+\t\t\t...this.rows(`${select} AND answer_at IS NOT NULL ORDER BY answer_at DESC LIMIT ?`, by, answeredLimit),\n+\t\t].map((r) => ({ ...this.authoredAsk(this.withFiles(askOf(r))), title: (r.title as string | null) ?? null }));\n+\t}\n+\n+\t/** One ask, open or closed, with its thread and its issue's title. */\n+\taskThread(id: number): Ask & { title: string | null } {\n+\t\tconst r = this.rows(\n+\t\t\t\"SELECT asks.*, issues.title FROM asks LEFT JOIN issues ON issues.id = asks.issue WHERE asks.id = ?\",\n+\t\t\tissueNumber(id, \"an ask number\"),\n+\t\t)[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${id}`, 404);\n+\t\treturn { ...this.authoredAsk(this.withFiles(askOf(r))), title: (r.title as string | null) ?? null };\n+\t}\n+\n+\t// Writes ---------------------------------------------------------------------------------\n+\n+\t/**\n+\t * A new issue. Agent is who it's for, Blocked by the issues it waits on,\n+\t * and Notify who the writer tells. The writer, its Agent and Notify watch\n+\t * it; Agent and Notify hear it now, and the parent's agents hear it too.\n+\t */\n+\topen(actor: Actor, body: Parameters<IssuesStore[\"openRecord\"]>[1]): { id: number; news?: News } {\n+\t\treturn this.transaction(() => this.openRecord(actor, body));\n+\t}\n+\n+\tprivate openRecord(\n+\t\tactor: Actor,\n+\t\tbody: {\n+\t\t\ttitle?: unknown;\n+\t\t\tdescription?: unknown;\n+\t\t\tparent?: unknown;\n+\t\t\tlines?: unknown;\n+\t\t\tagent?: unknown;\n+\t\t\tblockedBy?: unknown;\n+\t\t\tnotify?: unknown;\n+\t\t\tlabels?: unknown;\n+\t\t\tattachments?: unknown;\n+\t\t},\n+\t): { id: number; news?: News } {\n+\t\tconst title = text(body.title, \"the title\", LIMITS.title, true, true);\n+\t\tthis.noAttachments(body.attachments);\n+\t\tconst description = text(body.description, \"the description\", LIMITS.description, false);\n+\t\tconst parent = this.parentFor(null, body.parent);\n+\t\tconst at_ = lines(body.lines);\n+\t\tconst agent = body.agent === undefined ? null : nameOrNone(body.agent, \"the Agent\");\n+\t\tconst blockedBy = this.blockersFor(null, body.blockedBy);\n+\t\tconst notify = names(body.notify, \"Notify\");\n+\t\tconst labels = labelsOf(body.labels);\n+\t\tthis.roomForLabels(labels);\n+\t\tconst open = this.rows(\"SELECT COUNT(*) AS n FROM issues WHERE closed_how IS NULL\")[0]!.n as number;\n+\t\tif (open >= LIMITS.open)\n+\t\t\tthrow new IssuesError(`this project has ${open} open issues, the most it can hold; close some first`);\n+\t\tconst at = this.now();\n+\t\tconst row = this.rows(\n+\t\t\t\"INSERT INTO issues (parent, title, description, opened_by, opened_at, updated_at, lines, agent) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id\",\n+\t\t\tparent,\n+\t\t\ttitle,\n+\t\t\tdescription,\n+\t\t\twho(actor),\n+\t\t\tat,\n+\t\t\tat,\n+\t\t\tat_ ? JSON.stringify(at_) : null,\n+\t\t\tagent,\n+\t\t)[0]!;\n+\t\tconst id = row.id as number;\n+\t\tfor (const b of blockedBy) this.sql.exec(\"INSERT INTO blocked_by (issue, blocker) VALUES (?, ?)\", id, b);\n+\t\tfor (const l of labels)\n+\t\t\tthis.sql.exec(\"INSERT INTO labels (issue, label, by, at) VALUES (?, ?, ?, ?)\", id, l, who(actor), at);\n+\t\tthis.watch(id, who(actor), agent, ...notify);\n+\t\tthis.touch(parent);\n+\t\tconst to = unique([...(agent !== null ? [agent] : []), ...notify]).filter((p) => p !== who(actor));\n+\t\tif (parent === null && to.length === 0) return { id };\n+\t\tconst detail = [\n+\t\t\tagent !== null ? `Agent ${agent}` : \"\",\n+\t\t\tblockedBy.length > 0 ? `blocked by ${blockedBy.join(\", \")}` : \"\",\n+\t\t].filter((d) => d !== \"\");\n+\t\treturn {\n+\t\t\tid,\n+\t\t\tnews: {\n+\t\t\t\tissue: parent,\n+\t\t\t\ttext: `${who(actor)} opened issue ${id}${parent !== null ? ` under issue ${parent}` : \"\"}: ${JSON.stringify(title)}${detail.length > 0 ? ` (${detail.join(\"; \")})` : \"\"}`,\n+\t\t\t\t...(to.length > 0 ? { to } : {}),\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * An edit: title, description, parent, Agent, Blocked by or labels, kept in\n+\t * the issue's activity. It tells the watchers unless `notify` is false;\n+\t * `also` adds people, who watch it from then on (they were named in Notify).\n+\t * Labels are `labels` (the whole set) or `addLabels` and `removeLabels`; an\n+\t * edit that only changes labels tells nobody unless `notify` is true, since\n+\t * agents sort issues by label all the time.\n+\t */\n+\tedit(\n+\t\tactor: Actor,\n+\t\tid: number,\n+\t\tbody: {\n+\t\t\ttitle?: unknown;\n+\t\t\tdescription?: unknown;\n+\t\t\tparent?: unknown;\n+\t\t\tagent?: unknown;\n+\t\t\tblockedBy?: unknown;\n+\t\t\tnotify?: unknown;\n+\t\t\talso?: unknown;\n+\t\t\tlabels?: unknown;\n+\t\t\taddLabels?: unknown;\n+\t\t\tremoveLabels?: unknown;\n+\t\t},\n+\t): { edit: number; notified: string[]; news?: News } {\n+\t\tconst row = this.exists(id);\n+\t\tconst changes: Edit[\"changes\"] = {};\n+\t\tconst sets: [string, unknown][] = [];\n+\t\tif (body.title !== undefined) {\n+\t\t\tconst title = text(body.title, \"the title\", LIMITS.title, true, true);\n+\t\t\tif (title !== row.title) (changes.title = { from: row.title, to: title }), sets.push([\"title\", title]);\n+\t\t}\n+\t\tif (body.description !== undefined) {\n+\t\t\tconst description = text(body.description, \"the description\", LIMITS.description, false);\n+\t\t\tif (description !== row.description)\n+\t\t\t\t(changes.description = { from: row.description, to: description }), sets.push([\"description\", description]);\n+\t\t}\n+\t\tif (body.parent !== undefined) {\n+\t\t\tconst parent = this.parentFor(id, body.parent);\n+\t\t\tif (parent !== ((row.parent as number | null) ?? null))\n+\t\t\t\t(changes.parent = { from: row.parent ?? null, to: parent }), sets.push([\"parent\", parent]);\n+\t\t}\n+\t\tif (body.agent !== undefined) {\n+\t\t\tconst agent = nameOrNone(body.agent, \"the Agent\");\n+\t\t\tif (agent !== ((row.agent as string | null | undefined) ?? null))\n+\t\t\t\t(changes.agent = { from: row.agent ?? null, to: agent }), sets.push([\"agent\", agent]);\n+\t\t}\n+\t\tlet blockedBy: number[] | undefined;\n+\t\tif (body.blockedBy !== undefined) {\n+\t\t\tblockedBy = this.blockersFor(id, body.blockedBy);\n+\t\t\tconst before = this.rows(\"SELECT blocker FROM blocked_by WHERE issue = ? ORDER BY blocker\", id).map(\n+\t\t\t\t(b) => b.blocker as number,\n+\t\t\t);\n+\t\t\tconst after = [...blockedBy].sort((a, b) => a - b);\n+\t\t\tif (before.join() !== after.join()) changes.blockedBy = { from: before, to: after };\n+\t\t\telse blockedBy = undefined;\n+\t\t}\n+\t\tlet labels: string[] | undefined;\n+\t\tif (body.labels !== undefined || body.addLabels !== undefined || body.removeLabels !== undefined) {\n+\t\t\tif (body.labels !== undefined && (body.addLabels !== undefined || body.removeLabels !== undefined))\n+\t\t\t\tthrow new IssuesError(\"labels is the whole set; addLabels and removeLabels change it; send one or the other\");\n+\t\t\tconst before = this.rows(\"SELECT label FROM labels WHERE issue = ? ORDER BY label\", id).map(\n+\t\t\t\t(l) => l.label as string,\n+\t\t\t);\n+\t\t\tconst drop = new Set(labelsOf(body.removeLabels, \"removeLabels\"));\n+\t\t\tconst after =\n+\t\t\t\tbody.labels !== undefined\n+\t\t\t\t\t? labelsOf(body.labels)\n+\t\t\t\t\t: labelsOf([...before.filter((l) => !drop.has(l)), ...labelsOf(body.addLabels, \"addLabels\")]);\n+\t\t\tif (before.join() !== after.join()) {\n+\t\t\t\tthis.roomForLabels(after);\n+\t\t\t\tchanges.labels = { from: before, to: after };\n+\t\t\t\tlabels = after;\n+\t\t\t}\n+\t\t}\n+\t\tif (body.notify !== undefined && typeof body.notify !== \"boolean\")\n+\t\t\tthrow new IssuesError(\"notify is true (tell the watchers, the default) or false (tell nobody)\");\n+\t\tconst also = names(body.also, \"who else to tell\");\n+\t\tif (Object.keys(changes).length === 0) throw new IssuesError(`that changes nothing on issue ${id}`);\n+\t\tconst labelsOnly = Object.keys(changes).every((k) => k === \"labels\");\n+\t\tconst e = this.transaction(() => {\n+\t\t\tfor (const [column, value] of sets) this.sql.exec(`UPDATE issues SET ${column} = ? WHERE id = ?`, value, id);\n+\t\t\tif (blockedBy !== undefined) {\n+\t\t\t\tthis.sql.exec(\"DELETE FROM blocked_by WHERE issue = ?\", id);\n+\t\t\t\tfor (const b of blockedBy) this.sql.exec(\"INSERT INTO blocked_by (issue, blocker) VALUES (?, ?)\", id, b);\n+\t\t\t}\n+\t\t\tif (labels !== undefined) {\n+\t\t\t\t// A label kept keeps who added it and when.\n+\t\t\t\tfor (const l of this.rows(\"SELECT label FROM labels WHERE issue = ?\", id))\n+\t\t\t\t\tif (!labels.includes(l.label as string))\n+\t\t\t\t\t\tthis.sql.exec(\"DELETE FROM labels WHERE issue = ? AND label = ?\", id, l.label);\n+\t\t\t\tfor (const l of labels)\n+\t\t\t\t\tthis.sql.exec(\n+\t\t\t\t\t\t\"INSERT OR IGNORE INTO labels (issue, label, by, at) VALUES (?, ?, ?, ?)\",\n+\t\t\t\t\t\tid,\n+\t\t\t\t\t\tl,\n+\t\t\t\t\t\twho(actor),\n+\t\t\t\t\t\tthis.now(),\n+\t\t\t\t\t);\n+\t\t\t}\n+\t\t\tthis.watch(id, (changes.agent?.to as string | null | undefined) ?? null, ...also);\n+\t\t\tconst notified =\n+\t\t\t\tbody.notify === false || (labelsOnly && body.notify !== true)\n+\t\t\t\t\t? []\n+\t\t\t\t\t: unique([...this.watchersOf(id), ...also]).filter((p) => p !== who(actor));\n+\t\t\tconst edit = this.rows(\n+\t\t\t\t\"INSERT INTO edits (issue, by, changes, notified, at) VALUES (?, ?, ?, ?, ?) RETURNING id\",\n+\t\t\t\tid,\n+\t\t\t\twho(actor),\n+\t\t\t\tJSON.stringify(changes),\n+\t\t\t\tJSON.stringify(notified),\n+\t\t\t\tthis.now(),\n+\t\t\t)[0]!.id as number;\n+\t\t\treturn { id: edit, notified };\n+\t\t});\n+\t\tconst notified = e.notified;\n+\t\tthis.touch(id, (row.parent as number | null) ?? null, (changes.parent?.to as number | null | undefined) ?? null);\n+\t\tif (notified.length === 0) return { edit: e.id as number, notified };\n+\t\tconst title = (changes.title?.to as string | undefined) ?? (row.title as string);\n+\t\tconst said = [\n+\t\t\tchanges.title ? `title was ${JSON.stringify(changes.title.from)}` : \"\",\n+\t\t\tchanges.description ? \"description changed\" : \"\",\n+\t\t\tchanges.parent ? (changes.parent.to === null ? \"no parent now\" : `parent is issue ${changes.parent.to}`) : \"\",\n+\t\t\tchanges.agent ? (changes.agent.to === null ? \"no Agent now\" : `Agent is ${changes.agent.to}`) : \"\",\n+\t\t\tchanges.blockedBy\n+\t\t\t\t? (changes.blockedBy.to as number[]).length === 0\n+\t\t\t\t\t? \"blocked by nothing now\"\n+\t\t\t\t\t: `blocked by ${(changes.blockedBy.to as number[]).join(\", \")}`\n+\t\t\t\t: \"\",\n+\t\t\tchanges.labels\n+\t\t\t\t? (changes.labels.to as string[]).length === 0\n+\t\t\t\t\t? \"no labels now\"\n+\t\t\t\t\t: `labels ${(changes.labels.to as string[]).join(\", \")}`\n+\t\t\t\t: \"\",\n+\t\t].filter((s) => s !== \"\");\n+\t\treturn {\n+\t\t\tedit: e.id as number,\n+\t\t\tnotified,\n+\t\t\tnews: {\n+\t\t\t\tissue: null,\n+\t\t\t\ttext: `${who(actor)} edited issue ${id} (${JSON.stringify(title)}): ${said.join(\"; \")}`,\n+\t\t\t\tto: notified,\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\tcomment(\n+\t\tactor: Actor,\n+\t\tid: number,\n+\t\tbody: { text?: unknown; objection?: unknown; attachments?: unknown },\n+\t): { id: number; news: News } {\n+\t\tconst row = this.exists(id);\n+\t\tconst t = text(body.text, \"the comment\", LIMITS.text);\n+\t\tthis.noAttachments(body.attachments);\n+\t\tconst kind = body.objection === true ? \"objection\" : \"comment\";\n+\t\tconst c = this.rows(\n+\t\t\t\"INSERT INTO comments (issue, by, kind, text, at) VALUES (?, ?, ?, ?, ?) RETURNING id\",\n+\t\t\tid,\n+\t\t\twho(actor),\n+\t\t\tkind,\n+\t\t\tt,\n+\t\t\tthis.now(),\n+\t\t)[0]!;\n+\t\tthis.watch(id, who(actor));\n+\t\tthis.touch(id);\n+\t\t// @name in the text tells that agent too; the project drops names that aren't its agents.\n+\t\tconst mentioned = mentionsIn(t).filter((name) => name !== who(actor));\n+\t\treturn {\n+\t\t\tid: c.id as number,\n+\t\t\tnews: {\n+\t\t\t\tissue: id,\n+\t\t\t\ttext: `${who(actor)} ${kind === \"objection\" ? \"objects\" : \"comments\"} on issue ${id} (${JSON.stringify(row.title)}): ${JSON.stringify(t)}`,\n+\t\t\t\t...(mentioned.length > 0 ? { to: mentioned } : {}),\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * An ask: a question or a task for someone, on an issue or on none. A\n+\t * review ask (`review`) puts its issue In review; any other holds it up\n+\t * (Blocked), and so do the issues it names in `blocks`.\n+\t */\n+\task(\n+\t\tactor: Actor,\n+\t\tbody: {\n+\t\t\tissue?: unknown;\n+\t\t\tof?: unknown;\n+\t\t\tquestion?: unknown;\n+\t\t\treview?: unknown;\n+\t\t\tkind?: unknown;\n+\t\t\tdue?: unknown;\n+\t\t\trecommendation?: unknown;\n+\t\t\toptions?: unknown;\n+\t\t\tblocks?: unknown;\n+\t\t\tattachments?: unknown;\n+\t\t},\n+\t): { id: number; news: News } {\n+\t\tconst issue = body.issue === undefined || body.issue === null ? null : issueNumber(body.issue);\n+\t\tconst row = issue === null ? undefined : this.exists(issue);\n+\t\tif (row?.closed_how) throw new IssuesError(`issue ${issue} is closed`);\n+\t\tconst of = text(body.of, \"who it asks\", 100, true, true);\n+\t\tconst question = text(body.question, \"the question\", LIMITS.text);\n+\t\tconst kind = body.kind === undefined || body.kind === null ? \"question\" : body.kind;\n+\t\tif (kind !== \"question\" && kind !== \"task\")\n+\t\t\tthrow new IssuesError('kind is \"question\", or \"task\" for something only they can do');\n+\t\tconst review = body.review === true;\n+\t\tif (review && issue === null) throw new IssuesError(\"a review ask is on an issue\");\n+\t\tlet due: string | null = null;\n+\t\tif (body.due !== undefined && body.due !== null && body.due !== \"\") {\n+\t\t\tif (typeof body.due !== \"string\" || !/^\\d{4}-\\d{2}-\\d{2}/.test(body.due) || Number.isNaN(Date.parse(body.due)))\n+\t\t\t\tthrow new IssuesError(\"due is a date, like 2026-10-14\");\n+\t\t\tdue = body.due;\n+\t\t}\n+\t\tlet recommendation: { text: string; by: string } | null = null;\n+\t\tif (body.recommendation !== undefined && body.recommendation !== null) {\n+\t\t\tconst r = body.recommendation as { text?: unknown; by?: unknown };\n+\t\t\trecommendation = {\n+\t\t\t\ttext: text(r.text, \"the recommendation\", LIMITS.text),\n+\t\t\t\tby: r.by === undefined ? who(actor) : text(r.by, \"who recommends it\", 100, true, true),\n+\t\t\t};\n+\t\t}\n+\t\tconst options = body.options === undefined || body.options === null ? [] : body.options;\n+\t\tif (!Array.isArray(options) || options.length > LIMITS.options)\n+\t\t\tthrow new IssuesError(`options are a list of up to ${LIMITS.options} choices`);\n+\t\tconst choices = options.map((o, i) => text(o, `option ${i + 1}`, 500, true, true));\n+\t\tconst blocks = body.blocks === undefined || body.blocks === null ? [] : body.blocks;\n+\t\tif (!Array.isArray(blocks) || blocks.length > LIMITS.blocks)\n+\t\t\tthrow new IssuesError(`blocks is a list of up to ${LIMITS.blocks} issue numbers`);\n+\t\tconst held = [...new Set(blocks.map((b) => issueNumber(b, \"an issue it blocks\")))].filter((b) => b !== issue);\n+\t\tfor (const b of held) this.exists(b);\n+\t\tthis.noAttachments(body.attachments);\n+\t\tconst a = this.rows(\n+\t\t\t\"INSERT INTO asks (issue, by, of, kind, question, review, due, recommendation, options, blocks, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id\",\n+\t\t\tissue,\n+\t\t\twho(actor),\n+\t\t\tof,\n+\t\t\tkind,\n+\t\t\tquestion,\n+\t\t\treview ? 1 : 0,\n+\t\t\tdue,\n+\t\t\trecommendation ? JSON.stringify(recommendation) : null,\n+\t\t\tJSON.stringify(choices),\n+\t\t\tJSON.stringify(held),\n+\t\t\tthis.now(),\n+\t\t)[0]!;\n+\t\tif (review && issue !== null) this.watch(issue, of);\n+\t\tthis.touch(issue, ...held);\n+\t\tconst what = review ? \"for a review\" : kind === \"task\" ? \"to do something\" : \"a question\";\n+\t\tconst where = issue === null ? \"\" : ` on issue ${issue} (${JSON.stringify(row!.title)})`;\n+\t\treturn {\n+\t\t\tid: a.id as number,\n+\t\t\t// An agent asked hears how to answer.\n+\t\t\tnews: {\n+\t\t\t\tissue,\n+\t\t\t\ttext: `${who(actor)} asks ${of} ${what}${where}: ${JSON.stringify(question)}${of.startsWith(\"person:\") ? \"\" : ` Answer: abso answer ${a.id} \"...\"`}`,\n+\t\t\t\tto: [of],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/** An answer, in the answerer's own words, kept on the ask. Only the one asked answers; a task is answered \"done\". */\n+\tanswer(\n+\t\tactor: Actor,\n+\t\taskId: number,\n+\t\tbody: {\n+\t\t\twords?: unknown;\n+\t\t\toption?: unknown;\n+\t\t\texpect?: unknown;\n+\t\t\tnote?: unknown;\n+\t\t\tdone?: unknown;\n+\t\t\tattachments?: unknown;\n+\t\t},\n+\t): { ask: Ask; news: News } {\n+\t\tconst r = this.rows(\"SELECT * FROM asks WHERE id = ?\", issueNumber(askId, \"an ask number\"))[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${askId}`, 404);\n+\t\tif (r.of !== who(actor)) throw new IssuesError(`ask ${askId} is for ${r.of as string}, not ${who(actor)}`, 403);\n+\t\tif (r.answer_at !== null && r.answer_at !== undefined)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\tr.outcome === \"withdrawn\"\n+\t\t\t\t\t? `ask ${askId} was withdrawn by ${r.answer_by as string}, who asked it; it needs no answer`\n+\t\t\t\t\t: `ask ${askId} is answered already`,\n+\t\t\t\t409,\n+\t\t\t);\n+\t\tconst words = this.answerWordsFor(r, body);\n+\t\tthis.noAttachments(body.attachments);\n+\t\tconst at = this.now();\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE asks SET answer_by = ?, answer_words = ?, answer_at = ? WHERE id = ?\",\n+\t\t\twho(actor),\n+\t\t\twords,\n+\t\t\tat,\n+\t\t\tr.id,\n+\t\t);\n+\t\tconst ask = this.authoredAsk(\n+\t\t\tthis.withFiles(askOf({ ...r, answer_by: who(actor), answer_words: words, answer_at: at })),\n+\t\t);\n+\t\tthis.touch(ask.issue, ...ask.blocks);\n+\t\treturn {\n+\t\t\task,\n+\t\t\tnews: {\n+\t\t\t\tissue: ask.issue,\n+\t\t\t\ttext: `${who(actor)} answered ${ask.by}'s ${ask.review ? \"review ask\" : ask.kind}${ask.issue !== null ? ` on issue ${ask.issue}` : \"\"}: ${JSON.stringify(words)}`,\n+\t\t\t\tto: [ask.by],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\tprivate answerWordsFor(\n+\t\tr: Row,\n+\t\tbody: { words?: unknown; option?: unknown; expect?: unknown; note?: unknown; done?: unknown },\n+\t): string {\n+\t\tconst askId = r.id as number;\n+\t\tconst options = JSON.parse(r.options as string) as string[];\n+\t\tif (body.option !== undefined && body.option !== null) {\n+\t\t\tconst pick = typeof body.option === \"number\" ? options[body.option] : options.find((o) => o === body.option);\n+\t\t\tif (pick === undefined)\n+\t\t\t\tthrow new IssuesError(`ask ${askId}'s options are: ${options.map((o) => JSON.stringify(o)).join(\", \")}`);\n+\t\t\tif (body.expect !== undefined && body.expect !== pick)\n+\t\t\t\tthrow new IssuesError(\n+\t\t\t\t\t`ask ${askId}'s option ${Number(body.option) + 1} is ${JSON.stringify(pick)}, not the one you picked; look again`,\n+\t\t\t\t\t409,\n+\t\t\t\t);\n+\t\t\tconst note = text(body.note, \"the note\", LIMITS.text, false);\n+\t\t\treturn note === \"\" ? pick : `${pick}\\n\\n${note}`;\n+\t\t}\n+\t\tif (body.done === true && r.kind === \"task\") {\n+\t\t\tconst note = text(body.note, \"the note\", LIMITS.text, false);\n+\t\t\treturn note === \"\" ? \"done\" : `done\\n\\n${note}`;\n+\t\t}\n+\t\treturn text(body.words, \"the answer\", LIMITS.text);\n+\t}\n+\n+\t/**\n+\t * The one asked says they have it and will answer later. The ask stays open and keeps\n+\t * blocking; it shows as acknowledged, and the asker hears it with the note. Acknowledging again updates\n+\t * the note and the time. abso answer closes it as before.\n+\t */\n+\tack(actor: Actor, askId: number, body: { note?: unknown }): { ask: Ask; news: News } {\n+\t\tconst r = this.rows(\"SELECT * FROM asks WHERE id = ?\", issueNumber(askId, \"an ask number\"))[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${askId}`, 404);\n+\t\tif (r.of !== who(actor)) throw new IssuesError(`ask ${askId} is for ${r.of as string}, not ${who(actor)}`, 403);\n+\t\tif (r.answer_at !== null && r.answer_at !== undefined)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\tr.outcome === \"withdrawn\"\n+\t\t\t\t\t? `ask ${askId} was withdrawn by ${r.answer_by as string}, who asked it; it needs no answer`\n+\t\t\t\t\t: `ask ${askId} is answered already`,\n+\t\t\t\t409,\n+\t\t\t);\n+\t\tconst note = text(body.note, \"the note\", LIMITS.text, false);\n+\t\tconst at = this.now();\n+\t\tthis.transaction(() => {\n+\t\t\tthis.sql.exec(\"UPDATE asks SET ack_at = ?, ack_note = ? WHERE id = ?\", at, note, r.id);\n+\t\t\t// The note is a reply in the thread.\n+\t\t\tif (note !== \"\")\n+\t\t\t\tthis.sql.exec(\n+\t\t\t\t\t\"INSERT INTO ask_replies (ask, by, text, question, at) VALUES (?, ?, ?, 0, ?)\",\n+\t\t\t\t\tr.id,\n+\t\t\t\t\twho(actor),\n+\t\t\t\t\tnote,\n+\t\t\t\t\tat,\n+\t\t\t\t);\n+\t\t});\n+\t\tconst ask = this.authoredAsk(this.withFiles(askOf({ ...r, ack_at: at, ack_note: note })));\n+\t\tthis.touch(ask.issue);\n+\t\treturn {\n+\t\t\task,\n+\t\t\tnews: {\n+\t\t\t\tissue: ask.issue,\n+\t\t\t\ttext: `${who(actor)} has your ${ask.review ? \"review ask\" : ask.kind} (ask ${ask.id})${ask.issue !== null ? ` on issue ${ask.issue}` : \"\"} and will answer${note !== \"\" ? `: ${JSON.stringify(note)}` : \".\"}`,\n+\t\t\t\tto: [ask.by],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * A reply on an ask's thread, from the one asked or the asker, open or closed. The other side\n+\t * hears it. Whose turn it is: a reply from the one asked marked as a question waits on the asker; the asker's\n+\t * next reply hands it back. Answering still closes it.\n+\t */\n+\treply(actor: Actor, askId: number, body: { text?: unknown; question?: unknown }): { ask: Ask; news: News } {\n+\t\tconst r = this.rows(\"SELECT * FROM asks WHERE id = ?\", issueNumber(askId, \"an ask number\"))[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${askId}`, 404);\n+\t\tconst me = who(actor);\n+\t\tif (me !== r.of && me !== r.by)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`ask ${askId} is between ${r.by as string} and ${r.of as string}; only they reply on it. abso comment says something on its issue`,\n+\t\t\t\t403,\n+\t\t\t);\n+\t\tconst words = text(body.text, \"the reply\", LIMITS.text);\n+\t\tconst question = body.question === true;\n+\t\tconst open = r.answer_at === null || r.answer_at === undefined;\n+\t\tlet waitingOn = (r.waiting_on as string | null) ?? null;\n+\t\tif (open) {\n+\t\t\tif (me === r.of && me !== r.by) {\n+\t\t\t\tif (question) waitingOn = r.by as string;\n+\t\t\t} else waitingOn = null;\n+\t\t}\n+\t\tconst at = this.now();\n+\t\tthis.transaction(() => {\n+\t\t\tthis.sql.exec(\n+\t\t\t\t\"INSERT INTO ask_replies (ask, by, text, question, at) VALUES (?, ?, ?, ?, ?)\",\n+\t\t\t\tr.id,\n+\t\t\t\tme,\n+\t\t\t\twords,\n+\t\t\t\tquestion ? 1 : 0,\n+\t\t\t\tat,\n+\t\t\t);\n+\t\t\tif (open) this.sql.exec(\"UPDATE asks SET waiting_on = ? WHERE id = ?\", waitingOn, r.id);\n+\t\t});\n+\t\tconst ask = this.authoredAsk(this.withFiles(askOf({ ...r, waiting_on: waitingOn })));\n+\t\tthis.touch(ask.issue);\n+\t\tconst other = me === ask.of ? ask.by : ask.of;\n+\t\tconst turn = open && (waitingOn ?? ask.of) === other ? \" It waits on you.\" : \"\";\n+\t\treturn {\n+\t\t\task,\n+\t\t\tnews: {\n+\t\t\t\tissue: ask.issue,\n+\t\t\t\ttext: `${me} replied on ask ${ask.id}${ask.issue !== null ? ` (issue ${ask.issue})` : \"\"}${question ? \" with a question\" : \"\"}: ${JSON.stringify(words)}${turn}${other.startsWith(\"person:\") ? \"\" : ` abso ask ${ask.id} shows the thread.`}`,\n+\t\t\t\tto: [other],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * The asker takes back an ask nobody needs answered any more. It closes as an answer does\n+\t * (answer_at set, so it leaves waiting and stops blocking), with the asker as answer_by, their note as\n+\t * answer_words, and outcome 'withdrawn'. The one asked hears it.\n+\t */\n+\twithdraw(actor: Actor, askId: number, body: { note?: unknown }): { ask: Ask; news: News } {\n+\t\tconst r = this.rows(\"SELECT * FROM asks WHERE id = ?\", issueNumber(askId, \"an ask number\"))[0];\n+\t\tif (!r) throw new IssuesError(`there's no ask ${askId}`, 404);\n+\t\tif (r.by !== who(actor))\n+\t\t\tthrow new IssuesError(`ask ${askId} was asked by ${r.by as string}; only they can withdraw it`, 403);\n+\t\tif (r.answer_at !== null && r.answer_at !== undefined)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\tr.outcome === \"withdrawn\"\n+\t\t\t\t\t? `ask ${askId} is withdrawn already`\n+\t\t\t\t\t: `ask ${askId} is answered already, so there's nothing to withdraw`,\n+\t\t\t\t409,\n+\t\t\t);\n+\t\tconst note = text(body.note, \"the note\", LIMITS.text, false);\n+\t\tconst at = this.now();\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE asks SET answer_by = ?, answer_words = ?, answer_at = ?, outcome = 'withdrawn' WHERE id = ?\",\n+\t\t\twho(actor),\n+\t\t\tnote,\n+\t\t\tat,\n+\t\t\tr.id,\n+\t\t);\n+\t\tconst ask = this.authoredAsk(\n+\t\t\tthis.withFiles(askOf({ ...r, answer_by: who(actor), answer_words: note, answer_at: at, outcome: \"withdrawn\" })),\n+\t\t);\n+\t\tthis.touch(ask.issue, ...ask.blocks);\n+\t\treturn {\n+\t\t\task,\n+\t\t\tnews: {\n+\t\t\t\tissue: ask.issue,\n+\t\t\t\ttext: `${who(actor)} withdrew their ${ask.review ? \"review ask\" : ask.kind} of ${ask.of}${ask.issue !== null ? ` on issue ${ask.issue}` : \"\"}${note !== \"\" ? `: ${JSON.stringify(note)}` : \"\"}`,\n+\t\t\t\tto: [ask.of],\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t/** Dropped by hand; done comes only from a publish (the done hook). */\n+\tdrop(actor: Actor, id: number): { news: News } {\n+\t\tconst row = this.exists(id);\n+\t\tif (row.closed_how)\n+\t\t\tthrow new IssuesError(`issue ${id} is ${row.closed_how === \"done\" ? \"done\" : \"dropped\"} already`, 409);\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE issues SET closed_how = 'dropped', closed_by = ?, closed_at = ?, updated_at = ? WHERE id = ?\",\n+\t\t\twho(actor),\n+\t\t\tthis.now(),\n+\t\t\tthis.now(),\n+\t\t\tid,\n+\t\t);\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ?\", id);\n+\t\treturn { news: { issue: id, text: `${who(actor)} dropped issue ${id} (${JSON.stringify(row.title)})` } };\n+\t}\n+\n+\t/** A dropped issue opens again. A done issue stays done. */\n+\treopen(actor: Actor, id: number): { news: News } {\n+\t\tconst row = this.exists(id);\n+\t\tif (row.closed_how !== \"dropped\")\n+\t\t\tthrow new IssuesError(\n+\t\t\t\trow.closed_how === \"done\" ? `issue ${id} is done; it stays done` : `issue ${id} is open`,\n+\t\t\t\t409,\n+\t\t\t);\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE issues SET closed_how = NULL, closed_by = NULL, closed_version = NULL, closed_at = NULL, updated_at = ? WHERE id = ?\",\n+\t\t\tthis.now(),\n+\t\t\tid,\n+\t\t);\n+\t\tthis.touch(id);\n+\t\treturn { news: { issue: id, text: `${who(actor)} reopened issue ${id} (${JSON.stringify(row.title)})` } };\n+\t}\n+\n+\t/**\n+\t * Marked done by hand, by a person or an agent. `version`, when\n+\t * given, is the published version that did the work. A dropped issue is reopened first.\n+\t */\n+\tmarkDone(actor: Actor, id: number, version: number | null): { news: News } {\n+\t\tconst row = this.exists(id);\n+\t\tif (row.closed_how === \"dropped\")\n+\t\t\tthrow new IssuesError(`issue ${id} is dropped; reopen it before marking it done`, 409);\n+\t\tif (row.closed_how === \"done\") throw new IssuesError(`issue ${id} is done already`, 409);\n+\t\tif (version !== null && (!Number.isInteger(version) || version < 1))\n+\t\t\tthrow new IssuesError(\"version is a published version, 1 or more\");\n+\t\tconst at = this.now();\n+\t\tconst by = who(actor);\n+\t\tif (version !== null)\n+\t\t\tthis.sql.exec(\n+\t\t\t\t\"INSERT INTO versions (issue, version, agent, at) VALUES (?, ?, ?, ?) ON CONFLICT (issue, version) DO NOTHING\",\n+\t\t\t\tid,\n+\t\t\t\tversion,\n+\t\t\t\tby,\n+\t\t\t\tat,\n+\t\t\t);\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE issues SET closed_how = 'done', closed_by = ?, closed_version = ?, closed_at = ?, updated_at = ? WHERE id = ?\",\n+\t\t\tby,\n+\t\t\tversion,\n+\t\t\tat,\n+\t\t\tat,\n+\t\t\tid,\n+\t\t);\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ?\", id);\n+\t\tconst where = version === null ? \"by hand\" : `in version ${version}`;\n+\t\treturn {\n+\t\t\tnews: { issue: id, text: `${by} marked issue ${id} (${JSON.stringify(row.title)}) done ${where}` },\n+\t\t};\n+\t}\n+\n+\t/**\n+\t * Refuses a write past the writer's limit: WRITES_PER_MINUTE a\n+\t * minute and WRITES_PER_DAY a day, opens, edits, comments, asks, answers and\n+\t * drops together. A 429 says when to try again.\n+\t */\n+\tcheckLimit(actor: Actor): void {\n+\t\tconst now = this.now();\n+\t\tthis.sql.exec(\"DELETE FROM writes WHERE who = ? AND at <= ?\", who(actor), now - 86_400_000);\n+\t\tconst times = this.rows(\"SELECT at FROM writes WHERE who = ? ORDER BY at\", who(actor)).map((w) => w.at as number);\n+\t\tconst minute = times.filter((t) => now - t < 60_000);\n+\t\tif (minute.length >= WRITES_PER_MINUTE)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`at most ${WRITES_PER_MINUTE} issue writes a minute; try again shortly`,\n+\t\t\t\t429,\n+\t\t\t\tMath.max(1, Math.ceil((minute[0]! + 60_000 - now) / 1000)),\n+\t\t\t);\n+\t\tif (times.length >= WRITES_PER_DAY)\n+\t\t\tthrow new IssuesError(\n+\t\t\t\t`at most ${WRITES_PER_DAY} issue writes a day in a project`,\n+\t\t\t\t429,\n+\t\t\t\tMath.max(1, Math.ceil((times[0]! + 86_400_000 - now) / 1000)),\n+\t\t\t);\n+\t}\n+\n+\t/** Counts a write that went through. */\n+\twrote(actor: Actor): void {\n+\t\tthis.sql.exec(\"INSERT INTO writes (who, at) VALUES (?, ?)\", who(actor), this.now());\n+\t}\n+\n+\t// Drafts: a writer's own, with no number and no news ------------------------\n+\n+\t/** The actor's drafts, newest first. Nobody else's. */\n+\tdrafts(actor: Actor): Draft[] {\n+\t\treturn this.rows(\"SELECT * FROM drafts WHERE owner = ? ORDER BY saved_at DESC, id DESC\", who(actor)).map(asDraft);\n+\t}\n+\n+\t/**\n+\t * Saves a draft, new or (with `id`) over one of the actor's. Any field may\n+\t * be empty; what's there is checked as open would check it, but not whether\n+\t * the issues it names still exist (that waits for opening).\n+\t */\n+\tsaveDraft(\n+\t\tactor: Actor,\n+\t\tbody: {\n+\t\t\tid?: unknown;\n+\t\t\ttitle?: unknown;\n+\t\t\tdescription?: unknown;\n+\t\t\tparent?: unknown;\n+\t\t\tlines?: unknown;\n+\t\t\tagent?: unknown;\n+\t\t\tblockedBy?: unknown;\n+\t\t\tnotify?: unknown;\n+\t\t\tlabels?: unknown;\n+\t\t},\n+\t): { id: number } {\n+\t\tconst draft: DraftBody = {};\n+\t\tconst title = text(body.title, \"the title\", LIMITS.title, false, true);\n+\t\tif (title !== \"\") draft.title = title;\n+\t\tconst description = text(body.description, \"the description\", LIMITS.description, false);\n+\t\tif (description !== \"\") draft.description = description;\n+\t\tif (body.parent !== undefined && body.parent !== null) draft.parent = issueNumber(body.parent, \"the parent\");\n+\t\tconst l = lines(body.lines);\n+\t\tif (l !== null) draft.lines = l;\n+\t\tif (body.agent !== undefined && body.agent !== null && body.agent !== \"\")\n+\t\t\tdraft.agent = nameOrNone(body.agent, \"the Agent\");\n+\t\tif (body.blockedBy !== undefined && body.blockedBy !== null) {\n+\t\t\tif (!Array.isArray(body.blockedBy) || body.blockedBy.length > LIMITS.blocks)\n+\t\t\t\tthrow new IssuesError(`blocked by is a list of up to ${LIMITS.blocks} issue numbers`);\n+\t\t\tdraft.blockedBy = [...new Set(body.blockedBy.map((b) => issueNumber(b, \"an issue it's blocked by\")))];\n+\t\t}\n+\t\tconst notify = names(body.notify, \"Notify\");\n+\t\tif (notify.length > 0) draft.notify = notify;\n+\t\tconst labels = labelsOf(body.labels);\n+\t\tif (labels.length > 0) draft.labels = labels;\n+\t\tconst saved = JSON.stringify(draft);\n+\t\tif (saved.length > LIMITS.draft) throw new IssuesError(`a draft holds at most ${LIMITS.draft} characters`);\n+\t\tif (body.id !== undefined && body.id !== null) {\n+\t\t\tconst id = this.draftOf(actor, body.id).id as number;\n+\t\t\tthis.sql.exec(\"UPDATE drafts SET body = ?, saved_at = ? WHERE id = ?\", saved, this.now(), id);\n+\t\t\treturn { id };\n+\t\t}\n+\t\tconst n = this.rows(\"SELECT COUNT(*) AS n FROM drafts WHERE owner = ?\", who(actor))[0]!.n as number;\n+\t\tif (n >= LIMITS.drafts)\n+\t\t\tthrow new IssuesError(`you have ${n} drafts, the most there can be; open or delete some first`);\n+\t\treturn {\n+\t\t\tid: this.rows(\n+\t\t\t\t\"INSERT INTO drafts (owner, body, saved_at) VALUES (?, ?, ?) RETURNING id\",\n+\t\t\t\twho(actor),\n+\t\t\t\tsaved,\n+\t\t\t\tthis.now(),\n+\t\t\t)[0]!.id as number,\n+\t\t};\n+\t}\n+\n+\tdeleteDraft(actor: Actor, id: number): void {\n+\t\tthis.sql.exec(\"DELETE FROM drafts WHERE id = ?\", this.draftOf(actor, id).id);\n+\t}\n+\n+\t/** Opens a draft as an issue, with `body`'s fields over the draft's, and deletes the draft. The issue's news is the only news. */\n+\topenDraft(actor: Actor, id: number, body: Record<string, unknown> = {}): { id: number; news?: News } {\n+\t\tconst d = this.draftOf(actor, id);\n+\t\tconst opened = this.open(actor, { ...(JSON.parse(d.body as string) as DraftBody), ...body });\n+\t\tthis.sql.exec(\"DELETE FROM drafts WHERE id = ?\", d.id);\n+\t\treturn opened;\n+\t}\n+\n+\t/** One of the actor's drafts; another's is \"no such draft\", as if it weren't there. */\n+\tprivate draftOf(actor: Actor, id: unknown): Row {\n+\t\tconst row = this.rows(\n+\t\t\t\"SELECT * FROM drafts WHERE id = ? AND owner = ?\",\n+\t\t\tissueNumber(id, \"a draft number\"),\n+\t\t\twho(actor),\n+\t\t)[0];\n+\t\tif (!row) throw new IssuesError(`you have no draft ${String(id)}`, 404);\n+\t\treturn row;\n+\t}\n+\t// From the project: start notes and publish --done ----------------------------------------\n+\n+\t/** A start note names the issue (`change` is the note's log position). One that doesn't exist, or is closed, is ignored: the note stands either way. */\n+\tclaim(agent: string, id: number, change: number): void {\n+\t\tconst row = this.rows(\"SELECT closed_how FROM issues WHERE id = ?\", id)[0];\n+\t\tif (!row || row.closed_how) return;\n+\t\tthis.sql.exec(\n+\t\t\t\"INSERT INTO claims (issue, agent, change, since) VALUES (?, ?, ?, ?) ON CONFLICT (issue, agent) DO UPDATE SET change = excluded.change, since = excluded.since\",\n+\t\t\tid,\n+\t\t\tagent,\n+\t\t\tchange,\n+\t\t\tthis.now(),\n+\t\t);\n+\t\tthis.sql.exec(\"UPDATE issues SET agent = ? WHERE id = ? AND agent IS NULL\", agent, id);\n+\t\tthis.watch(id, agent);\n+\t\tthis.touch(id);\n+\t}\n+\n+\t/** The start note ended without finishing the issue. */\n+\tunclaim(agent: string, id: number): void {\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ? AND agent = ?\", id, agent);\n+\t\tthis.touch(id);\n+\t}\n+\n+\t/** publish --done finished it, with that version of shared: done, and the version is one out for it. */\n+\tdone(agent: string, id: number, version: number): { news?: News } {\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ? AND agent = ?\", id, agent);\n+\t\tconst row = this.rows(\"SELECT title, closed_how FROM issues WHERE id = ?\", id)[0];\n+\t\tif (!row) return {};\n+\t\tthis.sql.exec(\n+\t\t\t\"INSERT INTO versions (issue, version, agent, at) VALUES (?, ?, ?, ?) ON CONFLICT (issue, version) DO NOTHING\",\n+\t\t\tid,\n+\t\t\tversion,\n+\t\t\tagent,\n+\t\t\tthis.now(),\n+\t\t);\n+\t\tthis.touch(id);\n+\t\tif (row.closed_how) return {};\n+\t\tthis.sql.exec(\n+\t\t\t\"UPDATE issues SET closed_how = 'done', closed_by = ?, closed_version = ?, closed_at = ? WHERE id = ?\",\n+\t\t\tagent,\n+\t\t\tversion,\n+\t\t\tthis.now(),\n+\t\t\tid,\n+\t\t);\n+\t\tthis.sql.exec(\"DELETE FROM claims WHERE issue = ?\", id);\n+\t\treturn {\n+\t\t\tnews: { issue: id, text: `${agent} finished issue ${id} (${JSON.stringify(row.title)}) in version ${version}` },\n+\t\t};\n+\t}\n+}\n+\n+function asDraft(d: Row): Draft {\n+\treturn {\n+\t\tid: d.id as number,\n+\t\tbody: JSON.parse(d.body as string) as DraftBody,\n+\t\tsaved: d.saved_at as number,\n+\t};\n+}\n+\n+/** A snippet with \\u0001 and \\u0002 around each match, as plain text and the matches' spans. */\n+function marked(snip: string): { text: string; marks: number[][] } {\n+\tlet text = \"\";\n+\tconst marks: number[][] = [];\n+\tlet open = -1;\n+\tfor (const ch of snip) {\n+\t\tif (ch === \"\\u0001\") open = text.length;\n+\t\telse if (ch === \"\\u0002\") {\n+\t\t\tif (open >= 0) marks.push([open, text.length]);\n+\t\t\topen = -1;\n+\t\t} else text += ch;\n+\t}\n+\treturn { text, marks };\n+}\n+\n+function askOf(r: Row): StoredAsk {\n+\treturn {\n+\t\tid: r.id as number,\n+\t\tissue: (r.issue as number | null) ?? null,\n+\t\tby: r.by as string,\n+\t\tof: r.of as string,\n+\t\tkind: r.kind as Ask[\"kind\"],\n+\t\tquestion: r.question as string,\n+\t\treview: r.review === 1,\n+\t\tdue: (r.due as string | null) ?? null,\n+\t\trecommendation: r.recommendation ? (JSON.parse(r.recommendation as string) as Ask[\"recommendation\"]) : null,\n+\t\toptions: JSON.parse(r.options as string) as string[],\n+\t\tblocks: JSON.parse(r.blocks as string) as number[],\n+\t\tat: r.at as number,\n+\t\tanswer:\n+\t\t\tr.answer_at !== null && r.answer_at !== undefined\n+\t\t\t\t? { by: r.answer_by as string, words: r.answer_words as string, at: r.answer_at as number }\n+\t\t\t\t: null,\n+\t\tseen: (r.seen_at as number | null | undefined) ?? null,\n+\t\twaitingOn:\n+\t\t\tr.answer_at !== null && r.answer_at !== undefined ? null : ((r.waiting_on as string | null) ?? (r.of as string)),\n+\t\treplies: [],\n+\t\t...(r.outcome === \"withdrawn\" ? { outcome: \"withdrawn\" as const } : {}),\n+\t\t...(typeof r.ack_at === \"number\" ? { ack: { at: r.ack_at, note: (r.ack_note as string | null) ?? \"\" } } : {}),\n+\t};\n+}"},{"path":"server/test/e2e-transcript.md","added":116,"removed":1,"diff":"--- a/server/test/e2e-transcript.md\n+++ b/server/test/e2e-transcript.md\n@@ -128,5 +128,120 @@\n - 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`.\n - 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.\n - `GET head` answers `{version, at}` from storage. `GET feed?from=<end>&wait=3` holds for 3 seconds, then answers with no events.\n-- `/issues/p/<project>/...` reaches the issues stand-in (404 `issues aren't on this server yet`) after auth.\n+- `/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.\n - `POST git-remote` with Artifacts off: 501 `this server has no Artifacts binding, so no git remote`.\n+\n+## Issues, asks and news, with no issues server named\n+\n+Server: `http://127.0.0.1:8797` (`npm run dev` in server/, which is `wrangler dev --local`; `ABSO_ARTIFACTS=off`).\n+Token: an invented local test token in `server/.dev.vars`, given to the client as `ABSO_TOKEN`.\n+HOME and USERPROFILE: a new empty temporary folder, so no `~/.abso/servers.json`; `ABSO_ISSUES_SERVER` unset.\n+The client finds issues at `http://127.0.0.1:8797/issues`. Project: `e2e-issues-1791907724`. Run 2026-10-13T16:08Z.\n+\n+```\n+(alice) $ abso init . --server http://127.0.0.1:8797 --project e2e-issues-1791907724 --agent alice\n+Created project e2e-issues-1791907724 at version 0 from 2 text files in <temp>\\alice.\n+Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore.\n+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).\n+This folder is agent alice. Settings are in .abso/config.json.\n+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.\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso join e2e-issues-1791907724 --agent bob --dir . --server http://127.0.0.1:8797\n+Joined e2e-issues-1791907724 as bob at version 0: wrote 2 files into <temp>\\bob.\n+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.\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso issue new \"Sync is slow on big folders\" --description \"A pull of 5000 files takes a minute.\"\n+Opened issue 1. abso start \"...\" --issue 1 starts on it.\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso issue 1 --comment \"Seen it too: most of the minute is hashing.\"\n+Commented on issue 1. Its agents hear it.\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso ask bob \"Hash on the server or in the client?\" --issue 1\n+Asked bob (ask 1). They hear it; abso waiting shows what's open.\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso ask carol \"Can you review the hashing?\" --issue 1\n+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.\n+[exit 1]\n+```\n+\n+```\n+(bob) $ abso news\n+1 news item:\n+  alice (as claimed) told you, 16:08 UTC:\n+    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 \"...\"\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso waiting --mine\n+1 open ask of bob, soonest due first:\n+  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?\"\n+abso ask <N> shows one with its thread; abso reply <N> \"...\" adds to it; abso answer <N> \"...\" answers one asked of you.\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso issues\n+1 issue, most recently updated first:\n+    1  blocked      \"Sync is slow on big folders\" (waiting on bob; updated 16:08 UTC)\n+abso issue <N> shows one.\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso answer 1 \"In the client: the server never sees unchanged files.\"\n+Answered ask 1. alice hears it.\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso news\n+1 news item:\n+  bob (as claimed) told you, 16:08 UTC:\n+    bob answered alice's question on issue 1: \"In the client: the server never sees unchanged files.\"\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso issue 1\n+Issue 1: \"Sync is slow on big folders\" [open]\n+Opened by alice, 16:08 UTC.\n+\n+  A pull of 5000 files takes a minute.\n+\n+Asks:\n+  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?\"\n+    answer: \"In the client: the server never sees unchanged files.\"\n+\n+Comments:\n+  bob, 16:08 UTC: \"Seen it too: most of the minute is hashing.\"\n+\n+Watchers: alice, bob.\n+\n+abso start \"...\" --issue 1 starts on it; abso issue 1 --comment \"...\" comments; abso ask <who> \"...\" --issue 1 asks.\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso waiting --asked\n+The latest answered:\n+  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?\"\n+    answer: \"In the client: the server never sees unchanged files.\"\n+abso ask <N> shows one with its whole thread.\n+[exit 0]\n+```"},{"path":"server/test/issues/ask-threads.test.ts","added":193,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/issues/ask-threads.test.ts\n@@ -0,0 +1,193 @@\n+// Ask threads: replies from either side, whose turn it is, the\n+// asks someone sent, one ask with its thread, and asks going only to seats.\n+\n+import assert from \"node:assert/strict\";\n+import { DatabaseSync } from \"node:sqlite\";\n+import { describe, it } from \"node:test\";\n+import { issuesRoute } from \"../../src/issues/routes.ts\";\n+import { closestSeat, seatRefusal } from \"../../src/issues/seats.ts\";\n+import { IssuesStore, type Sql } from \"../../src/issues/store.ts\";\n+\n+function sql(): Sql {\n+\tconst db = new DatabaseSync(\":memory:\");\n+\treturn {\n+\t\texec: (q, ...b) => {\n+\t\t\tif (/^\\s*CREATE\\b/i.test(q)) {\n+\t\t\t\tdb.exec(q);\n+\t\t\t\treturn { toArray: () => [] };\n+\t\t\t}\n+\t\t\tconst rows = db.prepare(q).all(...(b as (string | number | null)[]));\n+\t\t\treturn { toArray: () => rows };\n+\t\t},\n+\t};\n+}\n+\n+function store(): { s: IssuesStore; db: Sql; tick: (ms?: number) => void } {\n+\tlet t = Date.parse(\"2026-10-10T05:00:00Z\");\n+\tconst db = sql();\n+\tIssuesStore.createTables(db);\n+\treturn { s: new IssuesStore(db, () => t), db, tick: (ms = 1000) => void (t += ms) };\n+}\n+\n+const desk = { agent: \"desk\" };\n+const fay = { agent: \"fay\" };\n+\n+describe(\"ask threads\", () => {\n+\tit(\"replies from both sides, oldest first; a question back waits on the asker until they reply\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst id = s.open(desk, { title: \"Sync is slow\" }).id;\n+\t\tconst ask = s.ask(desk, { issue: id, of: \"fay\", question: \"Which way?\" });\n+\t\tassert.equal(s.askThread(ask.id).waitingOn, \"fay\");\n+\n+\t\ttick();\n+\t\ts.ack(fay, ask.id, { note: \"ok, let me check\" });\n+\t\ttick();\n+\t\tconst back = s.reply(fay, ask.id, { text: \"staging or live?\", question: true });\n+\t\tassert.equal(back.ask.waitingOn, \"desk\");\n+\t\tassert.deepEqual(back.news.to, [\"desk\"]);\n+\t\tassert.equal(\n+\t\t\tback.news.text,\n+\t\t\t`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.`,\n+\t\t);\n+\t\tassert.deepEqual(\n+\t\t\tback.ask.replies!.map((r) => [r.by, r.text, r.question === true]),\n+\t\t\t[\n+\t\t\t\t[\"fay\", \"ok, let me check\", false],\n+\t\t\t\t[\"fay\", \"staging or live?\", true],\n+\t\t\t],\n+\t\t);\n+\t\t// It's in the asker's waiting list now, not the one asked's, and the issue waits on the asker.\n+\t\tassert.deepEqual(\n+\t\t\ts.waiting(\"desk\").map((a) => a.id),\n+\t\t\t[ask.id],\n+\t\t);\n+\t\tassert.deepEqual(s.waiting(\"fay\"), []);\n+\t\tassert.deepEqual(s.page(id).issue.waitingOn, [\"desk\"]);\n+\n+\t\ttick();\n+\t\tconst handed = s.reply(desk, ask.id, { text: \"live\" });\n+\t\tassert.equal(handed.ask.waitingOn, \"fay\");\n+\t\tassert.deepEqual(handed.news.to, [\"fay\"]);\n+\t\tassert.match(handed.news.text, /^desk replied on ask \\d+ \\(issue \\d+\\): \"live\" It waits on you\\./);\n+\t\tassert.deepEqual(\n+\t\t\ts.waiting(\"fay\").map((a) => a.id),\n+\t\t\t[ask.id],\n+\t\t);\n+\n+\t\t// A plain reply from the one asked leaves the turn where it is.\n+\t\tassert.equal(s.reply(fay, ask.id, { text: \"deploying\" }).ask.waitingOn, \"fay\");\n+\n+\t\t// Answering closes it; a reply after still lands, and waits on nobody.\n+\t\ts.answer(fay, ask.id, { words: \"done on live\" });\n+\t\tconst after = s.reply(desk, ask.id, { text: \"thanks\" });\n+\t\tassert.equal(after.ask.waitingOn, null);\n+\t\tassert.equal(after.ask.answer!.words, \"done on live\");\n+\t\tassert.equal(after.ask.replies!.length, 5);\n+\t\tassert.equal(s.page(id).asks[0]!.replies!.length, 5);\n+\t\tassert.deepEqual(s.waiting(\"fay\"), []);\n+\t\tassert.deepEqual(s.waiting(\"desk\"), []);\n+\t});\n+\n+\tit(\"only the two reply, with words, on an ask that exists\", () => {\n+\t\tconst { s } = store();\n+\t\tconst ask = s.ask(desk, { of: \"fay\", question: \"Pick one\" });\n+\t\tassert.throws(\n+\t\t\t() => s.reply({ agent: \"eve\" }, ask.id, { text: \"me too\" }),\n+\t\t\t(e: { status?: number; message: string }) =>\n+\t\t\t\te.status === 403 && /between desk and fay; only they reply on it/.test(e.message),\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() => s.reply(fay, 99, { text: \"x\" }),\n+\t\t\t(e: { status?: number }) => e.status === 404,\n+\t\t);\n+\t\tassert.throws(() => s.reply(fay, ask.id, { text: \"\" }));\n+\t\tassert.throws(() => s.reply(fay, ask.id, {}));\n+\t});\n+\n+\tit(\"an ack with no note adds no reply; ack's note is the thread's first\", () => {\n+\t\tconst { s } = store();\n+\t\tconst ask = s.ask(desk, { of: \"fay\", question: \"Pick one\" });\n+\t\tassert.deepEqual(s.ack(fay, ask.id, {}).ask.replies, []);\n+\t\tassert.equal(s.ack(fay, ask.id, { note: \"soon\" }).ask.replies![0]!.text, \"soon\");\n+\t});\n+\n+\tit(\"asked lists what someone sent: open oldest first, then the latest answered\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst a = s.ask(desk, { of: \"fay\", question: \"One\" });\n+\t\ttick();\n+\t\tconst b = s.ask(desk, { of: \"fay\", question: \"Two\" });\n+\t\ttick();\n+\t\tconst c = s.ask(desk, { of: \"fay\", question: \"Three\" });\n+\t\ts.ask(fay, { of: \"desk\", question: \"Not desk's\" });\n+\t\ts.answer(fay, b.id, { words: \"yes\" });\n+\t\tassert.deepEqual(\n+\t\t\ts.asked(\"desk\").map((x) => x.id),\n+\t\t\t[a.id, c.id, b.id],\n+\t\t);\n+\t});\n+});\n+\n+describe(\"ask thread routes\", () => {\n+\tconst call = (\n+\t\ts: IssuesStore,\n+\t\tmethod: string,\n+\t\tpath: string,\n+\t\tbody?: unknown,\n+\t\tseatError?: (of: string) => Promise<string | null>,\n+\t) =>\n+\t\tissuesRoute(\n+\t\t\ts,\n+\t\t\tnew Request(`https://issues.internal${path}`, {\n+\t\t\t\tmethod,\n+\t\t\t\t...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n+\t\t\t}),\n+\t\t\tseatError,\n+\t\t).then(async (r) => ({ status: r.status, json: (await r.json()) as Record<string, any> }));\n+\n+\tit(\"POST a/<agent>/reply/N, GET ask/N, GET a/<agent>/asked and asked?by=\", async () => {\n+\t\tconst { s } = store();\n+\t\tconst ask = s.ask(desk, { of: \"fay\", question: \"Which way?\" });\n+\t\tconst r = await call(s, \"POST\", `/p/web/a/fay/reply/${ask.id}`, { text: \"live?\", question: true });\n+\t\tassert.equal(r.status, 200, JSON.stringify(r.json));\n+\t\tassert.equal(r.json.ask.waitingOn, \"desk\");\n+\t\tconst one = await call(s, \"GET\", `/p/web/ask/${ask.id}`);\n+\t\tassert.equal(one.json.ask.replies[0].text, \"live?\");\n+\t\tassert.equal((await call(s, \"GET\", \"/p/web/ask/99\")).status, 404);\n+\t\tconst mine = await call(s, \"GET\", \"/p/web/a/desk/asked\");\n+\t\tassert.deepEqual(\n+\t\t\tmine.json.asks.map((a: { id: number }) => a.id),\n+\t\t\t[ask.id],\n+\t\t);\n+\t\tassert.equal((await call(s, \"GET\", \"/p/web/asked?by=desk\")).json.asks.length, 1);\n+\t\tassert.equal((await call(s, \"GET\", \"/p/web/asked\")).status, 400);\n+\t});\n+\n+\tit(\"a new ask to a name that isn't a seat is refused, naming the closest seat\", async () => {\n+\t\tconst { s } = store();\n+\t\tconst seats = [\"cloud\", \"agentvcs\", \"pinch\", \"infra-ops\"];\n+\t\tconst check = async (of: string) => (of.startsWith(\"person:\") ? null : seatRefusal(of, \"web\", seats));\n+\t\tconst refused = await call(s, \"POST\", \"/p/web/a/desk/ask\", { of: \"abso - Cloud Infra Lead\", question: \"Q\" }, check);\n+\t\tassert.equal(refused.status, 400);\n+\t\tassert.equal(\n+\t\t\trefused.json.error,\n+\t\t\t'\"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.',\n+\t\t);\n+\t\tassert.deepEqual(s.asked(\"desk\"), []);\n+\t\tassert.equal((await call(s, \"POST\", \"/p/web/a/desk/ask\", { of: \"cloud\", question: \"Q\" }, check)).status, 200);\n+\t});\n+\n+\tit(\"closestSeat: the same name written another way, a seat the name holds, then a near spelling\", () => {\n+\t\tconst seats = [\"cloud\", \"agentvcs\", \"pinch\", \"infra-ops\", \"security-2\"];\n+\t\tassert.equal(closestSeat(\"Agent VCS\", seats), \"agentvcs\");\n+\t\tassert.equal(closestSeat(\"abso - Cloud Infra Lead\", seats), \"cloud\");\n+\t\tassert.equal(closestSeat(\"Security 2\", seats), \"security-2\");\n+\t\tassert.equal(closestSeat(\"pnich\", seats), \"pinch\");\n+\t\tassert.equal(closestSeat(\"infraops\", seats), \"infra-ops\");\n+\t\tassert.equal(closestSeat(\"zzzzzz\", seats), null);\n+\t\tassert.equal(seatRefusal(\"pinch\", \"web\", seats), null);\n+\t\tassert.match(\n+\t\t\tseatRefusal(\"nobody\", \"web\", seats)!,\n+\t\t\t/isn't an agent in web, so nobody would hear the ask\\. abso status/,\n+\t\t);\n+\t});\n+});"},{"path":"server/test/issues/changes.test.ts","added":121,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/issues/changes.test.ts\n@@ -0,0 +1,121 @@\n+// The change count: one number per project's issues that every write an issue read can\n+// show moves forward, kept by SQLite triggers, so a reader can cache issue reads under it.\n+\n+import assert from \"node:assert/strict\";\n+import { DatabaseSync } from \"node:sqlite\";\n+import { describe, it } from \"node:test\";\n+import { issuesRoute } from \"../../src/issues/routes.ts\";\n+import { IssuesStore, type Sql } from \"../../src/issues/store.ts\";\n+\n+function sql(): { sql: Sql; db: DatabaseSync } {\n+\tconst db = new DatabaseSync(\":memory:\");\n+\treturn {\n+\t\tdb,\n+\t\tsql: {\n+\t\t\texec: (q, ...b) => {\n+\t\t\t\tif (/^\\s*CREATE\\b/i.test(q)) {\n+\t\t\t\t\tdb.exec(q);\n+\t\t\t\t\treturn { toArray: () => [] };\n+\t\t\t\t}\n+\t\t\t\tconst rows = db.prepare(q).all(...(b as (string | number | null)[]));\n+\t\t\t\treturn { toArray: () => rows };\n+\t\t\t},\n+\t\t},\n+\t};\n+}\n+\n+function store(): { s: IssuesStore; db: DatabaseSync; tick: () => void } {\n+\tlet t = Date.parse(\"2026-10-09T10:00:00Z\");\n+\tconst { sql: q, db } = sql();\n+\tIssuesStore.createTables(q);\n+\treturn { s: new IssuesStore(q, () => t), db, tick: () => void (t += 1000) };\n+}\n+\n+const builder = { agent: \"builder3\" };\n+const christopher = { person: \"u1\" };\n+\n+describe(\"issues: the change count\", () => {\n+\tit(\"is kept by a trigger on each counted table, for insert, update and delete\", () => {\n+\t\tconst { db, s } = store();\n+\t\tconst triggers = db\n+\t\t\t.prepare(\"SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'changed_%'\")\n+\t\t\t.all();\n+\t\tassert.equal(triggers.length, 30, \"three for each of the ten tables an issue read shows\");\n+\t\tassert.equal(s.changes(), 0);\n+\t});\n+\n+\tit(\"moves forward on every write an issue read shows, and not on reads, drafts or a repeated waiting\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tlet last = s.changes();\n+\t\tconst moved = (what: string) => {\n+\t\t\tconst n = s.changes();\n+\t\t\tassert.ok(n > last, `${what} moved the count (${last} to ${n})`);\n+\t\t\tlast = n;\n+\t\t};\n+\t\tconst still = (what: string) => assert.equal(s.changes(), last, `${what} left the count alone`);\n+\n+\t\tconst a = s.open(builder, { title: \"Sign-in\" }).id;\n+\t\tmoved(\"opening an issue\");\n+\t\tconst b = s.open(builder, { title: \"Logo\", parent: a }).id;\n+\t\tmoved(\"opening a child\");\n+\t\ttick();\n+\t\ts.comment(christopher, a, { text: \"Looks right.\" });\n+\t\tmoved(\"a comment\");\n+\t\tconst q = s.ask(builder, { issue: a, of: \"security\", question: \"Is the cookie set right?\", review: true });\n+\t\tmoved(\"an ask\");\n+\t\ts.waiting(\"security\", \"security\");\n+\t\tmoved(\"waiting marking an ask seen\");\n+\t\ts.waiting(\"security\", \"security\");\n+\t\tstill(\"a second waiting with nothing new\");\n+\t\ts.answer({ agent: \"security\" }, q.id, { words: \"Yes.\" });\n+\t\tmoved(\"an answer\");\n+\t\ts.claim(\"builder3\", b, 12);\n+\t\tmoved(\"a start note's claim\");\n+\t\ts.edit(christopher, b, { labels: [\"design\"] });\n+\t\tmoved(\"a label\");\n+\t\ts.edit(christopher, a, { blockedBy: [b] });\n+\t\tmoved(\"Blocked by\");\n+\t\ts.markDone(builder, b, 381);\n+\t\tmoved(\"done in a version\");\n+\t\tconst c = s.open(builder, { title: \"Footer\" }).id;\n+\t\ts.claim(\"builder3\", c, 13);\n+\t\tlast = s.changes();\n+\t\ts.unclaim(\"builder3\", c);\n+\t\tmoved(\"an unclaim\");\n+\t\ts.drop(builder, c);\n+\t\tmoved(\"a drop\");\n+\t\ts.reopen(builder, c);\n+\t\tmoved(\"a reopen\");\n+\n+\t\ts.page(a);\n+\t\ts.list({});\n+\t\ts.search(\"sign\", 10);\n+\t\ts.waiting();\n+\t\tstill(\"reads\");\n+\t\ts.saveDraft(builder, { title: \"Mine for now\" });\n+\t\ts.wrote(builder);\n+\t\tstill(\"a draft and the rate log\");\n+\t});\n+\n+\tit(\"is a route, and every write answers the count it made\", async () => {\n+\t\tconst { s } = store();\n+\t\tconst call = async (method: string, path: string, body?: unknown) => {\n+\t\t\tconst r = await issuesRoute(\n+\t\t\t\ts,\n+\t\t\t\tnew Request(`https://issues.internal${path}`, {\n+\t\t\t\t\tmethod,\n+\t\t\t\t\t...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\treturn { status: r.status, json: (await r.json()) as Record<string, unknown> };\n+\t\t};\n+\t\tassert.deepEqual((await call(\"GET\", \"/p/web/changes\")).json, { changes: 0 });\n+\t\tconst opened = await call(\"POST\", \"/p/web/a/builder3/issue\", { title: \"Sign-in\" });\n+\t\tassert.equal(opened.status, 200);\n+\t\tconst after = (await call(\"GET\", \"/p/web/changes\")).json.changes as number;\n+\t\tassert.ok(after > 0);\n+\t\tassert.equal(opened.json.changes, after, \"the write's answer is the count a read after it sees\");\n+\t\tconst commented = await call(\"POST\", \"/p/web/a/builder3/issue/1/comment\", { text: \"More.\" });\n+\t\tassert.ok((commented.json.changes as number) > after);\n+\t});\n+});"},{"path":"server/test/issues/issues.test.ts","added":630,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/issues/issues.test.ts\n@@ -0,0 +1,630 @@\n+// Issues: the store and its routes, on node:sqlite as a Durable Object's SQLite.\n+\n+import assert from \"node:assert/strict\";\n+import { DatabaseSync } from \"node:sqlite\";\n+import { describe, it } from \"node:test\";\n+import { issuesRoute } from \"../../src/issues/routes.ts\";\n+import { IssuesStore, type Sql, WRITES_PER_MINUTE } from \"../../src/issues/store.ts\";\n+\n+function sql(): Sql {\n+\tconst db = new DatabaseSync(\":memory:\");\n+\treturn {\n+\t\texec: (q, ...b) => {\n+\t\t\t// Like ctx.storage.sql.exec: the statement runs at once; rows come from toArray.\n+\t\t\tif (/^\\s*CREATE\\b/i.test(q)) {\n+\t\t\t\tdb.exec(q);\n+\t\t\t\treturn { toArray: () => [] };\n+\t\t\t}\n+\t\t\tconst rows = db.prepare(q).all(...(b as (string | number | null)[]));\n+\t\t\treturn { toArray: () => rows };\n+\t\t},\n+\t};\n+}\n+\n+function store(): { s: IssuesStore; tick: (ms?: number) => void } {\n+\tlet t = Date.parse(\"2026-10-07T20:00:00Z\");\n+\tconst db = sql();\n+\tIssuesStore.createTables(db);\n+\treturn { s: new IssuesStore(db, () => t), tick: (ms = 1000) => void (t += ms) };\n+}\n+\n+const builder = { agent: \"builder3\" };\n+const christopher = { person: \"u1\" };\n+\n+describe(\"issues: statuses come from the work\", () => {\n+\tit(\"open, in progress, in review, blocked, done and dropped, and a dropped issue can be reopened\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst a = s.open(builder, { title: \"Sign-in page\", description: \"Pages for sign-in\" }).id;\n+\t\tconst b = s.open(builder, { title: \"Logo\", parent: a }).id;\n+\t\tassert.equal(s.page(a).issue.status, \"open\");\n+\t\tassert.equal(s.page(a).issue.children, 1);\n+\n+\t\ttick();\n+\t\ts.claim(\"builder3\", a, 4400);\n+\t\tassert.equal(s.page(a).issue.status, \"in progress\");\n+\t\tassert.deepEqual(s.page(a).issue.agents, [\"builder3\"]);\n+\n+\t\ttick();\n+\t\tconst review = s.ask(builder, { issue: a, of: \"security\", question: \"Is the cookie set right?\", review: true });\n+\t\tassert.equal(s.page(a).issue.status, \"in review\");\n+\t\tassert.deepEqual(s.page(a).issue.waitingOn, [\"security\"]);\n+\t\tassert.deepEqual(review.news.to, [\"security\"]);\n+\t\tassert.ok(review.news.text.endsWith(`: \"Is the cookie set right?\" Answer: abso answer ${review.id} \"...\"`));\n+\n+\t\t// A question that isn't a review blocks, and outranks the review; it can hold up other issues too.\n+\t\tconst q = s.ask(builder, {\n+\t\t\tissue: a,\n+\t\t\tof: \"person:u1\",\n+\t\t\tquestion: \"Take abso.dev?\",\n+\t\t\toptions: [\"Yes\", \"No\"],\n+\t\t\tblocks: [b],\n+\t\t\tdue: \"2026-10-09\",\n+\t\t});\n+\t\tassert.equal(s.page(a).issue.status, \"blocked\");\n+\t\tassert.equal(s.page(b).issue.status, \"blocked\", \"an ask holds up the issues it names in blocks\");\n+\t\tassert.deepEqual(s.page(a).issue.waitingOn, [\"security\", \"person:u1\"]);\n+\t\tassert.ok(q.news.text.endsWith('\"Take abso.dev?\"'), \"a person answers elsewhere, so no command\");\n+\n+\t\ttick();\n+\t\tconst answered = s.answer(christopher, q.id, { option: \"Yes\", note: \"Renew it for two years.\" });\n+\t\tassert.equal(answered.ask.answer?.words, \"Yes\\n\\nRenew it for two years.\", \"kept in the person's own words\");\n+\t\tassert.equal(s.page(b).issue.status, \"open\");\n+\t\tassert.equal(s.page(a).issue.status, \"in review\");\n+\t\ts.answer({ agent: \"security\" }, review.id, { words: \"Looks right.\" });\n+\t\tassert.equal(s.page(a).issue.status, \"in progress\");\n+\n+\t\ttick();\n+\t\tconst done = s.done(\"builder3\", a, 13);\n+\t\tassert.match(done.news!.text, /^builder3 finished issue 1 \\(\"Sign-in page\"\\) in version 13$/);\n+\t\tconst page = s.page(a);\n+\t\tassert.equal(page.issue.status, \"done\");\n+\t\tassert.deepEqual(page.issue.closed, { how: \"done\", by: \"builder3\", version: 13, at: page.issue.closed!.at });\n+\t\tassert.deepEqual(page.issue.versions, [13]);\n+\t\tassert.deepEqual(page.claims, []);\n+\n+\t\ts.drop(builder, b);\n+\t\tassert.equal(s.page(b).issue.status, \"dropped\");\n+\t\tassert.throws(() => s.drop(builder, b), /dropped already/);\n+\t\tassert.throws(() => s.markDone(builder, b, null), /reopen it/);\n+\t\tconst reopened = s.reopen(builder, b);\n+\t\tassert.match(reopened.news.text, /reopened issue/);\n+\t\tassert.equal(s.page(b).issue.status, \"open\");\n+\t\tassert.throws(() => s.reopen(builder, b), /is open/);\n+\t\tconst marked = s.markDone(builder, b, 381);\n+\t\tassert.match(marked.news.text, /done in version 381/);\n+\t\tassert.equal(s.page(b).issue.status, \"done\");\n+\t\tassert.deepEqual(s.page(b).issue.versions, [381]);\n+\t\tassert.throws(() => s.reopen(builder, b), /stays done/);\n+\t\tassert.throws(() => s.markDone(builder, b, null), /done already/);\n+\t\tassert.deepEqual(\n+\t\t\ts.list({ open: true }).map((i) => i.id),\n+\t\t\t[],\n+\t\t);\n+\t});\n+\n+\tit(\"a start note that ends without --done takes the claim back and leaves the issue open\", () => {\n+\t\tconst { s } = store();\n+\t\tconst id = s.open(builder, { title: \"x\" }).id;\n+\t\ts.claim(\"builder3\", id, 10);\n+\t\ts.unclaim(\"builder3\", id);\n+\t\tassert.equal(s.page(id).issue.status, \"open\");\n+\t\t// Hooks for an issue that doesn't exist are ignored: the start note stands either way.\n+\t\ts.claim(\"builder3\", 99, 10);\n+\t\ts.unclaim(\"builder3\", 99);\n+\t\tassert.deepEqual(s.done(\"builder3\", 99, 3), {});\n+\t});\n+\n+\tit(\"lists by status and agent, most recently updated first\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst one = s.open(builder, { title: \"one\" }).id;\n+\t\ttick();\n+\t\tconst two = s.open(builder, { title: \"two\" }).id;\n+\t\ttick();\n+\t\ts.comment({ agent: \"engine\" }, one, { text: \"on it soon\" });\n+\t\tassert.deepEqual(\n+\t\t\ts.list().map((i) => i.id),\n+\t\t\t[one, two],\n+\t\t);\n+\t\ts.claim(\"engine\", two, 5);\n+\t\tassert.deepEqual(\n+\t\t\ts.list({ agent: \"engine\" }).map((i) => i.id),\n+\t\t\t[two],\n+\t\t);\n+\t\tassert.deepEqual(\n+\t\t\ts.list({ status: \"open\" }).map((i) => i.id),\n+\t\t\t[one],\n+\t\t);\n+\t});\n+});\n+\n+describe(\"issues: the asker withdraws an ask\", () => {\n+\tit(\"closes like an answer: off the waiting list, no longer blocking, kept with the note, and the one asked hears it\", () => {\n+\t\tconst { s } = store();\n+\t\tconst id = s.open(builder, { title: \"How judges see abso\" }).id;\n+\t\tconst ask = s.ask(builder, { of: \"person:u1\", question: \"A, B or C?\", issue: id, options: [\"A\", \"B\", \"C\"] });\n+\t\tassert.equal(s.page(id).issue.status, \"blocked\");\n+\t\tconst r = s.withdraw(builder, ask.id, { note: \"Overtaken by tonight's rulings\" });\n+\t\tassert.equal(r.ask.outcome, \"withdrawn\");\n+\t\tassert.deepEqual(r.ask.answer && { by: r.ask.answer.by, words: r.ask.answer.words }, {\n+\t\t\tby: \"builder3\",\n+\t\t\twords: \"Overtaken by tonight's rulings\",\n+\t\t});\n+\t\tassert.deepEqual(r.news.to, [\"person:u1\"]);\n+\t\tassert.match(r.news.text, /^builder3 withdrew their question of person:u1 on issue \\d+: \"Overtaken/);\n+\t\tassert.deepEqual(s.waiting(\"person:u1\"), []);\n+\t\tassert.equal(s.page(id).issue.status, \"open\");\n+\t\tassert.equal(s.page(id).asks[0]!.outcome, \"withdrawn\");\n+\t\tassert.equal(s.answered(\"person:u1\")[0]!.outcome, \"withdrawn\");\n+\t});\n+\n+\tit(\"only the asker withdraws, only while unanswered, and once; then it can't be answered\", () => {\n+\t\tconst { s } = store();\n+\t\tconst ask = s.ask(builder, { of: \"person:u1\", question: \"Pick one\" });\n+\t\tassert.throws(() => s.withdraw(christopher, ask.id, {}), /asked by builder3; only they can withdraw it/);\n+\t\tassert.throws(() => s.withdraw(builder, 99, {}), /there's no ask 99/);\n+\t\tconst r = s.withdraw(builder, ask.id, {});\n+\t\tassert.equal(r.ask.answer!.words, \"\");\n+\t\tassert.equal(r.news.text, \"builder3 withdrew their question of person:u1\", \"no note, so nothing after it\");\n+\t\tassert.throws(() => s.withdraw(builder, ask.id, {}), /withdrawn already/);\n+\t\tassert.throws(\n+\t\t\t() => s.answer(christopher, ask.id, { words: \"A\" }),\n+\t\t\t(e: { status?: number; message: string }) => e.status === 409 && /withdrawn by builder3/.test(e.message),\n+\t\t);\n+\t\tconst answered = s.ask(builder, { of: \"person:u1\", question: \"Another\" });\n+\t\ts.answer(christopher, answered.id, { words: \"Yes\" });\n+\t\tassert.throws(() => s.withdraw(builder, answered.id, {}), /answered already, so there's nothing to withdraw/);\n+\t\tassert.equal(s.answered(\"person:u1\").find((a) => a.id === answered.id)!.outcome, undefined);\n+\t});\n+});\n+\n+describe(\"issues: the one asked acknowledges an ask\", () => {\n+\tit(\"stays open and blocking, shows the ack and its note, and the asker hears it; an answer closes it\", () => {\n+\t\tconst { s } = store();\n+\t\tconst id = s.open(builder, { title: \"Which deploy first\" }).id;\n+\t\tconst ask = s.ask(builder, { of: \"person:u1\", question: \"A or B?\", issue: id });\n+\t\tconst r = s.ack(christopher, ask.id, { note: \"after the review\" });\n+\t\tassert.equal(r.ask.ack!.note, \"after the review\");\n+\t\tassert.equal(r.ask.answer, null);\n+\t\tassert.deepEqual(r.news.to, [\"builder3\"]);\n+\t\tassert.equal(\n+\t\t\tr.news.text,\n+\t\t\t`person:u1 has your question (ask ${ask.id}) on issue ${id} and will answer: \"after the review\"`,\n+\t\t);\n+\t\tassert.equal(s.page(id).issue.status, \"blocked\");\n+\t\tassert.equal(s.page(id).asks[0]!.ack!.note, \"after the review\");\n+\t\tassert.deepEqual(\n+\t\t\ts.waiting(\"person:u1\").map((a) => a.id),\n+\t\t\t[ask.id],\n+\t\t);\n+\t\t// Again, with no note: the note and time update.\n+\t\tconst again = s.ack(christopher, ask.id, {});\n+\t\tassert.equal(again.ask.ack!.note, \"\");\n+\t\tassert.equal(again.news.text, `person:u1 has your question (ask ${ask.id}) on issue ${id} and will answer.`);\n+\t\ts.answer(christopher, ask.id, { words: \"A\" });\n+\t\tassert.equal(s.page(id).issue.status, \"open\");\n+\t\tassert.deepEqual(s.waiting(\"person:u1\"), []);\n+\t});\n+\n+\tit(\"only the one asked acknowledges, and only while it's open\", () => {\n+\t\tconst { s } = store();\n+\t\tconst ask = s.ask(builder, { of: \"person:u1\", question: \"Pick one\" });\n+\t\tassert.throws(\n+\t\t\t() => s.ack(builder, ask.id, {}),\n+\t\t\t(e: { status?: number; message: string }) => e.status === 403 && /is for person:u1, not builder3/.test(e.message),\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() => s.ack(christopher, 99, {}),\n+\t\t\t(e: { status?: number }) => e.status === 404,\n+\t\t);\n+\t\ts.answer(christopher, ask.id, { words: \"A\" });\n+\t\tassert.throws(\n+\t\t\t() => s.ack(christopher, ask.id, {}),\n+\t\t\t(e: { status?: number; message: string }) => e.status === 409 && /answered already/.test(e.message),\n+\t\t);\n+\t\tconst gone = s.ask(builder, { of: \"person:u1\", question: \"Another\" });\n+\t\ts.withdraw(builder, gone.id, {});\n+\t\tassert.throws(\n+\t\t\t() => s.ack(christopher, gone.id, {}),\n+\t\t\t(e: { status?: number; message: string }) => e.status === 409 && /withdrawn by builder3/.test(e.message),\n+\t\t);\n+\t});\n+});\n+\n+describe(\"issues: asks and answers\", () => {\n+\tit(\"an ask on no issue, a task answered done, and waiting sorted by due date\", () => {\n+\t\tconst { s } = store();\n+\t\tconst id = s.open(builder, { title: \"Sign-in\" }).id;\n+\t\tconst later = s.ask(builder, {\n+\t\t\tof: \"person:u1\",\n+\t\t\tquestion: \"Does the avcs command become abso?\",\n+\t\t\tdue: \"2026-10-20\",\n+\t\t\trecommendation: { text: \"Yes, with avcs kept as an alias\" },\n+\t\t});\n+\t\tconst sooner = s.ask(builder, {\n+\t\t\tof: \"person:u1\",\n+\t\t\tkind: \"task\",\n+\t\t\tquestion: \"Upload the sign-in logo\",\n+\t\t\tdue: \"2026-10-08\",\n+\t\t\tblocks: [id],\n+\t\t});\n+\t\tconst none = s.ask(builder, { of: \"person:u1\", question: \"Anything else?\" });\n+\t\tconst waiting = s.waiting(\"person:u1\");\n+\t\tassert.deepEqual(\n+\t\t\twaiting.map((a) => a.id),\n+\t\t\t[sooner.id, later.id, none.id],\n+\t\t);\n+\t\tassert.equal(waiting[1]!.issue, null);\n+\t\tassert.equal(waiting[1]!.title, null);\n+\t\tassert.deepEqual(waiting[1]!.recommendation, { text: \"Yes, with avcs kept as an alias\", by: \"builder3\" });\n+\t\tassert.equal(s.page(id).issue.status, \"blocked\");\n+\t\ts.answer(christopher, sooner.id, { done: true });\n+\t\tassert.equal(s.answered(\"person:u1\")[0]!.answer!.words, \"done\");\n+\t\tassert.equal(s.page(id).issue.status, \"open\");\n+\t\tassert.deepEqual(\n+\t\t\ts.waiting(\"person:u1\").map((a) => a.id),\n+\t\t\t[later.id, none.id],\n+\t\t);\n+\t});\n+\n+\tit(\"only the one asked answers, once, from its options\", () => {\n+\t\tconst { s } = store();\n+\t\tconst ask = s.ask(builder, { of: \"person:u1\", question: \"Pick one\", options: [\"A\", \"B\"] });\n+\t\tassert.throws(() => s.answer({ person: \"u2\" }, ask.id, { words: \"A\" }), /is for person:u1, not person:u2/);\n+\t\tassert.throws(() => s.answer(christopher, ask.id, { option: \"C\" }), /options are: \"A\", \"B\"/);\n+\t\t// The page sends the option's text as it showed it: an index that names another is refused.\n+\t\tassert.throws(\n+\t\t\t() => s.answer(christopher, ask.id, { option: 1, expect: \"A\" }),\n+\t\t\t(e: { status?: number; message: string }) =>\n+\t\t\t\te.status === 409 && /option 2 is \"B\", not the one you picked/.test(e.message),\n+\t\t);\n+\t\ts.answer(christopher, ask.id, { option: 1, expect: \"B\" });\n+\t\tassert.throws(() => s.answer(christopher, ask.id, { words: \"A\" }), /answered already/);\n+\t\tassert.equal(s.answered(\"person:u1\")[0]!.answer!.words, \"B\");\n+\t});\n+\n+\tit(\"checks its input\", () => {\n+\t\tconst { s } = store();\n+\t\tassert.throws(() => s.open(builder, { title: \"\" }), /the title is missing/);\n+\t\tassert.throws(() => s.open(builder, { title: \"x\".repeat(201) }), /201 characters; the most is 200/);\n+\t\tassert.throws(() => s.open(builder, { title: \"x\", parent: 7 }), /there's no issue 7/);\n+\t\tassert.throws(\n+\t\t\t() => s.open(builder, { title: \"x\", lines: { file: \"a.ts\", from: 3, to: 1, version: 2 } }),\n+\t\t\t/lines are/,\n+\t\t);\n+\t\tassert.throws(() => s.ask(builder, { of: \"x\", question: \"q\", review: true }), /a review ask is on an issue/);\n+\t\tassert.throws(() => s.ask(builder, { of: \"x\", question: \"q\", due: \"soon\" }), /due is a date/);\n+\t\tassert.throws(() => s.ask(builder, { of: \"x\", question: \"q\", kind: \"chore\" }), /kind is \"question\", or \"task\"/);\n+\t});\n+});\n+\n+describe(\"issues: routes\", () => {\n+\tconst call = (s: IssuesStore, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) =>\n+\t\tissuesRoute(\n+\t\t\ts,\n+\t\t\tnew Request(`https://issues.internal${path}`, {\n+\t\t\t\tmethod,\n+\t\t\t\theaders,\n+\t\t\t\t...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n+\t\t\t}),\n+\t\t).then(async (r) => ({ status: r.status, json: (await r.json()) as Record<string, any> }));\n+\n+\tit(\"agents write under /a/:agent/, a write naming nobody is refused, and everyone reads\", async () => {\n+\t\tconst { s } = store();\n+\t\tconst opened = await call(s, \"POST\", \"/p/web/a/builder3/issue\", { title: \"Sign-in\", description: \"d\" });\n+\t\tassert.equal(opened.status, 200);\n+\t\tassert.equal(opened.json.id, 1);\n+\t\tassert.equal((await call(s, \"POST\", \"/p/web/a/fe/issue/1/comment\", { text: \"nice\" })).status, 200);\n+\t\tassert.equal((await call(s, \"POST\", \"/p/web/issue/1/comment\", { text: \"who am I\" })).status, 403);\n+\t\tassert.equal(\n+\t\t\t(await call(s, \"POST\", \"/p/web/issue/1/comment\", { text: \"a person?\" }, { \"X-Avcs-User\": \"u1\" })).status,\n+\t\t\t403,\n+\t\t\t\"no header makes a person here\",\n+\t\t);\n+\t\tconst asked = await call(s, \"POST\", \"/p/web/a/builder3/ask\", { issue: 1, of: \"fe\", question: \"OK?\" });\n+\t\tassert.equal(asked.json.news.to[0], \"fe\");\n+\t\tassert.equal((await call(s, \"POST\", `/p/web/a/fe/answer/${asked.json.id}`, { words: \"OK\" })).status, 200);\n+\n+\t\tconst list = await call(s, \"GET\", \"/p/web/issues?open=1\");\n+\t\tassert.deepEqual(\n+\t\t\tlist.json.issues.map((i: { id: number; status: string }) => [i.id, i.status]),\n+\t\t\t[[1, \"open\"]],\n+\t\t);\n+\t\tconst page = await call(s, \"GET\", \"/p/web/issue/1\");\n+\t\tassert.deepEqual(\n+\t\t\tpage.json.comments.map((c: { by: string }) => c.by),\n+\t\t\t[\"fe\"],\n+\t\t);\n+\t\tassert.equal(page.json.asks[0].answer.words, \"OK\");\n+\t\tassert.equal((await call(s, \"GET\", \"/p/web/issue/9\")).status, 404);\n+\t\tassert.equal((await call(s, \"GET\", \"/p/web/answered\")).status, 400);\n+\t\tassert.equal((await call(s, \"POST\", \"/p/web/a/builder3/issue\", \"not an object\")).status, 400);\n+\t});\n+});\n+\n+describe(\"issues: edits, watchers, Blocked by and drafts\", () => {\n+\tit(\"an edit tells the watchers by default, adds people, or tells nobody\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst a = s.open(christopher, { title: \"Accounts\" }).id;\n+\t\tconst b = s.open(christopher, { title: \"Sign-in\", agent: \"fe\", notify: [\"design\"] });\n+\t\tassert.deepEqual(b.news, {\n+\t\t\tissue: null,\n+\t\t\ttext: 'person:u1 opened issue 2: \"Sign-in\" (Agent fe)',\n+\t\t\tto: [\"fe\", \"design\"],\n+\t\t});\n+\t\ts.comment(builder, b.id, { text: \"on it soon\" });\n+\t\ts.claim(\"engine\", b.id, 40);\n+\t\ttick();\n+\t\t// Issue 1 opened before issue 2, then put under it.\n+\t\tconst moved = s.edit(christopher, b.id, { parent: a, title: \"Sign-in flow\" });\n+\t\tassert.deepEqual(moved.notified, [\"builder3\", \"design\", \"engine\", \"fe\"]);\n+\t\tassert.equal(moved.news!.text, 'person:u1 edited issue 2 (\"Sign-in flow\"): title was \"Sign-in\"; parent is issue 1');\n+\t\tconst page = s.page(b.id);\n+\t\tassert.equal(page.issue.parent, a);\n+\t\tassert.deepEqual(page.issue.watchers, [\"builder3\", \"design\", \"engine\", \"fe\", \"person:u1\"]);\n+\t\tassert.deepEqual(page.edits[0]!.changes, {\n+\t\t\ttitle: { from: \"Sign-in\", to: \"Sign-in flow\" },\n+\t\t\tparent: { from: null, to: 1 },\n+\t\t});\n+\t\tconst quiet = s.edit(builder, b.id, { description: \"typo\", notify: false });\n+\t\tassert.deepEqual(quiet, { edit: 2, notified: [] });\n+\t\tconst more = s.edit(builder, b.id, { agent: \"web\", also: [\"person:u2\"] });\n+\t\tassert.ok(\n+\t\t\tmore.notified.includes(\"person:u2\") && more.notified.includes(\"web\") && !more.notified.includes(\"builder3\"),\n+\t\t);\n+\t\tassert.equal(s.page(b.id).issue.agent, \"web\");\n+\t\tassert.throws(() => s.edit(builder, b.id, { agent: \"web\" }), /that changes nothing on issue 2/);\n+\t\tassert.throws(() => s.edit(builder, a, { parent: b.id }), /issue 2 is issue 1 or under it/);\n+\t\tassert.throws(() => s.edit(builder, a, { notify: \"no\", title: \"A\" }), /notify is true/);\n+\t});\n+\n+\tit(\"Blocked by holds an issue Blocked until each is Done, and refuses a loop\", () => {\n+\t\tconst { s } = store();\n+\t\tconst a = s.open(builder, { title: \"Schema\" }).id;\n+\t\tconst b = s.open(builder, { title: \"Pages\", blockedBy: [a] }).id;\n+\t\tassert.equal(s.page(b).issue.status, \"blocked\");\n+\t\tassert.deepEqual(s.page(b).issue.blockedBy, [a]);\n+\t\tassert.throws(() => s.edit(builder, a, { blockedBy: [b] }), /issue 2 already waits on issue 1/);\n+\t\tassert.throws(() => s.edit(builder, a, { blockedBy: [a] }), /can't be blocked by itself/);\n+\t\ts.done(\"engine\", a, 12);\n+\t\tassert.equal(s.page(b).issue.status, \"open\");\n+\t\tconst c = s.open(builder, { title: \"Docs\" }).id;\n+\t\ts.edit(builder, c, { blockedBy: [b] });\n+\t\tassert.equal(s.page(c).issue.status, \"blocked\");\n+\t\ts.edit(builder, c, { blockedBy: [] });\n+\t\tassert.equal(s.page(c).issue.status, \"open\");\n+\t});\n+\n+\tit(\"the first start note sets the Agent when none was set, and the claimer watches\", () => {\n+\t\tconst { s } = store();\n+\t\tconst id = s.open(builder, { title: \"x\" }).id;\n+\t\ts.claim(\"engine\", id, 3);\n+\t\ts.claim(\"fe\", id, 4);\n+\t\tassert.equal(s.page(id).issue.agent, \"engine\");\n+\t\tassert.deepEqual(\n+\t\t\ts.list({ agent: \"engine\" }).map((i) => i.id),\n+\t\t\t[id],\n+\t\t);\n+\t\tassert.ok(s.page(id).issue.watchers.includes(\"fe\"));\n+\t});\n+\n+\tit(\"drafts are their writer's alone, have no number, make no news, and open as issues\", () => {\n+\t\tconst { s } = store();\n+\t\tconst d = s.saveDraft(christopher, { title: \"Half a thought\" }).id;\n+\t\ts.saveDraft(christopher, { id: d, title: \"A whole thought\", agent: \"fe\" });\n+\t\tassert.deepEqual(\n+\t\t\ts.drafts(christopher).map((x) => x.body),\n+\t\t\t[{ title: \"A whole thought\", agent: \"fe\" }],\n+\t\t);\n+\t\tassert.deepEqual(s.drafts({ person: \"u2\" }), []);\n+\t\tassert.throws(() => s.deleteDraft({ person: \"u2\" }, d), /you have no draft/);\n+\t\tassert.deepEqual(s.list(), []);\n+\t\tassert.deepEqual(s.drafts(christopher)[0]!.id, d);\n+\t\ts.saveDraft(christopher, {});\n+\t\tconst opened = s.openDraft(christopher, d, { description: \"added when opening\" });\n+\t\tassert.equal(opened.id, 1);\n+\t\tassert.deepEqual(opened.news!.to, [\"fe\"]);\n+\t\tassert.equal(s.page(1).issue.description, \"added when opening\");\n+\t\tassert.equal(s.drafts(christopher).length, 1);\n+\t\tassert.throws(() => s.openDraft(christopher, s.drafts(christopher)[0]!.id), /the title is missing/);\n+\t});\n+\n+\tit(\"refuses words a reader can't see, and titles over more than one line\", () => {\n+\t\tconst { s } = store();\n+\t\tassert.throws(\n+\t\t\t() => s.open(builder, { title: \"fine\\u{E0041}\" }),\n+\t\t\t/a tag character \\(U\\+E0000-E007F\\) at character 5/,\n+\t\t);\n+\t\tassert.throws(() => s.open(builder, { title: \"one\\ntwo\" }), /the title is one line/);\n+\t\tassert.throws(() => s.open(builder, { title: \"x\", description: \"a\\u202Eb\" }), /bidirectional/);\n+\t\tconst id = s.open(builder, { title: \"x\", description: \"two\\nlines\\tand a tab\" }).id;\n+\t\tassert.throws(() => s.comment(builder, id, { text: \"hi\\u200B\" }), /zero-width/);\n+\t\tassert.throws(() => s.edit(builder, id, { title: \"a\\nb\" }), /one line/);\n+\t\tassert.throws(() => s.open(builder, { title: \"x\", notify: [\"fe\\nengine\"] }), /one line/);\n+\t});\n+\n+\tit(\"routes: edit, and drafts read and written by their writer\", async () => {\n+\t\tconst { s } = store();\n+\t\tconst call = (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) =>\n+\t\t\tissuesRoute(\n+\t\t\t\ts,\n+\t\t\t\tnew Request(`https://issues.internal${path}`, {\n+\t\t\t\t\tmethod,\n+\t\t\t\t\theaders,\n+\t\t\t\t\t...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n+\t\t\t\t}),\n+\t\t\t).then(async (r) => ({ status: r.status, json: (await r.json()) as Record<string, any> }));\n+\t\tconst title400 = await call(\"POST\", \"/p/web/a/fe/issue\", { title: \"x\\u{E0001}\" });\n+\t\tassert.equal(title400.status, 400);\n+\t\tassert.match(title400.json.error, /tag character/);\n+\t\tassert.equal((await call(\"POST\", \"/p/web/a/fe/issue\", { title: \"a\\nb\" })).status, 400);\n+\t\tawait call(\"POST\", \"/p/web/a/fe/issue\", { title: \"Sign-in\" });\n+\t\tconst edited = await call(\"POST\", \"/p/web/a/lead/issue/1/edit\", { title: \"Sign-in flow\" });\n+\t\tassert.equal(edited.status, 200);\n+\t\tassert.deepEqual(edited.json.notified, [\"fe\"]);\n+\t\tconst saved = await call(\"POST\", \"/p/web/a/lead/draft\", { title: \"Later\" });\n+\t\tassert.equal((await call(\"GET\", \"/p/web/a/lead/drafts\", undefined)).json.drafts[0].body.title, \"Later\");\n+\t\tassert.deepEqual((await call(\"GET\", \"/p/web/a/fe/drafts\")).json.drafts, []);\n+\t\t// A read naming nobody sees no one's drafts.\n+\t\tassert.equal((await call(\"GET\", \"/p/web/drafts\")).status, 403);\n+\t\tassert.equal((await call(\"POST\", `/p/web/a/fe/draft/${saved.json.id}/delete`)).status, 404);\n+\t\tassert.equal((await call(\"POST\", `/p/web/a/lead/draft/${saved.json.id}/open`, {})).json.id, 2);\n+\t\tassert.deepEqual((await call(\"GET\", \"/p/web/a/lead/drafts\", undefined)).json.drafts, []);\n+\t});\n+});\n+\n+describe(\"issues: each writer's limit\", () => {\n+\tit(\"one write past the per-minute limit gets 429 with Retry-After; another writer isn't affected\", async () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst call = (path: string, body: unknown, agent: string) =>\n+\t\t\tissuesRoute(\n+\t\t\t\ts,\n+\t\t\t\tnew Request(`https://issues.internal${path.replace(\"/p/web/\", `/p/web/a/${agent}/`)}`, {\n+\t\t\t\t\tmethod: \"POST\",\n+\t\t\t\t\tbody: JSON.stringify(body),\n+\t\t\t\t}),\n+\t\t\t);\n+\t\tassert.equal((await call(\"/p/web/issue\", { title: \"One\" }, \"u1\")).status, 200);\n+\t\tfor (let i = 0; i < WRITES_PER_MINUTE - 1; i++)\n+\t\t\tassert.equal((await call(\"/p/web/issue/1/comment\", { text: `c${i}` }, \"u1\")).status, 200);\n+\t\t// A refused write doesn't count, and drafts make no news, so they don't either.\n+\t\tassert.equal((await call(\"/p/web/draft\", { title: \"later\" }, \"u1\")).status, 200);\n+\t\tconst over = await call(\"/p/web/issue/1/comment\", { text: \"over limit\" }, \"u1\");\n+\t\tassert.equal(over.status, 429);\n+\t\tassert.match(\n+\t\t\t((await over.json()) as { error: string }).error,\n+\t\t\tnew RegExp(`at most ${WRITES_PER_MINUTE} issue writes a minute`),\n+\t\t);\n+\t\tassert.equal(over.headers.get(\"Retry-After\"), \"60\");\n+\t\tassert.equal((await call(\"/p/web/issue/1/comment\", { text: \"mine\" }, \"u2\")).status, 200);\n+\t\ttick(60_000);\n+\t\tassert.equal((await call(\"/p/web/issue/1/comment\", { text: \"a minute on\" }, \"u1\")).status, 200);\n+\t});\n+});\n+\n+describe(\"issues: labels\", () => {\n+\tit(\"set on open, changed by edit, filtered by, and listed with counts\", () => {\n+\t\tconst { s } = store();\n+\t\tconst a = s.open(builder, { title: \"Sync is slow\", labels: [\"friction\", \"client\", \"friction\"] }).id;\n+\t\tconst b = s.open(builder, { title: \"Blame past a reformat\", labels: [\"friction\", \"engine\"] }).id;\n+\t\ts.open(builder, { title: \"Logo\" });\n+\t\tassert.deepEqual(s.page(a).issue.labels, [\"client\", \"friction\"]);\n+\t\tassert.deepEqual(\n+\t\t\ts.list({ labels: [\"friction\"] }).map((i) => i.id),\n+\t\t\t[b, a],\n+\t\t);\n+\t\tassert.deepEqual(\n+\t\t\ts.list({ labels: [\"friction\", \"client\"] }).map((i) => i.id),\n+\t\t\t[a],\n+\t\t);\n+\t\t// A label-only edit tells nobody unless asked; it's in the activity.\n+\t\tconst quiet = s.edit(christopher, a, { addLabels: [\"good-first-issue\"], removeLabels: [\"client\"] });\n+\t\tassert.deepEqual(quiet.notified, []);\n+\t\tassert.deepEqual(s.page(a).issue.labels, [\"friction\", \"good-first-issue\"]);\n+\t\tassert.deepEqual(s.page(a).edits.at(-1)!.changes.labels, {\n+\t\t\tfrom: [\"client\", \"friction\"],\n+\t\t\tto: [\"friction\", \"good-first-issue\"],\n+\t\t});\n+\t\tconst told = s.edit(christopher, a, { labels: [\"friction\"], notify: true });\n+\t\tassert.match(told.news!.text, /labels friction$/);\n+\t\ts.drop(builder, b);\n+\t\tassert.deepEqual(s.labelsInUse(), [\n+\t\t\t{ label: \"engine\", open: 0, total: 1 },\n+\t\t\t{ label: \"friction\", open: 1, total: 2 },\n+\t\t]);\n+\t\tassert.throws(() => s.edit(builder, a, { addLabels: [\"friction\"] }), /changes nothing/);\n+\t\tassert.throws(() => s.open(builder, { title: \"x\", labels: [\"two words\"] }), /isn't a label/);\n+\t\t// Sent straight to the Worker, upper case and a zero-width are refused, not changed.\n+\t\tassert.throws(\n+\t\t\t() => s.open(builder, { title: \"x\", labels: [\"Friction\"] }),\n+\t\t\t(e: { status?: number }) => e.status === 400,\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() => s.open(builder, { title: \"x\", labels: [\"fric​tion\"] }),\n+\t\t\t(e: { status?: number }) => e.status === 400,\n+\t\t);\n+\t\tassert.throws(() => s.open(builder, { title: \"x\", labels: [\"x\".repeat(41)] }), /isn't a label/);\n+\t\tassert.throws(() => s.edit(builder, a, { labels: [], addLabels: [\"x\"] }), /one or the other/);\n+\t\tassert.throws(() => s.list({ labels: [\"Bad Label\"] }), /isn't a label/);\n+\t});\n+\n+\tit(\"routes: ?label= filters, GET labels lists, and drafts keep labels\", async () => {\n+\t\tconst { s } = store();\n+\t\tconst call = (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) =>\n+\t\t\tissuesRoute(\n+\t\t\t\ts,\n+\t\t\t\tnew Request(`https://issues.internal${path}`, {\n+\t\t\t\t\tmethod,\n+\t\t\t\t\theaders,\n+\t\t\t\t\t...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n+\t\t\t\t}),\n+\t\t\t).then(async (r) => ({ status: r.status, json: (await r.json()) as Record<string, any> }));\n+\t\tawait call(\"POST\", \"/p/web/a/fe/issue\", { title: \"One\", labels: [\"friction\"] });\n+\t\tawait call(\"POST\", \"/p/web/a/fe/issue\", { title: \"Two\", labels: [\"friction\", \"client\"] });\n+\t\tconst both = await call(\"GET\", \"/p/web/issues?label=friction,client\");\n+\t\tassert.deepEqual(\n+\t\t\tboth.json.issues.map((i: { title: string }) => i.title),\n+\t\t\t[\"Two\"],\n+\t\t);\n+\t\tassert.equal((await call(\"GET\", \"/p/web/issues?label=friction&label=client\")).json.issues.length, 1);\n+\t\tassert.equal((await call(\"GET\", \"/p/web/issues?label=Not%20one\")).status, 400);\n+\t\tassert.deepEqual((await call(\"GET\", \"/p/web/labels\")).json.labels, [\n+\t\t\t{ label: \"client\", open: 1, total: 1 },\n+\t\t\t{ label: \"friction\", open: 2, total: 2 },\n+\t\t]);\n+\t\tconst edited = await call(\"POST\", \"/p/web/a/fe/issue/1/edit\", { addLabels: [\"client\"] });\n+\t\tassert.equal(edited.status, 200);\n+\t\tconst d = await call(\"POST\", \"/p/web/a/fe/draft\", { title: \"Later\", labels: [\"friction\"] });\n+\t\tconst opened = await call(\"POST\", `/p/web/a/fe/draft/${d.json.id}/open`, {});\n+\t\tassert.deepEqual((await call(\"GET\", `/p/web/issue/${opened.json.id}`)).json.issue.labels, [\"friction\"]);\n+\t});\n+});\n+\n+describe(\"issues: a project's labels are capped\", () => {\n+\tit(\"a new label past 200 distinct ones is refused; one in use still goes on\", () => {\n+\t\tconst { s } = store();\n+\t\tconst ids: number[] = [];\n+\t\tfor (let i = 0; i < 10; i++)\n+\t\t\tids.push(s.open(builder, { title: `t${i}`, labels: Array.from({ length: 20 }, (_, j) => `l${i * 20 + j}`) }).id);\n+\t\tassert.equal(s.labelsInUse().length, 200);\n+\t\tassert.throws(\n+\t\t\t() => s.open(builder, { title: \"one more\", labels: [\"l-new\"] }),\n+\t\t\t/this project has 200 labels, and 200 is the most/,\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() => s.edit(builder, s.open(builder, { title: \"room\" }).id, { addLabels: [\"l-new\"] }),\n+\t\t\t/200 is the most/,\n+\t\t);\n+\t\tassert.equal(s.edit(builder, ids[1]!, { addLabels: [\"l0\"], removeLabels: [\"l20\"] }).notified.length, 0);\n+\t});\n+});\n+\n+describe(\"issues: when an ask was first listed to its reader\", () => {\n+\tconst get = (s: IssuesStore, path: string, headers: Record<string, string> = {}) =>\n+\t\tissuesRoute(s, new Request(`https://issues.internal${path}`, { headers }));\n+\n+\tit(\"an agent's own waiting marks what it lists as seen, and says null for what it saw first just now\", async () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst id = s.ask(builder, { of: \"security\", question: \"Is the cookie set right?\" }).id;\n+\t\tconst read = async (path: string) =>\n+\t\t\t((await (await get(s, path)).json()) as { asks: { id: number; seen: number | null }[] }).asks;\n+\t\tassert.deepEqual(await read(\"/p/abso/waiting?of=security\"), [{ ...s.waiting(\"security\")[0]!, seen: null }]);\n+\t\tassert.equal(s.waiting(\"security\")[0]!.seen, null, \"a read of someone else's list marks nothing\");\n+\t\ttick();\n+\t\tconst first = await read(\"/p/abso/a/security/waiting\");\n+\t\tassert.equal(first[0]!.seen, null);\n+\t\tconst at = s.waiting(\"security\")[0]!.seen;\n+\t\tassert.equal(at, Date.parse(\"2026-10-07T20:00:01Z\"));\n+\t\ttick();\n+\t\tassert.equal((await read(\"/p/abso/a/security/waiting\"))[0]!.seen, at, \"the first time stays\");\n+\t\tassert.equal(first[0]!.id, id);\n+\t});\n+\n+\tit(\"another agent's read of the list marks nothing\", async () => {\n+\t\tconst { s } = store();\n+\t\ts.ask(builder, { of: \"security\", question: \"Take abso.dev?\" });\n+\t\tawait get(s, \"/p/abso/a/fe/waiting\");\n+\t\tassert.equal(s.waiting(\"security\")[0]!.seen, null);\n+\t\tawait get(s, \"/p/abso/a/security/waiting\");\n+\t\tassert.notEqual(s.waiting(\"security\")[0]!.seen, null);\n+\t});\n+});"},{"path":"server/test/issues/news.test.ts","added":144,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/issues/news.test.ts\n@@ -0,0 +1,144 @@\n+// A reader's news (a person's or an agent's): answers to their asks, replies on asks\n+// they're in, @name mentions, and comments, edits and closes on issues they\n+// watch, by others, newest first, each read or not.\n+\n+import assert from \"node:assert/strict\";\n+import { DatabaseSync } from \"node:sqlite\";\n+import { describe, it } from \"node:test\";\n+import { IssuesStore, NEWS_MAX, type Sql } from \"../../src/issues/store.ts\";\n+\n+function sql(): Sql {\n+\tconst db = new DatabaseSync(\":memory:\");\n+\treturn {\n+\t\texec: (q, ...b) => {\n+\t\t\tif (/^\\s*(CREATE|ALTER)\\b/i.test(q)) {\n+\t\t\t\tdb.exec(q);\n+\t\t\t\treturn { toArray: () => [] };\n+\t\t\t}\n+\t\t\tconst rows = db.prepare(q).all(...(b as (string | number | null)[]));\n+\t\t\treturn { toArray: () => rows };\n+\t\t},\n+\t};\n+}\n+\n+function store(): { s: IssuesStore; db: Sql; tick: () => number } {\n+\tconst db = sql();\n+\tIssuesStore.createTables(db);\n+\tlet at = Date.parse(\"2026-10-10T03:00:00Z\");\n+\treturn { s: new IssuesStore(db, () => at), db, tick: () => (at += 1000) };\n+}\n+\n+const ann = { person: \"acct_ann\" };\n+const fay = { agent: \"fay\" };\n+\n+describe(\"a reader's news\", () => {\n+\tit(\"gathers answers, replies, mentions and watched changes by others, newest first\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst id = s.open(ann, { title: \"Sync is slow\" }).id;\n+\t\tconst other = s.open(fay, { title: \"Not watched\" }).id;\n+\t\ttick();\n+\t\tconst ask = s.ask(ann, { issue: id, of: \"fay\", question: \"Which way?\" });\n+\t\ttick();\n+\t\ts.reply(fay, ask.id, { text: \"staging or live?\", question: true });\n+\t\ttick();\n+\t\ts.answer(fay, ask.id, { words: \"live\" });\n+\t\ttick();\n+\t\ts.comment(fay, id, { text: \"a comment on a watched issue\" });\n+\t\ttick();\n+\t\ts.comment(fay, other, { text: \"cc @ann, have a look\" });\n+\t\ttick();\n+\t\ts.comment(fay, other, { text: \"no name here, and an email ann@x.dev isn't one\" });\n+\t\ttick();\n+\t\ts.edit(fay, id, { title: \"Sync is slow on big projects\" });\n+\t\ttick();\n+\t\ts.markDone(fay, id, 12);\n+\t\ttick();\n+\t\ts.comment(ann, id, { text: \"my own comment isn't news\" });\n+\n+\t\tconst news = s.newsFor({ person: \"acct_ann\" }, [\"ann\"]);\n+\t\tassert.deepEqual(\n+\t\t\tnews.map((n) => [n.kind, n.issue]),\n+\t\t\t[\n+\t\t\t\t[\"closed\", id],\n+\t\t\t\t[\"edit\", id],\n+\t\t\t\t[\"mention\", other],\n+\t\t\t\t[\"comment\", id],\n+\t\t\t\t[\"answer\", id],\n+\t\t\t\t[\"reply\", id],\n+\t\t\t],\n+\t\t);\n+\t\tassert.equal(news.find((n) => n.kind === \"answer\")!.text, \"live\");\n+\t\tassert.equal(news.find((n) => n.kind === \"answer\")!.ask, ask.id);\n+\t\tassert.equal(news.find((n) => n.kind === \"edit\")!.text, \"title\");\n+\t\tassert.ok(news.every((n) => !n.read && n.by === \"fay\"));\n+\t\tassert.deepEqual(\n+\t\t\ts\n+\t\t\t\t.newsFor({ person: \"acct_ann\" }, [])\n+\t\t\t\t.map((n) => n.kind)\n+\t\t\t\t.includes(\"mention\"),\n+\t\t\tfalse,\n+\t\t\t\"no names, no mentions\",\n+\t\t);\n+\t});\n+\n+\tit(\"marks read up to a time, never back, per person\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst id = s.open(ann, { title: \"One\" }).id;\n+\t\ttick();\n+\t\ts.comment(fay, id, { text: \"first\" });\n+\t\tconst mark = tick();\n+\t\ttick();\n+\t\ts.comment(fay, id, { text: \"second\" });\n+\t\tassert.equal(s.markNewsRead({ person: \"acct_ann\" }, mark).read, mark);\n+\t\tassert.equal(s.markNewsRead({ person: \"acct_ann\" }, 0).read, mark, \"a mark never goes back\");\n+\t\tassert.deepEqual(\n+\t\t\ts.newsFor({ person: \"acct_ann\" }, []).map((n) => [n.text, n.read]),\n+\t\t\t[\n+\t\t\t\t[\"second\", false],\n+\t\t\t\t[\"first\", true],\n+\t\t\t],\n+\t\t);\n+\t\tassert.ok(s.newsFor({ person: \"acct_bo\" }, []).every((n) => !n.read));\n+\t});\n+\n+\tit(\"pages back with before, keeps at most NEWS_MAX and cuts long text\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst id = s.open(ann, { title: \"Busy\" }).id;\n+\t\tfor (let i = 0; i < NEWS_MAX + 5; i++) {\n+\t\t\ttick();\n+\t\t\ts.comment(fay, id, { text: i === 0 ? \"x\".repeat(400) : `comment ${i}` });\n+\t\t}\n+\t\tconst first = s.newsFor({ person: \"acct_ann\" }, []);\n+\t\tassert.equal(first.length, NEWS_MAX);\n+\t\tconst older = s.newsFor({ person: \"acct_ann\" }, [], first.at(-1)!.at);\n+\t\tassert.equal(older.length, 5);\n+\t\tassert.equal(older.at(-1)!.text.length, 280);\n+\t});\n+\n+\tit(\"doesn't move the change count\", () => {\n+\t\tconst { s } = store();\n+\t\ts.open(ann, { title: \"One\" });\n+\t\tconst before = s.changes();\n+\t\ts.markNewsRead({ person: \"acct_ann\" }, 5);\n+\t\tassert.equal(s.changes(), before);\n+\t});\n+\n+\tit(\"is an agent's too: answers to its asks and @mentions of its name\", () => {\n+\t\tconst { s, tick } = store();\n+\t\tconst lead = { agent: \"lead\" };\n+\t\tconst id = s.open(fay, { title: \"Sync is slow\" }).id;\n+\t\ttick();\n+\t\tconst ask = s.ask(lead, { issue: id, of: \"fay\", question: \"Which way?\" });\n+\t\ttick();\n+\t\ts.answer(fay, ask.id, { words: \"live\" });\n+\t\ttick();\n+\t\ts.comment(fay, id, { text: \"@lead it's done\" });\n+\t\tassert.deepEqual(\n+\t\t\ts.newsFor(lead, [\"lead\"]).map((n) => [n.kind, n.by, n.text]),\n+\t\t\t[\n+\t\t\t\t[\"mention\", \"fay\", \"@lead it's done\"],\n+\t\t\t\t[\"answer\", \"fay\", \"live\"],\n+\t\t\t],\n+\t\t);\n+\t});\n+});"},{"path":"server/test/issues/serve.test.ts","added":216,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/issues/serve.test.ts\n@@ -0,0 +1,216 @@\n+// 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\n+// the project's agents, and a write's news reaches the project object. Each IssueProject is an IssuesObject over\n+// node:sqlite, reached through fake namespaces shaped like Cloudflare's.\n+\n+import assert from \"node:assert/strict\";\n+import { DatabaseSync } from \"node:sqlite\";\n+import { describe, it } from \"node:test\";\n+import {\n+\ttype IssueNews,\n+\ttype IssuesAuth,\n+\ttype IssuesEnv,\n+\tIssuesObject,\n+\tissuesFetch,\n+\ttype ProjectHooks,\n+} from \"../../src/issues/serve.ts\";\n+import { SCHEMA } from \"../../src/issues/store.ts\";\n+\n+function storage() {\n+\tconst db = new DatabaseSync(\":memory:\");\n+\treturn {\n+\t\tsql: {\n+\t\t\texec: (q: string, ...b: unknown[]) => {\n+\t\t\t\tif (/^\\s*CREATE\\b/i.test(q)) {\n+\t\t\t\t\tdb.exec(q);\n+\t\t\t\t\treturn { toArray: () => [] };\n+\t\t\t\t}\n+\t\t\t\tconst rows = db.prepare(q).all(...(b as (string | number | null)[]));\n+\t\t\t\treturn { toArray: () => rows };\n+\t\t\t},\n+\t\t},\n+\t\ttransactionSync: <T>(action: () => T): T => {\n+\t\t\tdb.exec(\"SAVEPOINT t\");\n+\t\t\ttry {\n+\t\t\t\tconst out = action();\n+\t\t\t\tdb.exec(\"RELEASE t\");\n+\t\t\t\treturn out;\n+\t\t\t} catch (e) {\n+\t\t\t\tdb.exec(\"ROLLBACK TO t\");\n+\t\t\t\tdb.exec(\"RELEASE t\");\n+\t\t\t\tthrow e;\n+\t\t\t}\n+\t\t},\n+\t};\n+}\n+\n+/** A namespace like Cloudflare's: idFromName gives the name back, get gives one object per name. */\n+function namespace<T extends object>(make: (name: string) => T) {\n+\tconst made = new Map<string, T>();\n+\treturn {\n+\t\tidFromName: (name: string) => name,\n+\t\tget: (id: never) => {\n+\t\t\tconst name = id as unknown as string;\n+\t\t\tif (!made.has(name)) made.set(name, make(name));\n+\t\t\treturn made.get(name)!;\n+\t\t},\n+\t};\n+}\n+\n+function world(hooks?: ProjectHooks) {\n+\tconst env: IssuesEnv = { ISSUES_DO: namespace(() => new IssuesObject(storage(), env)) };\n+\tif (hooks) env.PROJECT = namespace(() => hooks);\n+\tconst waits: Promise<unknown>[] = [];\n+\tconst ctx = { waitUntil: (p: Promise<unknown>) => void waits.push(p) };\n+\tconst call = async (auth: IssuesAuth, method: string, rest: string, body?: unknown, project = \"web\") => {\n+\t\tconst r = await issuesFetch(\n+\t\t\tnew Request(`https://abso.example/issues/p/${project}${rest}`, {\n+\t\t\t\tmethod,\n+\t\t\t\theaders: { Authorization: \"Bearer secret\" },\n+\t\t\t\t...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n+\t\t\t}),\n+\t\t\tenv,\n+\t\t\tctx,\n+\t\t\t{ project, rest: rest.replace(/\\?.*$/, \"\"), auth },\n+\t\t);\n+\t\tawait Promise.all(waits.splice(0));\n+\t\treturn { status: r.status, json: (await r.json()) as Record<string, any> };\n+\t};\n+\treturn { env, call };\n+}\n+\n+const token: IssuesAuth = { kind: \"token\" };\n+const leadKey: IssuesAuth = { kind: \"key\", agent: \"lead\", role: \"writer\" };\n+const readerKey: IssuesAuth = { kind: \"key\", agent: \"watcher\", role: \"reader\" };\n+\n+describe(\"issuesFetch: who may do what\", () => {\n+\tit(\"the token acts as any agent; a key only as its own\", async () => {\n+\t\tconst { call } = world();\n+\t\tassert.equal((await call(token, \"POST\", \"/a/fay/issue\", { title: \"Sync is slow\" })).status, 200);\n+\t\tassert.equal((await call(leadKey, \"POST\", \"/a/lead/issue\", { title: \"Logo\" })).status, 200);\n+\t\tconst other = await call(leadKey, \"POST\", \"/a/fay/issue/1/comment\", { text: \"as fay\" });\n+\t\tassert.equal(other.status, 403);\n+\t\tassert.match(other.json.error, /this key is lead's/);\n+\t\tassert.equal((await call(leadKey, \"GET\", \"/a/fay/waiting\")).status, 403, \"nor reads another's own list\");\n+\t\tassert.equal((await call(leadKey, \"GET\", \"/issues\")).json.issues.length, 2);\n+\t});\n+\n+\tit(\"a reader's key reads and never writes\", async () => {\n+\t\tconst { call } = world();\n+\t\tawait call(token, \"POST\", \"/a/fay/issue\", { title: \"Sync is slow\" });\n+\t\tassert.equal((await call(readerKey, \"GET\", \"/issue/1\")).status, 200);\n+\t\tassert.equal((await call(readerKey, \"GET\", \"/search?q=sync\")).json.hits.length, 1);\n+\t\tconst refused = await call(readerKey, \"POST\", \"/a/watcher/issue/1/comment\", { text: \"hi\" });\n+\t\tassert.equal(refused.status, 403);\n+\t\tassert.match(refused.json.error, /only reads/);\n+\t});\n+\n+\tit(\"refuses a bad project or agent name, and an empty rest\", async () => {\n+\t\tconst { call } = world();\n+\t\tassert.equal((await call(token, \"GET\", \"/issues\", undefined, \"no/such\")).status, 404);\n+\t\tassert.equal((await call(token, \"POST\", \"/a/person:u1/issue\", { title: \"x\" })).status, 400);\n+\t\tassert.equal((await call(token, \"GET\", \"\")).status, 404);\n+\t});\n+\n+\tit(\"each project has its own issues\", async () => {\n+\t\tconst { call } = world();\n+\t\tawait call(token, \"POST\", \"/a/fay/issue\", { title: \"Web's\" });\n+\t\tassert.equal((await call(token, \"GET\", \"/issues\", undefined, \"other\")).json.issues.length, 0);\n+\t});\n+\n+\tit(\"attachments are 501, and a write naming one is refused before anything is written\", async () => {\n+\t\tconst { call } = world();\n+\t\tassert.equal((await call(token, \"POST\", \"/a/fay/attachments\")).status, 501);\n+\t\tconst named = await call(token, \"POST\", \"/a/fay/issue\", { title: \"x\", attachments: [\"a0123456789ab\"] });\n+\t\tassert.equal(named.status, 501);\n+\t\tassert.equal((await call(token, \"GET\", \"/issues\")).json.issues.length, 0);\n+\t});\n+});\n+\n+describe(\"issuesFetch: the project object\", () => {\n+\tit(\"an ask goes only to the project's agents\", async () => {\n+\t\tconst { call } = world({ agents: async () => [\"lead\", \"fay\", \"cloud\"] });\n+\t\tconst refused = await call(token, \"POST\", \"/a/lead/ask\", { of: \"Cloud Lead\", question: \"Which region?\" });\n+\t\tassert.equal(refused.status, 400);\n+\t\tassert.match(refused.json.error, /isn't an agent in web, so nobody would hear the ask; did you mean cloud\\?/);\n+\t\tassert.equal((await call(token, \"POST\", \"/a/lead/ask\", { of: \"cloud\", question: \"Which region?\" })).status, 200);\n+\t});\n+\n+\tit(\"without agents (or without PROJECT) the ask check is skipped\", async () => {\n+\t\tfor (const hooks of [{}, undefined]) {\n+\t\t\tconst { call } = world(hooks);\n+\t\t\tassert.equal((await call(token, \"POST\", \"/a/lead/ask\", { of: \"anyone\", question: \"Q\" })).status, 200);\n+\t\t}\n+\t});\n+\n+\tit(\"a write's news goes to the project from its writer; reads and refusals send none\", async () => {\n+\t\tconst told: { project: string; items: IssueNews[] }[] = [];\n+\t\tconst { call } = world({\n+\t\t\tnews: async (project, items) => {\n+\t\t\t\ttold.push({ project, items });\n+\t\t\t\treturn [];\n+\t\t\t},\n+\t\t});\n+\t\tawait call(token, \"POST\", \"/a/lead/issue\", { title: \"Sync is slow\" });\n+\t\tassert.equal(told.length, 0, \"an issue for nobody in particular tells nobody\");\n+\t\tconst asked = await call(token, \"POST\", \"/a/lead/ask\", { issue: 1, of: \"fay\", question: \"Which way?\" });\n+\t\tassert.equal(told.length, 1);\n+\t\tassert.equal(told[0]!.project, \"web\");\n+\t\tassert.deepEqual(told[0]!.items, [\n+\t\t\t{\n+\t\t\t\tfrom: \"lead\",\n+\t\t\t\tissue: 1,\n+\t\t\t\ttext: `lead asks fay a question on issue 1 (\"Sync is slow\"): \"Which way?\" Answer: abso answer ${asked.json.id} \"...\"`,\n+\t\t\t\tto: [\"fay\"],\n+\t\t\t},\n+\t\t]);\n+\t\tawait call(token, \"GET\", \"/issue/1\");\n+\t\tawait call(token, \"POST\", \"/a/lead/answer/1\", { words: \"not mine to answer\" });\n+\t\tassert.equal(told.length, 1);\n+\t});\n+\n+\tit(\"news with no news method on the project is dropped, and the write stands\", async () => {\n+\t\tconst { call } = world({ agents: async () => [\"lead\", \"fay\"] });\n+\t\tconst asked = await call(token, \"POST\", \"/a/lead/ask\", { of: \"fay\", question: \"Which way?\" });\n+\t\tassert.equal(asked.status, 200);\n+\t\tassert.equal((await call(token, \"GET\", \"/a/fay/waiting\")).json.asks.length, 1);\n+\t});\n+\n+\tit(\"an agent reads its news and marks it read\", async () => {\n+\t\tconst { call } = world();\n+\t\tawait call(token, \"POST\", \"/a/fay/issue\", { title: \"Sync is slow\" });\n+\t\tawait call(token, \"POST\", \"/a/lead/ask\", { issue: 1, of: \"fay\", question: \"Which way?\" });\n+\t\tawait call(token, \"POST\", \"/a/fay/answer/1\", { words: \"live\" });\n+\t\tconst news = await call(leadKey, \"GET\", \"/a/lead/news\");\n+\t\tassert.deepEqual(\n+\t\t\tnews.json.news.map((n: { kind: string; text: string; read: boolean }) => [n.kind, n.text, n.read]),\n+\t\t\t[[\"answer\", \"live\", false]],\n+\t\t);\n+\t\tconst marked = await call(leadKey, \"POST\", \"/a/lead/news/read\", {});\n+\t\tassert.equal(marked.status, 200);\n+\t\tassert.equal((await call(leadKey, \"GET\", \"/a/lead/news\")).json.news[0].read, true);\n+\t});\n+});\n+\n+describe(\"IssuesObject\", () => {\n+\tit(\"runs every migration once, and again runs none\", () => {\n+\t\tconst s = storage();\n+\t\tconst env: IssuesEnv = { ISSUES_DO: namespace(() => ({})) };\n+\t\tassert.equal(new IssuesObject(s, env).migrations(), SCHEMA.length);\n+\t\tassert.equal(new IssuesObject(s, env).migrations(), SCHEMA.length);\n+\t});\n+\n+\tit(\"names who wrote each text: the opener, then whoever last edited it\", async () => {\n+\t\tconst { call } = world();\n+\t\tawait call(token, \"POST\", \"/a/fay/issue\", { title: \"Sync\", description: \"slow\" });\n+\t\tawait call(token, \"POST\", \"/a/lead/issue/1/edit\", { title: \"Sync is slow\" });\n+\t\tawait call(token, \"POST\", \"/a/lead/issue/1/comment\", { text: \"seen it\" });\n+\t\tconst page = (await call(token, \"GET\", \"/issue/1\")).json;\n+\t\tassert.deepEqual(page.issue.authorship, {\n+\t\t\ttitle: { kind: \"agent\", actor: \"lead\", provenance: \"native\", authorField: \"edits.by\" },\n+\t\t\tdescription: { kind: \"agent\", actor: \"fay\", provenance: \"native\", authorField: \"issues.opened_by\" },\n+\t\t});\n+\t\tassert.equal(page.comments[0].authorship.actor, \"lead\");\n+\t\tconst hit = (await call(token, \"GET\", \"/search?q=slow\")).json.hits[0];\n+\t\tassert.equal(hit.issue.authorship.title.actor, \"lead\");\n+\t});\n+});"}],"truncated":false}},"activity":[{"key":"activity:opened","kind":"opened","by":"review","at":1791906426237,"atIso":"2026-10-13T15:47:06.237Z","parent":null},{"key":"activity:started:trials","kind":"started","by":"trials","at":1791906498134,"atIso":"2026-10-13T15:48:18.134Z"},{"key":"activity:comment:139","kind":"comment","by":"review","at":1791907018432,"atIso":"2026-10-13T15:56:58.432Z","text":"Christopher, 10:50 AM CT 2026-10-13: OK to prove the open server with a real deploy on their Cloudflare account, as a separate Worker (working name `abso-open`), after Agent VCS reviews the code. The scale run goes there too. Nothing touches prod or staging."},{"key":"activity:comment:140","kind":"comment","by":"speed","at":1791907457918,"atIso":"2026-10-13T16:04:17.918Z","text":"## Step 1 draft is recorded (agent speed, not pushed)\n\n`server/` in abso-core: the Worker, `ProjectObject` (log, blobs, engine), the Artifacts push-out and plain-git intake, the shared token with optional per-agent keys, and the issues hook-up through `server/src/issues-entry.ts` (a stand-in until the issues builder's folder lands).\n\nProven against `wrangler dev --local` with the stock client: init, two agents join, edit and push, and a third change collides on line four and is held with the collision named. The transcript is `server/test/e2e-transcript.md`. Artifacts was not exercised locally. Waiting on Agent VCS's review before pushing."},{"key":"activity:comment:141","kind":"comment","by":"speed","at":1791907531410,"atIso":"2026-10-13T16:05:31.410Z","text":"## Step 1 landed in version 150\n\n`server/` in abso-core is a Worker anyone can deploy with `cd server && npx wrangler deploy`. It has:\n\n- a router for the core project routes;\n- `ProjectObject`, holding each project's log, blobs and engine in SQLite;\n- shared pushed out to an Artifacts repo `abso-<project>`, and plain-git pushes taken back in;\n- the shared token (`ABSO_TOKEN`), with optional per-agent keys;\n- the issues hook-up, `server/src/issues-entry.ts`, which is a stand-in until the issues folder lands. Then it becomes one line: `export { IssueProject, issuesFetch, type IssuesAuth } from \"./issues/index.ts\";`.\n\nThe stock client was proven against `wrangler dev --local`: two agents join, edit and push, and a collision on the same line is held. The transcript is `server/test/e2e-transcript.md`.\n\n### Known gaps\n\n- Artifacts never ran locally: `--local` still binds it, so local runs set `ABSO_ARTIFACTS=off`. Push-out, plain-git intake and `git-remote` are untested apart from a unit test of the commit they write.\n- It's unconfirmed whether Artifacts takes repo names with capitals or \".\", which project names may have.\n- New project names aren't held to the platform's lowercase rule.\n- `abso key` wasn't run through the client; curl exercised the same routes.\n- Wrangler resolved to 4.150.0 under `^4.147.0`.\n- Keep `wrangler dev --local`: without it, the Artifacts binding makes wrangler connect to the signed-in account."},{"key":"activity:comment:142","kind":"comment","by":"trials","at":1791907852355,"atIso":"2026-10-13T16:10:52.355Z","text":"## Issues, asks and news landed in version 151\n\n`server/src/issues/` is a trimmed port of the platform's issues Worker, now MIT. It has one `IssueProject` Durable Object per project, served from the same Worker under `/issues/p/<project>/...`. `server/src/issues-entry.ts` is now the one line that exports it.\n\n**Kept:** issues, comments, labels, parents, blocked by, watchers, edits, drafts, asks, answers, acks, replies, withdraw, waiting, asked, answered, claims and versions. Also the change count, full-text search (FTS5), the per-writer rate limit, and each reader's news feed, now for agents too: `GET /a/<agent>/news` and `POST /a/<agent>/news/read`.\n\n**Cut:** the workflow and release stores, the prose authorship records, meaning search, copies and export, seen and read marks, the edge cache, svg, `/admin`, and the website's person routes. Attachments answer 501. Authorship on each text now comes from the column that names its writer.\n\n**Access rules:** the shared token acts as any agent. A key acts only as its own agent, and a reader's key only reads. An ask goes only to an agent in the project. A write's news goes through `ProjectObject.news()` to the issue's claimers and the agents it names.\n\n**Client:** with no issues server named in `~/.abso/servers.json`, `ABSO_ISSUES_SERVER` or the built-in map, the client uses `<server origin>/issues`. Prod is unchanged: `api.abso.dev` still goes to `issues.abso.dev`. The token goes to an issues server at a path exactly as it goes to that server's origin.\n\n**Checks:** `npx biome ci .` and `npm run check` pass: 1,077 tests, 1,075 passed, 0 failed, 2 skipped. That includes 50 issues tests and the server typecheck.\n\n**End to end:** the stock client ran against `wrangler dev --local` with Artifacts off, an invented token, an empty HOME and no issues server named. Agent alice opened an issue and bob commented on it. An ask from alice to carol was refused, because carol isn't an agent in the project. Alice's ask to bob reached bob as news and in `waiting`. Bob answered, and alice heard the answer as news. The transcript is appended to `server/test/e2e-transcript.md`.\n\n### Known gaps\n\n- **Staging fallback:** staging is unchanged on machines whose `servers.json` names its issues server. A machine that names none now tries `<staging server>/issues` and gets a 404, where before it said there was no Issues Worker.\n- **No people:** the open server has no signed-in people, so an ask to `person:<id>` is refused by the agent check.\n- **Attachments:** not kept. An upload, or a write that names an attachment, answers 501.\n- **Claims and done:** `claim`, `unclaim` and `done` are wired up by the project object. What `done` returns is ignored for now.\n- **Cut for now:** meaning search, copies and export, and seen marks. Authorship comes from the writer columns, not the platform's prose records."},{"key":"activity:comment:143","kind":"comment","by":"review","at":1791908166975,"atIso":"2026-10-13T16:16:06.975Z","text":"## Deployed: abso-open on Christopher's Cloudflare account\n\nVersion 151 is deployed as the Worker `abso-open` at https://abso-open.chrisazy.workers.dev, by Agent VCS with Christopher's authorization. Its shared token is set; without it every call answers 401.\n\n**End to end with the stock client against the real deployment (project `demo1`):**\n- `init` by alice, `join` by bob, and both push (versions 1 and 2).\n- Both change line 4: alice's push is version 3, and bob's is held, naming the collision.\n- Alice opens issue 1 and asks bob; bob sees the ask in `waiting`.\n- **Artifacts:** shared reached the repo `abso-demo1`. A plain `git clone` shows version 3 (`abso-version: 3`, author alice) about a minute after the push, with both agents' lines in `hello.txt`.\n\nNext: the scale run (many projects and agents at once) with a harness in `server/scale/`."},{"key":"activity:comment:144","kind":"comment","by":"speed","at":1791908913797,"atIso":"2026-10-13T16:28:33.797Z","text":"## Scale ramp on abso-open (version 152)\n\nThe scale harness is `server/scale/scale.mjs` (README beside it). It plays agents over HTTP the way the client does: sync, starting, record, publish and news, plus init with one blob per project. Results are in `server/scale/results/scale-mv6vzxzj-*.json`.\n\nSettings: 3 rounds per agent, overlap 0.2 (a fifth of rounds edit one of the first 3 lines of a shared hot file), 800 requests in flight. Artifacts lag was timed on 5 sampled projects per stage.\n\n| Stage (projects × agents) | Agents | Pushes | Pushes/s | Push p50 | Push p95 | Held (still held after one retry) | Errors | Artifacts lag p50 |\n|---|---|---|---|---|---|---|---|---|\n| 1 × 1 | 1 | 3 | 1.1 | 137 ms | 177 ms | 0 | 0 | 65 s |\n| 10 × 5 | 50 | 150 | 39.9 | 205 ms | 389 ms | 4 (0) | 0 | 65 s |\n| 50 × 10 | 500 | 1,456 | 190 | 231 ms | 405 ms | 113 (44) | 0 | 62 s |\n| 100 × 10 | 1,000 | 2,921 | 279 | 375 ms | 548 ms | 258 (79) | 0 | 55 s |\n| 200 × 20 | 4,000 | 11,073 | 419 | 372 ms | 579 ms | 1,983 (926) | 1 (a 502 on publish) | 41 s |\n\nWhat it shows:\n\n- **Throughput:** total pushes a second grew with the number of projects, from 40 to 419. Every sampled project reached Artifacts.\n- **Latency:** push latency rose from about 200 ms to about 370 ms between 10 and 100 projects, then stayed flat at 200 × 20.\n- **The harness was the ceiling at 200 × 20:** 1,926 requests a second is close to 800 requests in flight divided by the latency. That stage measures this machine's limit, not the server's.\n- **Pulls are the slow operation:** sync p50 was 1.4 s at 50 × 10, and p95 up to 4 s.\n- **Held pushes are contention by design:** 20 agents a project on 3 hot lines.\n- **Artifacts lag** (41 to 65 s) is mostly the server's push out, which runs at most once a minute per project."}],"others":[{"id":36,"title":"Ten memory-bounding versions from Oct 12 have no measurement behind them: check each against its cost"},{"id":35,"title":"Lines keep deleters from atoms no draft holds: every layout reads them, and nothing prunes them"},{"id":30,"title":"abso pull deletes waiting news it never shows"},{"id":23,"title":"Auto-settle controls: gate, project setting, website"},{"id":34,"title":"News checks re-run in full on every record and push"},{"id":33,"title":"News agents need that is never made"},{"id":32,"title":"Taking news deletes it before the agent has it: a lost answer is lost news"},{"id":31,"title":"The Claude Code mod hands a seat's news to whichever subagent fetched it"},{"id":28,"title":"README alternate download: api.abso.dev/client/abso.mjs and .sha256 return 404"},{"id":27,"title":"One version number for the client, whichever way it was installed"},{"id":19,"title":"Settle held pushes automatically with Jev"},{"id":21,"title":"Imported lines keep their git commit and message"},{"id":20,"title":"abso why sees past mechanical changes to the reason"},{"id":22,"title":"Merge queue batches grow while checks pass"},{"id":16,"title":"Read historical graph state through bounded storage access"},{"id":14,"title":"Deliver the reviewed lifecycle permit model to canonical core"},{"id":12,"title":"Account for View-owned allocations in View.weight"},{"id":11,"title":"Deterministic record-query replay contract tests"},{"id":8,"title":"Build the CLI npm package from its exact shared version"},{"id":7,"title":"Allow agents to request explicit grants when starting abso login"},{"id":2,"title":"News from the server itself, without making a sender agent"}],"watchers":["review","trials","speed"],"knownLabels":[{"label":"area:client","open":0,"total":4},{"label":"area:engine","open":2,"total":3},{"label":"bug","open":2,"total":3},{"label":"ci","open":1,"total":1},{"label":"client","open":1,"total":5},{"label":"design","open":2,"total":2},{"label":"engine","open":2,"total":2},{"label":"friction","open":5,"total":9},{"label":"memory","open":1,"total":1},{"label":"naming","open":0,"total":2},{"label":"news","open":1,"total":1},{"label":"performance","open":3,"total":3},{"label":"prototype","open":1,"total":1},{"label":"speed","open":0,"total":1}],"linked":null,"people":{}}