visualproof 0.6.0 → 0.7.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 (60) hide show
  1. package/README.md +2 -2
  2. package/dist/extractor/Extract.lean +13 -3
  3. package/dist/server/agent.js +102 -2879
  4. package/dist/server/agentactivity.js +72 -0
  5. package/dist/server/agentadvice.js +115 -0
  6. package/dist/server/agentdocs.js +1 -1
  7. package/dist/server/agententry.js +180 -0
  8. package/dist/server/agentexport.js +469 -0
  9. package/dist/server/agentfollow.js +384 -0
  10. package/dist/server/agentgraph.js +128 -0
  11. package/dist/server/agentlean.js +144 -0
  12. package/dist/server/agentlibrary.js +1 -1
  13. package/dist/server/agentplaces.js +242 -0
  14. package/dist/server/agentread.js +569 -0
  15. package/dist/server/agenttalk.js +282 -0
  16. package/dist/server/agenttcb.js +378 -0
  17. package/dist/server/agentviews.js +2 -2
  18. package/dist/server/app.js +377 -0
  19. package/dist/server/appaccess.js +127 -0
  20. package/dist/server/appagent.js +110 -0
  21. package/dist/server/appgraph.js +176 -0
  22. package/dist/server/appshare.js +179 -0
  23. package/dist/server/appsite.js +120 -0
  24. package/dist/server/apptalk.js +178 -0
  25. package/dist/server/artcmd.js +1 -1
  26. package/dist/server/events.js +1 -1
  27. package/dist/server/history.js +51 -3
  28. package/dist/server/historyapi.js +34 -2
  29. package/dist/server/hover.js +11 -7
  30. package/dist/server/identity.js +1 -1
  31. package/dist/server/libraryroute.js +3 -3
  32. package/dist/server/live.js +61 -2
  33. package/dist/server/main.js +17 -1746
  34. package/dist/server/options.js +350 -0
  35. package/dist/server/outside.js +311 -0
  36. package/dist/server/pastdoc.js +22 -3
  37. package/dist/server/project.js +28 -4
  38. package/dist/server/send.js +259 -0
  39. package/dist/server/talk.js +13 -7
  40. package/dist/server/tokens.js +3 -3
  41. package/dist/server/view.js +3 -1
  42. package/dist/server/views.js +1 -1
  43. package/dist/shared/artrecipe.js +3 -3
  44. package/dist/shared/collab.js +1 -1
  45. package/dist/shared/comment.js +1 -1
  46. package/dist/shared/doc/build.js +30 -14
  47. package/dist/shared/doc/latex.js +7 -2
  48. package/dist/shared/doc/model.js +4 -2
  49. package/dist/shared/doc/sections.js +21 -4
  50. package/dist/shared/outside.js +16 -0
  51. package/dist/shared/pastgraph.js +11 -2
  52. package/dist/shared/scope.js +1 -1
  53. package/dist/web/bundle/app.js +49580 -49284
  54. package/dist/web/src/selection.js +1 -1
  55. package/dist/web/src/theme.js +1 -1
  56. package/dist/web/src/visitors.js +1 -1
  57. package/docs/agent-api/export.md +8 -5
  58. package/docs/agent-api/history.md +3 -1
  59. package/docs/agent-api/reading.md +8 -2
  60. package/package.json +1 -1
