visualproof 0.4.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +16 -7
  2. package/dist/assets/tips/phone-fingers.light.mp4 +0 -0
  3. package/dist/assets/tips/phone-fingers.light.webp +0 -0
  4. package/dist/assets/tips/tour-agent.webp +0 -0
  5. package/dist/assets/tips/tour-arrange.webp +0 -0
  6. package/dist/assets/tips/tour-artwork.webp +0 -0
  7. package/dist/assets/tips/tour-checks.webp +0 -0
  8. package/dist/assets/tips/tour-keys.webp +0 -0
  9. package/dist/assets/tips/tour-library.webp +0 -0
  10. package/dist/assets/tips/tour-project.webp +0 -0
  11. package/dist/assets/tips/tour-review.webp +0 -0
  12. package/dist/assets/tips/tour-share.webp +0 -0
  13. package/dist/assets/tips/tour-source.webp +0 -0
  14. package/dist/assets/tips/tour-target.webp +0 -0
  15. package/dist/assets/tips/tour-view.webp +0 -0
  16. package/dist/assets/tips/tour.json +132 -117
  17. package/dist/assets/tips/tour.webp +0 -0
  18. package/dist/mcp/visualproof-mcp.mjs +20 -9
  19. package/dist/server/access.js +31 -1
  20. package/dist/server/accesspage.js +130 -0
  21. package/dist/server/agent.js +143 -50
  22. package/dist/server/askfollow.js +1 -1
  23. package/dist/server/buildwatch.js +133 -0
  24. package/dist/server/deploy.js +995 -0
  25. package/dist/server/doctor.js +15 -3
  26. package/dist/server/film.js +1 -1
  27. package/dist/server/historyapi.js +100 -50
  28. package/dist/server/historythread.js +206 -0
  29. package/dist/server/hover.js +8 -0
  30. package/dist/server/invites.js +113 -20
  31. package/dist/server/live.js +308 -60
  32. package/dist/server/main.js +450 -77
  33. package/dist/server/mcptools.js +33 -20
  34. package/dist/server/presence.js +3 -3
  35. package/dist/server/prompt.js +8 -3
  36. package/dist/server/readonlygate.js +4 -4
  37. package/dist/server/review.js +27 -7
  38. package/dist/server/reviewapi.js +51 -17
  39. package/dist/server/status.js +119 -46
  40. package/dist/server/talk.js +231 -115
  41. package/dist/server/tokens.js +10 -2
  42. package/dist/server/usage.js +51 -0
  43. package/dist/shared/board.js +2 -1
  44. package/dist/shared/build.js +35 -1
  45. package/dist/shared/collab.js +8 -0
  46. package/dist/shared/deploy.js +35 -0
  47. package/dist/shared/keys.js +66 -37
  48. package/dist/shared/layout.js +297 -70
  49. package/dist/shared/libm.js +366 -0
  50. package/dist/shared/lostfound.js +1 -0
  51. package/dist/shared/mentions.js +83 -0
  52. package/dist/shared/palette.js +1 -1
  53. package/dist/shared/query.js +13 -4
  54. package/dist/shared/review.js +91 -21
  55. package/dist/shared/reviewqueue.js +6 -1
  56. package/dist/shared/separate.js +556 -32
  57. package/dist/web/bundle/app.js +5022 -2736
  58. package/dist/web/bundle/edges.js +2 -1
  59. package/dist/web/bundle/layout.js +1026 -80
  60. package/dist/web/index.html +45 -9
  61. package/dist/web/src/canvas.js +47 -34
  62. package/dist/web/src/overview.js +4 -1
  63. package/dist/web/src/reviewqueue.js +52 -19
  64. package/dist/web/src/scene.js +13 -12
  65. package/dist/web/src/status.js +28 -0
  66. package/dist/web/src/theme.js +108 -0
  67. package/dist/web/src/trust.js +271 -0
  68. package/dist/web/style.css +283 -105
  69. package/docs/agent-api/README.md +13 -11
  70. package/docs/agent-api/advice.md +8 -2
  71. package/docs/agent-api/export.md +1 -1
  72. package/docs/agent-api/following.md +11 -12
  73. package/docs/agent-api/history.md +6 -2
  74. package/docs/agent-api/mcp.md +15 -15
  75. package/docs/agent-api/notes.md +1 -1
  76. package/docs/agent-api/reading.md +2 -2
  77. package/docs/agent-api/requests.md +16 -18
  78. package/docs/agent-api/talking.md +60 -55
  79. package/docs/agent-api/tcb.md +21 -21
  80. package/docs/agent-api/views.md +3 -4
  81. package/docs/agent-api/words.md +8 -8
  82. package/package.json +2 -1
@@ -7,8 +7,8 @@ import { createHash } from "node:crypto";
7
7
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
8
8
  import { createServer } from "node:http";
9
9
  import { basename, dirname, extname, join, resolve } from "node:path";
10
- import { tmpdir } from "node:os";
11
- import { gunzipSync, gzip, gzipSync } from "node:zlib";
10
+ import { freemem, tmpdir } from "node:os";
11
+ import { gunzip, gunzipSync, gzip, gzipSync } from "node:zlib";
12
12
  import { WEB, WEBFONTS, bundleDir, bundleDirIn, ensureBundle, prepare, useBundleDir } from "./pipeline.js";
13
13
  import { makeArtwork, pngOf, projectView } from "./artcmd.js";
14
14
  import { SiteBusy, cacheHome, dataHome, lockSite, openSite, projectDirs } from "./dirs.js";
@@ -19,18 +19,20 @@ import { isDeclName, LeanHover } from "./hover.js";
19
19
  import { Identities, layoutAuthor } from "./identity.js";
20
20
  import { LAYOUT_VERSION } from "../shared/graph.js";
21
21
  import { MAX_MEMORY_BYTES, readProjectView, Views } from "./views.js";
22
- import { cleanView, defaultAgentName, nameKey, validSession, withoutArtwork } from "../shared/collab.js";
22
+ import { cleanView, defaultAgentName, madeBy, nameKey, validSession, withoutArtwork } from "../shared/collab.js";
23
23
  import { writeSnapshot } from "./snapshot.js";
24
24
  import { lakeTextHash } from "./status.js";
25
25
  import { invalidTemplate } from "../shared/editor.js";
26
26
  import { packEdges } from "../shared/edgecodec.js";
27
- import { Access, hostAllowed, KEY_PATH, loadKey, urlHost } from "./access.js";
27
+ import { Access, fromOwnPage, hostAllowed, KEY_PATH, loadKey, urlHost } from "./access.js";
28
+ import { asksForPage, sendAccessPage } from "./accesspage.js";
28
29
  import { INVITE_PATH, invalidPersonName, Invites, taken } from "./invites.js";
29
30
  import { AGENT_LEVELS, AgentApi, lower, needOf, refusal } from "./agent.js";
30
31
  import { AgentTokens, bearerOf, DEFAULT_DAYS, invalidAgentName, looksLikeToken, TOKEN_DAYS } from "./tokens.js";
31
32
  import { agentPrompt } from "./prompt.js";
32
- import { MAX_PERSON } from "./talk.js";
33
- import { DEFAULT_JOBS, UsagePass, mergeUsage, saveMerged } from "./usage.js";
33
+ import { forPages, MAX_PERSON, PUBLIC, THREAD } from "./talk.js";
34
+ import { mentioned } from "../shared/mentions.js";
35
+ import { DEFAULT_JOBS, inGB, jobsAdvice, memoryFloor, onMathlib, UsagePass, mergeUsage, saveMerged, WORKER_PEAK } from "./usage.js";
34
36
  import { extract } from "./extract.js";
35
37
  import { Exporter } from "./export.js";
36
38
  import { Library, libraryApiOf } from "./library.js";
@@ -46,10 +48,13 @@ import { RESTART_STATUS, supervise } from "./supervise.js";
46
48
  import { stopChildren } from "./children.js";
47
49
  import { filmStatus, serveFilm, useFilm } from "./film.js";
48
50
  import { finalAnswer, readOnlyAllows, ReadOnlyBounds } from "./readonlygate.js";
51
+ import { branchProblem, branchToFollow, DEFAULT_BUILD_HOURS, DEFAULT_POLL_MINUTES, DeployBusy, deployFolder, Deployment, deploySite, ensureClone, isGitAddress, limitInWords, lockDeployment, MATHLIB_CACHES, MAX_BUILD_HOURS, MIN_BUILD_HOURS, MIN_POLL_MINUTES, parseBuildHours, parseRemote, recordedDefault, sharedMathlibCache } from "./deploy.js";
52
+ import { shortCommit, slimDeploy } from "../shared/deploy.js";
49
53
  /** The usage, to stderr with status 2 for a command line it cannot read; asked for (`--help`),
50
54
  * to stdout with status 0. */
