entrylib-pages 0.1.0__py3-none-any.whl

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.
entrylib_pages/page.py ADDED
@@ -0,0 +1,1696 @@
1
+ """The page view: a claimset as HTML for people, in the order of the paper's argument. EntryLib's own (design
2
+ §7.1): moved here from the claimset package, which keeps only the reading view for models (claimset.render), whose way
3
+ of writing values (numbers, intervals, statistics) this view shares.
4
+
5
+ render_parts(doc, file_url=None, ref_text=None, digits=None, number=None, person=None, marker=None,
6
+ claim_url=None) -> HTML fragments: header,
7
+ nav, body (and the title, the origin label, the brief, the sections)
8
+ render_html(doc) -> a whole page, with the stylesheet inline, for previewing a claimset locally
9
+ origin(doc) -> the origin label: lab, lab · record withheld, converted or native
10
+
11
+ The view is derived mechanically from a valid claimset file, like the reading view (render.py), and adds nothing that
12
+ is not in the file except what is computed from it: the support lights (from verifiability, §5), the selection of
13
+ claims under Highlights when the authors gave no highlights, and the author-year labels of references.
14
+
15
+ Everything taken from the file is escaped: the view is safe to publish however the file was written. Links are made
16
+ only to the file's own objects (#C3), to ORCID and doi.org, and to http(s) addresses the file gives. Images (figures,
17
+ and the images behind observation records) are shown only from addresses the caller gives for the claimset's own files
18
+ (`file_url`); an image elsewhere is linked, never embedded, so reading the page loads nothing from other sites.
19
+ A site may also write out references the file gives only by identifier (`ref_text(reference)`: a DOI's metadata, as
20
+ "Surname, A., & Other, B. (2018). Title. Journal."), so that they read as author (year) too.
21
+
22
+ Maths in text ($...$) is MathML (mathml.py), which browsers show without a script; `code` in backticks is code.
23
+
24
+ Order: Summary (when the paper has one), Highlights, Context, Definitions (grouped by kind), Assumptions, Principal claims, Supporting claims, Evidence,
25
+ Limitations, Open questions, References, Artefacts. The classes are stable: a site styles them with claimset.css, or
26
+ its own rules.
27
+ """
28
+
29
+ import html
30
+ import json
31
+ import re
32
+
33
+ from claimset.render import DIGITS
34
+ from claimset.render import interval as _interval
35
+ from claimset.render import number as _num
36
+ from claimset.render import statistic as _statistic
37
+ from claimset.render import statistic_note as _stat_note
38
+ from claimset.render import uncertainty as _uncertainty
39
+ from claimset.render import value as _val
40
+
41
+ from . import refs as source_paper
42
+ from .mathml import to_mathml
43
+
44
+
45
+ def _s(x):
46
+ return x if isinstance(x, str) else json.dumps(x, ensure_ascii=False)
47
+
48
+
49
+ def _join(items, sep="; "):
50
+ return sep.join(i for i in items if i)
51
+
52
+ #: How many principal claims Highlights shows at most.
53
+ BRIEF_MAX = 5
54
+
55
+ TERM = re.compile(r"\[\[([^:\]]+):([^\]]+)\]\]")
56
+ #: A marker whose text holds a formula: shown as a link around the formula (see _Paper._maths).
57
+ FORMULA_MARK = re.compile(r"\[\[([^:\]]+):([^\]]*\$[^\]]*)\]\]")
58
+ #: The year of a written reference: in brackets ("Kolassa, S. (2011). …") or, in a classical list, after the authors
59
+ #: ("Kolassa, S., 2011. …").
60
+ YEAR = re.compile(r"\((\d{4}[a-z]?)\)|(?<=[.\w], )(\d{4}[a-z]?)(?=\.(?:\s|$))")
61
+ SURNAME = re.compile(r"(?:^|,\s*|&\s*|and\s+)([^\W\d_][^,&()]*?),\s*(?:[^\W\d_]\.)")
62
+
63
+ #: Definition groups, in the order a reader meets them, with their headings.
64
+ KIND_GROUPS = [("method", "Methods"), ("data", "Data"), ("variable", "Variables and measures"),
65
+ ("design", "Study design"), ("population", "Populations"), ("intervention", "Interventions"),
66
+ ("setting", "Settings"), ("substance", "Substances"), ("organism", "Organisms"),
67
+ ("biological_material", "Biological materials"), ("entity", "Entities"), ("process", "Processes"),
68
+ ("source", "Sources"), ("concept", "Concepts"), ("theory", "Theories"), ("other", "Other terms")]
69
+
70
+ #: Files shown as images, by extension.
71
+ IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".avif")
72
+
73
+ SUPPORT_LABELS = {"empirical_quant": "Data", "empirical_qual": "Qualitative data", "empirical_obs": "Observations",
74
+ "simulation": "Simulation", "formal_proof": "Proof", "demonstration": "Demonstration",
75
+ "argument": "Argument", "cited": "Cited", "expert_judgement": "Expert judgement",
76
+ "consensus": "Consensus", "unstated": "Support not stated"}
77
+
78
+ #: The file's vocabularies as a reader would say them (the reading view, for models, keeps the values).
79
+ SCOPE_WORDS = {"population": "population", "setting": "setting", "geography": "where", "language": "language",
80
+ "period": "period", "data_type": "data", "conditions": "conditions", "excludes": "not for"}
81
+ NOVELTY_WORDS = {"replication": "replicates earlier work", "extension": "extends earlier work",
82
+ "refutation": "refutes earlier work",
83
+ "synthesis": "summarises earlier work"} # claimset v0.43
84
+ VERIFICATION_WORDS = {"machine_checked": "checked by a proof assistant", "agent_checked": "checked by an agent",
85
+ "peer_checked": "checked by a person", "disputed": "disputed", "unchecked": "not checked"}
86
+ VERDICT_WORDS = {"computed": "computed from the recorded results", "judged": "judged by the writer"}
87
+ FLAG_WORDS = {"code_changed_after_plan": "the code changed after the plan",
88
+ "holdout_used_elsewhere": "the held-out data was used elsewhere",
89
+ "reproduces_prompting_result": "it repeats the result that suggested it",
90
+ "sources_captured_after_plan": "sources were captured after the plan",
91
+ "diagnostic_missing": "a run left out a check the plan required",
92
+ "coded_before_plan": "material was coded before the plan",
93
+ "codebook_changed_after_plan": "the codebook changed after the plan"}
94
+ MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
95
+ "November", "December"]
96
+
97
+ #: Lights (§2.3 of the website design): from the claim's verifiability and the kinds of its support.
98
+ LIGHTS = {"green": "checkable", "amber": "supported, not checkable", "red": "unsupported"}
99
+ NOT_CHECKABLE = {"argument", "cited", "expert_judgement", "consensus"}
100
+
101
+
102
+ MATH = re.compile(r"\$\$(.+?)\$\$|\$([^$\s][^$]*?)\$|\\\((.+?)\\\)", re.S)
103
+ CODE = re.compile(r"(`+)(.+?)\1", re.S)
104
+ #: A fenced block (claimset §8 rule 12): three backticks, an optional language on the same line, the lines, three
105
+ #: backticks. Shown as a block whose lines are kept, inside the paragraph that holds it.
106
+ FENCED_CODE = re.compile(r"```[ \t]*([^\n`]*)\n(.*?)\n?[ \t]*```", re.S)
107
+
108
+
109
+ #: LaTeX in a text: a command (\\mu, \\frac) or a sub- or superscript.
110
+ TEX_MARK = re.compile(r"\\[A-Za-z]+|[_^]")
111
+ #: Prose: two words of letters in a row, outside commands and \\text{…} (an `E` or `d` of a formula is not a word).
112
+ PROSE = re.compile(r"(?<![\\A-Za-z])[A-Za-z]{3,}\s+[A-Za-z]{3,}(?![A-Za-z]*\})")
113
+
114
+
115
+ def bare_formula(s):
116
+ """Whether a proof step's statement is a formula written without $…$ (claimset spec §3.4: a step's `statement`
117
+ is LaTeX): LaTeX and no delimiters, code, term marks or prose."""
118
+ if not isinstance(s, str) or not s.strip() or MATH.search(s) or CODE.search(s) or TERM.search(s):
119
+ return False
120
+ words = re.sub(r"\\(?:text|mathrm|operatorname|mbox)\{[^}]*\}|\\[A-Za-z]+", " ", s)
121
+ return bool(TEX_MARK.search(s)) and not PROSE.search(words)
122
+
123
+
124
+ def math(tex, display=False):
125
+ """An expression as MathML (claimset.mathml), on a line of its own when the author wrote it as $$...$$ (spec §8
126
+ rule 6), in the sentence when written as $...$; one it cannot read is shown as written, as code."""
127
+ out = to_mathml(tex, display)
128
+ return out if out is not None else f'<code class="math-tex">{esc(tex)}</code>'
129
+
130
+
131
+ def esc(x):
132
+ return html.escape(x if isinstance(x, str) else _s(x), quote=True)
133
+
134
+
135
+ def _safe_url(url):
136
+ """An address a site gives for a link (a path on the site or an http(s) address), safe to put in an attribute."""
137
+ return (url.startswith("/") and not url.startswith("//") or url.startswith(("https://", "http://"))) \
138
+ and not any(ch in url for ch in "\"'<> ")
139
+
140
+
141
+ def _href(uri):
142
+ """A link only to an http(s) address; anything else is shown as text."""
143
+ return isinstance(uri, str) and uri.startswith(("https://", "http://")) and not any(c in uri for c in "\"'<> ")
144
+
145
+
146
+ def _link(uri, text=None):
147
+ text = esc(text if text is not None else uri)
148
+ return f'<a href="{esc(uri)}">{text}</a>' if _href(uri) else text
149
+
150
+
151
+ #: An item of the file named in a text (claimset §8 rule 13): `C27`, `E3`, `E3.R2`, `D4`; not inside a word, a link, an
152
+ #: EntryLib identifier or a file name.
153
+ LOCAL_ID = re.compile(r"(?<![\w.:/#@-])([A-Z]\d+)(?:\.([A-Z]+\d+))?(?![\w])")
154
+ #: A blank line between paragraphs (claimset §8 rule 15).
155
+ PARAGRAPH = re.compile(r"[ \t]*\n[ \t]*\n\s*")
156
+ #: The parts of a statement (claimset §8 rule 11): `(a)`, `(b)`, … where a word may begin.
157
+ PART = re.compile(r"(?:(?<=\s)|^)\(([a-h])\)(?=\s)")
158
+ GLOBAL_ID = re.compile(r"entrylib:(\d{4}\.\d{6,})(@v\d+)?(?:#([A-Z]+\d+(?:\.\d+)*))?")
159
+
160
+
161
+ def _global_link(m):
162
+ """A claimset's identifier on EntryLib (entrylib:2026.000008, …@v2, …@v2#C4) as a link to its page on this site:
163
+ the paper, its version, and the claim in it."""
164
+ key, version, obj = m.group(1), m.group(2) or "", m.group(3)
165
+ return f'<a class="global-id" href="/p/{key}{version}{"#" + obj if obj else ""}">{esc(m.group(0))}</a>'
166
+
167
+
168
+ def linked(s):
169
+ """Text escaped, with EntryLib identifiers linked."""
170
+ out, last = [], 0
171
+ for m in GLOBAL_ID.finditer(s):
172
+ out.append(esc(s[last:m.start()]))
173
+ out.append(_global_link(m))
174
+ last = m.end()
175
+ out.append(esc(s[last:]))
176
+ return "".join(out)
177
+
178
+
179
+ def _target(t, id_type):
180
+ """A cited work or claim named by identifier: a DOI or an EntryLib identifier as a link, anything else as text."""
181
+ if id_type == "doi":
182
+ return _doi(t)
183
+ if id_type == "claimset" and isinstance(t, str) and GLOBAL_ID.fullmatch(t):
184
+ return _global_link(GLOBAL_ID.fullmatch(t))
185
+ return esc(t)
186
+
187
+
188
+ def _link_name(uri, limit=40):
189
+ """What a link to an artefact is called: its file's name, or else its site (`model.R`, `zenodo.org`)."""
190
+ path = re.sub(r"[?#].*$", "", str(uri)).rstrip("/")
191
+ host = re.sub(r"^https?://", "", path).split("/")[0]
192
+ tail = path.rsplit("/", 1)[-1] if "/" in re.sub(r"^https?://", "", path) else ""
193
+ name = tail or host or str(uri)
194
+ if re.fullmatch(r"[0-9a-f]{40}", name) and re.search(r"/(tree|commit)/[0-9a-f]{40}$", path):
195
+ name = f"repository at {name[:7]}" # a repository at a commit: its hash says nothing to a reader
196
+ return name if len(name) <= limit else name[:limit - 1] + "…"
197
+
198
+
199
+ def _doi(x):
200
+ return _link(f"https://doi.org/{x}", f"doi:{x}") if isinstance(x, str) and x.startswith("10.") else esc(x)
201
+
202
+
203
+ def _readable(text):
204
+ """Text for a tooltip, which shows no markup: terms as shown, formulas as the characters their MathML shows
205
+ ("$\\epsilon_t$" as "ϵt"), never as LaTeX."""
206
+ text = TERM.sub(lambda m: m.group(2), text or "")
207
+
208
+ def formula(m):
209
+ tex = m.group(1) or m.group(2) or m.group(3) or ""
210
+ shown = to_mathml(tex)
211
+ if shown is None:
212
+ return tex
213
+ shown = re.sub(r"<annotation\b.*?</annotation>", "", shown, flags=re.S) # the TeX it was made from
214
+ return html.unescape(re.sub(r"<[^>]+>", "", shown))
215
+ return MATH.sub(formula, text)
216
+
217
+
218
+ def _first_sentence(text, limit=160):
219
+ text = _readable(text)
220
+ m = re.search(r"(?<=[.;])\s", text)
221
+ text = text[:m.start()] if m and m.start() < limit else text
222
+ return text if len(text) <= limit else text[:limit - 1].rstrip() + "…"
223
+
224
+
225
+ class _Paper:
226
+ """The claimset's objects indexed, and what is computed once for the whole view."""
227
+
228
+ def __init__(self, doc, file_url=None, ref_text=None):
229
+ self.doc = doc
230
+ self.person = None # the site's choices (render_parts): people,
231
+ self.marker = None # what marks a claim,
232
+ self.claim_url = None # and a claim's own page
233
+ self.file_url = file_url
234
+ self.ref_text = ref_text
235
+ self.paper = doc.get("paper") if isinstance(doc.get("paper"), dict) else {}
236
+ def listed(k):
237
+ return [x for x in doc.get(k) or [] if isinstance(x, dict) and isinstance(x.get("id"), str)]
238
+ self.claims, self.defs, self.evidence = listed("claims"), listed("definitions"), listed("evidence")
239
+ self.limitations, self.questions = listed("limitations"), listed("open_questions")
240
+ self.refs, self.artefacts, self.warrants = listed("references"), listed("artefacts"), listed("warrants")
241
+ self.by_id = {x["id"]: x for lst in (self.claims, self.defs, self.evidence, self.limitations, self.refs,
242
+ self.artefacts, self.warrants, self.questions) for x in lst}
243
+ self.labels = self._reference_labels()
244
+ self.corrections, self.against = _corrections(self.paper)
245
+ self.corrected = {}
246
+ for corr in self.corrections:
247
+ self.corrected.setdefault(corr["field"].split(".")[0], []).append(corr)
248
+ self.computed = self._verifiability()
249
+ self.used_by = self._uses()
250
+ # table rows a claim cites: a long table keeps them in view when it is folded (design §7.1)
251
+ self.cited_rows = {x for c in self.claims for sp in c.get("support") or [] if isinstance(sp, dict)
252
+ for x in sp.get("results") or [] if isinstance(x, str)}
253
+ # the main evidence of the claims shown, whose small tables stay open (design §7.4, *Tables*): every claim's,
254
+ # unless the page shows one claim (render_parts' `claim`)
255
+ self.main = {main_evidence(c) for c in self.claims} - {None}
256
+ # the formal verdicts that give no claim (claimset §3.1.1), and the lab record a reader follows for them
257
+ self.not_claimed = not_claimed_entries(doc)
258
+ self.lab_record = lab_record_uri(doc)
259
+ self.hypotheses = hypothesis_claims(self.claims)
260
+
261
+ # ---------- references ----------
262
+ def _reference_labels(self):
263
+ """Author (year) for each reference: "Hyndman et al. (2008)", "Kolassa (2011)"; a, b for repeats."""
264
+ labels, self.written, self.by_identifier = {}, {}, set()
265
+ for b in self.refs:
266
+ t, kind = b.get("target"), b.get("id_type")
267
+ if kind not in (None, "reference") and self.ref_text is not None:
268
+ written = self.ref_text(b) # the site's lookup (a DOI's metadata, say)
269
+ if isinstance(written, str) and written.strip():
270
+ self.written[b["id"]] = t = written.strip()
271
+ kind = "reference"
272
+ if kind == "doi":
273
+ labels[b["id"]] = f"doi:{t}"
274
+ self.by_identifier.add(b["id"])
275
+ continue
276
+ if kind not in (None, "reference") or not isinstance(t, str):
277
+ labels[b["id"]] = _s(t)
278
+ self.by_identifier.add(b["id"])
279
+ continue
280
+ y = YEAR.search(t)
281
+ if not y:
282
+ labels[b["id"]] = t if len(t) <= 40 else t[:39].rstrip() + "…"
283
+ continue
284
+ names = [n.strip() for n in SURNAME.findall(t[:y.start()])] or [t.split(",")[0].strip()]
285
+ who = (names[0] if len(names) == 1 else f"{names[0]} and {names[1]}" if len(names) == 2
286
+ else f"{names[0]} et al.")
287
+ labels[b["id"]] = f"{who} ({y.group(1) or y.group(2)})"
288
+ # One work, one label: claims of one claimset share it, each named after it ("Svetunkov (2026a), C33").
289
+ claim_of, work = {}, {}
290
+ for b in self.refs:
291
+ m = GLOBAL_ID.fullmatch(b["target"]) if b.get("id_type") == "claimset" and isinstance(
292
+ b.get("target"), str) else None
293
+ if m and b["id"] in self.written:
294
+ work[b["id"]] = m.group(1) + (m.group(2) or "")
295
+ if m.group(3):
296
+ claim_of[b["id"]] = m.group(3)
297
+ seen = {}
298
+ for rid, lab in labels.items():
299
+ works = seen.setdefault(lab, [])
300
+ if work.get(rid, rid) not in works:
301
+ works.append(work.get(rid, rid))
302
+ for rid, lab in list(labels.items()):
303
+ works = seen[lab]
304
+ if len(works) > 1 and lab.endswith(")"):
305
+ labels[rid] = f"{lab[:-1]}{chr(97 + works.index(work.get(rid, rid)))})"
306
+ if rid in claim_of:
307
+ labels[rid] += f", {claim_of[rid]}"
308
+ self.work, self.claim_of = work, claim_of
309
+ return labels
310
+
311
+ def refs_in_order(self):
312
+ """The references in the order of a reference list: by their labels, those known only by an identifier
313
+ after those with an author, a number in a label by its value (C6 before C33)."""
314
+ def key(b):
315
+ lab = self.labels.get(b["id"], b["id"])
316
+ return (b["id"] in self.by_identifier,
317
+ [(0, int(x), "") if x.isdigit() else (1, 0, x.casefold()) for x in re.split(r"(\d+)", lab) if x])
318
+ return sorted(self.refs, key=key)
319
+
320
+ def ref(self, rid, locator=None):
321
+ lab = self.labels.get(rid, rid)
322
+ return f'<a class="ref" href="#{esc(rid)}">{esc(lab)}</a>' + (f", {esc(locator)}" if locator else "")
323
+
324
+ # ---------- verifiability and lights ----------
325
+ def _verifiability(self):
326
+ """The platform's verifiability where the file lacks it (a submission being previewed)."""
327
+ if all("verifiability" in c for c in self.claims):
328
+ return {}
329
+ try:
330
+ from claimset.validate import validate
331
+ return {cid: v.get("verifiability") for cid, v in (validate(self.doc).computed or {}).items()}
332
+ except Exception: # noqa: BLE001 - a preview without lights is still a preview
333
+ return {}
334
+
335
+ def is_assumption(self, c):
336
+ return bool(c.get("assumption_category")) or any(
337
+ isinstance(s, dict) and s.get("kind") == "assumption" for s in c.get("support") or [])
338
+
339
+ def light(self, c):
340
+ if self.is_assumption(c):
341
+ return None
342
+ v = c.get("verifiability") or self.computed.get(c["id"])
343
+ kinds = {s.get("kind") for s in c.get("support") or [] if isinstance(s, dict)}
344
+ if v == "unverifiable" or not kinds or kinds == {"unstated"}:
345
+ return "red"
346
+ if v == "audit_only" or kinds <= NOT_CHECKABLE:
347
+ return "amber"
348
+ return "green"
349
+
350
+ def mark(self, c, where):
351
+ """What comes before a claim (`where`: `claim` or `brief`) and after its meta line: the site's (`marker`,
352
+ render_parts), or the claim's support light before and nothing after."""
353
+ if self.marker is not None:
354
+ shown = self.marker(c, where)
355
+ if isinstance(shown, str):
356
+ return shown, ""
357
+ if isinstance(shown, tuple) and len(shown) == 2 and all(isinstance(x, str) for x in shown):
358
+ return shown
359
+ return self.lamp(c), ""
360
+
361
+ def claim_id(self, c):
362
+ """A claim's ID in its meta line: linked to the claim's own page when the site gives one (`claim_url`)."""
363
+ url = self.claim_url(c["id"]) if self.claim_url is not None else None
364
+ if isinstance(url, str) and _safe_url(url):
365
+ return f'<a class="cs-claim-page" href="{esc(url)}">{esc(c["id"])}</a>'
366
+ return esc(c["id"])
367
+
368
+ def lamp(self, c):
369
+ light = self.light(c)
370
+ if not light:
371
+ return ""
372
+ return f'<span class="light light-{light}" role="img" aria-label="{LIGHTS[light]}" title="{LIGHTS[light]}"></span>'
373
+
374
+ # ---------- who uses what ----------
375
+ def _uses(self):
376
+ """For each object, the objects that point to it: claims using a claim, claims citing evidence, places
377
+ citing a reference."""
378
+ used = {}
379
+
380
+ def add(target, by):
381
+ if isinstance(target, str) and target in self.by_id and by not in used.setdefault(target, []):
382
+ used[target].append(by)
383
+ for c in self.claims:
384
+ for t in (c.get("depends_on") or []) + (c.get("assumptions") or []) + (c.get("limitations") or []):
385
+ add(t, c["id"])
386
+ for s in c.get("support") or []:
387
+ if isinstance(s, dict):
388
+ for key in ("evidence", "warrant", "reference"):
389
+ add(s.get(key), c["id"])
390
+ for rel in c.get("relations") or []:
391
+ if isinstance(rel, dict):
392
+ add(rel.get("reference"), "context")
393
+ if isinstance(c.get("test"), dict):
394
+ add(c["test"].get("registration"), c["id"])
395
+ for d in self.defs + self.evidence:
396
+ for t in d.get("assumptions") or []:
397
+ add(t, d["id"])
398
+ src = d.get("source")
399
+ add(src.get("reference") if isinstance(src, dict) else src, d["id"])
400
+ for lim in self.limitations:
401
+ for t in lim.get("affects") or []:
402
+ add(lim["id"], t)
403
+ for a in self.artefacts:
404
+ add(a.get("reference"), a["id"])
405
+ return used
406
+
407
+ def users(self, oid, skip=()):
408
+ out = []
409
+ for u in self.used_by.get(oid, []):
410
+ if u in skip:
411
+ continue
412
+ out.append('<a href="#context">Context</a>' if u == "context" else f'<a href="#{esc(u)}">{esc(u)}</a>')
413
+ return ", ".join(out)
414
+
415
+ # ---------- text ----------
416
+ def text(self, s):
417
+ """A statement or description: escaped, with [[D1:term]] as a link to the definition, inline LaTeX
418
+ ($...$, $$...$$, \\(...\\)) as MathML and `code` as code."""
419
+ if not isinstance(s, str):
420
+ return esc(s)
421
+ out, last = [], 0
422
+ for m in CODE.finditer(s):
423
+ out.append(self._maths(s[last:m.start()]))
424
+ block = FENCED_CODE.fullmatch(m.group(0))
425
+ if block: # a fenced block (claimset §8 rule 12): its lines kept, its language named in the class
426
+ lang = re.sub(r"[^A-Za-z0-9+#-]", "", block.group(1))[:20]
427
+ cls = f" language-{lang}" if lang else ""
428
+ out.append(f'<code class="cs-code cs-code-block{cls}">{esc(block.group(2).rstrip())}</code>')
429
+ else:
430
+ out.append(f'<code class="cs-code">{esc(m.group(2).strip())}</code>')
431
+ last = m.end()
432
+ out.append(self._maths(s[last:]))
433
+ return "".join(out)
434
+
435
+ def step(self, s):
436
+ """A proof step's statement: a bare formula as a formula (bare_formula), in a box that scrolls when it is
437
+ wider than the line; anything else as text."""
438
+ if bare_formula(s):
439
+ shown = to_mathml(s.strip())
440
+ if shown is not None:
441
+ return f'<span class="cs-step-math">{shown}</span>'
442
+ return self.text(s)
443
+
444
+ def _maths(self, s):
445
+ """Formulas and markers. A marker whose text holds a formula (`[[D46:$I_n$]]`, which claimset §8 rule 5 and
446
+ warning 67 ask to write as words) is shown as a link around the formula, not broken apart by it."""
447
+ out, last = [], 0
448
+ for m in FORMULA_MARK.finditer(s):
449
+ out.append(self._maths_in(s[last:m.start()]))
450
+ tid, inner = m.group(1), self._maths_in(m.group(2))
451
+ d = self.by_id.get(tid)
452
+ kind = "ref" if d is not None and d in self.refs else "term" if d is not None and d in self.defs else None
453
+ out.append(f'<a class="{kind}" href="#{esc(tid)}">{inner}</a>' if kind else inner)
454
+ last = m.end()
455
+ out.append(self._maths_in(s[last:]))
456
+ return "".join(out)
457
+
458
+ def _maths_in(self, s):
459
+ out, last = [], 0
460
+ for m in MATH.finditer(s):
461
+ out.append(self._terms(s[last:m.start()]))
462
+ tex, end = m.group(1) or m.group(2) or m.group(3), m.end()
463
+ display = m.group(1) is not None # the author's choice: $$…$$ (§8 rule 6)
464
+ if display and end < len(s) and s[end] in ",.;:": # a formula on its own line keeps its punctuation
465
+ tex, end = tex + s[end], end + 1
466
+ shown = math(tex, display=display)
467
+ if not display and end < len(s) and s[end] in ",.;:!?)":
468
+ # the punctuation after a formula in a sentence stays on its line: a formula does not break, and
469
+ # a full stop alone at the start of the next line reads as a mistake
470
+ shown, end = f'<span class="cs-nw">{shown}{esc(s[end])}</span>', end + 1
471
+ out.append(shown)
472
+ last = end
473
+ out.append(self._terms(s[last:]))
474
+ return "".join(out)
475
+
476
+ def _terms(self, s):
477
+ out, last = [], 0
478
+ for m in TERM.finditer(s):
479
+ out.append(self._plain(s[last:m.start()]))
480
+ tid, shown = m.group(1), m.group(2)
481
+ d = self.by_id.get(tid)
482
+ if d is not None and d in self.refs: # a citation marker (claimset §8 rule 14)
483
+ tip = self.labels.get(tid) or tid
484
+ out.append(f'<a class="ref" href="#{esc(tid)}" title="{esc(tip)}">{esc(shown)}</a>')
485
+ elif d is not None and d in self.defs:
486
+ tip = f"{d.get('term', '')}: " + _first_sentence(d.get("definition", ""))
487
+ out.append(f'<a class="term" href="#{esc(tid)}" title="{esc(tip)}">{esc(shown)}</a>')
488
+ else:
489
+ out.append(esc(shown))
490
+ last = m.end()
491
+ out.append(self._plain(s[last:]))
492
+ return "".join(out)
493
+
494
+ def _plain(self, s):
495
+ """Plain text: escaped, EntryLib identifiers and the file's own items (claimset §8 rule 13) linked, a blank line
496
+ kept as a break between paragraphs (§8 rule 15)."""
497
+ out = []
498
+ for i, para in enumerate(PARAGRAPH.split(s)):
499
+ if i:
500
+ out.append('<span class="cs-para"></span>')
501
+ last, kept = 0, []
502
+ for m in GLOBAL_ID.finditer(para):
503
+ kept.append(self._items(para[last:m.start()]))
504
+ kept.append(_global_link(m))
505
+ last = m.end()
506
+ kept.append(self._items(para[last:]))
507
+ out.append("".join(kept))
508
+ return "".join(out)
509
+
510
+ def _items(self, s):
511
+ out, last = [], 0
512
+ for m in LOCAL_ID.finditer(s):
513
+ oid, sub = m.group(1), m.group(2)
514
+ if oid not in self.by_id:
515
+ continue
516
+ out.append(esc(s[last:m.start()]))
517
+ target = f"{oid}.{sub}" if sub and self._has_part(oid, sub) else oid
518
+ out.append(f'<a class="cs-ref-id" href="#{esc(target)}">{esc(m.group(0))}</a>')
519
+ last = m.end()
520
+ out.append(esc(s[last:]))
521
+ return "".join(out)
522
+
523
+ def _has_part(self, oid, sub):
524
+ """Whether `E3.R2` (a result, a table, a step of evidence E3) has an anchor of its own on the page."""
525
+ e = self.by_id.get(oid)
526
+ return isinstance(e, dict) and any(isinstance(x, dict) and x.get("id") == sub
527
+ for k in ("results", "tables", "steps") for x in e.get(k) or [])
528
+
529
+ def statement(self, s):
530
+ """A claim's statement: as text, its parts (claimset §8 rule 11: `(a)`, `(b)`, …) set out one per line after
531
+ the words that hold for all of them. Marks inside a formula, code or a marker are not parts."""
532
+ if not isinstance(s, str):
533
+ return self.text(s)
534
+ hidden = re.sub(r"```.*?```|`[^`]*`|\$\$.+?\$\$|\$[^$]+?\$|\[\[[^\]]*\]\]",
535
+ lambda m: "x" * len(m.group(0)), s, flags=re.S)
536
+ marks, want = [], "a"
537
+ for m in PART.finditer(hidden):
538
+ if m.group(1) == want:
539
+ marks.append(m)
540
+ want = chr(ord(want) + 1)
541
+ if len(marks) < 2:
542
+ return self.text(s)
543
+ parts = [self.text(s[:marks[0].start()].rstrip())] if s[:marks[0].start()].strip() else []
544
+ for i, m in enumerate(marks):
545
+ end = marks[i + 1].start() if i + 1 < len(marks) else len(s)
546
+ parts.append(f'<span class="cs-part"><span class="cs-part-mark">({m.group(1)})</span> '
547
+ f'{self.text(s[m.end():end].strip())}</span>')
548
+ return "".join(parts)
549
+
550
+ # ---------- images ----------
551
+ def image_src(self, a):
552
+ """Where an artefact's image is shown from, or None: only a file of the claimset. With `file_url`, the site
553
+ says (a published file's address need not end in its type, so the site, which holds the file, decides
554
+ whether it is an image); without it, a relative path ending in an image extension (a local preview)."""
555
+ uri = a.get("uri")
556
+ if not isinstance(uri, str):
557
+ return None
558
+ if self.file_url is not None:
559
+ src = self.file_url(a)
560
+ elif not uri.lower().split("?")[0].endswith(IMAGE_EXTENSIONS):
561
+ return None
562
+ else:
563
+ src = None if "://" in uri or uri.startswith(("/", "\\")) or ".." in uri.split("/") else uri
564
+ return src if isinstance(src, str) and src and not any(c in src for c in "\"'<> ") else None
565
+
566
+ def figure(self, a, small=False):
567
+ """An artefact shown as an image with its caption, or linked when it is not a file of the claimset."""
568
+ desc = a.get("description") or a.get("uri") or a["id"]
569
+ src = self.image_src(a)
570
+ caption = f'<span class="cs-id">{esc(a["id"])}</span> {self.text(desc)}'
571
+ if src is None:
572
+ return (f'<p class="cs-links"><span class="k">Figure:</span> {caption}'
573
+ + (f" ({_link(a['uri'], 'open')})" if _href(a.get("uri")) else "") + "</p>")
574
+ cls = "cs-figure cs-figure-small" if small else "cs-figure"
575
+ return (f'<figure class="{cls}"><a href="{esc(src)}"><img src="{esc(src)}" alt="{esc(_first_sentence(desc))}" '
576
+ f'loading="lazy"></a><figcaption>{caption}</figcaption></figure>')
577
+
578
+ def figures_of(self, e):
579
+ """The artefacts that show this evidence: the images its observation records are read from, figures whose
580
+ `shows` names its results or tables, and figures named in the support that cites it."""
581
+ eid, found = e["id"], []
582
+ for x in e.get("records") or []:
583
+ if isinstance(x, dict) and x.get("artefact") in self.by_id:
584
+ found.append(x["artefact"])
585
+ for a in self.artefacts:
586
+ shows = a.get("shows") or []
587
+ if a.get("kind") == "figure" and any(isinstance(s, str) and (s == eid or s.startswith(eid + "."))
588
+ for s in shows):
589
+ found.append(a["id"])
590
+ for c in self.claims:
591
+ for s in c.get("support") or []:
592
+ if isinstance(s, dict) and s.get("evidence") == eid:
593
+ found += [x for x in s.get("artefacts") or [] if x in self.by_id
594
+ and self.by_id[x].get("kind") == "figure"]
595
+ out = []
596
+ for aid in found:
597
+ if aid not in out:
598
+ out.append(aid)
599
+ return [self.by_id[aid] for aid in out]
600
+
601
+ def term(self, x):
602
+ """A value that is a definition's ID, shown as its term (linked); anything else as text, its formulas set
603
+ (claimset §8 rule 6: a condition's value may be `real part $\\alpha_0$`)."""
604
+ if isinstance(x, str) and x in self.by_id and self.by_id[x] in self.defs:
605
+ d = self.by_id[x]
606
+ tip = f"{d.get('term', '')}: " + _first_sentence(d.get("definition", ""))
607
+ return f'<a class="term" href="#{esc(x)}" title="{esc(tip)}">{esc(d.get("term", x))}</a>'
608
+ return self.text(_s(x))
609
+
610
+ def conditions(self, c):
611
+ if not isinstance(c, dict) or not c:
612
+ return ""
613
+ return "(" + ", ".join(f"{self.term(k)}: {self.term(v)}" for k, v in c.items()) + ")"
614
+
615
+ def column(self, c):
616
+ if isinstance(c, dict):
617
+ note = _stat_note(c)
618
+ return _join([self.term(c.get("variable")), self.conditions(c.get("conditions"))], " ") + esc(note)
619
+ return self.term(c)
620
+
621
+ def value(self, v):
622
+ return self.term(v) if isinstance(v, str) else esc(_val(v))
623
+
624
+ def ids(self, ids):
625
+ return ", ".join(f'<a href="#{esc(i)}">{esc(i)}</a>' if i in self.by_id else esc(i)
626
+ for i in ids if isinstance(i, str))
627
+
628
+
629
+ # ---------- Highlights ----------
630
+ def brief(doc):
631
+ """The IDs shown under Highlights, and whether they were selected automatically. The authors' highlights when the file
632
+ has them (principal claims and terms the paper introduces, spec §3.1); otherwise all principal claims when there are at most five; otherwise a computed choice:
633
+ ranked by how many claims, warrants and open questions use them (directly or through other claims), one per claim
634
+ type first, near-duplicates skipped, shown in the file's order."""
635
+ P = doc if isinstance(doc, _Paper) else _Paper(doc)
636
+ principal = [c for c in P.claims if c.get("role") == "principal"]
637
+ order = [cid for cid in P.paper.get("contributions") or [] if cid in P.by_id] or [c["id"] for c in principal]
638
+ hl = [h for h in P.paper.get("highlights") or [] if isinstance(h, str) and h in P.by_id
639
+ and (P.by_id[h] in P.defs or P.by_id[h] in P.claims)]
640
+ if hl:
641
+ return hl[:BRIEF_MAX], False
642
+ if len(order) <= BRIEF_MAX:
643
+ return order, False
644
+ users = {}
645
+ for c in P.claims:
646
+ for t in c.get("depends_on") or []:
647
+ users.setdefault(t, set()).add(c["id"])
648
+ for q in P.questions:
649
+ for t in q.get("claims") or []:
650
+ users.setdefault(t, set()).add(q["id"])
651
+ for w in P.warrants:
652
+ for t in w.get("premises") or []:
653
+ users.setdefault(t, set()).add(w["id"])
654
+
655
+ def reach(cid, seen=None):
656
+ seen = set() if seen is None else seen
657
+ for u in users.get(cid, ()):
658
+ if u not in seen:
659
+ seen.add(u)
660
+ reach(u, seen)
661
+ return seen
662
+ score = {cid: len(reach(cid)) for cid in order}
663
+ ranked = sorted(order, key=lambda cid: (-score[cid], order.index(cid)))
664
+ words = {cid: set(re.findall(r"\w+", TERM.sub(lambda m: m.group(2), P.by_id[cid].get("statement", "")).lower()))
665
+ for cid in order}
666
+
667
+ def near(a, b):
668
+ u = words[a] | words[b]
669
+ return bool(u) and len(words[a] & words[b]) / len(u) > 0.7
670
+ chosen, types = [], set()
671
+ for first_pass in (True, False):
672
+ for cid in ranked:
673
+ if len(chosen) >= BRIEF_MAX or cid in chosen or any(near(cid, x) for x in chosen):
674
+ continue
675
+ t = P.by_id[cid].get("type")
676
+ if first_pass and t in types:
677
+ continue
678
+ chosen.append(cid)
679
+ types.add(t)
680
+ return sorted(chosen, key=order.index), True
681
+
682
+
683
+ # ---------- the parts ----------
684
+ def _origin(P):
685
+ if isinstance(P.paper.get("converted_from"), dict) or P.paper.get("origin") == "converted":
686
+ return "converted"
687
+ lab = any(a.get("kind") == "lab_record" for a in P.artefacts) or isinstance(P.paper.get("exploration"), dict)
688
+ if lab:
689
+ withheld = any(a.get("kind") == "lab_record" and (a.get("availability") or {}).get("level") not in (None, "public")
690
+ for a in P.artefacts)
691
+ return "lab · record withheld" if withheld else "lab"
692
+ return "native"
693
+
694
+
695
+ def origin(doc):
696
+ """Where a claimset comes from, as its label reads: `lab`, `lab · record withheld`, `converted` or `native`."""
697
+ return _origin(_Paper(doc))
698
+
699
+
700
+ def model_names(c, models):
701
+ """The models an agent contributor ran on, by name, as people know them ("Claude Opus 5.5"): its `models`
702
+ entries looked up in the claimset's `models` (claimset §3.12), each a name and a version (the version left out
703
+ when the name ends with it), in the order the agent lists them, each once. Plain text; [] when none is known."""
704
+ by_id = {m.get("id"): m for m in models or [] if isinstance(m, dict) and isinstance(m.get("id"), str)}
705
+ out = []
706
+ for use in c.get("models") or [] if isinstance(c.get("models"), list) else []:
707
+ m = by_id.get(use.get("model")) if isinstance(use, dict) else None
708
+ if not m or not isinstance(m.get("name"), str) or not m["name"].strip():
709
+ continue
710
+ name = m["name"].strip()
711
+ version = str(m["version"]).strip() if isinstance(m.get("version"), (str, int, float)) else ""
712
+ if version and not name.endswith(version):
713
+ name = f"{name} {version}"
714
+ if name not in out:
715
+ out.append(name)
716
+ return out
717
+
718
+
719
+ def agent_name(c, models):
720
+ """An agent contributor as the site names it (design §7.4): by the model it ran on, "Claude Opus 5.5" (several:
721
+ "Claude Opus 5.5 and GPT-6"); without a known model, by its own name. The harness it ran in is a detail of how
722
+ the paper was made (harness). Plain text, to be escaped."""
723
+ names = model_names(c, models)
724
+ if names:
725
+ return " and ".join(names)
726
+ return c["name"].strip() if isinstance(c.get("name"), str) and c["name"].strip() else "an AI agent"
727
+
728
+
729
+ def harness(c):
730
+ """The harness an agent ran in, with its version when recorded ("Claude Code 2.1"): its `system` (claimset
731
+ §3.11), else its name when a model names it; None when unknown. Plain text."""
732
+ system = c.get("system") if isinstance(c.get("system"), dict) else {}
733
+ name = system.get("name") if isinstance(system.get("name"), str) and system["name"].strip() else None
734
+ if name is None:
735
+ return None
736
+ version = system.get("version")
737
+ version = str(version).strip() if isinstance(version, (str, int, float)) else ""
738
+ return f"{name.strip()} {version}" if version and not name.strip().endswith(version) else name.strip()
739
+
740
+
741
+ def _person(c, verified=False):
742
+ name = esc(c.get("name", ""))
743
+ orcid = c.get("orcid")
744
+ if not isinstance(orcid, str) or not orcid:
745
+ return name
746
+ cls = "orcid orcid-verified" if verified else "orcid"
747
+ return (f'{name} <span class="orcid-wrap">(<a class="{cls}" href="https://orcid.org/{esc(orcid)}">'
748
+ f'{esc(orcid)}</a>)</span>')
749
+
750
+
751
+ def _author(c, P=None, where="author", models=None):
752
+ """A person or agent named in the header: the site's way (`person`, render_parts), or plain text: a person with
753
+ their ORCID link; an agent by agent_name, with its label after it (v0.41: `Claude Code · drafting`), and
754
+ "(AI agent)" only when no model names it (a model's name says what it is)."""
755
+ if P is not None:
756
+ models = P.doc.get("models")
757
+ if P is not None and P.person is not None:
758
+ shown = P.person(c, where)
759
+ if isinstance(shown, str):
760
+ return shown
761
+ if where == "guarantor":
762
+ return _person(c, True)
763
+ if c.get("type") == "agent":
764
+ label = c.get("label") if isinstance(c.get("label"), str) and c.get("label").strip() else None
765
+ ran = harness(c) if where == "credit" and model_names(c, models) else None
766
+ return (f'{esc(agent_name(c, models))}'
767
+ + (f' <span class="cs-label">· {esc(label.strip())}</span>' if label else "")
768
+ + (f' <span class="cs-label">in {esc(ran)}</span>' if ran else "")
769
+ + ("" if model_names(c, models) else " (AI agent)"))
770
+ return _person(c)
771
+
772
+
773
+ def _line(P, role, people, default):
774
+ """One line of people in the header: the site's (`byline`) or `default`."""
775
+ if getattr(P, "byline", None):
776
+ shown = P.byline(role, people)
777
+ if isinstance(shown, str):
778
+ return shown
779
+ return default
780
+
781
+
782
+ def _corrections(p):
783
+ """Where the claimset departs from what it restates (claimset spec §3.1): the corrections of a converted source, or
784
+ those of the published paper its authors converted; and the words for what they correct."""
785
+ if isinstance(p.get("converted_from"), dict):
786
+ found, against = p["converted_from"].get("corrections"), "the source paper"
787
+ elif isinstance(p.get("published_as"), dict):
788
+ found, against = p["published_as"].get("corrections"), "the published paper"
789
+ else:
790
+ return [], ""
791
+ if not isinstance(found, list):
792
+ return [], against
793
+ return [c for c in found if isinstance(c, dict) and isinstance(c.get("field"), str) and c["field"]], against
794
+
795
+
796
+ CORRECTION_WORDS = {"misprint": "misprint", "correction": "correction by the authors"}
797
+
798
+
799
+ def correction_id(P, corr):
800
+ """The anchor of a correction in the list of corrections: corr-<its number, from 1>. A link to it opens the
801
+ correction in a pop-up (page.js), on the paper view as on the record."""
802
+ return f"corr-{next(i for i, c in enumerate(P.corrections, 1) if c is corr)}"
803
+
804
+
805
+ def _corrected(P, oid):
806
+ """The note under an object the claimset corrects: what was printed, and a link to why, which opens the
807
+ correction in a pop-up (spec §3.1)."""
808
+ out = []
809
+ for corr in P.corrected.get(oid, []):
810
+ kind = CORRECTION_WORDS.get(corr.get("kind"), "corrected")
811
+ where = f", {P.text(corr['where'])}" if corr.get("where") else ""
812
+ out.append(f'<p class="cs-correction"><span class="k">Corrected from {P.against}</span> ({esc(kind)}{where}): '
813
+ f'printed {P.text(str(corr.get("printed", "")))}. '
814
+ f'<a href="#{correction_id(P, corr)}">Why</a></p>')
815
+ return "".join(out)
816
+
817
+
818
+ def _header(P):
819
+ p, out = P.paper, []
820
+ out.append(f'<h1 class="cs-title">{esc(p.get("title", ""))}</h1>')
821
+ people = [c for c in P.doc.get("contributors") or [] if isinstance(c, dict)]
822
+ guarantors = [c for c in people if "guarantor" in (c.get("positions") or [])]
823
+ if guarantors:
824
+ out.append('<p class="cs-guarantor">' + _line(P, "guarantor", guarantors, "Guarantor: " + ", ".join(
825
+ _author(g, P, "guarantor") for g in guarantors)) + "</p>")
826
+ cf = p.get("converted_from") if isinstance(p.get("converted_from"), dict) else None
827
+ if cf:
828
+ authors = [a for a in cf.get("source_authors") or [] if isinstance(a, dict)]
829
+ if authors:
830
+ source = [{**a, "type": "human"} for a in authors]
831
+ out.append('<p class="cs-authors">' + _line(P, "source_authors", source, "Authors of the source paper: "
832
+ + ", ".join(_author(a, P, "source_author") for a in source)) + "</p>")
833
+ converters = [c for c in people if "converter" in (c.get("positions") or [])]
834
+ by = ", ".join(_author(c, P, "converter") for c in converters)
835
+ src = _doi(cf.get("source_id")) if cf.get("id_type", "doi") == "doi" else esc(cf.get("source_id"))
836
+ out.append(f'<p class="cs-source">Converted from {src}'
837
+ + (f" ({esc(cf['source_version'])})" if cf.get("source_version") else "")
838
+ + (f" by {by}" if by else "") + "</p>")
839
+ else:
840
+ # People besides the responsible researcher (design §7.4): every author of the original paper, for a paper its
841
+ # authors converted, in the file's order; else the co-authors, those who supervised and those who contributed.
842
+ # The position `author` is for agents.
843
+ humans = [c for c in people if c.get("type") != "agent"]
844
+ if source_paper.own_paper(P.doc) and len(humans) > 1:
845
+ out.append('<p class="cs-authors">' + _line(P, "paper_authors", humans, "Authors of the original paper: "
846
+ + ", ".join(_author(c, P, "author") for c in humans)) + "</p>")
847
+ else:
848
+ for role, label, position in (("coauthors", "Co-authors: ", "coauthor"),
849
+ ("supervisors", "Supervised by: ", "supervisor"),
850
+ ("contributors", "Contributors: ", "contributor")):
851
+ group = [c for c in humans if position in (c.get("positions") or [])
852
+ and "guarantor" not in (c.get("positions") or [])]
853
+ if group:
854
+ out.append('<p class="cs-authors">' + _line(P, role, group, label
855
+ + ", ".join(_author(c, P, "author") for c in group)) + "</p>")
856
+ authors = [c for c in people if "author" in (c.get("positions") or [])]
857
+ if authors:
858
+ out.append('<p class="cs-authors">' + _line(P, "authors", authors, "Authors: "
859
+ + ", ".join(_author(c, P) for c in authors)) + "</p>")
860
+ kw = (p.get("classification") or {}).get("keywords") if isinstance(p.get("classification"), dict) else None
861
+ meta = [esc(p["licence"]) if p.get("licence") else "",
862
+ ("Keywords: " + esc(", ".join(k for k in kw if isinstance(k, str)))) if isinstance(kw, list) and kw else ""]
863
+ if isinstance(P.doc.get("extensions"), dict) and P.doc["extensions"]:
864
+ meta.append("Extensions: " + esc(", ".join(f"{k} {v}" for k, v in P.doc["extensions"].items())))
865
+ meta = [m for m in meta if m]
866
+ credit = _contributions(people, P.doc.get("models"), P) # beside the people it details (design §7.4)
867
+ if credit:
868
+ out.append(credit)
869
+ if meta:
870
+ out.append('<p class="cs-meta">' + " · ".join(meta) + "</p>")
871
+ if P.corrections:
872
+ # each place a link that opens its correction in a pop-up (page.js): what was printed, what is stated, why
873
+ n = len(P.corrections)
874
+ oids = [corr["field"].split(".")[0] for corr in P.corrections]
875
+ seen = {}
876
+
877
+ def label(oid): # an object corrected twice: E2 (1), E2 (2)
878
+ seen[oid] = seen.get(oid, 0) + 1
879
+ return f"{oid} ({seen[oid]})" if oids.count(oid) > 1 else oid
880
+ places = ", ".join(f'<a href="#{correction_id(P, corr)}">{esc(label(oid))}</a>'
881
+ for corr, oid in zip(P.corrections, oids, strict=True))
882
+ out.append(f'<p class="cs-correction">This claimset corrects {P.against} in {n} place{"s" if n != 1 else ""}: '
883
+ f'{places}.</p>')
884
+ return "\n".join(out)
885
+
886
+
887
+ #: CRediT roles by their names in the taxonomy (claimset spec §3.3, `credit_roles`).
888
+ CREDIT_NAMES = {"conceptualization": "Conceptualization", "data_curation": "Data curation",
889
+ "formal_analysis": "Formal analysis", "funding_acquisition": "Funding acquisition",
890
+ "investigation": "Investigation", "methodology": "Methodology",
891
+ "project_administration": "Project administration", "resources": "Resources",
892
+ "software": "Software", "supervision": "Supervision", "validation": "Validation",
893
+ "visualization": "Visualization", "writing_original_draft": "Writing – original draft",
894
+ "writing_review_editing": "Writing – review & editing"}
895
+
896
+
897
+ def _contributions(people, models=None, P=None):
898
+ """The fold *Contributions* under the names (design §5.2): each contributor's CRediT roles, as the file states
899
+ them; nothing when no contributor has any."""
900
+ rows = []
901
+ for c in people:
902
+ roles = [r for r in c.get("credit_roles") or [] if isinstance(r, str)]
903
+ if roles:
904
+ names = ", ".join(esc(CREDIT_NAMES.get(r, r.replace("_", " ").capitalize())) for r in roles)
905
+ rows.append(f"<li>{_author(c, P, 'credit', models=models)}: {names}</li>") # the site's, with icons
906
+ if not rows:
907
+ return ""
908
+ return ('<details class="cs-credit"><summary>Contributions</summary><ul>' + "".join(rows) + "</ul></details>")
909
+
910
+
911
+ def _support(P, c):
912
+ parts = []
913
+ for s in c.get("support") or []:
914
+ if not isinstance(s, dict) or s.get("kind") == "assumption":
915
+ continue
916
+ label = SUPPORT_LABELS.get(s.get("kind"), esc(s.get("kind")))
917
+ ptr = []
918
+ if s.get("evidence"):
919
+ e = s["evidence"]
920
+ res = [r[len(e) + 1:] if isinstance(r, str) and r.startswith(f"{e}.") else r for r in s.get("results") or []]
921
+ ptr.append(f'<a href="#{esc(e)}">{esc(e)}</a>' + (f" ({esc(', '.join(map(str, res)))})" if res else ""))
922
+ if s.get("warrant"):
923
+ ptr.append(f'<a href="#{esc(s["warrant"])}">{esc(s["warrant"])}</a>')
924
+ if s.get("reference"):
925
+ ptr.append(P.ref(s["reference"], s.get("locator")))
926
+ elif s.get("target"):
927
+ ptr.append(_target(s["target"], s.get("id_type")))
928
+ if s.get("artefacts"):
929
+ ptr.append("artefacts " + P.ids(s["artefacts"]))
930
+ if s.get("self"):
931
+ ptr.append("own earlier work")
932
+ parts.append(f"{label}: " + ", ".join(ptr) if ptr else label)
933
+ return parts
934
+
935
+
936
+ def _scope(sc):
937
+ """A claim's scope in words: "data: M4 yearly series; conditions: backcasting, smooth 1.3.0"."""
938
+ if not isinstance(sc, dict):
939
+ return ""
940
+ out = []
941
+ for k, v in sc.items():
942
+ vals = v if isinstance(v, list) else [v]
943
+ vals = [_s(x) for x in vals if x not in (None, "")]
944
+ if vals:
945
+ out.append(f"{SCOPE_WORDS.get(k, _words(k))}: " + ", ".join(vals))
946
+ return "; ".join(out)
947
+
948
+
949
+ def _words(x):
950
+ """A value of the file's vocabularies as words: code_changed_after_plan -> code changed after plan."""
951
+ return _s(x).replace("_", " ")
952
+
953
+
954
+ def _date(x):
955
+ """An ISO date or time as a reader's date: 2026-11-05T11:37:01Z -> 5 November 2026; anything else as written."""
956
+ m = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})(?:[T ].*)?", _s(x).strip())
957
+ if not m or not 1 <= int(m.group(2)) <= 12:
958
+ return _s(x)
959
+ return f"{int(m.group(3))} {MONTHS[int(m.group(2)) - 1]} {m.group(1)}"
960
+
961
+
962
+ def _claim(P, c, principal=False):
963
+ head = [P.claim_id(c), esc(c.get("type"))]
964
+ before, after = P.mark(c, "claim")
965
+ # The novelty once: the site's marker gives it after the meta line ("novelty: …, by the authors", with the
966
+ # close-match check); without one (no scores), the meta line names it.
967
+ if NOVELTY_WORDS.get(c.get("novelty")) and "novelty" not in (after or ""):
968
+ head.append(NOVELTY_WORDS[c["novelty"]])
969
+ if c.get("planning") == "confirmatory":
970
+ head.append("planned test")
971
+ elif c.get("planning") == "planned_estimate":
972
+ head.append("planned estimate")
973
+ lines = [f'<p class="cs-claim-meta">{before}' + " · ".join(h for h in head if h) + f"{after}</p>",
974
+ f'<p class="cs-statement">{P.statement(c.get("statement", ""))}</p>' + _corrected(P, c.get("id"))]
975
+ links = []
976
+ if c.get("scope"):
977
+ links.append(f'<span class="k">Scope:</span> {P.text(_scope(c["scope"]))}')
978
+ sup = _support(P, c)
979
+ if sup:
980
+ links.append(" · ".join(sup))
981
+ if c.get("depends_on"):
982
+ links.append('<span class="k">Uses:</span> ' + P.ids(c["depends_on"]))
983
+ if c.get("assumptions"):
984
+ links.append('<span class="k">Assumes:</span> ' + P.ids(c["assumptions"]))
985
+ if c.get("limitations"):
986
+ links.append('<span class="k">Limitations:</span> ' + P.ids(c["limitations"]))
987
+ rels = []
988
+ for rel in c.get("relations") or []:
989
+ if not isinstance(rel, dict):
990
+ continue
991
+ target = (P.ref(rel["reference"], rel.get("locator")) if rel.get("reference")
992
+ else P.ids([rel.get("target")]) if rel.get("id_type") == "local"
993
+ else _target(rel.get("target"), rel.get("id_type")))
994
+ rels.append(f'<span class="k">{esc(str(rel.get("type", "")).replace("_", " ").capitalize())}:</span> {target}')
995
+ links += rels
996
+ if c.get("warrant"):
997
+ links.append('<span class="k">Warrant:</span> ' + P.ids([c["warrant"]]))
998
+ if c.get("verification"):
999
+ links.append(f'<span class="k">Verification:</span> '
1000
+ f'{esc(VERIFICATION_WORDS.get(c["verification"], _words(c["verification"])))}')
1001
+ t = c.get("test")
1002
+ if isinstance(t, dict):
1003
+ plan = _join([f"lab plan {t['lab_plan']}" if t.get("lab_plan") else "",
1004
+ f"registered {t['registration']}" if t.get("registration") else "",
1005
+ f"planned {_date(c['planned_at'])}" if c.get("planned_at") else ""], ", ")
1006
+ if plan:
1007
+ links.append(f'<span class="k">Planned:</span> {esc(plan)}')
1008
+ if t.get("verdict"):
1009
+ links.append(f'<span class="k">Outcome:</span> {esc(VERDICT_WORDS.get(t["verdict"], _words(t["verdict"])))}')
1010
+ if t.get("flags"):
1011
+ links.append('<span class="k">Weaknesses:</span> '
1012
+ + esc("; ".join(FLAG_WORDS.get(f, _words(f)) for f in t["flags"])))
1013
+ e = c.get("estimate")
1014
+ if isinstance(e, dict):
1015
+ plan = _join([f"lab plan {e['lab_plan']}" if e.get("lab_plan") else "",
1016
+ f"registered {e['registration']}" if e.get("registration") else "",
1017
+ f"planned {_date(c['planned_at'])}" if c.get("planned_at") else ""], ", ")
1018
+ if plan:
1019
+ links.append(f'<span class="k">Planned:</span> {esc(plan)}')
1020
+ if e.get("not_obtained"):
1021
+ links.append('<span class="k">Not obtained:</span> ' + esc(", ".join(map(str, e["not_obtained"]))))
1022
+ if e.get("flags"):
1023
+ links.append('<span class="k">Weaknesses:</span> '
1024
+ + esc("; ".join(FLAG_WORDS.get(f, _words(f)) for f in e["flags"])))
1025
+ if not principal:
1026
+ used = P.users(c["id"])
1027
+ if used:
1028
+ links.append(f'<span class="k">Used by:</span> {used}')
1029
+ if links:
1030
+ lines.append('<p class="cs-links">' + " · ".join(links) + "</p>")
1031
+ # what went into it (design §7.6)
1032
+ lines.append(earlier_block(P.not_claimed, c["id"], P.text, P.lab_record, P.hypotheses))
1033
+ return f'<div class="cs-item cs-claim" id="{esc(c["id"])}">' + "".join(lines) + "</div>"
1034
+
1035
+
1036
+ def _def_tables(text, d):
1037
+ """The tables by which a definition specifies its term (claimset §3.2, `tables`, as amended on 2026-11-23): each a
1038
+ caption and a table of text cells, mathematics shown as the definition's text is. '' without tables."""
1039
+ out = []
1040
+ for t in d.get("tables") or []:
1041
+ if not isinstance(t, dict) or not isinstance(t.get("columns"), list) or not isinstance(t.get("rows"), list):
1042
+ continue
1043
+ rows = [r for r in t["rows"] if isinstance(r, list)]
1044
+ out.append('<div class="cs-table cs-def-table"><table>'
1045
+ + (f"<caption>{text(t['description'])}</caption>" if isinstance(t.get("description"), str) else "")
1046
+ + "<thead><tr>" + "".join(f'<th scope="col">{text(str(c))}</th>' for c in t["columns"])
1047
+ + "</tr></thead><tbody>"
1048
+ + "".join("<tr>" + "".join(f"<td>{text(str(x))}</td>" for x in r) + "</tr>" for r in rows)
1049
+ + "</tbody></table></div>")
1050
+ return "".join(out)
1051
+
1052
+
1053
+ def _definition(P, d, nested=False):
1054
+ head = f'<span class="cs-id">{esc(d["id"])}</span>'
1055
+ rel = []
1056
+ for key, label in (("part_of", "part of"), ("broader", "a kind of")):
1057
+ if d.get(key):
1058
+ rel.append(f"{label} " + P.ids(d[key] if isinstance(d[key], list) else [d[key]]))
1059
+ tail = []
1060
+ if d.get("members"):
1061
+ tail.append("Members: " + P.ids(d["members"]))
1062
+ if d.get("assumptions"):
1063
+ tail.append("Assumes " + P.ids(d["assumptions"]))
1064
+ src = d.get("source")
1065
+ if src:
1066
+ rid = src.get("reference") if isinstance(src, dict) else src
1067
+ tail.append("Source: " + (P.ref(rid) if rid in P.labels else esc(rid if isinstance(rid, str) else src)))
1068
+ if d.get("identifiers"):
1069
+ tail.append("Identifiers: " + esc(", ".join(map(str, d["identifiers"]))))
1070
+ cls = "cs-def cs-def-nested" if nested else "cs-def"
1071
+ return (f'<div class="{cls}" id="{esc(d["id"])}"><p><span class="cs-def-head">{head}'
1072
+ + (f' · {" · ".join(rel)}' if rel and nested else "")
1073
+ + f' <strong>{esc(d.get("term", ""))}</strong></span>: {P.text(d.get("definition", ""))}'
1074
+ + (f' <span class="cs-tail">{". ".join(tail)}.</span>' if tail else "") + "</p>"
1075
+ + _def_tables(P.text, d) + _corrected(P, d.get("id")) + "</div>")
1076
+
1077
+
1078
+ def _definitions(P):
1079
+ if not P.defs:
1080
+ return ""
1081
+ ids = {d["id"] for d in P.defs}
1082
+ parent = {}
1083
+ for d in P.defs:
1084
+ for key in ("part_of", "broader"):
1085
+ v = d.get(key)
1086
+ v = v[0] if isinstance(v, list) and v else v
1087
+ if isinstance(v, str) and v in ids and P.by_id[v].get("kind") == d.get("kind"):
1088
+ parent[d["id"]] = v
1089
+ break
1090
+ kids = {}
1091
+ for cid, pid in parent.items():
1092
+ kids.setdefault(pid, []).append(cid)
1093
+ out = ['<section class="cs-section" id="definitions"><h2>Definitions</h2>']
1094
+ for kind, heading in KIND_GROUPS + [(None, "Other terms")]:
1095
+ group = [d for d in P.defs if (d.get("kind") == kind if kind else d.get("kind") not in dict(KIND_GROUPS))]
1096
+ if not group:
1097
+ continue
1098
+ out.append(f'<h3>{heading} <span class="count">{len(group)}</span></h3>')
1099
+
1100
+ def tree(d, depth=0):
1101
+ yield _definition(P, d, nested=depth > 0)
1102
+ for k in kids.get(d["id"], []):
1103
+ yield from tree(P.by_id[k], depth + 1)
1104
+ for d in group:
1105
+ if d["id"] not in parent:
1106
+ out += list(tree(d))
1107
+ out.append("</section>")
1108
+ return "\n".join(out)
1109
+
1110
+
1111
+ #: A table longer than this many rows starts folded on the page, showing its first SHOWN_ROWS rows and the rows a claim
1112
+ #: cites (page.js; without the script every row shows). The file and the reading view for models keep every row.
1113
+ LONG_TABLE, SHOWN_ROWS = 12, 8
1114
+ #: An evidence table starts closed, under a line with its ID, description and size, except a table of fewer than this
1115
+ #: many rows in the main evidence of the claim shown (design §7.4, *Tables*).
1116
+ SMALL_TABLE = 10
1117
+
1118
+
1119
+ def main_evidence(c):
1120
+ """The ID of a claim's main evidence, the evidence of its first support entry, or None."""
1121
+ support = c.get("support") if isinstance(c, dict) else None
1122
+ first = support[0] if isinstance(support, list) and support else None
1123
+ ev = first.get("evidence") if isinstance(first, dict) else None
1124
+ return ev if isinstance(ev, str) else None
1125
+
1126
+
1127
+ #: The verdicts that give no claim (claimset §3.1.1, `exploration.not_claimed`), in plain words (design §7.6, *Not
1128
+ #: claimed*): a formal verdict's supported is proved; a void plan (`because: defective`) is named so, whatever its verdict.
1129
+ NOT_CLAIMED_VERDICT = {"supported": "proved", "not_supported": "not proved",
1130
+ "inconclusive": "tried by proof, inconclusive"}
1131
+ NOT_CLAIMED_BECAUSE = {"reworded": "then reworded", "revised": "then merged", "abandoned": "then dropped",
1132
+ "defective": "repeated"}
1133
+ #: What an entry with neither `statement` nor `why` reads: never its lab ID.
1134
+ NOT_CLAIMED_FALLBACK = {"reworded": "An earlier wording of this claim", "revised": "A hypothesis merged into this claim",
1135
+ "abandoned": "A dropped hypothesis", "defective": "A void plan"}
1136
+ #: A lab record's event ID (lab record §4.2, §5): a writer's prefix (an agent's `AC2.`, a contributor's ORCID iD or
1137
+ #: `github-<account>.`), the event's type prefix and number, and a revision suffix (`.R2`, §4.3). A list of them
1138
+ #: ("H1, H2 and RN3") is taken as one.
1139
+ _LAB_ONE = (r"(?:(?:AC\d+|\d{4}-\d{4}-\d{4}-\d{3}[\dX]|github-[a-z0-9-]+)\.)?"
1140
+ r"(?:AC|AP|AR|AS|CD|CK|DC|DV|EX|H|MG|MV|NT|PA|PL|Q|RN|RS|SR|ST|TM)\d+(?:\.R\d+)?")
1141
+ LAB_ID = re.compile(_LAB_ONE)
1142
+ LAB_IDS = re.compile(rf"(?<![\w.-])(?P<word>(?i:hypothes[ie]s)\s+)?(?P<ids>{_LAB_ONE}"
1143
+ rf"(?:(?:\s*,\s*|\s+(?:and|or)\s+|\s*&\s*){_LAB_ONE})*)(?![\w])")
1144
+ #: A word that only introduced an ID taken out at the end of a clause ("decided again under PL8."): it goes too.
1145
+ _LEFT_BARE = re.compile(r"\s*\b(?:see|under|per|in|by|from|as|at|with|via|of|to|cf\.)\s*\x03[\s\x03]*(?=[,.;:)]|$)",
1146
+ re.I)
1147
+ #: The longest `why` shown whole; a longer one is cut at the first sentence end after this many characters.
1148
+ WHY_SHOWN = 200
1149
+
1150
+
1151
+ def _lab_root(i):
1152
+ """A lab ID without its revision suffix: `AC2.H4.R2` → `AC2.H4`."""
1153
+ return re.sub(r"\.R\d+$", "", i)
1154
+
1155
+
1156
+ def hypothesis_claims(claims):
1157
+ """{lab hypothesis ID → claim ID} of a paper's claims (`hypothesis.lab_event`, claimset §3.3.3), by the root ID
1158
+ and, without a writer's prefix, by the bare ID too."""
1159
+ found = {}
1160
+ for c in claims:
1161
+ h = c.get("hypothesis") if isinstance(c.get("hypothesis"), dict) else {}
1162
+ ev = h.get("lab_event")
1163
+ if isinstance(ev, str) and isinstance(c.get("id"), str):
1164
+ root = _lab_root(ev)
1165
+ found.setdefault(root, c["id"])
1166
+ found.setdefault(root.rsplit(".", 1)[-1], c["id"])
1167
+ return found
1168
+
1169
+
1170
+ def clean_why(why, hyps):
1171
+ """A `why` without its lab IDs, for display (design §7.6, *Not claimed*): (text, IDs taken out). A hypothesis of
1172
+ this paper becomes its claim's ID, marked "\x01C4\x02" for the caller to link; another hypothesis becomes "another
1173
+ hypothesis" (nothing after the word *hypothesis*); every other ID is dropped, with the spaces and punctuation it
1174
+ leaves."""
1175
+ removed = []
1176
+
1177
+ def one(m):
1178
+ claims, others = [], 0
1179
+ for i in LAB_ID.findall(m.group("ids")):
1180
+ root = _lab_root(i)
1181
+ cid = hyps.get(root) or hyps.get(root.rsplit(".", 1)[-1])
1182
+ if cid:
1183
+ if cid not in claims:
1184
+ claims.append(cid)
1185
+ continue
1186
+ removed.append(i)
1187
+ others += re.sub(r"\d.*", "", root.rsplit(".", 1)[-1]) == "H"
1188
+ words = [f"\x01{c}\x02" for c in claims]
1189
+ if others:
1190
+ words.append("another hypothesis" if others == 1 else "other hypotheses")
1191
+ elif m.group("word") and not claims:
1192
+ words.append(m.group("word").strip()) # "hypothesis" of a dropped non-hypothesis ID
1193
+ return " and ".join(words) or "\x03"
1194
+
1195
+ text = LAB_IDS.sub(one, why)
1196
+ text = re.sub(r"\s*\([\s,;:\x03]*\)", "\x03", text) # brackets left empty
1197
+ text = _LEFT_BARE.sub("", text).replace("\x03", "")
1198
+ text = re.sub(r"([,;:])(?:\s*[,;:])+", r"\1", text) # punctuation doubled
1199
+ text = re.sub(r"[,;:]+(?=\s*[.)])", "", text)
1200
+ text = re.sub(r"\(\s+", "(", text)
1201
+ text = re.sub(r"\s+([,.;:)])", r"\1", text)
1202
+ text = re.sub(r"[ \t]{2,}", " ", text).strip()
1203
+ text = re.sub(r"^[,;:.]\s*", "", text)
1204
+ text = re.sub(r"[,;:]+(?=\.?$)", "", text)
1205
+ text = text[:1].upper() + text[1:] # a clause that lost its opening ID
1206
+ out = []
1207
+ for i in removed:
1208
+ if i not in out:
1209
+ out.append(i)
1210
+ return text, out
1211
+
1212
+
1213
+ def _cut(text, limit=WHY_SHOWN):
1214
+ """The text cut at the first sentence end after `limit` characters (or, with none soon after, at a word), with
1215
+ "…"; whole when it is not longer."""
1216
+ if len(text) <= limit:
1217
+ return text
1218
+ m = re.compile(r"[.!?](?=\s|$)").search(text, limit)
1219
+ cut = text[:m.end()] if m and m.end() <= limit + 150 else text[:limit].rsplit(" ", 1)[0].rstrip(",;:")
1220
+ return cut + " …" if len(cut) < len(text) else text
1221
+
1222
+
1223
+ def not_claimed_entries(doc):
1224
+ """The entries of `paper.exploration.not_claimed` (claimset §3.1.1), [] when there are none."""
1225
+ p = doc.get("paper") if isinstance(doc.get("paper"), dict) else {}
1226
+ ex = p.get("exploration") if isinstance(p.get("exploration"), dict) else {}
1227
+ items = ex.get("not_claimed")
1228
+ return [x for x in items if isinstance(x, dict)] if isinstance(items, list) else []
1229
+
1230
+
1231
+ def lab_record_uri(doc):
1232
+ """The address of the paper's lab record (its first artefact of kind `lab_record` at an http(s) address), or None."""
1233
+ for a in doc.get("artefacts") or []:
1234
+ if isinstance(a, dict) and a.get("kind") == "lab_record" and _href(a.get("uri")):
1235
+ return a["uri"]
1236
+ return None
1237
+
1238
+
1239
+ def not_claimed_item(x, text, lab=None, hyps=None, claim_href=None):
1240
+ """One entry of `not_claimed` as a list item (design §7.6, *Not claimed*): what its verdict decided (`statement`,
1241
+ written by `text`, maths as formulae; or else its `why` cleaned of lab IDs, a hypothesis of this paper as a link to
1242
+ its claim, `hyps` {lab ID → claim ID}, at `claim_href(cid)`), the verdict and the reason, and a link to the lab
1243
+ record whose tooltip alone names the lab IDs."""
1244
+ because = x.get("because")
1245
+ st, why = x.get("statement"), x.get("why")
1246
+ href = claim_href or (lambda cid: f"#{cid}")
1247
+ removed, title = [], ""
1248
+ if isinstance(st, str) and st.strip():
1249
+ what = text(st)
1250
+ elif isinstance(why, str) and why.strip():
1251
+ full, removed = clean_why(why.strip(), hyps or {})
1252
+ shown = _cut(full)
1253
+ if shown != full:
1254
+ title = f' title="{esc(full.replace(chr(1), "").replace(chr(2), ""))}"'
1255
+ what = "".join(text(part) if i % 2 == 0 else f'<a href="{esc(href(part))}">{esc(part)}</a>'
1256
+ for i, part in enumerate(re.split("\x01(C\\d+)\x02", shown)) if part)
1257
+ elif because == "revised" and not x.get("into"):
1258
+ what = "A hypothesis merged into another"
1259
+ else:
1260
+ what = esc(NOT_CLAIMED_FALLBACK.get(because, "A planned test"))
1261
+ verdict = ("void plan" if because == "defective"
1262
+ else NOT_CLAIMED_VERDICT.get(x.get("outcome"), _words(x.get("outcome") or "")))
1263
+ tail = ", ".join(w for w in (verdict, NOT_CLAIMED_BECAUSE.get(because, "")) if w)
1264
+ ids = " under ".join(x[k] for k in ("lab_event", "lab_plan") if isinstance(x.get(k), str) and x[k])
1265
+ more = [i for i in removed if i not in (x.get("lab_event"), x.get("lab_plan"))]
1266
+ ids = "; ".join(t for t in (ids, ", ".join(more)) if t)
1267
+ link = (f' <a class="nc-lab" href="{esc(lab)}" title="{esc(ids)}">lab record</a>' if lab else "")
1268
+ return (f'<li><span class="nc-what"{title}>{what}</span> <span class="nc-tail">— {esc(tail)}</span>{link}'
1269
+ "</li>")
1270
+
1271
+
1272
+ def earlier_block(entries, cid, text, lab=None, hyps=None, claim_href=None):
1273
+ """Under a claim, the entries of `not_claimed` that went into it, folded: "Earlier wordings (2)". "" when none."""
1274
+ mine = [x for x in entries if x.get("into") == cid]
1275
+ if not mine:
1276
+ return ""
1277
+ kinds = {x.get("because") for x in mine}
1278
+ title = ("Earlier wordings" if kinds == {"reworded"} else "Merged hypotheses" if kinds == {"revised"}
1279
+ else "Earlier wordings and merged hypotheses")
1280
+ return (f'<details class="cs-earlier"><summary>{title} ({len(mine)})</summary><ul>'
1281
+ + "".join(not_claimed_item(x, text, lab, hyps, claim_href) for x in mine) + "</ul></details>")
1282
+
1283
+
1284
+ def _plural(n, word):
1285
+ return f"{n} {word}{'' if n == 1 else 's'}"
1286
+
1287
+
1288
+ def _file_table(P, eid, t, head, caption):
1289
+ """A table whose rows are held in a file of the package (claimset §3.4, *Tables held in a file*: `rows_file`, the
1290
+ data artefact whose CSV file holds them, and `n_rows`): its description, its columns and a link that downloads
1291
+ the file. The page never reads the file. (`artefact` keeps its own meaning, the source of the full table.)"""
1292
+ a = P.by_id.get(t["rows_file"])
1293
+ n = t.get("n_rows")
1294
+ size = [_plural(n, "row")] if isinstance(n, int) and not isinstance(n, bool) else []
1295
+ size.append(_plural(len(t.get("columns") or []), "column"))
1296
+ uri = a.get("uri") if a in P.artefacts else None
1297
+ if _href(uri):
1298
+ where = (f'<a class="cs-download" href="{esc(uri)}" download>Download the rows (CSV)</a> '
1299
+ f'<span class="cs-id">{esc(t["rows_file"])}</span>')
1300
+ else: # a preview, which serves no files: the artefact by its ID
1301
+ where = "In the package's file " + P.ids([t["rows_file"]])
1302
+ return (f'<div class="cs-table cs-table-file" id="{esc(eid)}.{esc(t.get("id", ""))}">'
1303
+ f'<p class="cs-table-caption">{caption} <span class="cs-size">({" × ".join(size)})</span></p>'
1304
+ f'<p class="cs-links"><span class="k">Columns:</span> {" · ".join(head)}</p>'
1305
+ f'<p class="cs-links">{where}</p></div>')
1306
+
1307
+
1308
+ def _table(P, eid, t, main=None):
1309
+ """An evidence table. It starts closed (a <details> whose line names it and its size), except a small table of
1310
+ the main evidence of the claim shown: `main` says whether `eid` is that evidence (by default, whether it is the
1311
+ main evidence of a claim the page shows, P.main). A table whose rows are in a file links to the file."""
1312
+ cols = [P.column(c) for c in t.get("columns") or []]
1313
+ units = t.get("units")
1314
+ if isinstance(units, list):
1315
+ cols = [f"{c} ({esc(u)})" if u else c for c, u in zip(cols, units, strict=False)]
1316
+ head = ["Row"] + [P.term(x) for x in t.get("row_labels") or []] + cols
1317
+ caption = (f"{esc(eid)}.{esc(t.get('id'))} · {P.text(t.get('description', ''))}"
1318
+ + (f" {P.conditions(t.get('conditions'))}" if t.get("conditions") else ""))
1319
+ if not isinstance(t.get("rows"), list) and isinstance(t.get("rows_file"), str):
1320
+ return _file_table(P, eid, t, head[1:], caption)
1321
+ rows = []
1322
+ all_rows = [r for r in t.get("rows") or [] if isinstance(r, dict)]
1323
+ long = len(all_rows) > LONG_TABLE
1324
+ for i, r in enumerate(all_rows):
1325
+ if isinstance(r, dict):
1326
+ labels = [P.term(x) for x in r.get("label") or []]
1327
+ vals = r.get("values") or []
1328
+ rid = f"{eid}.{t.get('id', '')}.{r.get('id', '')}"
1329
+ more = ' class="cs-more"' if long and i >= SHOWN_ROWS and rid not in P.cited_rows else ""
1330
+ rows.append(f'<tr id="{esc(rid)}"{more}>'
1331
+ + f'<th scope="row">{esc(r.get("id", ""))}{esc(_stat_note(r))}</th>'
1332
+ + "".join(f"<td>{x}</td>" for x in labels)
1333
+ + "".join(_cell(P, v) for v in vals) + "</tr>")
1334
+ cls, toggle = "cs-table", ""
1335
+ if long:
1336
+ cls += " cs-table-long"
1337
+ toggle = (f'<button type="button" class="button-quiet cs-rows-toggle" hidden '
1338
+ f'data-all="Show all {len(all_rows)} rows" data-fewer="Show fewer rows">Show all {len(all_rows)} rows'
1339
+ f'</button>')
1340
+ table = (f'<div class="{cls}" id="{esc(eid)}.{esc(t.get("id", ""))}"><table><caption>{caption}</caption>'
1341
+ "<thead><tr>" + "".join(f'<th scope="col">{h}</th>' for h in head) + "</tr></thead>"
1342
+ "<tbody>" + "".join(rows) + f"</tbody></table>{toggle}</div>")
1343
+ if (eid in P.main if main is None else main) and len(all_rows) < SMALL_TABLE:
1344
+ return table
1345
+ size = f"{_plural(len(all_rows), 'row')} × {_plural(len(t.get('columns') or []), 'column')}"
1346
+ return (f'<details class="cs-table-fold"><summary>{caption} <span class="cs-size">({size})</span></summary>'
1347
+ f"{table}</details>")
1348
+
1349
+
1350
+ def _result(P, e, r, ids=True):
1351
+ """One result of an evidence object, as a list item; without `ids` it carries no ID of its own in the page (the
1352
+ paper view shows a result where a claim cites it, and the record page holds it)."""
1353
+ stat = _statistic(r.get("statistic"))
1354
+ more = esc(_join([_uncertainty(r.get("uncertainty")), r.get("unit"), _interval(r.get("interval")),
1355
+ f"n {_num(r['n'])}" if r.get("n") is not None else ""], " "))
1356
+ cond = P.conditions(r.get("conditions"))
1357
+ var = r.get("variable")
1358
+ shown = P.term(var) if isinstance(var, str) and var in P.by_id else P.text(_s(var))
1359
+ rid = f' id="{esc(e["id"])}.{esc(r.get("id", ""))}"' if ids else ""
1360
+ return (f'<li{rid}><span class="cs-id">{esc(r.get("id", ""))}</span> '
1361
+ f'{shown}{(" (" + esc(stat) + ")") if stat else ""} = '
1362
+ f'{"about " if r.get("approximate") is True else ""}{P.value(r.get("value"))}'
1363
+ f'{(" " + more) if more.strip() else ""}{(" " + cond) if cond else ""}</li>')
1364
+
1365
+
1366
+ def _evidence(P, e, source_link):
1367
+ head = [esc(e["id"]), esc(e.get("profile"))]
1368
+ for key in ("design", "data_origin", "analytic_approach", "sampling"):
1369
+ if e.get(key):
1370
+ head.append(esc(_s(e[key]).replace("_", " ")))
1371
+ if e.get("n") is not None:
1372
+ head.append(f"n {esc(_num(e['n']))}")
1373
+ if e.get("preregistered"):
1374
+ head.append("preregistered")
1375
+ cited = P.users(e["id"])
1376
+ if cited:
1377
+ head.append(f"cited by {cited}")
1378
+ out = [f'<p class="cs-claim-meta">{" · ".join(head)}</p>', f'<p>{P.text(e.get("description", ""))}</p>'
1379
+ + _corrected(P, e.get("id"))]
1380
+ setup = e.get("setup") if isinstance(e.get("setup"), dict) else {}
1381
+ parts = [f"{role} " + ", ".join(P.term(x) for x in setup[role]) for role in ("studied", "cases", "procedure", "lens", "context")
1382
+ if isinstance(setup.get(role), list) and setup[role]]
1383
+ if parts:
1384
+ out.append(f'<p class="cs-links"><span class="k">Setup:</span> {" · ".join(parts)}</p>')
1385
+ extra = []
1386
+ if e.get("foundation"):
1387
+ extra.append(f'<span class="k">Foundation:</span> {P.text(e["foundation"])}')
1388
+ if e.get("assumptions"):
1389
+ extra.append('<span class="k">Assumes:</span> ' + P.ids(e["assumptions"]))
1390
+ if e.get("checker"):
1391
+ extra.append(f'<span class="k">Checked by:</span> {esc(e["checker"])}')
1392
+ if e.get("proof_artefact"):
1393
+ extra.append('<span class="k">Proof:</span> ' + P.ids([e["proof_artefact"]]))
1394
+ if e.get("profile") == "formal" and not e.get("steps") and not e.get("proof_artefact") and e.get("source_spans"):
1395
+ extra.append(f'<span class="k">Derivation:</span> in the source{(", " + source_link) if source_link else ""}')
1396
+ if extra:
1397
+ out.append('<p class="cs-links">' + " · ".join(extra) + "</p>")
1398
+ if e.get("estimate") is not None:
1399
+ out.append(f'<p>{P.text(e.get("estimand", ""))} = {esc(_num(e["estimate"]))} '
1400
+ f'{esc(_uncertainty(e.get("uncertainty")))} {esc(_interval(e.get("interval")))}</p>')
1401
+ # figures before the numbers: a reader sees the pattern first, then the values behind it (design §7.6)
1402
+ figures = P.figures_of(e)
1403
+ if figures:
1404
+ many = " cs-figures-many" if len(figures) > 3 else ""
1405
+ out.append(f'<div class="cs-figures{many}">' + "".join(P.figure(a) for a in figures) + "</div>")
1406
+ results = [_result(P, e, r) for r in e.get("results") or [] if isinstance(r, dict)]
1407
+ if results:
1408
+ out.append('<ul class="cs-results">' + "".join(results) + "</ul>")
1409
+ for t in e.get("tables") or []:
1410
+ if isinstance(t, dict):
1411
+ out.append(_table(P, e["id"], t))
1412
+ steps = [s for s in e.get("steps") or [] if isinstance(s, dict)]
1413
+ if steps:
1414
+ out.append('<ol class="cs-steps">' + "".join(
1415
+ f'<li id="{esc(e["id"])}.{esc(s.get("id", ""))}">{P.step(s.get("statement", ""))}'
1416
+ f' <span class="cs-tail">({P.text(s.get("rule", ""))}'
1417
+ f'{"; from " + P.ids(s["by"]) if s.get("by") else ""})</span></li>' for s in steps) + "</ol>")
1418
+ for x in e.get("records") or []:
1419
+ if isinstance(x, dict):
1420
+ out.append(f'<p class="cs-links"><span class="k">Record:</span> {esc(x.get("kind"))}'
1421
+ f'{" in " + P.ids([x["artefact"]]) if x.get("artefact") else ""} · {P.text(x.get("description", ""))}</p>')
1422
+ return f'<div class="cs-item cs-evidence" id="{esc(e["id"])}">' + "".join(out) + "</div>"
1423
+
1424
+
1425
+ def _correction_item(P, corr):
1426
+ """One correction in the paper's list (spec §3.1): what it corrects, where in the paper, what was printed, what is
1427
+ stated instead, why, and who found it. Its anchor (correction_id) is what the links to it open."""
1428
+ oid = corr["field"].split(".")[0]
1429
+ head = [P.ids([oid]) if oid in P.by_id else esc(oid), esc(CORRECTION_WORDS.get(corr.get("kind"), "correction")),
1430
+ P.text(corr.get("where") or "")]
1431
+ finder = next((c for c in P.doc.get("contributors") or [] if isinstance(c, dict)
1432
+ and c.get("id") == corr.get("found_by")), None)
1433
+ if finder:
1434
+ head.append("found by " + esc(finder.get("name") or finder.get("id")))
1435
+ cid = correction_id(P, corr)
1436
+ return (f'<div class="cs-item cs-correction-item" id="{cid}" data-name="Correction {cid[5:]}">'
1437
+ f'<p class="cs-claim-meta">{" · ".join(h for h in head if h)}</p>'
1438
+ f'<p><span class="k">Printed:</span> {P.text(str(corr.get("printed", "")))}</p>'
1439
+ f'<p><span class="k">Stated here:</span> {P.text(str(corr.get("recorded", "")))}</p>'
1440
+ f'<p><span class="k">Why:</span> {P.text(str(corr.get("reason", "")))}</p></div>')
1441
+
1442
+
1443
+ def _section(sid, title, items, intro=""):
1444
+ if not items:
1445
+ return ""
1446
+ return (f'<section class="cs-section" id="{sid}"><h2>{title}</h2>{intro}' + "\n".join(items) + "</section>")
1447
+
1448
+
1449
+ def render_parts(doc, file_url=None, ref_text=None, digits=None, number=None, person=None, marker=None,
1450
+ claim_url=None, byline=None, claim=None):
1451
+ """The page view of a claimset in parts, each HTML: `header` (title, guarantor, authors, source, licence and
1452
+ keywords), `nav` (the sections with their counts), `body` (the sections), plus `title`, `origin` (lab, converted,
1453
+ native), `brief` (the IDs shown under Highlights, and whether they were selected automatically) and `lights` (claims per
1454
+ light). `file_url(artefact)` gives the address an image of the claimset is served at, or None when the
1455
+ artefact is not an image the site shows; without it, image files are shown from their relative paths (a local
1456
+ preview beside the package's files). `ref_text(reference)` writes out a reference the file gives only by
1457
+ identifier (a DOI), or returns None. How numbers are written is the site's choice: `number(value)` returns the
1458
+ text to show for a number of the file (int or float), or None for the default; `digits` (when there is no
1459
+ `number`) shows non-integer numbers to that many significant digits. The file keeps every digit, and a table cell
1460
+ shown otherwise than as written carries the exact value as its title. `sections` lists the sections shown, as
1461
+ (id, title, count), for a site that builds its own navigation instead of using `nav`. How people are shown is the
1462
+ site's choice too: `person(contributor, where)` returns the HTML for a person or agent in the header (`where`:
1463
+ `guarantor`, `author`, `converter`, `source_author`), escaping what it takes from the file, or None for the
1464
+ default (a name, a person's ORCID link, an agent's label and "(AI agent)"). `byline(role, people)` returns the
1465
+ HTML inside one line of people in the header, its label included (`role`: `guarantor`, `authors`,
1466
+ `source_authors`; `people`: their contributor objects), or None for the default ("Guarantor: …", "Authors: …",
1467
+ "Authors of the source paper: …"). `marker(claim, where)` gives what
1468
+ marks a claim (`where`: `claim`, before its meta line, or `brief`, before its statement under Highlights): HTML, or a pair
1469
+ (before, after the meta line), or None for its support light. `claim_url(id)` gives the address of a claim's own
1470
+ page, which its ID then links to, or None. `blocks` holds each section's HTML by its id, for a site that arranges
1471
+ the sections itself. `claim`: the ID of the one claim a page shows (a claim's page), whose main evidence alone
1472
+ keeps its small tables open; by default every claim's does."""
1473
+ if callable(number):
1474
+ rounding = number
1475
+ elif isinstance(digits, int) and not isinstance(digits, bool) and digits > 0:
1476
+ rounding = ("digits", digits)
1477
+ else:
1478
+ rounding = None
1479
+ token = DIGITS.set(rounding)
1480
+ try:
1481
+ return _render_parts(doc, file_url, ref_text, person, marker, claim_url, byline, claim)
1482
+ finally:
1483
+ DIGITS.reset(token)
1484
+
1485
+
1486
+ def _render_parts(doc, file_url, ref_text, person=None, marker=None, claim_url=None, byline=None, claim=None):
1487
+ P = _Paper(doc, file_url, ref_text)
1488
+ if claim is not None:
1489
+ P.main = {main_evidence(c) for c in P.claims if c["id"] == claim} - {None}
1490
+ P.byline = byline if callable(byline) else None
1491
+ P.person = person if callable(person) else None
1492
+ P.marker = marker if callable(marker) else None
1493
+ P.claim_url = claim_url if callable(claim_url) else None
1494
+ source_link = ""
1495
+ cf = P.paper.get("converted_from")
1496
+ if isinstance(cf, dict) and isinstance(cf.get("source_id"), str):
1497
+ source_link = _doi(cf["source_id"])
1498
+
1499
+ brief_ids, automatic = brief(P)
1500
+ def brief_item(oid):
1501
+ x = P.by_id[oid]
1502
+ if x in P.defs: # a term the paper introduces (highlights, §3.1)
1503
+ return (f'<li class="cs-brief-term"><span class="kind-tag" title="Definition">'
1504
+ '<span class="long">Definition</span><span class="short">D</span></span>'
1505
+ f'<span><strong>{esc(x.get("term", ""))}</strong>: '
1506
+ f'{P.text(x.get("definition", ""))} <a class="cs-id" href="#{esc(oid)}">{esc(oid)}</a></span></li>')
1507
+ return (f'<li>{P.mark(x, "brief")[0]}<span>{P.statement(x.get("statement", ""))} '
1508
+ f'<a class="cs-id" href="#{esc(oid)}">{esc(oid)}</a></span></li>')
1509
+ brief_items = [brief_item(oid) for oid in brief_ids]
1510
+ principal = [c for c in P.claims if c.get("role") == "principal" and not P.is_assumption(c)]
1511
+ assumptions = [c for c in P.claims if P.is_assumption(c)]
1512
+ supporting = [c for c in P.claims if c.get("role") != "principal" and not P.is_assumption(c)]
1513
+ note = ""
1514
+ if automatic:
1515
+ note = (f'<p class="cs-note">Selected automatically; the authors chose no highlights. '
1516
+ f'<a href="#principal">All {len(principal)} principal claims</a></p>')
1517
+
1518
+ context = []
1519
+ for c in P.claims:
1520
+ for rel in c.get("relations") or []:
1521
+ if isinstance(rel, dict) and rel.get("id_type") != "local" and rel.get("type") in (
1522
+ "extends", "addresses", "contradicts", "replicates", "fails_to_replicate", "supersedes",
1523
+ "refines", "qualifies", "supports", "explains", "disputes_evidence"):
1524
+ target = (P.ref(rel["reference"], rel.get("locator")) if rel.get("reference")
1525
+ else _target(rel.get("target"), rel.get("id_type")))
1526
+ own = ' <span class="cs-tail">· own earlier work</span>' if rel.get("self") else ""
1527
+ context.append(f'<dt>{esc(str(rel["type"]).replace("_", " ").capitalize())} {target}{own}'
1528
+ f' <span class="cs-tail">· from <a href="#{esc(c["id"])}">{esc(c["id"])}</a></span></dt>'
1529
+ f'<dd>{P.text(rel.get("note", ""))}</dd>')
1530
+
1531
+ def rested(c):
1532
+ r = P.users(c["id"])
1533
+ return f' <span class="cs-tail">Rested on by {r}.</span>' if r else ""
1534
+
1535
+ assumption_items = [
1536
+ f'<div class="cs-item" id="{esc(c["id"])}"><p class="cs-claim-meta">{esc(c["id"])}'
1537
+ + (f' · {esc(c["assumption_category"])}' if c.get("assumption_category") else "")
1538
+ + f' · {esc(c.get("check", "unchecked"))}</p><p>{P.text(c.get("statement", ""))}{rested(c)}</p>'
1539
+ + _corrected(P, c.get("id")) + "</div>"
1540
+ for c in assumptions]
1541
+
1542
+ warrants = [f'<div class="cs-item" id="{esc(w["id"])}"><p class="cs-claim-meta">{esc(w["id"])} · argument'
1543
+ + (f' · {esc(w["reasoning"])}' if w.get("reasoning") else "")
1544
+ + (f' · premises {P.ids(w["premises"])}' if w.get("premises") else "")
1545
+ + f'</p><p>{P.text(w.get("text", ""))}</p></div>' for w in P.warrants]
1546
+
1547
+ limitation_items = [
1548
+ f'<div class="cs-item" id="{esc(lim["id"])}"><p class="cs-claim-meta">{esc(lim["id"])}'
1549
+ + "".join(f" · {esc(str(lim[k]).replace('_', ' '))}" for k in ("category", "impact") if lim.get(k))
1550
+ + (f' · affects {P.ids(lim["affects"])}' if lim.get("affects") else "")
1551
+ + (f' · mitigation: {esc(lim["mitigation"])}' if lim.get("mitigation") else "")
1552
+ + f'</p><p>{P.text(lim.get("statement", ""))}</p></div>' for lim in P.limitations]
1553
+
1554
+ question_items = [
1555
+ f'<div class="cs-item" id="{esc(q["id"])}"><p class="cs-claim-meta">{esc(q["id"])}'
1556
+ + (f' · from {P.ids(q["claims"])}' if q.get("claims") else "")
1557
+ + f'</p><p>{P.text(q.get("question", ""))}</p></div>' for q in P.questions]
1558
+
1559
+ def reference(b):
1560
+ """One entry of the list, as a classical reference list has it: the reference as written (authors, year,
1561
+ title, where it appeared), then its identifier as a link, a DOI by its address. No label before it: the
1562
+ entry starts with the authors and the year its label is made of. A year that two entries share carries the
1563
+ label's letter (2018a)."""
1564
+ t, kind = b.get("target"), b.get("id_type")
1565
+ shown = (_link(t) if kind == "url" else
1566
+ _link(f"https://doi.org/{t}") if kind == "doi" and isinstance(t, str) and t.startswith("10.")
1567
+ else _target(t, kind))
1568
+ if b["id"] in P.written: # written out by the site, then its identifier
1569
+ text = P.written[b["id"]]
1570
+ lettered = re.search(r"\((\d{4})([a-z])\)", P.labels.get(b["id"], ""))
1571
+ if lettered:
1572
+ text = re.sub(rf"(?<=, ){lettered.group(1)}(?=\.)", lettered.group(1) + lettered.group(2), text, count=1)
1573
+ shown = f"{esc(text)} {shown}"
1574
+ used = P.users(b["id"])
1575
+ return (f'<li id="{esc(b["id"])}">{shown}'
1576
+ + (f' <span class="cs-tail">Used by: {used}</span>' if used else "") + "</li>")
1577
+
1578
+ def work_entry(group):
1579
+ """One entry for a claimset published here of which the paper cites several claims (or one): the work is
1580
+ written once, as a list of references has a work once, then its identifier, then the claims cited, each a
1581
+ link to that claim. The entry answers to every reference's ID, so a citation in the text still lands here."""
1582
+ first = group[0]
1583
+ m = GLOBAL_ID.fullmatch(first["target"])
1584
+ text = P.written[first["id"]]
1585
+ lettered = re.search(r"\((\d{4})([a-z])\)", P.labels.get(first["id"], ""))
1586
+ if lettered:
1587
+ text = re.sub(rf"(?<=, ){lettered.group(1)}(?=\.)", lettered.group(1) + lettered.group(2), text, count=1)
1588
+ key, version = m.group(1), m.group(2) or ""
1589
+ whole = f'<a class="global-id" href="/p/{key}{version}">entrylib:{esc(key + version)}</a>'
1590
+ cited = sorted({P.claim_of[b["id"]] for b in group if b["id"] in P.claim_of},
1591
+ key=lambda c: [int(x) if x.isdigit() else x for x in re.split(r"(\d+)", c)])
1592
+ claims = ", ".join(f'<a href="/p/{key}{version}#{esc(c)}">{esc(c)}</a>' for c in cited)
1593
+ users = list(dict.fromkeys(u for b in group for u in P.used_by.get(b["id"], [])))
1594
+ used = ", ".join('<a href="#context">Context</a>' if u == "context" else f'<a href="#{esc(u)}">{esc(u)}</a>'
1595
+ for u in users)
1596
+ anchors = "".join(f'<span id="{esc(b["id"])}"></span>' for b in group[1:])
1597
+ return (f'<li id="{esc(first["id"])}">{anchors}{esc(text)} {whole}'
1598
+ + (f' <span class="cs-cited">Claim{"s" if len(cited) > 1 else ""} cited: {claims}.</span>' if cited else "")
1599
+ + (f' <span class="cs-tail">Used by: {used}</span>' if used else "") + "</li>")
1600
+
1601
+ def reference_list():
1602
+ """The entries in the list's order; the claims cited from one claimset published here share one entry."""
1603
+ ordered, out, done = P.refs_in_order(), [], set()
1604
+ for b in ordered:
1605
+ if b["id"] in done:
1606
+ continue
1607
+ if b["id"] in P.work:
1608
+ group = [x for x in ordered if P.work.get(x["id"]) == P.work[b["id"]]]
1609
+ done.update(x["id"] for x in group)
1610
+ out.append(work_entry(group))
1611
+ else:
1612
+ out.append(reference(b))
1613
+ return "".join(out)
1614
+
1615
+ def artefact(a):
1616
+ desc = a.get("description") or a.get("uri") or ""
1617
+ src = P.image_src(a)
1618
+ uri = a.get("uri") # the description is read; the link is its file or site
1619
+ target = src or (uri if _href(uri) and desc != uri else None)
1620
+ name = (f'{P.text(desc)} <a class="cs-open" href="{esc(target)}">{esc(_link_name(target))}</a>' if target
1621
+ else _link(uri) if _href(uri) and desc == uri else P.text(desc))
1622
+ bits = [esc(x) for x in (a.get("kind"), a.get("function")) if x]
1623
+ v = a.get("version") # a package's version; a content hash is not shown
1624
+ if isinstance(v, str) and v.strip() and not v.startswith("sha256:"):
1625
+ bits.append(f"version {esc(v)}")
1626
+ if a.get("reference"):
1627
+ bits.append(P.ref(a["reference"]))
1628
+ return (f'<li id="{esc(a["id"])}"><span class="cs-id">{esc(a["id"])} · {" · ".join(bits)}</span> {name}</li>')
1629
+
1630
+ summary = P.paper.get("summary") if isinstance(P.paper.get("summary"), str) and P.paper["summary"].strip() \
1631
+ else None # the authors' summary, first (spec §3.1)
1632
+ sections = [
1633
+ ("summary", "Summary", [f'<p class="cs-summary">{P.text(summary)}</p>'] if summary else []),
1634
+ ("highlights", "Highlights", [f'<ul class="cs-brief">{"".join(brief_items)}</ul>{note}'] if brief_items else []),
1635
+ ("context", "Context", [f'<dl class="cs-context">{"".join(context)}</dl>'] if context else []),
1636
+ ("definitions", "Definitions", None),
1637
+ ("assumptions", "Assumptions", assumption_items),
1638
+ ("principal", "Principal claims", [_claim(P, c, True) for c in principal]),
1639
+ ("supporting", "Supporting claims", [_claim(P, c) for c in supporting]),
1640
+ ("evidence", "Evidence", [_evidence(P, e, source_link) for e in P.evidence] + warrants),
1641
+ ("limitations", "Limitations", limitation_items),
1642
+ ("questions", "Open questions", question_items),
1643
+ ("corrections", "Corrections to " + P.against.removeprefix("the "),
1644
+ [_correction_item(P, corr) for corr in P.corrections]),
1645
+ ("references", "References", [f'<ol class="cs-refs">{reference_list()}</ol>']
1646
+ if P.refs else []),
1647
+ ("artefacts", "Artefacts", [f'<ul class="cs-artefacts">{"".join(artefact(a) for a in P.artefacts)}</ul>']
1648
+ if P.artefacts else []),
1649
+ ]
1650
+ counts = {"definitions": len(P.defs), "assumptions": len(assumptions), "principal": len(principal),
1651
+ "supporting": len(supporting), "evidence": len(P.evidence) + len(P.warrants),
1652
+ "limitations": len(P.limitations), "questions": len(P.questions), "corrections": len(P.corrections),
1653
+ "references": len({P.work.get(b["id"], b["id"]) for b in P.refs}), # entries: a cited claimset once
1654
+ "artefacts": len(P.artefacts)}
1655
+ body, nav, shown, blocks = [], [], [], {}
1656
+ for sid, title, items in sections:
1657
+ part = _definitions(P) if items is None else _section(sid, title, items)
1658
+ if part:
1659
+ body.append(part)
1660
+ blocks[sid] = part
1661
+ n = counts.get(sid)
1662
+ nav.append(f'<li><a href="#{sid}">{title}</a>' + (f' <span class="count">{n}</span>' if n else "") + "</li>")
1663
+ shown.append((sid, title, n or 0))
1664
+ return {"title": P.paper.get("title", ""), "origin": _origin(P), "brief": (brief_ids, automatic),
1665
+ "header": _header(P),
1666
+ "nav": '<nav class="cs-toc" aria-label="Sections of the claimset"><p class="cs-toc-title">On this page</p>'
1667
+ f'<ol>{"".join(nav)}</ol></nav>',
1668
+ "body": "\n".join(body), "sections": shown, "blocks": blocks,
1669
+ "lights": {lt: sum(1 for c in P.claims if P.light(c) == lt) for lt in LIGHTS}}
1670
+
1671
+
1672
+ def _cell(P, v):
1673
+ """A table cell: a number (with its exact value as the title when the view rounds it), or anything else."""
1674
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
1675
+ shown = P.value(v)
1676
+ exact = repr(v) if isinstance(v, float) else str(v)
1677
+ title = f' title="{esc(exact)}"' if DIGITS.get() and shown != exact else ""
1678
+ return f'<td class="num"{title}>{shown}</td>'
1679
+ return f'<td class="txt">{P.value(v)}</td>'
1680
+
1681
+
1682
+ def stylesheet():
1683
+ """The stylesheet for the page view, for a site to serve (as claimset.css) or a page to inline."""
1684
+ from .page_css import CSS
1685
+ return CSS
1686
+
1687
+
1688
+ def render_html(doc, file_url=None):
1689
+ """A whole page for previewing a claimset locally: the page view, with its stylesheet inline and no scripts."""
1690
+ parts = render_parts(doc, file_url)
1691
+ return ("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">"
1692
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
1693
+ f"<title>{esc(parts['title'])}</title><style>{stylesheet()}</style></head>\n"
1694
+ f'<body><div class="cs-page"><div class="cs-header"><p class="cs-origin">{esc(parts["origin"])}</p>'
1695
+ f'{parts["header"]}</div><div class="cs-layout">{parts["nav"]}<article class="cs-body">'
1696
+ f'{parts["body"]}</article></div></div></body></html>\n')