@@ -0,0 +1,569 @@
1
+ // Reading declarations (docs/agent-api/reading.md), the endpoints of server/agent.ts an agent reads
2
+ // the project by: the search; a declaration, or several at once, with the answers of the other
3
+ // endpoints for it (`include`); its source as compiled, or at a past build; the context it is written
4
+ // in; what it uses and what uses it; a module of the project, with its doc comments. Only the files
5
+ // the graph was read from are read.
6
+ import { contextText, readContext } from "../shared/context.js";
7
+ import { compiledExcerpt, excerptOf } from "../shared/excerpt.js";
8
+ import { tokenizeLean } from "../shared/lexer.js";
9
+ import { SITE_BODY, SITE_GRAMMAR, SITE_PROOF, SITE_STMT } from "../shared/graph.js";
10
+ import { advice, current, keyFor, STANDARD_AXIOMS, statusOf } from "../shared/review.js";
11
+ import { contextAt, namespacesOf } from "../shared/scope.js";
12
+ import { PLACES, search, snippet } from "../shared/search.js";
13
+ import { ALL_SITES } from "../shared/viewgraph.js";
14
+ import { View } from "./agentgraph.js";
15
+ import { MAX_WAIT, describeOf, leanHome, printOf } from "./agentlean.js";
16
+ import { pastOutside } from "./historyapi.js";
17
+ import { clampInt, fail, flag, ok } from "./agent.js";
18
+ /** A module of the project (AgentSpec, after the trial of decision 7): its file's doc comments
19
+ * (`/-! … -/`, where a project keeps the reasons behind its definitions) and every declaration
20
+ * in it in the order of the file, so that what sits beside a declaration — a variant, a weaker
21
+ * form — can be found without reading the file. */
22
+ export function moduleGet(api, a) {
23
+ const v = api.graph();
24
+ if (!(v instanceof View))
25
+ return v;
26
+ let name = (a.query.get("name") ?? "").trim();
27
+ const of = a.query.get("of");
28
+ if (!name && of) {
29
+ const i = api.find(v, of, "of");
30
+ if (typeof i !== "number")
31
+ return i;
32
+ name = v.g.nodes[i].module;
33
+ }
34
+ if (!name)
35
+ return fail(400, "name is missing.", "Give name=<a module of the project> (a declaration's module, as GET declaration says it), or of=<a declaration>.");
36
+ const m = v.modules.get(name);
37
+ if (!m) {
38
+ const last = name.split(".").pop().toLowerCase();
39
+ const near = [...v.modules.keys()].filter((x) => x.toLowerCase().split(".").pop() === last || x.toLowerCase() === name.toLowerCase()).slice(0, 5);
40
+ return fail(404, `${name} is not a module of the project's graph.`, near.length ? `Did you mean ${near[0]}?` : "A declaration's answer gives its module (GET /api/agent/declaration?name=…).", { didYouMean: near });
41
+ }
42
+ const g = v.g;
43
+ const decls = [];
44
+ for (let i = 0; i < g.projectCount; i++)
45
+ if (g.nodes[i].module === name)
46
+ decls.push({ i, line: g.nodes[i].range?.[0] ?? Infinity });
47
+ decls.sort((x, y) => x.line - y.line || (g.nodes[x.i].name < g.nodes[y.i].name ? -1 : 1));
48
+ const f = api.file(v, name);
49
+ const docs = [];
50
+ let docChars = 0, cut = false;
51
+ if (f) {
52
+ const text = f.lines.join("\n");
53
+ const starts = [0];
54
+ for (let k = 0; k < text.length; k++)
55
+ if (text[k] === "\n")
56
+ starts.push(k + 1);
57
+ const lineOf = (at) => {
58
+ let lo = 0, hi = starts.length - 1;
59
+ while (lo < hi) {
60
+ const mid = (lo + hi + 1) >> 1;
61
+ if (starts[mid] <= at)
62
+ lo = mid;
63
+ else
64
+ hi = mid - 1;
65
+ }
66
+ return lo + 1;
67
+ };
68
+ for (const t of tokenizeLean(text)) {
69
+ if (t.kind !== "doc" || !t.text.startsWith("/-!"))
70
+ continue;
71
+ const body = t.text.replace(/^\/-!/, "").replace(/-\/$/, "").replace(/^[ \t]*\n?/, "").trimEnd();
72
+ if (docChars + body.length > MAX_MODULE_DOCS) {
73
+ cut = true;
74
+ break;
75
+ }
76
+ docChars += body.length;
77
+ docs.push({ line: lineOf(t.at), endLine: lineOf(t.at + t.text.length - 1), text: body });
78
+ }
79
+ }
80
+ return ok({
81
+ name,
82
+ file: m.file,
83
+ ...(f ? { compiled: !f.edited, ...(f.edited ? { note: "The file changed since it was compiled: its doc comments are read from the present text, its declarations are the compiled ones." } : {}) } : {}),
84
+ imports: m.imports,
85
+ importedBy: [...v.modules].filter(([, x]) => x.imports.includes(name)).map(([k]) => k).sort(),
86
+ docs,
87
+ ...(cut ? { docsCut: `Doc comments past ${MAX_MODULE_DOCS.toLocaleString("en")} characters are left out; GET /api/agent/source of a declaration further down shows its text.` } : {}),
88
+ count: decls.length,
89
+ declarations: decls.map(({ i }) => {
90
+ const n = g.nodes[i];
91
+ return { name: n.name, kind: n.kind, line: n.range?.[0] ?? null, ...(n.display ? { display: n.display } : {}), ...(g.isGrammar(i) ? { grammar: true } : {}), ...(n.also?.length ? { also: n.also.length } : {}) };
92
+ }),
93
+ });
94
+ }
95
+ export function searchGet(api, a) {
96
+ const v = api.graph();
97
+ if (!(v instanceof View))
98
+ return v;
99
+ const q = (a.query.get("q") ?? "").trim();
100
+ if (q.length < 2)
101
+ return fail(400, "q is missing or shorter than two characters.", "GET /api/agent/search?q=<words>: every word must be found in the name, the statement or the docstring.");
102
+ const limit = clampInt(a.query.get("limit"), 20, 1, 200);
103
+ const f = search(v.index, q);
104
+ const hits = PLACES.flatMap((w) => f.hits[w]);
105
+ return ok({
106
+ query: q,
107
+ counts: { name: f.hits.name.length, statement: f.hits.statement.length, doc: f.hits.doc.length },
108
+ hits: hits.slice(0, limit).map((h) => {
109
+ const p = h.where === "statement" ? 1 : h.where === "doc" ? 2 : null;
110
+ const s = p === null ? null : snippet(v.index.text[p][h.i], v.index.lower[p][h.i], f.words, h.word, 160, 50);
111
+ return {
112
+ ...api.brief(v, h.i),
113
+ where: h.where,
114
+ // found by a name Lean generated from its command, folded into it
115
+ ...(h.via !== undefined ? { via: h.via } : {}),
116
+ ...(s ? { snippet: (s.before ? "…" : "") + s.pieces.map((x) => x.text).join("") + (s.after ? "…" : "") } : {}),
117
+ };
118
+ }),
119
+ more: Math.max(0, hits.length - limit),
120
+ });
121
+ }
122
+ export async function declaration(api, a) {
123
+ // several at once: as GET declarations answers them
124
+ if (a.query.has("names"))
125
+ return declarations(api, a);
126
+ const v = api.graph();
127
+ if (!(v instanceof View))
128
+ return v;
129
+ const include = parts(a.query.get("include"));
130
+ if (!Array.isArray(include))
131
+ return include;
132
+ const i = api.find(v, a.query.get("name"));
133
+ if (typeof i !== "number")
134
+ return i;
135
+ return ok({ ...(await withParts(api, v, i, a, include, Date.now() + clampInt(a.query.get("wait"), 20_000, 1000, MAX_WAIT))), ...api.folded(v, a.query.get("name"), i) });
136
+ }
137
+ /** Several declarations at once, each answered as GET declaration would (with the same
138
+ * `include`); a name that is not there is answered on its own and does not refuse the others. */
139
+ export async function declarations(api, a) {
140
+ const v = api.graph();
141
+ if (!(v instanceof View))
142
+ return v;
143
+ const include = parts(a.query.get("include"));
144
+ if (!Array.isArray(include))
145
+ return include;
146
+ const names = [...new Set(a.query.getAll("names").flatMap(splitNames))];
147
+ if (!names.length)
148
+ return fail(400, "names is missing.", `Give names=<full name>,<full name>,… (at most ${MAX_NAMES}).`);
149
+ if (names.length > MAX_NAMES)
150
+ return fail(400, `${names.length} names: at most ${MAX_NAMES} are read at once.`, "Ask again for the rest.");
151
+ // Lean's parts share the request's wait: one name's slow answer leaves less for the next
152
+ const deadline = Date.now() + clampInt(a.query.get("wait"), 20_000, 1000, MAX_WAIT);
153
+ const out = [];
154
+ for (const name of names) {
155
+ const i = api.find(v, name);
156
+ out.push(typeof i === "number" ? { ...(await withParts(api, v, i, a, include, deadline)), ...api.folded(v, name, i) } : { name, status: i.status, ...i.body });
157
+ }
158
+ return ok({ count: names.length, found: out.filter((x) => x.status === undefined).length, declarations: out });
159
+ }
160
+ /** A declaration's answer with the parts asked for, each what its own endpoint answers — or, where
161
+ * that part could not be answered, its error with its `status`, listed in `failed`. */
162
+ async function withParts(api, v, i, a, include, deadline) {
163
+ const out = declarationOf(api, v, i, a.caller);
164
+ const failed = {};
165
+ const own = leanHome(api, v, v.g.nodes[i].leanName ?? v.g.nodes[i].name, i, "its own");
166
+ for (const p of include) {
167
+ const left = deadline - Date.now();
168
+ // Lean's parts wait for what is left of the request's wait
169
+ const r = p === "source" ? sourceOf(api, v, i)
170
+ : p === "context" ? contextOf(api, v, i)
171
+ : p === "uses" || p === "users" ? refs(api, v, i, p, a.query)
172
+ : !("module" in own) ? own
173
+ : left < 500 ? fail(503, "Not asked: the request's wait ran out.", "Ask for this part again.", { retryAfter: 1 })
174
+ : p === "describe" ? await describeOf(api, v, own, left)
175
+ : await printOf(api, v, own, flag(a.query.get("proofs")), left);
176
+ if (r.status === 200)
177
+ out[p] = r.body;
178
+ else {
179
+ out[p] = { status: r.status, ...r.body };
180
+ failed[p] = r.status;
181
+ }
182
+ }
183
+ if (Object.keys(failed).length)
184
+ out.failed = failed;
185
+ return out;
186
+ }
187
+ /** Everything about one declaration, as GET declaration answers it without parts. */
188
+ function declarationOf(api, v, i, me) {
189
+ const g = v.g;
190
+ const n = g.nodes[i];
191
+ const d = api.world.review.data;
192
+ const ext = g.isExt(i);
193
+ const axioms = g.axiomsOf(i);
194
+ const t = api.trust(v, i);
195
+ const targets = Object.keys(d.targets)
196
+ .sort()
197
+ .filter((x) => {
198
+ const r = g.byName.get(x);
199
+ return r !== undefined && v.tcb(r)[i] === 1;
200
+ });
201
+ const users = new Set();
202
+ for (let e = g.inStart[i]; e < g.inStart[i + 1]; e++)
203
+ if (g.inSrc[e] !== i)
204
+ users.add(g.inSrc[e]);
205
+ const uses = new Set();
206
+ for (let e = g.outStart[i]; e < g.outStart[i + 1]; e++)
207
+ if (g.outDst[e] !== i)
208
+ uses.add(g.outDst[e]);
209
+ const all = g.reach([i], ALL_SITES, "in").reduce((s, x) => s + x, 0) - 1;
210
+ const tcb = v.tcb(i);
211
+ let tcbOwn = 0, tcbExt = 0;
212
+ for (let j = 0; j < g.n; j++)
213
+ if (tcb[j] && j !== i)
214
+ g.isExt(j) ? tcbExt++ : tcbOwn++;
215
+ const file = ext ? null : v.modules.get(n.module)?.file ?? null;
216
+ const f = ext ? null : api.file(v, n.module);
217
+ return {
218
+ name: n.name,
219
+ kind: n.kind,
220
+ module: n.module,
221
+ external: ext,
222
+ file,
223
+ range: n.range ? { line: n.range[0], col: n.range[1], endLine: n.range[2], endCol: n.range[3] } : null,
224
+ statement: n.type ?? null,
225
+ doc: n.doc ?? null,
226
+ // what Lean generated from the command that writes it, folded into it: one unit, whose
227
+ // references, axioms and hash are theirs too
228
+ also: n.also ?? [],
229
+ // a notation unit: the Lean constant it is made of (for #print and hovers), what the page calls
230
+ // it, whether it only declares grammar (and is in no TCB), what it interprets or what
231
+ // interprets it
232
+ ...(n.leanName ? { leanName: n.leanName } : {}),
233
+ ...(n.display ? { display: n.display } : {}),
234
+ ...(v.g.isGrammar(i) ? { grammar: true, interpretedBy: n.rules ?? [] } : {}),
235
+ ...(n.interprets?.length ? { interprets: n.interprets } : {}),
236
+ flags: n.flags ?? [],
237
+ axioms,
238
+ nonStandardAxioms: axioms.filter((x) => !STANDARD_AXIOMS.includes(x)),
239
+ hash: n.hash ?? null,
240
+ // the kernel's own content hash, names included, which a rename changes (server/versions.ts)
241
+ ...(n.kernel ? { kernel: n.kernel } : {}),
242
+ // the file is not what was compiled: the graph, and an opinion's hash, are about the compiled text
243
+ editedSinceCompiled: f ? f.edited : null,
244
+ review: {
245
+ status: statusOf(d, n.name, n.hash),
246
+ trusted: t.trusted,
247
+ trustedBy: t.trustedBy,
248
+ needsReview: !t.trusted,
249
+ opinions: current(d, n.name).map((o) => api.opinion(o, n.hash, me)),
250
+ advice: advice(d, n.name).map((o) => api.opinion(o, n.hash, me)),
251
+ youAdvised: api.advised(v, i, me),
252
+ },
253
+ isTarget: !!d.targets[n.name],
254
+ // the targets it is marked key for (ExportSpec decision 1)
255
+ keyFor: keyFor(d, n.name),
256
+ inTcbOf: targets,
257
+ tcbSize: { project: tcbOwn, external: tcbExt },
258
+ // how many it refers to by name (GET uses lists them); `uses` is the name of that part
259
+ usesDirect: uses.size,
260
+ usedBy: { direct: users.size, all },
261
+ };
262
+ }
263
+ export function source(api, a) {
264
+ // a past build's text (HistorySpec decision 23), which needs no graph on show
265
+ const snap = a.query.get("snapshot");
266
+ if (snap !== null && snap !== "")
267
+ return pastSource(api, a.query.get("name"), snap);
268
+ const v = api.graph();
269
+ if (!(v instanceof View))
270
+ return v;
271
+ const i = api.find(v, a.query.get("name"));
272
+ if (typeof i !== "number")
273
+ return i;
274
+ const r = sourceOf(api, v, i);
275
+ return r.status === 200 ? ok({ ...r.body, ...api.folded(v, a.query.get("name"), i) }) : r;
276
+ }
277
+ function sourceOf(api, v, i) {
278
+ const n = v.g.nodes[i];
279
+ // outside the project, its package's file (the owner's decision of 2026-10-20)
280
+ const ext = v.g.isExt(i);
281
+ if (!n.range)
282
+ return fail(404, `The graph records no place for ${n.name} in its file.`, "GET /api/agent/declaration gives its statement; /api/agent/print what Lean elaborated.");
283
+ const f = ext ? api.outsideText(n.module) : api.file(v, n.module);
284
+ if (!f && ext)
285
+ return fail(404, `${n.name} is outside the project (${n.module}), and its file is not found here.`, `Ask Lean about it: GET /api/agent/describe or /api/agent/print?name=${encodeURIComponent(n.name)}.`);
286
+ if (!f)
287
+ return fail(404, `The file of ${n.module} cannot be read.`, "GET /api/agent/declaration gives its statement.");
288
+ const out = f.outside ?? null;
289
+ const at = excerptOf(f.lines, f.edited, n.name, n.range);
290
+ if (!at && out)
291
+ return fail(404, `${n.name} is no longer in ${f.rel}: ${out.package} is at another revision than the graph was read at.`, `Ask Lean about it: GET /api/agent/describe?name=${encodeURIComponent(n.name)}.`);
292
+ if (!at)
293
+ return fail(404, `${n.name} is no longer in ${f.rel}: the file changed since it was compiled.`, "Wait for the build; GET /api/agent/declaration gives the compiled statement.");
294
+ return ok({
295
+ name: n.name,
296
+ module: n.module,
297
+ file: f.rel,
298
+ ...(out ? { outside: out } : {}),
299
+ compiled: !f.edited,
300
+ ...(n.gen !== undefined
301
+ ? { generatedNote: `Lean generated ${n.name} from a command, and no declaration that command writes was found to fold it into: it is not written in the source, and this is the command's text. GET /api/agent/print gives what Lean made of it.` }
302
+ : {}),
303
+ ...(n.also?.length
304
+ ? { also: n.also, alsoNote: `Lean generated these from the same command; they are part of ${n.name}'s unit, and its hash covers them. GET /api/agent/print?name=<one of them> shows what Lean made.` }
305
+ : {}),
306
+ ...(f.edited && out
307
+ ? { note: `${out.package} is at another revision than the graph was read at: this is its present text, found by name.` }
308
+ : f.edited
309
+ ? { note: "The file changed since it was compiled: this is the present text, found by name. The graph and the content hash are about the compiled text, so advice on it waits until the file is compiled again." }
310
+ : {}),
311
+ // what is in force where it is written, as Lean (shared/context.ts): advice records it with
312
+ // the text, a blank line between them
313
+ context: contextText(readContext(f.lines, at.start, out ? null : api.exact(n.module, n.name, f))),
314
+ text: f.lines.slice(at.start, at.end + 1).join("\n"),
315
+ });
316
+ }
317
+ /** Declaration `name`'s source at the build of snapshot `raw` (HistorySpec decision 23): found in
318
+ * that build's graph by its name then, by its name now through the renames since, or as a name
319
+ * Lean generated from a command; read from the text its module's build was compiled from, the
320
+ * context it is written in read from that text. A text not kept is said so, never stood in for
321
+ * by another. */
322
+ function pastSource(api, name, raw) {
323
+ const h = api.world.history;
324
+ if (!h)
325
+ return fail(404, "This server keeps no history: it serves a saved graph.", "Leave snapshot out for the source as it was compiled last.");
326
+ const id = Number(raw);
327
+ const s = Number.isInteger(id) ? h.get(id) : null;
328
+ if (!s)
329
+ return fail(404, `There is no snapshot ${raw.slice(0, 40)}.`, "GET /api/agent/history lists them.");
330
+ const want = name?.trim();
331
+ if (!want)
332
+ return fail(400, "name is missing.", "Give name=<a declaration's full name> and snapshot=<a snapshot's id>.");
333
+ const g = h.graph(id);
334
+ const own = (k) => k < g.projectCount;
335
+ let i = g.nodes.findIndex((n, k) => own(k) && n.name === want);
336
+ if (i < 0) {
337
+ // renamed since: its name then
338
+ const latest = h.latest();
339
+ for (const [then, now] of latest ? api.world.renamesBetween?.(id, latest.id) ?? [] : [])
340
+ if (now === want)
341
+ i = g.nodes.findIndex((n, k) => own(k) && n.name === then);
342
+ }
343
+ if (i < 0)
344
+ i = g.nodes.findIndex((n, k) => own(k) && !!n.also?.includes(want));
345
+ const build = { id, at: s.at, commit: s.commit };
346
+ // outside the project, nothing is kept per build (HistorySpec decision 24)
347
+ const e = i < 0 ? g.nodes.findIndex((n, k) => !own(k) && n.name === want) : -1;
348
+ if (e >= 0)
349
+ return pastOutsideSource(api, s, g.nodes[e], build);
350
+ if (i < 0) {
351
+ return fail(404, `There is no declaration ${want} in the graph of snapshot ${id}.`, `GET /api/agent/history/last?name=${encodeURIComponent(want)} finds the newest build that had it.`, { snapshot: build });
352
+ }
353
+ const n = g.nodes[i];
354
+ const renamed = n.name !== want ? { asked: want } : {};
355
+ if (!n.range)
356
+ return fail(404, `Snapshot ${id} records no place for ${n.name} in its file.`, `GET /api/agent/history/graph?id=${id} gives its statement then.`, { snapshot: build });
357
+ const t = h.textOf(id, n.module);
358
+ if (!t || t.text === null) {
359
+ const why = t?.ref.why ?? (h.sourcesOf(id) === null ? "the texts of that build are still being looked for" : "its module has no file of the project");
360
+ return fail(404, `The source of ${n.name} at snapshot ${id} is not kept: ${why}.`, `Its statement and doc then are below; GET /api/agent/history/graph?id=${id} gives the whole graph then.`, {
361
+ kept: false,
362
+ name: n.name,
363
+ ...renamed,
364
+ module: n.module,
365
+ snapshot: build,
366
+ statement: n.type,
367
+ ...(n.doc ? { doc: n.doc } : {}),
368
+ });
369
+ }
370
+ const lines = t.text.split("\n");
371
+ const at = compiledExcerpt(lines, n.range);
372
+ return ok({
373
+ name: n.name,
374
+ ...renamed,
375
+ module: n.module,
376
+ file: t.ref.file,
377
+ snapshot: build,
378
+ compiled: true,
379
+ check: t.ref.check,
380
+ note: t.ref.check === "places"
381
+ ? "The text this build was compiled from, matched by the places the build recorded — its imports, where each declaration starts and ends, its doc comments and names — since its Lake hash was not kept (a build from before the history kept texts). A past build is not reviewed: advice is given on the latest build."
382
+ : "The text this build was compiled from: its Lake hash is the one the build recorded. A past build is not reviewed: advice is given on the latest build.",
383
+ line: at.start + 1,
384
+ endLine: at.end + 1,
385
+ context: contextText(readContext(lines, at.start, null)),
386
+ text: lines.slice(at.start, at.end + 1).join("\n"),
387
+ });
388
+ }
389
+ /** Outside declaration `n`'s source at snapshot `s`'s build (HistorySpec decision 24): its
390
+ * package's file as it is now, where the package is at the revision that build had (Lean's core:
391
+ * the same toolchain), at the place the build recorded — the place now, where a snapshot read
392
+ * before 0.7.0 recorded none; else that build's outside source was not kept. */
393
+ function pastOutsideSource(api, s, n, build) {
394
+ const w = api.world;
395
+ const r = w.outsideNow ? pastOutside(s, n.module, (m) => w.outsideNow(m)) : null;
396
+ if (!r || r.status !== 200) {
397
+ const why = r?.body?.why ?? "outside sources are not kept per build";
398
+ return fail(404, `The source of ${n.name} at snapshot ${build.id} was not kept: ${why}.`, `Ask Lean about it as it is now: GET /api/agent/describe?name=${encodeURIComponent(n.name)}.`, { kept: false, outside: true, name: n.name, module: n.module, snapshot: build });
399
+ }
400
+ const body = r.body;
401
+ const now = api.graph();
402
+ const j = now instanceof View ? now.g.byName.get(n.name) : undefined;
403
+ const range = n.range ?? (now instanceof View && j !== undefined && now.g.isExt(j) ? now.g.nodes[j].range : undefined);
404
+ if (!range)
405
+ return fail(404, `Snapshot ${build.id} records no place for ${n.name} in its file.`, `GET /api/agent/history/graph?id=${build.id} gives the graph then.`, { snapshot: build });
406
+ const lines = body.text.split("\n");
407
+ const at = compiledExcerpt(lines, range);
408
+ return ok({
409
+ name: n.name,
410
+ module: n.module,
411
+ file: body.file,
412
+ outside: body.outside,
413
+ snapshot: build,
414
+ compiled: true,
415
+ check: "rev",
416
+ note: `Outside sources are not kept per build: this is ${body.outside.package} as it is now, at the same revision as at that build. A past build is not reviewed: advice is given on the latest build.`,
417
+ line: at.start + 1,
418
+ endLine: at.end + 1,
419
+ context: contextText(readContext(lines, at.start, null)),
420
+ text: lines.slice(at.start, at.end + 1).join("\n"),
421
+ });
422
+ }
423
+ export function context(api, a) {
424
+ const v = api.graph();
425
+ if (!(v instanceof View))
426
+ return v;
427
+ const i = api.find(v, a.query.get("name"));
428
+ if (typeof i !== "number")
429
+ return i;
430
+ const r = contextOf(api, v, i);
431
+ return r.status === 200 ? ok({ ...r.body, ...api.folded(v, a.query.get("name"), i) }) : r;
432
+ }
433
+ /** What is in force where a declaration is written, read from its file up to its text: the
434
+ * namespaces and sections around it, opens, variables, universes, options, local commands. */
435
+ function contextOf(api, v, i) {
436
+ const n = v.g.nodes[i];
437
+ // outside the project, read from its package's file, never elaborated
438
+ const ext = v.g.isExt(i);
439
+ if (!n.range)
440
+ return fail(404, `The graph records no place for ${n.name} in its file.`, "GET /api/agent/print shows what Lean elaborated, every name in full.");
441
+ const f = ext ? api.outsideText(n.module) : api.file(v, n.module);
442
+ if (!f && ext)
443
+ return fail(404, `${n.name} is outside the project (${n.module}), and its file is not found here.`, `Ask Lean about it: GET /api/agent/print?name=${encodeURIComponent(n.name)}.`);
444
+ if (!f)
445
+ return fail(404, `The file of ${n.module} cannot be read.`, "GET /api/agent/print shows what Lean elaborated, every name in full.");
446
+ const at = excerptOf(f.lines, f.edited, n.name, n.range);
447
+ if (!at)
448
+ return fail(404, `${n.name} is no longer in ${f.rel}: ${ext ? "its package is at another revision than the graph was read at" : "the file changed since it was compiled"}.`, "Wait for the build; GET /api/agent/declaration gives the compiled statement.");
449
+ const spaces = namespacesOf(v.g);
450
+ const exact = ext ? null : api.exact(n.module, n.name, f);
451
+ return ok({
452
+ name: n.name,
453
+ module: n.module,
454
+ file: f.rel,
455
+ ...(f.outside ? { outside: f.outside } : {}),
456
+ compiled: !f.edited,
457
+ ...(f.edited ? { note: "The file changed since it was compiled: this is read from the present text, up to where the declaration is found by name now." } : {}),
458
+ line: at.start + 1,
459
+ imports: v.modules.get(n.module)?.imports ?? [],
460
+ // the elaborator's scope where the usage pass read it (opens resolved, variables Lean included
461
+ // marked used), else the file's text read up to the declaration
462
+ precision: exact ? "elaborated" : "text",
463
+ ...(exact ?? contextAt(f.lines, at.start, (x) => spaces.has(x))),
464
+ });
465
+ }
466
+ export function refsGet(api, a, dir) {
467
+ const v = api.graph();
468
+ if (!(v instanceof View))
469
+ return v;
470
+ const i = api.find(v, a.query.get("name"));
471
+ if (typeof i !== "number")
472
+ return i;
473
+ const r = refs(api, v, i, dir, a.query);
474
+ return r.status === 200 ? ok({ ...r.body, ...api.folded(v, a.query.get("name"), i) }) : r;
475
+ }
476
+ /** What a declaration refers to by name (`uses`), or what refers to it (`users`), with where each
477
+ * reference sits — in the statement, a definition's body, a proof (of the declaration that makes
478
+ * it) — and whether what it names is trusted. Statement first, then body, then proof; the
479
+ * project before the outside world; then by name. Paged. */
480
+ function refs(api, v, i, dir, q) {
481
+ const g = v.g;
482
+ const where = q.get("where");
483
+ const only = where === null || where === "" ? 0 : WHERE[where];
484
+ if (only === undefined)
485
+ return fail(400, `where is statement, body, proof or grammar, not ${where}.`, "Leave it out for every reference.");
486
+ const start = dir === "uses" ? g.outStart : g.inStart;
487
+ const adj = dir === "uses" ? g.outDst : g.inSrc;
488
+ const site = dir === "uses" ? g.outSite : g.inSite;
489
+ // a declaration may refer to another from several places: one row, every place
490
+ const sites = new Map();
491
+ for (let e = start[i]; e < start[i + 1]; e++)
492
+ if (adj[e] !== i)
493
+ sites.set(adj[e], (sites.get(adj[e]) ?? 0) | site[e]);
494
+ const counts = { total: sites.size, statement: 0, body: 0, proof: 0, project: 0, external: 0, trusted: 0 };
495
+ const rows = [];
496
+ for (const [j, s] of sites) {
497
+ const t = api.trust(v, j);
498
+ if (s & SITE_STMT)
499
+ counts.statement++;
500
+ if (s & SITE_BODY)
501
+ counts.body++;
502
+ if (s & SITE_PROOF)
503
+ counts.proof++;
504
+ g.isExt(j) ? counts.external++ : counts.project++;
505
+ if (t.trusted)
506
+ counts.trusted++;
507
+ if (!only || s & only)
508
+ rows.push({ j, s, first: s & SITE_STMT ? 0 : s & SITE_BODY ? 1 : 2, ...t });
509
+ }
510
+ rows.sort((x, y) => x.first - y.first || Number(g.isExt(x.j)) - Number(g.isExt(y.j)) || (g.nodes[x.j].name < g.nodes[y.j].name ? -1 : 1));
511
+ const offset = clampInt(q.get("offset"), 0, 0, Number.MAX_SAFE_INTEGER);
512
+ const limit = clampInt(q.get("limit"), 100, 1, 1000);
513
+ return ok({
514
+ name: g.nodes[i].name,
515
+ direction: dir,
516
+ note: (dir === "uses" ? `What ${g.nodes[i].name} refers to by name; where: the parts of it each reference sits in.` : `What refers to ${g.nodes[i].name} by name; where: the parts of each of them the reference sits in.`) +
517
+ " A reference to a constructor, field, matcher or other generated constant is one to the declaration that owns it." +
518
+ " The notation a text is written in is listed too, as units of kind notation: the rule that ran, where it is used, and the syntax, at the grammar site (grammar: true), which no TCB holds.",
519
+ counts,
520
+ ...(only ? { where } : {}),
521
+ offset,
522
+ limit,
523
+ total: rows.length,
524
+ next: offset + limit < rows.length ? offset + limit : null,
525
+ refs: rows.slice(offset, offset + limit).map((r) => ({
526
+ ...api.brief(v, r.j),
527
+ where: Object.keys(WHERE).filter((w) => r.s & WHERE[w]),
528
+ trusted: r.trusted,
529
+ ...(r.trusted ? { trustedBy: r.trustedBy } : {}),
530
+ })),
531
+ });
532
+ }
533
+ /** the most of a module's doc comments one answer carries, in UTF-16 units */
534
+ const MAX_MODULE_DOCS = 60_000;
535
+ /** the most declarations one request reads, and the most advice one request gives */
536
+ export const MAX_NAMES = 25;
537
+ /** what a declaration's answer can carry besides itself, each what its own endpoint answers */
538
+ export const PARTS = ["source", "context", "uses", "users", "describe", "print"];
539
+ /** where a reference sits, by its site bit */
540
+ const WHERE = { statement: SITE_STMT, body: SITE_BODY, proof: SITE_PROOF, grammar: SITE_GRAMMAR };
541
+ /** The parts asked for with a declaration (`include=source,context,…`), or why they are refused. */
542
+ function parts(s) {
543
+ if (s === null || !s.trim())
544
+ return [];
545
+ const asked = s.split(",").map((x) => x.trim()).filter(Boolean);
546
+ const bad = asked.filter((x) => !PARTS.includes(x));
547
+ if (bad.length)
548
+ return fail(400, `include: ${bad.join(", ")} is not a part.`, `The parts are ${PARTS.join(", ")}, separated by commas.`);
549
+ return [...new Set(asked)];
550
+ }
551
+ /** Names separated by commas, as `names=a,b,c` gives them; a comma inside «…» is part of a name. */
552
+ function splitNames(s) {
553
+ const out = [];
554
+ let cur = "", quoted = false;
555
+ for (const c of s) {
556
+ if (c === "«")
557
+ quoted = true;
558
+ else if (c === "»")
559
+ quoted = false;
560
+ if (c === "," && !quoted) {
561
+ out.push(cur);
562
+ cur = "";
563
+ }
564
+ else
565
+ cur += c;
566
+ }
567
+ out.push(cur);
568
+ return out.map((x) => x.trim()).filter(Boolean);
569
+ }