51
55
  function usage(code = 2) {
52
- (code === 0 ? console.log : console.error)(`usage: visualproof serve <lean-project> [--root Name]... [--port 4173] [--host 127.0.0.1]
56
+ (code === 0 ? console.log : console.error)(`usage: visualproof serve <lean-project | git URL> [--branch name] [--poll ${DEFAULT_POLL_MINUTES}] [--build-timeout ${DEFAULT_BUILD_HOURS}]
57
+ [--mathlib-cache shared|own] [--root Name]... [--port 4173] [--host 127.0.0.1]
53
58
  [--site dir] [--cache dir] [--graph saved.json]
54
59
  [--identity-header X-Forwarded-User] [--editor URL-template]
55
60
  [--agents read|advise|full] [--access-key-file file] [--public] [--jobs ${DEFAULT_JOBS}]
@@ -66,6 +71,25 @@ function usage(code = 2) {
66
71
  Reads what \`lake build\` left in <lean-project>/.lake. It never builds the project, and writes
67
72
  nothing into it.
68
73
 
74
+ A git URL where the project goes (https://github.com/owner/repo, ssh://…, git@host:owner/repo, or
75
+ file:///path for a repository on this machine): the server follows that branch of the repository
76
+ in a clone of its own in the cache, never a workspace, and builds each new commit itself —
77
+ \`lake exe cache get\` where the project is on Mathlib, then \`lake build\` — one at a time, the
78
+ newest commit pushed meanwhile the only one built after it; the board shows the last build
79
+ meanwhile. Git's own credentials (an SSH key, a deploy key, a credential helper): VisualProof keeps
80
+ none, and nothing waits on a prompt. Whoever can push to the branch runs code on this machine, as
81
+ the server's user (SECURITY.md): run it as a user of its own, and protect the branch.
82
+ --branch the branch followed (default: the remote's default branch); never a pull request's or
83
+ a fork's
84
+ --poll how often the remote is asked for the branch's head, in minutes (default ${DEFAULT_POLL_MINUTES})
85
+ --build-timeout the hours past which \`lake build\` is stopped and the build failed, its commit
86
+ not tried again (default ${DEFAULT_BUILD_HOURS}; ${MIN_BUILD_HOURS} to ${MAX_BUILD_HOURS}, fractions too: 1.5)
87
+ --mathlib-cache where \`lake exe cache get\` keeps Mathlib's files: shared (the default) — the
88
+ user's, as their own builds' (~/.cache/mathlib, or MATHLIB_CACHE_DIR), so that a build
89
+ fetches only what they have not; own — the deployment's, in its folder of the cache
90
+ (deploy/<repo>-<hash>/mathlib-cache/): about 0.45 GB, the version of Mathlib checked
91
+ out alone (\`lake exe cache clean\` after each fetch), removed with that folder
92
+
69
93
  --root what to read: a library of the lakefile (the modules Lake builds of it) or a module;
70
94
  repeatable. By default the lakefile's default targets.
71
95
  --site the site's folder: the review's logs and what this running site accumulates — the
@@ -117,25 +141,30 @@ function usage(code = 2) {
117
141
  --jobs how many modules the usage pass elaborates at once (default ${DEFAULT_JOBS}; 0: no pass). The
118
142
  pass finds which notation each declaration is written in and the exact context it is
119
143
  written in (TCBSpec.md, decisions 2 and 4); its findings follow the extractor's graph
120
- as its next version. Each worker takes about 400 MB of its own and the import of a
121
- module is bound by memory bandwidth: past about a quarter of the cores it gains little.
144
+ as its next version. Each worker takes about 400 MB of its own, several GB on a large
145
+ project on Mathlib (serve and doctor say which --jobs the memory fits); with memory
146
+ short, fewer run at a time. The import of a module is bound by memory bandwidth: past
147
+ about a quarter of the cores it gains little.
122
148
 
123
149
  --access-key-file let in only those given the link http://<host>:<port>/k/<key>, the key being
124
150
  what the file holds (one is made there, readable by its owner alone, if there is none).
125
151
  The link leaves a cookie in the browser; agents send Authorization: Bearer <key>.
126
- Anything else is answered 404. Over plain HTTP the key crosses the network in the
127
- clear: it keeps out who was not given the link, not who can watch the traffic.
152
+ Anything else is answered 404, but a browser asking for a page, which is shown one
153
+ that says the site is private and nothing of it. Over plain HTTP the key crosses the
154
+ network in the clear: it keeps out who was not given the link, not who can watch the
155
+ traffic.
128
156
  Share also gives an AI agent a token of its own (vpa_…), which reaches /api/agent only,
129
157
  and a person a link of their own (/i/vpp_…), which lets them in and says who they are,
130
158
  and anyone a read-only link (/r/vpr_…), which lets them see and change nothing shared.
131
159
 
132
160
  --public with --access-key-file: whoever comes without the key or a link of their own is let
133
- in read-only, rather than answered 404: they see the project, its review and its
161
+ in read-only, rather than turned away: they see the project, its review and its
134
162
  history, change nothing that is shared, and are seen by nobody. For a project anyone
135
163
  may read (a showcase); never for a private one.
136
164
 
137
165
  --public-url the address people reach this server at, when it is not the one their browser
138
- sends (a proxy in front): the prompt Share makes for an agent tells it this address.
166
+ sends (a proxy in front): the links Share and Copy link make, and the prompt Share
167
+ makes for an agent, carry it.
139
168
 
140
169
  --allowed-host without --access-key-file, a name this server is reached by; repeatable. A
141
170
  server without a key answers only requests for an IP address, localhost (and the names
@@ -181,7 +210,7 @@ function parseArgs(argv) {
181
210
  console.error(`visualproof: VISUALPROOF_UPDATES=${fromEnv}: say auto, notify or off`);
182
211
  process.exit(2);
183
212
  }
184
- const o = { cmd, path: "", roots: [], port: 4173, host: "127.0.0.1", site: null, cache: null, graph: null, out: null, label: "VisualProof", identityHeader: null, editor: null, agents: "full", accessKeyFile: null, jobs: DEFAULT_JOBS, publicUrl: null, allowedHosts: [], libraryLimit: DEFAULT_LIBRARY_LIMIT, sha: null, publicRead: false, recipe: null, png: false, svg: false, screen: { w: 1920, h: 1200 }, updates: UPDATE_MODES.includes(fromEnv) ? fromEnv : "auto" };
213
+ const o = { cmd, path: "", roots: [], port: 4173, host: "127.0.0.1", site: null, cache: null, graph: null, out: null, label: "VisualProof", identityHeader: null, editor: null, agents: "full", accessKeyFile: null, jobs: DEFAULT_JOBS, publicUrl: null, allowedHosts: [], libraryLimit: DEFAULT_LIBRARY_LIMIT, sha: null, publicRead: false, recipe: null, png: false, svg: false, screen: { w: 1920, h: 1200 }, updates: UPDATE_MODES.includes(fromEnv) ? fromEnv : "auto", remote: null, branch: null, poll: null, buildHours: null, mathlibCache: null };
185
214
  for (let i = 0; i < rest.length; i++) {
186
215
  const a = rest[i];
187
216
  const val = () => rest[++i] ?? usage();
@@ -248,6 +277,34 @@ function parseArgs(argv) {
248
277
  usage();
249
278
  o.jobs = n;
250
279
  }
280
+ else if (a === "--branch" && cmd === "serve")
281
+ o.branch = val();
282
+ else if (a === "--poll" && cmd === "serve") {
283
+ const v = val();
284
+ const m = Number(v);
285
+ // said in a line, as --screen is
286
+ if (!/^\d+(\.\d+)?$/.test(v) || m < MIN_POLL_MINUTES || m > 1440) {
287
+ console.error(`visualproof: --poll ${v}: say how often the remote is asked, in minutes, from ${MIN_POLL_MINUTES} to 1440 (a day)`);
288
+ process.exit(2);
289
+ }
290
+ o.poll = m;
291
+ }
292
+ else if (a === "--build-timeout" && cmd === "serve") {
293
+ const h = parseBuildHours(val());
294
+ if (typeof h !== "number") {
295
+ console.error(`visualproof: ${h.error}`);
296
+ process.exit(2);
297
+ }
298
+ o.buildHours = h;
299
+ }
300
+ else if (a === "--mathlib-cache" && cmd === "serve") {
301
+ const v = val();
302
+ if (!MATHLIB_CACHES.includes(v)) {
303
+ console.error(`visualproof: --mathlib-cache ${v.slice(0, 40)}: say shared (the user's Mathlib cache, as their builds': the default) or own (the deployment's, in its folder of the cache)`);
304
+ process.exit(2);
305
+ }
306
+ o.mathlibCache = v;
307
+ }
251
308
  else if (a === "--updates" && cmd === "serve") {
252
309
  const mode = val();
253
310
  if (!UPDATE_MODES.includes(mode))
@@ -277,6 +334,38 @@ function parseArgs(argv) {
277
334
  }
278
335
  if ((!o.path && cmd !== "doctor") || (cmd === "export" && !o.out) || (cmd === "artwork" && !o.recipe))
279
336
  usage();
337
+ // a git address where the project goes: the branch followed and built (DeploySpec decisions 1,
338
+ // 10 and 11), its address and branch checked before anything is run
339
+ if (o.path && isGitAddress(o.path)) {
340
+ if (cmd !== "serve") {
341
+ console.error(`visualproof ${cmd}: ${o.path.slice(0, 200)} is a git address: only serve follows a branch. Give the folder of its clone, which serve names as it starts (its "clone:" line).`);
342
+ process.exit(2);
343
+ }
344
+ const r = parseRemote(o.path);
345
+ if ("error" in r) {
346
+ console.error(`visualproof: ${r.error}`);
347
+ process.exit(2);
348
+ }
349
+ if (o.graph) {
350
+ console.error("visualproof: --graph does not go with a git address: the server builds what it shows");
351
+ process.exit(2);
352
+ }
353
+ const why = o.branch === null ? null : branchProblem(o.branch);
354
+ if (why) {
355
+ console.error(`visualproof: --branch ${why}`);
356
+ process.exit(2);
357
+ }
358
+ o.remote = r;
359
+ }
360
+ else {
361
+ // what is about following a branch and building it: a folder is never built (DeploySpec
362
+ // decision 15)
363
+ const given = [["--branch", o.branch], ["--poll", o.poll], ["--build-timeout", o.buildHours], ["--mathlib-cache", o.mathlibCache]].filter(([, v]) => v !== null).map(([n]) => n);
364
+ if (given.length) {
365
+ console.error(`visualproof: ${given.length > 1 ? `${given.slice(0, -1).join(", ")} and ${given[given.length - 1]} go` : `${given[0]} goes`} with a git address (serve https://github.com/owner/repo): a folder is read as its owner's builds leave it, never built`);
366
+ process.exit(2);
367
+ }
368
+ }
280
369
  // read-only for whoever comes, beside those the key or a link lets in: without a key, everyone is in
281
370
  // already; behind a sign-in, there is nobody else
282
371
  if (o.publicRead && (!o.accessKeyFile || o.identityHeader)) {
@@ -456,42 +545,65 @@ export class App {
456
545
  return sendGz(req, res, a.gz.body, a.gz.type);
457
546
  sendJson(res, a.body, a.status, a.headers);
458
547
  }
459
- /** Talking with an agent (AgentSpec decision 8), for pages: an agent's conversation (GET), and a
460
- * message to it (POST) — from a person with a name, to an agent that is not offline (409
461
- * otherwise: one listening has it at once, one thinking or working at its next wait), at most so
462
- * many a minute. The agent is named as presence names it. */
548
+ /** The conversations (CollabSpec decision 13, AgentSpec decision 8), for pages: a channel read
549
+ * (GET ?channel=public|<agent id>&before=<id>, the newest 200 first) and a message written in it
550
+ * (POST {channel, text, place}). Everyone with a name reads and writes the public channel; an
551
+ * agent's private channel is its maker's alone (shared/collab.ts, madeBy: 403 to anyone else).
552
+ * A read-only reader neither sees nor writes any (403), whatever the page sends; agents talk
553
+ * through their API. A private channel cannot be written to while its agent is offline (409); a
554
+ * mention of it in the public channel can, and is handed to it when it comes back. At most so
555
+ * many messages a minute, a person's in every channel together. */
463
556
  async chat(req, res, url) {
464
557
  const live = this.live;
465
- if (req.method === "GET") {
466
- const id = url.searchParams.get("agent") ?? "";
467
- const tok = live.presence.tokenOf(id);
468
- if (!tok)
469
- return sendJson(res, { error: "There is no such agent: only an agent with a token of its own can be talked to." }, 404);
470
- return sendJson(res, { agent: { id, name: live.tokens.get(tok)?.name ?? null, talk: live.talk.talk(tok) }, messages: live.talk.thread(tok) });
471
- }
472
- if (req.method !== "POST")
558
+ if (req.method !== "GET" && req.method !== "POST")
473
559
  return sendJson(res, { error: "/api/chat answers GET and POST." }, 405);
560
+ if (this.readOnlyOf.has(req))
561
+ return sendJson(res, { error: "This page is read-only.", readOnly: true }, 403);
474
562
  if (this.ids.kind(req) === "agent")
475
- return sendJson(res, { error: "Agents answer through their API.", hint: "POST /api/agent/reply." }, 403);
563
+ return sendJson(res, { error: "Agents talk through their API.", hint: "GET /api/agent/channel, POST /api/agent/reply." }, 403);
476
564
  const me = this.ids.who(req);
477
565
  if (!me)
478
- return sendJson(res, { error: "Say who you are first: a message is sent under your name.", who: true }, 401);
566
+ return sendJson(res, { error: "Say who you are first: the conversations are for people with a name, and a message is sent under yours.", who: true }, 401);
567
+ const who = { name: me, person: this.ids.person(req)?.id ?? null };
568
+ /** the channel a request names: the public one, or an agent's private one that is this
569
+ * reader's — 404 where there is no such agent, 403 where it is someone else's */
570
+ const channelOf = (raw) => {
571
+ if (raw === "public" || raw === undefined || raw === null || raw === "")
572
+ return { key: PUBLIC, agent: null };
573
+ const tok = typeof raw === "string" ? live.presence.tokenOf(raw) : null;
574
+ const record = tok ? live.tokens.get(tok) : undefined;
575
+ if (!tok || !record)
576
+ return { status: 404, body: { error: "There is no such channel: public, or the id of an agent with a token of its own." } };
577
+ if (!madeBy(record, who))
578
+ return { status: 403, body: { error: `${record.name}'s private channel is ${record.by}'s, who made its token: nobody else reads or writes it.`, private: true } };
579
+ return { key: tok, agent: { id: raw, record } };
580
+ };
581
+ if (req.method === "GET") {
582
+ const c = channelOf(url.searchParams.get("channel") ?? url.searchParams.get("agent"));
583
+ if ("status" in c)
584
+ return sendJson(res, c.body, c.status);
585
+ const raw = url.searchParams.get("before");
586
+ const before = raw && /^\d{1,9}$/.test(raw) ? Number(raw) : null;
587
+ const messages = live.talk.thread(c.key, THREAD, before).map(forPages);
588
+ if (!c.agent)
589
+ return sendJson(res, { channel: PUBLIC, messages });
590
+ return sendJson(res, { channel: c.agent.id, agent: { id: c.agent.id, name: c.agent.record.name, talk: live.talk.talk(c.key) }, messages });
591
+ }
479
592
  const r = await this.json(req, 1 << 16);
480
593
  if (r.error !== undefined)
481
594
  return sendJson(res, { error: `The body is ${r.error}.` }, 400);
482
595
  const b = (r.body ?? {});
483
- const tok = typeof b.agent === "string" ? live.presence.tokenOf(b.agent) : null;
484
- if (!tok)
485
- return sendJson(res, { error: "There is no such agent: only an agent with a token of its own can be talked to." }, 404);
486
- const name = live.tokens.get(tok)?.name ?? "The agent";
487
- if (live.talk.state(tok) === "offline")
488
- return sendJson(res, { error: "offline", message: `${name} is offline: it can be written to once it listens again.` }, 409);
596
+ const c = channelOf(b.channel ?? b.agent);
597
+ if ("status" in c)
598
+ return sendJson(res, c.body, c.status);
599
+ if (c.agent && live.talk.state(c.key) === "offline")
600
+ return sendJson(res, { error: "offline", message: `${c.agent.record.name} is offline: it can be written to once it listens again.` }, 409);
489
601
  const text = typeof b.text === "string" ? b.text.trim() : "";
490
602
  if (!text)
491
603
  return sendJson(res, { error: "The message is empty." }, 400);
492
604
  if (text.length > MAX_PERSON)
493
605
  return sendJson(res, { error: `A message is at most ${MAX_PERSON.toLocaleString("en")} characters.` }, 400);
494
- const wait = live.talk.allow("person", me);
606
+ const wait = live.talk.allow("person", who.person ? `p:${who.person}` : `n:${nameKey(me)}`);
495
607
  if (wait)
496
608
  return sendJson(res, { error: `Too many messages at once: wait ${wait} s.`, retryAfter: wait }, 429, { "retry-after": String(wait) });
497
609
  // where the writer was, as the page says it, bounded: a selection can be a long query; a private
@@ -500,17 +612,23 @@ export class App {
500
612
  const at = view ? this.agents.placeOf(view) : null;
501
613
  const clip = (x, n) => (x !== null && x.length > n ? x.slice(0, n - 1) + "…" : x);
502
614
  const where = at ? { inWords: clip(at.inWords, 600), view: at.view, declaration: clip(at.declaration, 300), selection: clip(at.selection, 300) } : null;
503
- const message = live.talk.post(tok, { from: me, kind: "person", text, where });
504
- return sendJson(res, { ok: true, message });
615
+ // the names it mentions; in the public channel, the agents among them are handed it
616
+ const can = live.mentionable();
617
+ const mentions = mentioned(text, can.names);
618
+ const to = c.agent ? [] : [...new Set(mentions.flatMap((n) => can.agents.get(nameKey(n)) ?? []))];
619
+ const message = live.talk.post(c.key, { from: me, kind: "person", text, ...(mentions.length ? { mentions } : {}), where, to });
620
+ return sendJson(res, { ok: true, channel: c.agent?.id ?? PUBLIC, message: forPages(message) });
505
621
  }
506
- /** A new conversation with an agent (AgentSpec decision 8, the owner's decision of 2026-10-11):
507
- * a divider, from anyone who may write to it — a person with a name — and held to the rate of
508
- * their messages; an offline agent's too, so that its next session starts clean. One right after
622
+ /** A new conversation in an agent's private channel (AgentSpec decision 8, the owner's decisions
623
+ * of 2026-10-11 and 2026-10-19): a divider, from its maker alone, held to the rate of their
624
+ * messages; an offline agent's too, so that its next session starts clean. One right after
509
625
  * another divides nothing: it is answered `unchanged`, and neither written nor counted. */
510
626
  async chatNew(req, res) {
511
627
  const live = this.live;
512
628
  if (req.method !== "POST")
513
629
  return sendJson(res, { error: "/api/chat/new answers POST." }, 405);
630
+ if (this.readOnlyOf.has(req))
631
+ return sendJson(res, { error: "This page is read-only.", readOnly: true }, 403);
514
632
  if (this.ids.kind(req) === "agent")
515
633
  return sendJson(res, { error: "A new conversation is for people to start." }, 403);
516
634
  const me = this.ids.who(req);
@@ -521,14 +639,19 @@ export class App {
521
639
  return sendJson(res, { error: `The body is ${r.error}.` }, 400);
522
640
  const b = (r.body ?? {});
523
641
  const tok = typeof b.agent === "string" ? live.presence.tokenOf(b.agent) : null;
524
- if (!tok)
525
- return sendJson(res, { error: "There is no such agent: only an agent with a token of its own can be talked to." }, 404);
642
+ const record = tok ? live.tokens.get(tok) : undefined;
643
+ if (!tok || !record)
644
+ return sendJson(res, { error: "There is no such agent: only an agent with a token of its own has a private channel." }, 404);
645
+ const person = this.ids.person(req)?.id ?? null;
646
+ if (!madeBy(record, { name: me, person }))
647
+ return sendJson(res, { error: `Only ${record.by}, who made ${record.name}'s token, starts a new conversation with it.`, private: true }, 403);
526
648
  if (live.talk.fresh(tok))
527
649
  return sendJson(res, { ok: true, unchanged: true, divider: null, message: "Nothing was said since the conversation began: it is new already." });
528
- const wait = live.talk.allow("person", me);
650
+ const wait = live.talk.allow("person", person ? `p:${person}` : `n:${nameKey(me)}`);
529
651
  if (wait)
530
652
  return sendJson(res, { error: `Too many at once: wait ${wait} s.`, retryAfter: wait }, 429, { "retry-after": String(wait) });
531
- return sendJson(res, { ok: true, divider: live.talk.restart(tok, me) });
653
+ const divider = live.talk.restart(tok, me);
654
+ return sendJson(res, { ok: true, divider: divider && forPages(divider) });
532
655
  }
533
656
  /** Asking others to follow (CollabSpec decision 10, the owner's decision of 2026-10-12), for pages:
534
657
  * POST /api/ask {token, to?} — the page whose event stream holds `token` asks everyone on the
@@ -606,10 +729,13 @@ export class App {
606
729
  // the server as the prompt names it
607
730
  const address = this.publicUrl ?? reachedAt(req);
608
731
  if (path === "/api/share/agents/prompt") {
609
- // a token that ended has no prompt: it lets nothing in
732
+ // a token that ended has no prompt: it lets nothing in. Its maker alone is shown it again (the
733
+ // owner's decision of 2026-10-19): whoever holds the token reads its private channel
610
734
  const t = typeof b.id === "string" ? tokens.token(b.id) : null;
611
735
  if (!t)
612
736
  return sendJson(res, { error: "There is no such token in force." }, 404);
737
+ if (!madeBy(t.record, { name: me, person: this.ids.person(req)?.id ?? null }))
738
+ return sendJson(res, { error: `Only ${t.record.by}, who made it, is shown this token's prompt again: whoever holds a token reads its agent's private channel.`, maker: false }, 403);
613
739
  return sendJson(res, { token: AgentTokens.info(t.record), prompt: agentPrompt({ url: address, token: t.token, record: t.record }) });
614
740
  }
615
741
  if (path !== "/api/share/agents")
@@ -627,21 +753,23 @@ export class App {
627
753
  const days = b.days ?? DEFAULT_DAYS;
628
754
  if (!TOKEN_DAYS.includes(days))
629
755
  return sendJson(res, { error: `days is one of ${TOKEN_DAYS.join(", ")}.` }, 400);
630
- const made = tokens.create({ name: name.trim(), by: me, level, days: days });
756
+ const made = tokens.create({ name: name.trim(), by: me, person: this.ids.person(req)?.id ?? null, level, days: days });
631
757
  const prompt = agentPrompt({ url: address, token: made.token, record: made.record });
632
758
  return sendJson(res, { token: AgentTokens.info(made.record), prompt, tokens: tokens.inForce().map(AgentTokens.info) });
633
759
  }
634
760
  /** Inviting a person (CollabSpec decision 9), for people: the personal links in force (GET), a new
635
761
  * one for a person named in the body (POST), and revoking one (POST …/revoke). Making and
636
762
  * revoking need a name: who made a link, and who revoked it, is said in Share. The link itself
637
- * is answered once, to whoever made it: the server keeps only its digest (server/invites.ts). */
763
+ * is answered once to whoever made it, and again to its holder alone (`mine`). */
638
764
  async sharePeople(req, res, url) {
639
765
  if (this.ids.kind(req) === "agent")
640
- return sendJson(res, { error: "Personal links are for people: an agent cannot make, list or revoke them." }, 403);
766
+ return sendJson(res, { error: "Personal links are for people: an agent cannot make, list, show or revoke them." }, 403);
641
767
  if (this.ids.header)
642
768
  return sendJson(res, { error: "Names come from the sign-in in front of this server: it has no personal links." }, 404);
643
769
  const invites = this.live.invites;
644
770
  const path = url.pathname.replace(/\/+$/, "");
771
+ if (path === "/api/share/people/mine" || path === "/api/share/people/mine/renew")
772
+ return this.myLink(req, res, path);
645
773
  const list = () => invites.inForce().map(Invites.info);
646
774
  if (path === "/api/share/people" && req.method === "GET")
647
775
  return sendJson(res, { invites: list() });
@@ -671,6 +799,38 @@ export class App {
671
799
  const link = `${this.publicUrl ?? reachedAt(req)}${INVITE_PATH}${made.token}`;
672
800
  return sendJson(res, { invite: Invites.info(made.record), link, invites: list() });
673
801
  }
802
+ /** The personal link a page came by, for its holder alone (CollabSpec decision 9, the owner's
803
+ * decision of 2026-10-19): shown again (POST /api/share/people/mine; `link` null for a link made
804
+ * before 0.6.0, of which the server kept only the digest), or made anew (POST …/mine/renew,
805
+ * `{stream}` the event stream of the page asking, which stays open) — the same id under a new
806
+ * secret, the old link and the browsers it let in cut off, this browser given the new cookie.
807
+ * Whoever else asks is refused: its maker, a guest, an agent; a read-only reader's page posts
808
+ * nothing here (server/readonlygate.ts). Asked for by POST, as an agent's prompt is, so that the
809
+ * browser sends its Origin and the link names the server as the page reached it. */
810
+ async myLink(req, res, path) {
811
+ const p = this.ids.person(req);
812
+ if (!p)
813
+ return sendJson(res, { error: "A personal link is shown to its holder alone, in a browser it let in: this page came by none.", holder: false }, 403);
814
+ if (req.method !== "POST")
815
+ return sendJson(res, { error: `${path} answers POST.` }, 405);
816
+ const invites = this.live.invites;
817
+ const address = this.publicUrl ?? reachedAt(req);
818
+ if (path === "/api/share/people/mine") {
819
+ const token = invites.tokenOf(p.id);
820
+ return sendJson(res, { invite: Invites.info(p), link: token ? `${address}${INVITE_PATH}${token}` : null });
821
+ }
822
+ const r = await this.json(req, 4096);
823
+ if (r.error !== undefined)
824
+ return sendJson(res, { error: `The body is ${r.error}.` }, 400);
825
+ const keep = r.body?.stream;
826
+ const made = invites.renew(p.id, { keep: typeof keep === "string" ? keep : undefined });
827
+ if (!made)
828
+ return sendJson(res, { error: "There is no such personal link in force." }, 404);
829
+ // this browser stays in: the cookie of the new link, beside what the request was given already
830
+ const set = res.getHeader("set-cookie");
831
+ res.setHeader("set-cookie", [...(Array.isArray(set) ? set : set === undefined ? [] : [String(set)]), invites.cookie(made.record)]);
832
+ return sendJson(res, { invite: Invites.info(made.record), link: `${address}${INVITE_PATH}${made.token}` });
833
+ }
674
834
  /** Read-only links (CollabSpec decision 11), for people: every link (GET), a new one (POST), and
675
835
  * revoking one (POST …/revoke). Anyone let in may make one; revoking needs a name, which Share
676
836
  * says beside the link. A server open to all, or behind a sign-in, has none. */
@@ -707,31 +867,43 @@ export class App {
707
867
  /** A personal link opened (CollabSpec decision 9): the browser is given the cookie that lets its
708
868
  * holder in, as who the link says, and goes on to the page — the token leaves the address, and a
709
869
  * place after it (a fragment) comes along. A revoked link says so; anything else is answered as
710
- * any address nobody was given. */
711
- enter(req, res, token) {
870
+ * any address nobody was given. On a server with a key, a browser is shown the page of a link
871
+ * that does not open the site instead (CollabSpec decision 7), which says neither which it was
872
+ * nor who revoked it — unless the key or a link of its own lets it in, and it may be told. */
873
+ enter(req, res, token, path) {
712
874
  const c = this.ids.header ? null : this.live.invites.check(token);
713
875
  if (c && "ok" in c) {
714
876
  res.writeHead(303, { location: "/", "set-cookie": this.live.invites.cookie(c.ok), "cache-control": "no-store", "referrer-policy": "no-referrer" });
715
877
  return void res.end();
716
878
  }
879
+ if (this.access && asksForPage(req, path) && (!c || !this.letIn(req)))
880
+ return sendAccessPage(res, "link", this.publicRead);
717
881
  if (c)
718
- return sendText(req, res, revokedWords(c.record, "personal") + "\n", "text/plain; charset=utf-8", 410);
882
+ return sendText(req, res, endedWords(c) + "\n", "text/plain; charset=utf-8", 410);
719
883
  sendJson(res, { error: "not found" }, 404);
720
884
  }
721
885
  /** A read-only link opened (CollabSpec decision 11): the browser is given the cookie that lets
722
886
  * its holder read, and goes on to the page — the token leaves the address, and a place after it
723
887
  * (a fragment) comes along. A revoked link says so; anything else, and any link on a server
724
- * open to all or behind a sign-in, which have none, is answered as an address nobody was given. */
725
- enterReadOnly(req, res, token) {
888
+ * open to all or behind a sign-in, which have none, is answered as an address nobody was given;
889
+ * to a browser, on a server with a key, as a personal link's (enter). */
890
+ enterReadOnly(req, res, token, path) {
726
891
  const c = this.access && !this.ids.header ? this.live.readOnly.check(token) : null;
727
892
  if (c && "ok" in c) {
728
893
  res.writeHead(303, { location: "/", "set-cookie": this.live.readOnly.cookie(c.ok.id), "cache-control": "no-store", "referrer-policy": "no-referrer" });
729
894
  return void res.end();
730
895
  }
896
+ if (this.access && asksForPage(req, path) && (!c || !this.letIn(req)))
897
+ return sendAccessPage(res, "link", this.publicRead);
731
898
  if (c)
732
899
  return sendText(req, res, revokedWords(c.link, "read-only") + "\n", "text/plain; charset=utf-8", 410);
733
900
  sendJson(res, { error: "not found" }, 404);
734
901
  }
902
+ /** Whether the key's cookie or a personal link in force lets a request in: someone who sees the
903
+ * site's people, and may be told who revoked a link. */
904
+ letIn(req) {
905
+ return !!this.ids.person(req) || this.access?.admit(req, "/") === "in";
906
+ }
735
907
  /** Who the reader is (POST /api/identity {name}): the name someone invited by a personal link goes
736
908
  * by from now on — kept with their link, and said in their review log, so that what they wrote
737
909
  * shows under it — or, for a guest, whether a name is theirs to take: one a link's holder goes
@@ -767,8 +939,10 @@ export class App {
767
939
  }
768
940
  /** A request for a name this server without a key does not answer (CollabSpec decision 12): 403,
769
941
  * saying which option lets the name in; and, once per name, the server's console says it too,
770
- * for whoever runs it behind a proxy that forwards the name people reach it by. */
771
- refuseHost(req, res) {
942
+ * for whoever runs it behind a proxy that forwards the name people reach it by. A browser asking
943
+ * for a page is shown a page that says so (the owner's decision of 2026-10-18), which does not
944
+ * repeat the name: it is the requester's, any text at all. */
945
+ refuseHost(req, res, path) {
772
946
  const raw = req.headers.host ?? "";
773
947
  const name = /^\[/.test(raw) ? raw : raw.replace(/:\d{1,5}$/, "");
774
948
  const shown = /^[A-Za-z0-9._\-[\]:]{1,253}$/.test(name) ? name : null;
@@ -776,6 +950,8 @@ export class App {
776
950
  this.refusedHosts.add(shown.toLowerCase());
777
951
  console.error(`refused a request for ${shown}: without an access key this server answers only its addresses, localhost, --public-url's host and the --allowed-host names; --allowed-host ${shown} lets this one in`);
778
952
  }
953
+ if (asksForPage(req, path))
954
+ return sendAccessPage(res, "host");
779
955
  sendText(req, res, `This server answers only the names it is meant to be reached by${shown ? `, and ${shown} is not one of them` : ""}. Whoever runs it can let a name in with --allowed-host${shown ? ` ${shown}` : " <name>"}.\n`, "text/plain; charset=utf-8", 403);
780
956
  }
781
957
  /** The answer to a request that needs a name and has none: the page asks for one (`who`). Where
@@ -865,7 +1041,11 @@ export class App {
865
1041
  // rebinding) is refused whatever it asks — the page, its data, the event stream, the agents'
866
1042
  // API, the MCP server's file
867
1043
  if (this.hostNames && !hostAllowed(req.headers.host, this.hostNames))
868
- return this.refuseHost(req, res);
1044
+ return this.refuseHost(req, res, path);
1045
+ // what may write, only from a page of this server's own (server/access.ts, fromOwnPage): a page
1046
+ // of another site, or of another port of this host, would send this server's cookies with it
1047
+ if (!fromOwnPage(req.method, req.headers, this.publicUrl))
1048
+ return sendJson(res, { error: "A page of another site cannot change anything here." }, 403);
869
1049
  // every route; whatever one throws, handle() answers
870
1050
  {
871
1051
  // an agent's own token (server/tokens.ts) lets it into its API alone: the page and the page's
@@ -888,13 +1068,19 @@ export class App {
888
1068
  // it says, and its cookie does from then on; a revoked one's cookie is forgotten, and lets
889
1069
  // nobody in
890
1070
  if (path.startsWith(INVITE_PATH))
891
- return this.enter(req, res, path.slice(INVITE_PATH.length));
1071
+ return this.enter(req, res, path.slice(INVITE_PATH.length), path);
892
1072
  // a read-only link (CollabSpec decision 11, server/readonly.ts): its cookie lets its holder
893
1073
  // read, where nothing else lets them in
894
1074
  if (path.startsWith(READONLY_PATH))
895
- return this.enterReadOnly(req, res, path.slice(READONLY_PATH.length));
1075
+ return this.enterReadOnly(req, res, path.slice(READONLY_PATH.length), path);
896
1076
  const link = this.ids.link(req);
897
- const cookies = link && "ended" in link ? [live.invites.forget()] : [];
1077
+ // a link that ended: its cookie is forgotten as a page loads, once the page has said so. Not
1078
+ // before: the page's requests meanwhile are told (a browser the key lets in too, as a guest,
1079
+ // by /api/identity: web/src/people.ts); and the browser that made a link anew has the new
1080
+ // cookie under the same name, which a request of its pages still on its way with the old one
1081
+ // would answer with the forgetting after it
1082
+ const forget = link && "ended" in link && (path === "/" || path === "/index.html" || asksForPage(req, path));
1083
+ const cookies = forget ? [live.invites.forget()] : [];
898
1084
  const ro = this.access && !this.ids.header ? live.readOnly.ofCookie(req.headers.cookie) : null;
899
1085
  if (ro && "ended" in ro)
900
1086
  cookies.push(live.readOnly.forget());
@@ -905,20 +1091,39 @@ export class App {
905
1091
  const reader = ro && "ok" in ro ? ro.ok.id : this.publicRead && !this.ids.header ? "public" : null;
906
1092
  // a page whose link was revoked, which nothing else lets in, is told so (CollabSpec
907
1093
  // decisions 9 and 11): its requests are answered 410 with who revoked it and when, and the
908
- // page, reloaded, says it in words; the cookie is forgotten there, once it has been said
909
- const revoked = reader === null && this.ids.kind(req) !== "agent" ? (link && "ended" in link ? revokedWords(link.record, "personal") : ro && "ended" in ro ? revokedWords(ro.link, "read-only") : null) : null;
1094
+ // page, reloaded, says the link no longer opens the site (decision 7: to a browser, the
1095
+ // page of a link that does not, which names nobody); the cookie is forgotten there, once
1096
+ // it has been said
1097
+ const revoked = reader === null && this.ids.kind(req) !== "agent" ? (link && "ended" in link ? endedWords(link) : ro && "ended" in ro ? revokedWords(ro.link, "read-only") : null) : null;
910
1098
  if (revoked) {
1099
+ if (asksForPage(req, path)) {
1100
+ res.setHeader("set-cookie", cookies);
1101
+ return sendAccessPage(res, "link");
1102
+ }
911
1103
  if (path === "/" || path === "/index.html") {
912
1104
  res.setHeader("set-cookie", cookies);
913
1105
  return sendText(req, res, revoked + "\n", "text/plain; charset=utf-8", 410);
914
1106
  }
915
1107
  return sendJson(res, { error: revoked, revoked: true }, 410);
916
1108
  }
1109
+ // nothing lets them in: a browser asking for a page is told the site is private, or that
1110
+ // its link (`/k/…`, a key replaced) does not open it (CollabSpec decision 7, the owner's
1111
+ // decision of 2026-10-18); anything else is answered as if there were nothing here
917
1112
  if (reader === null || this.ids.kind(req) === "agent") {
918
1113
  if (cookies.length)
919
1114
  res.setHeader("set-cookie", cookies);
1115
+ if (asksForPage(req, path))
1116
+ return sendAccessPage(res, path.startsWith(KEY_PATH) ? "link" : "private");
920
1117
  return sendJson(res, { error: "not found" }, 404);
921
1118
  }
1119
+ // a link of the key's that is not the key, opened where the address, or a read-only link,
1120
+ // lets them read: the page of a link that does not open the site, which says whether the
1121
+ // address alone does (--public)
1122
+ if (path.startsWith(KEY_PATH) && asksForPage(req, path)) {
1123
+ if (cookies.length)
1124
+ res.setHeader("set-cookie", cookies);
1125
+ return sendAccessPage(res, "link", this.publicRead);
1126
+ }
922
1127
  this.readOnlyOf.set(req, reader);
923
1128
  // the page renews a read-only link's cookie, as a personal link's
924
1129
  if (reader !== "public" && (path === "/" || path === "/index.html"))
@@ -981,11 +1186,19 @@ export class App {
981
1186
  return pdfjsAsset(res, path);
982
1187
  // with Lean's language server as it is (server/hover.ts): what is open, what crashed
983
1188
  // a read-only reader is told how the server is, not its log nor where its review is kept
1189
+ // `?brief`: the build status without its files, which the page reads by GET /api/build
984
1190
  if (path === "/api/status") {
985
- const st = { ...live.status(), lean: this.hover.state() };
1191
+ const st = { ...live.status(url.searchParams.has("brief")), lean: this.hover.state() };
1192
+ // the address people reach the server at (--public-url): links of it are this site's, and the
1193
+ // page makes its own with it (CollabSpec, "Copied links")
1194
+ if (this.publicUrl)
1195
+ st.publicUrl = this.publicUrl;
986
1196
  if (this.readOnlyOf.get(req) !== undefined) {
987
1197
  delete st.log;
988
1198
  st.review = { ...st.review, folder: undefined };
1199
+ // a branch's build log is not a read-only reader's (DeploySpec decision 11)
1200
+ if (st.deploy)
1201
+ st.deploy = slimDeploy(st.deploy);
989
1202
  }
990
1203
  return sendJson(res, st);
991
1204
  }
@@ -1034,7 +1247,7 @@ export class App {
1034
1247
  // name — a private reader's too (CollabSpec decision 8) — with the personal link of someone
1035
1248
  // invited by one, whose moves go to their link's log (decision 9); by an agent at level full
1036
1249
  const person = this.ids.person(req)?.id;
1037
- const a = historyAnswer(live, { method: req.method ?? "GET", path, query: url.searchParams, body, caller: { name: this.ids.who(req), kind: this.ids.kind(req), ...(person ? { person } : {}) } }, (q) => q.caller.kind === "agent" ? refusal(this.agents.level, "full") : null);
1250
+ const a = await historyAnswer(live, { method: req.method ?? "GET", path, query: url.searchParams, body, caller: { name: this.ids.who(req), kind: this.ids.kind(req), ...(person ? { person } : {}) } }, (q) => q.caller.kind === "agent" ? refusal(this.agents.level, "full") : null);
1038
1251
  // a snapshot's graph in parts, as the Time Machine takes it: compressed once, and tagged
1039
1252
  if (a.gz)
1040
1253
  return sendGz(req, res, a.gz.body, a.gz.type);
@@ -1057,9 +1270,15 @@ export class App {
1057
1270
  // an agent may use the page's own endpoints too: the same rules hold there (AgentSpec)
1058
1271
  const agent = this.ids.kind(req) === "agent";
1059
1272
  // the review (ReviewSpec.md): the whole of it, as a page takes it on, with the lines of its
1060
- // logs that cannot be read
1273
+ // logs that cannot be read; tagged with its revision, compressed once a revision
1061
1274
  if (path === "/api/review" && req.method === "GET")
1062
- return sendJsonText(res, live.review.wholeText());
1275
+ return sendRevision(req, res, live.review, live.review.tag(), () => live.review.wholeText());
1276
+ // the whole build status, tagged with its revision (the owner's decision of 2026-10-19): what
1277
+ // changes after comes by the event stream
1278
+ if (path === "/api/build" && req.method === "GET") {
1279
+ const b = live.buildWhole();
1280
+ return sendRevision(req, res, live, b.tag, () => b.text);
1281
+ }
1063
1282
  if (path === "/api/review" && req.method === "POST") {
1064
1283
  // an opinion, a target, a trusted prefix or a key declaration is recorded under the
1065
1284
  // reader's name (CollabSpec decision 3), not one in the body; what it is about is
@@ -1085,11 +1304,11 @@ export class App {
1085
1304
  return this.export(req, res, url, agent, reader !== undefined);
1086
1305
  // who the reader is (CollabSpec decisions 3 and 9): the name their page gives, the proxy's, or
1087
1306
  // their personal link's — with the link, and whether the page's own name is a link holder's
1088
- // and not theirs; a link revoked says by whom
1307
+ // and not theirs; a link revoked says by whom, one made anew since this browser had it, when
1089
1308
  if (path === "/api/identity" && req.method === "GET") {
1090
1309
  const person = this.ids.person(req);
1091
1310
  const holder = this.ids.taken(req);
1092
- const ended = link && "ended" in link ? link.record : null;
1311
+ const ended = link && "ended" in link ? link : null;
1093
1312
  if (reader !== undefined)
1094
1313
  return sendJson(res, { mode: this.ids.mode, name: null, readOnly: { by: reader === "public" ? "public" : "link" } });
1095
1314
  return sendJson(res, {
@@ -1097,7 +1316,8 @@ export class App {
1097
1316
  name: this.ids.who(req),
1098
1317
  ...(person ? { person: Invites.info(person) } : {}),
1099
1318
  ...(holder ? { taken: taken(holder) } : {}),
1100
- ...(ended ? { revoked: { by: ended.revokedBy, at: ended.revoked, name: ended.name } } : {}),
1319
+ ...(ended?.ended === "revoked" ? { revoked: { by: ended.record.revokedBy, at: ended.record.revoked, name: ended.record.name } } : {}),
1320
+ ...(ended?.ended === "replaced" ? { replaced: { at: ended.at, name: ended.record.name } } : {}),
1101
1321
  });
1102
1322
  }
1103
1323
  if (path === "/api/identity" && req.method === "POST")
@@ -1116,13 +1336,14 @@ export class App {
1116
1336
  // agents have no artwork (ExportSpec decision 19): the page draws it
1117
1337
  if (agent && name)
1118
1338
  live.presence.agentBeat(name, withoutArtwork(cleanView(b.view)));
1119
- else if (!live.beat(b.token, priv ? null : name, priv ? null : cleanView(b.view), !priv && b.idle === true, priv, !!this.ids.person(req)))
1339
+ else if (!live.beat(b.token, priv ? null : name, priv ? null : cleanView(b.view), !priv && b.idle === true, priv, !!this.ids.person(req), name))
1120
1340
  return sendJson(res, { error: "This heartbeat is not from an open event stream of this page's: it is sent with the token the stream says hello with.", stream: false }, 403);
1121
1341
  return sendJson(res, { ok: true });
1122
1342
  }
1123
1343
  if (path === "/api/events") {
1124
1344
  const session = url.searchParams.get("session");
1125
- return live.subscribe(res, validSession(session) ? session : null, this.ids.person(req)?.id ?? null, reader ?? null, this.toldAll(req));
1345
+ // `build=delta`: the page takes the build status as changes (a page of 0.6.0 or later)
1346
+ return live.subscribe(res, validSession(session) ? session : null, this.ids.person(req)?.id ?? null, reader ?? null, this.toldAll(req), url.searchParams.get("build") === "delta", this.ids.who(req));
1126
1347
  }
1127
1348
  // what happened (CollabSpec decision 5): what the server stored; the review's own history the
1128
1349
  // page reads from the review
@@ -1149,6 +1370,11 @@ export class App {
1149
1370
  // the project's git source and commit as git says them now, not as the build was read (an
1150
1371
  // artwork's foot, ExportSpec decision 19; the owner's decision of 2026-10-15)
1151
1372
  if (path === "/api/git") {
1373
+ // following a branch, the commit of the build on show, on that branch: what is checked out
1374
+ // meanwhile is the build going on (DeploySpec decision 12)
1375
+ const shown = live.shownCommit();
1376
+ if (shown !== undefined)
1377
+ return sendJson(res, { git: shown && { source: live.deploy.status(false).source, commit: shown.hash, branch: shown.branch } });
1152
1378
  if (!this.gitRead || Date.now() - this.gitRead.at >= this.gitFreshMs)
1153
1379
  this.gitRead = { git: gitSource(live.project.root), at: Date.now() };
1154
1380
  return sendJson(res, { git: this.gitRead.git });
@@ -1272,6 +1498,13 @@ export class App {
1272
1498
  function revokedWords(r, kind) {
1273
1499
  return `This ${kind} link was revoked by ${r.revokedBy} on ${(r.revoked ?? "").slice(0, 10)}. Ask whoever ${kind === "personal" ? "invited you" : "gave it to you"} for a new one.`;
1274
1500
  }
1501
+ /** What a personal link that lets nobody in any more is told (410): revoked, by whom and when, or
1502
+ * made anew by its holder, and when (CollabSpec decision 9). */
1503
+ function endedWords(c) {
1504
+ if (c.ended === "revoked")
1505
+ return revokedWords(c.record, "personal");
1506
+ return `This personal link was made anew on ${c.at.slice(0, 10)}: it lets nobody in any more. Open the new one instead (My personal link, in the menu under your name where it was made anew).`;
1507
+ }
1275
1508
  /** an artwork's font file (assets/webfonts/) */
1276
1509
  const FONT_PATH = /^\/fonts\/(source-sans-3|source-serif-4|jost)-[a-z-]+\.woff2$/;
1277
1510
  const TYPES = {
@@ -1388,7 +1621,7 @@ export function sendJson(res, body, code = 200, headers = {}) {
1388
1621
  return;
1389
1622
  sendJsonText(res, JSON.stringify(body), code, headers);
1390
1623
  }
1391
- /** The same, of an answer written as JSON already (the whole review, server/review.ts). */
1624
+ /** The same, of an answer written as JSON already. */
1392
1625
  function sendJsonText(res, text, code = 200, headers = {}) {
1393
1626
  if (res.headersSent || res.writableEnded || refused.has(res))
1394
1627
  return;
@@ -1403,6 +1636,43 @@ function sendJsonText(res, text, code = 200, headers = {}) {
1403
1636
  res.writeHead(code, { "content-type": "application/json", "cache-control": "no-store", ...headers });
1404
1637
  res.end(text);
1405
1638
  }
1639
+ /** what is sent whole under the tag of its revision, compressed, per what it is of (the review, the
1640
+ * build status) */
1641
+ const revisionGz = new WeakMap();
1642
+ /** A whole sent under the tag of its revision: the review (GET /api/review), tagged with its run and
1643
+ * its revision (server/review.ts), and the build status (GET /api/build, server/live.ts). A page that
1644
+ * has it is answered 304, which a reload is, and one that fell behind is sent it compressed — once a
1645
+ * revision, off the server's thread when it is large, the same bytes for every page (a review of
1646
+ * 5,000 opinions on Sphere-Packing-Lean: 8.5 MB of JSON, 1.1 MB sent; the build status of
1647
+ * NavierStokesAndEuler's 2,657 files: 362 KB, 42 KB sent). `of` is what it is of; `whole` writes it,
1648
+ * asked only where it is sent. */
1649
+ function sendRevision(req, res, of, tag, whole) {
1650
+ if (res.headersSent || res.writableEnded || refused.has(res))
1651
+ return;
1652
+ const head = { "content-type": "application/json", "cache-control": "private, no-cache", etag: tag, vary: "accept-encoding" };
1653
+ if (fresh(req, tag)) {
1654
+ res.writeHead(304, head);
1655
+ return void res.end();
1656
+ }
1657
+ const text = whole();
1658
+ if (text.length <= JSON_GZIP_FROM || !acceptsGzip(req)) {
1659
+ res.writeHead(200, head);
1660
+ return void res.end(text);
1661
+ }
1662
+ let c = revisionGz.get(of);
1663
+ if (c?.tag !== tag) {
1664
+ const gz = text.length < JSON_GZIP_AWAY_FROM ? Promise.resolve(gzipSync(text)) : new Promise((ok, fail) => gzip(text, (e, b) => (e ? fail(e) : ok(b))));
1665
+ revisionGz.set(of, (c = { tag, gz }));
1666
+ // a compression that failed is tried again by the next page that asks
1667
+ gz.catch(() => revisionGz.get(of)?.gz === gz && revisionGz.delete(of));
1668
+ }
1669
+ c.gz.then((gz) => {
1670
+ if (res.headersSent || res.destroyed)
1671
+ return;
1672
+ res.writeHead(200, { ...head, "content-encoding": "gzip" });
1673
+ res.end(gz);
1674
+ }, (e) => res.destroy(e));
1675
+ }
1406
1676
  /** Send a text that is not JSON (the agents' documentation, the MCP server's file), compressed
1407
1677
  * where the client takes it. */
1408
1678
  function sendText(req, res, text, type, code = 200) {
@@ -1449,18 +1719,26 @@ const JSON_GZIP_FROM = 2048;
1449
1719
  export const JSON_GZIP_AWAY_FROM = 1 << 20;
1450
1720
  /** the graph's parts as sent, each tagged once (a graph's buffers live as long as it does) */
1451
1721
  const gzTags = new WeakMap();
1452
- /** A part of the graph, gzipped already: tagged, so that a page that has it gets 304. */
1722
+ /** A part of the graph, gzipped already: tagged, so that a page that has it gets 304; a client that
1723
+ * does not take gzip (an agent's) is sent it as it is, made so off the server's thread. */
1453
1724
  function sendGz(req, res, gz, type) {
1454
1725
  if (refused.has(res))
1455
1726
  return;
1456
1727
  let etag = gzTags.get(gz);
1457
1728
  if (!etag)
1458
1729
  gzTags.set(gz, (etag = tagOf(gz)));
1459
- const head = { "content-type": type, "cache-control": "private, no-cache", etag };
1730
+ const head = { "content-type": type, "cache-control": "private, no-cache", etag, vary: "accept-encoding" };
1460
1731
  if (fresh(req, etag)) {
1461
1732
  res.writeHead(304, head);
1462
1733
  return void res.end();
1463
1734
  }
1735
+ if (!acceptsGzip(req))
1736
+ return void gunzip(gz, (e, plain) => {
1737
+ if (e)
1738
+ return res.destroy(e);
1739
+ res.writeHead(200, head);
1740
+ res.end(plain);
1741
+ });
1464
1742
  res.writeHead(200, { ...head, "content-encoding": "gzip" });
1465
1743
  res.end(gz);
1466
1744
  }
@@ -1489,7 +1767,7 @@ async function main() {
1489
1767
  // an installed package's server runs under the supervisor, which stays while it restarts into
1490
1768
  // another version (UpdateSpec decision 5); `--updates off`, and a checkout, run it as they are
1491
1769
  if (o.cmd === "serve" && FROM_PACKAGE && o.updates !== "off" && process.env.VISUALPROOF_SUPERVISED !== "1") {
1492
- const site = projectDirs(resolve(o.path), o.site, o.cache).site;
1770
+ const site = o.remote ? deploySiteOf(o) : projectDirs(resolve(o.path), o.site, o.cache).site;
1493
1771
  process.exit(await supervise({ installedRoot: PACKAGE_ROOT, cacheRoot: o.cache ? resolve(o.cache) : cacheHome(), argv: process.argv.slice(2), site, mode: o.updates }));
1494
1772
  }
1495
1773
  // a stop asked before the server can stop gracefully (it reads the project, takes the site) ends
@@ -1506,13 +1784,18 @@ async function main() {
1506
1784
  // whatever fails ends it, with status 1)
1507
1785
  if (o.cmd !== "artwork")
1508
1786
  process.on("unhandledRejection", (e) => console.error("unhandled:", e instanceof Error ? e.message : e));
1787
+ // following a branch (DeploySpec): its clone in the cache, made at the first start, is the project
1788
+ const deploy = o.remote ? await openDeployment(o) : null;
1789
+ if (o.remote && !deploy)
1790
+ return;
1509
1791
  let project;
1510
1792
  try {
1511
- project = openProject(o.path, o.roots, o.graph === null);
1793
+ // a branch's clone is read before its build: the server builds it
1794
+ project = openProject(deploy ? deploy.folder.checkout : o.path, o.roots, !deploy && o.graph === null);
1512
1795
  }
1513
1796
  catch (e) {
1514
1797
  if (e instanceof ProjectError) {
1515
- console.error(`visualproof: ${e.message}`);
1798
+ console.error(`visualproof: ${deploy ? `${deploy.branch} of ${deploy.remote.source ?? deploy.remote.url}, at ${shortCommit(deploy.head)}: ` : ""}${e.message}`);
1516
1799
  return endNotTheCode(1);
1517
1800
  }
1518
1801
  throw e;
@@ -1520,7 +1803,8 @@ async function main() {
1520
1803
  // a picture: the site read, never made, locked or written (ExportSpec decision 21)
1521
1804
  if (o.cmd === "artwork")
1522
1805
  return artworkCommand(project, o);
1523
- const dirs = projectDirs(project.root, o.site, o.cache);
1806
+ // a branch's site is the address's and the branch's, wherever the cache is
1807
+ const dirs = { ...projectDirs(project.root, o.site, o.cache), ...(deploy && o.site === null ? { site: deploySite(deploy.remote, deploy.branch) } : {}) };
1524
1808
  openSite(dirs.site);
1525
1809
  mkdirSync(dirs.cache, { recursive: true });
1526
1810
  // one server at a time writes a site; an export only reads it
@@ -1597,6 +1881,31 @@ async function main() {
1597
1881
  live.invites.close();
1598
1882
  live.readOnly.close();
1599
1883
  });
1884
+ // the branch followed: asked every --poll minutes, each new head built in turn (DeploySpec)
1885
+ const deployment = deploy
1886
+ ? new Deployment({
1887
+ remote: deploy.remote,
1888
+ branch: deploy.branch,
1889
+ folder: deploy.folder,
1890
+ project,
1891
+ roots: o.roots,
1892
+ everyMs: (o.poll ?? DEFAULT_POLL_MINUTES) * 60_000,
1893
+ buildMs: (o.buildHours ?? DEFAULT_BUILD_HOURS) * 3600_000,
1894
+ mathlibCache: o.mathlibCache ?? "shared",
1895
+ head: deploy.head,
1896
+ hooks: {
1897
+ reading: () => live.reading,
1898
+ // the usage pass of the build before is cut short: what it finished is kept
1899
+ starting: () => live.usage.cancel(),
1900
+ toolchainChanged: () => hover.toolchainChanged(),
1901
+ // the pages are told at the live loop's next look, within a second
1902
+ changed: () => live.lookSoon(),
1903
+ log: (l) => live.say(l),
1904
+ ended: () => live.reread(),
1905
+ },
1906
+ })
1907
+ : null;
1908
+ live.deploy = deployment;
1600
1909
  const exporter = new Exporter(dirs.cache);
1601
1910
  const app = new App(live, hover, ids, new AgentApi(live, hover, o.agents), key ? new Access(key.key) : null, exporter, o.publicUrl, o.publicRead, o.allowedHosts);
1602
1911
  const server = createServer((req, res) => app.handle(req, res));
@@ -1620,6 +1929,8 @@ async function main() {
1620
1929
  stopping = true;
1621
1930
  exitStatus = status;
1622
1931
  updates.stop();
1932
+ // a build going on is stopped with the programs, and done again at the next start
1933
+ deployment?.stop();
1623
1934
  server.close();
1624
1935
  live.end(why);
1625
1936
  hover.stop();
@@ -1677,13 +1988,75 @@ async function main() {
1677
1988
  console.log(` editor: ${o.editor ?? "no link unless a reader sets one"}`);
1678
1989
  console.log(` agents: ${o.agents} — their API is http://${o.host}:${o.port}/api/agent`);
1679
1990
  console.log(` usage pass: ${o.graph ? "none for a saved graph" : o.jobs > 0 ? `${o.jobs} module(s) at a time` : "off (--jobs 0)"}`);
1991
+ // what the pass's workers may hold on a project on Mathlib, against what the machine has
1992
+ const memory = o.graph || o.jobs <= 0 ? null : jobsAdvice(o.jobs, onMathlib(project.root));
1993
+ if (memory)
1994
+ console.log(` memory: ${inGB(freemem())} available; on Mathlib the pass's workers may hold up to ${inGB(WORKER_PEAK)} each, ${inGB(memory.need)} at ${o.jobs}: ` +
1995
+ `--jobs ${memory.fits} if memory runs short (it starts fewer while less than ${inGB(memoryFloor())} is available)`);
1680
1996
  console.log(` access: ${key ? `by its link only, /k/<the key in ${o.accessKeyFile}>${key.made ? " (a new key was made there)" : ""}${o.publicRead ? "; anyone else read-only (--public)" : ""}` : `anyone who reaches the port, by its address, localhost${[...(o.publicUrl ? [urlHost(o.publicUrl)] : []), ...o.allowedHosts].map((n) => `, ${n}`).join("")} (other names are refused: --allowed-host)`}`);
1681
1997
  console.log(` version: ${version}; updates ${updatesInWords(o.updates, version, supervised)}`);
1998
+ if (deployment) {
1999
+ const d = deployment.status(true);
2000
+ console.log(` following: ${d.branch} of ${d.source ?? deployment.remote.url}, asked every ${o.poll ?? DEFAULT_POLL_MINUTES} min; a build stopped past ${limitInWords(deployment.buildMs)}`);
2001
+ console.log(` clone: ${deployment.folder.checkout}`);
2002
+ // a failed build that wrote nothing is not built (DeploySpec decision 6): before any that did,
2003
+ // none is, and the next is the next commit pushed
2004
+ const next = deployment.toBuild();
2005
+ const l = d.last;
2006
+ const why = l ? (l.error ?? (l.exit === null ? "lake build was stopped" : l.exit !== undefined ? `lake build exited with ${l.exit}` : null)) : null;
2007
+ const none = next
2008
+ ? `none yet: the first, of ${shortCommit(next)}, starts now, and the page says so until it is done`
2009
+ : `none yet: that of ${shortCommit(l?.commit ?? deploy.head)} failed${why ? ` (${why})` : ""}, and the next commit pushed is built`;
2010
+ console.log(` builds: ${d.built ? `the tree holds the build of ${shortCommit(d.built)}${deployment.holds() ? ", cut short: it is done again" : ""}` : none}; their logs in ${deployment.folder.logs}`);
2011
+ // where the project is on Mathlib, its cache: the user's, or the deployment's own (DeploySpec decision 2)
2012
+ console.log(` Mathlib's cache: ${o.mathlibCache === "own" ? `${deployment.folder.mathlib}, the deployment's own` : `${sharedMathlibCache()}, the user's, shared by their builds`}`);
2013
+ }
1682
2014
  recordVersion(live, version, supervised);
1683
2015
  process.send?.({ vp: "listening", version });
1684
2016
  updates.start();
1685
2017
  });
1686
2018
  live.start();
2019
+ deployment?.start();
2020
+ }
2021
+ /** The site a branch's server keeps, as the supervisor finds it (UpdateSpec decision 7): `--site`,
2022
+ * else the address's and the branch's — the default branch as it was last asked, without the network;
2023
+ * null at a first start without --branch, which the server alone resolves. */
2024
+ function deploySiteOf(o) {
2025
+ if (o.site !== null)
2026
+ return resolve(o.site);
2027
+ const branch = o.branch ?? recordedDefault(o.cache ? resolve(o.cache) : cacheHome(), o.remote.url);
2028
+ return branch ? deploySite(o.remote, branch) : null;
2029
+ }
2030
+ /** A branch's deployment as the server starts (DeploySpec decisions 1–2): the branch (the remote's
2031
+ * default where none is given), its folder in the cache taken for this server, its clone made at
2032
+ * the first start. Null where it cannot be had: said, and the server ends, which is not its code. */
2033
+ async function openDeployment(o) {
2034
+ const remote = o.remote;
2035
+ const cacheRoot = o.cache ? resolve(o.cache) : cacheHome();
2036
+ const branch = await branchToFollow(remote, o.branch, cacheRoot);
2037
+ if (typeof branch !== "string") {
2038
+ console.error(`visualproof: ${remote.source ?? remote.url}: ${branch.error}`);
2039
+ endNotTheCode(1);
2040
+ return null;
2041
+ }
2042
+ const folder = deployFolder(cacheRoot, remote, branch);
2043
+ try {
2044
+ process.on("exit", lockDeployment(folder, remote, branch));
2045
+ }
2046
+ catch (e) {
2047
+ if (!(e instanceof DeployBusy))
2048
+ throw e;
2049
+ console.error(`visualproof: ${e.message}`);
2050
+ endNotTheCode(1);
2051
+ return null;
2052
+ }
2053
+ const c = await ensureClone(remote, branch, folder, (l) => console.log(l));
2054
+ if ("error" in c) {
2055
+ console.error(`visualproof: ${c.error}`);
2056
+ endNotTheCode(1);
2057
+ return null;
2058
+ }
2059
+ return { remote, branch, folder, head: c.commit };
1687
2060
  }
1688
2061
  /** What the server does with its releases, for its first lines (UpdateSpec decisions 2–4, 13). */
1689
2062
  function updatesInWords(mode, version, supervised) {