返回 last30days-skill
html_render.py
根目录 / skills / last30days / scripts / lib / html_render.py
1 """HTML rendering for shareable last30days reports."""
2
3 from __future__ import annotations
4
5 import html
6 import re
7 import secrets
8 from collections import OrderedDict
9 from collections.abc import Mapping, Sequence
10 from datetime import date
11 from urllib.parse import urlsplit
12
13 from . import registers, render, schema
14 from .library import LibraryEntry, public_markdown
15
16
17 PROSE_LABELS = [
18 ("What I learned:", "What I learned"),
19 ("KEY PATTERNS from the research:", "Key patterns from the research"),
20 ]
21
22 # The invitation closes a report, so it runs to the end of the text. Reports
23 # saved before the closing "Just ask." line was dropped stop at that line.
24 INVITATION_PATTERN = re.compile(
25 r"^(?:---\nI'm now an expert|I've compared [^\n]*\. Some things you could ask:)"
26 r".*?(?:Just ask\.$|\Z)",
27 re.MULTILINE | re.DOTALL,
28 )
29 EVIDENCE_BLOCK_PATTERN = re.compile(r"<!-- EVIDENCE FOR SYNTHESIS.*?<!-- END EVIDENCE FOR SYNTHESIS -->", re.DOTALL)
30 PASS_THROUGH_FOOTER_PATTERN = re.compile(
31 r"^<!-- PASS-THROUGH FOOTER[^\n]*-->[ \t]*\n(.*?)^<!-- END PASS-THROUGH FOOTER -->[ \t]*$",
32 re.MULTILINE | re.DOTALL,
33 )
34 _PASS_THROUGH_FOOTER_START = re.compile(r"^<!-- PASS-THROUGH FOOTER[^\n]*-->[ \t]*$")
35 _PASS_THROUGH_FOOTER_END = re.compile(r"^<!-- END PASS-THROUGH FOOTER -->[ \t]*$")
36 # Line-by-line on purpose: no row inside the match may itself open or close a
37 # fence, so an earlier ordinary ```text block cannot be stitched to the real
38 # footer with the prose between them swallowed into the footer box.
39 _FOOTER_ROWS = r"(?:(?!```)[^\n]*\n)*?"
40 FENCED_ENGINE_FOOTER_PATTERN = re.compile(
41 r"^```text\n(---\n"
42 + _FOOTER_ROWS
43 + r"[^\n]*All agents reported back![^\n]*\n"
44 + _FOOTER_ROWS
45 + r"---)\n```$",
46 re.MULTILINE,
47 )
48 CANONICAL_BOUNDARY_PATTERN = re.compile(r"\n?---\n# END OF last30days CANONICAL OUTPUT.*$", re.DOTALL)
49 # render_for_html emits metadata as <!-- META: ... --> so it survives the
50 # markdown converter (which escapes raw HTML inside paragraphs). Promoted to
51 # a styled <div class="meta"> at the block level.
52 META_MARKER_PATTERN = re.compile(r"<!--\s*META:((?:(?!-->).)*?)-->")
53 _STANDALONE_META_RAW_PATTERN = re.compile(r"<!--\s*META:((?:(?!-->).)*?)-->")
54 _STANDALONE_META_PROMOTE_PATTERNS = (
55 re.compile(r"<p>\s*&lt;!--\s*META:((?:(?!--&gt;).)*?)--&gt;\s*</p>"),
56 re.compile(r"&lt;!--\s*META:((?:(?!--&gt;).)*?)--&gt;"),
57 re.compile(r"<p>\s*<!--\s*META:((?:(?!-->).)*?)-->\s*</p>"),
58 re.compile(r"<!--\s*META:((?:(?!-->).)*?)-->"),
59 )
60 _OPEN_PRE_RE = re.compile(r"<pre(?:\s[^>]*)?>", re.IGNORECASE)
61 _CLOSE_PRE_RE = re.compile(r"</pre\s*>", re.IGNORECASE)
62 _OPEN_CODE_RE = re.compile(r"<code(?:\s[^>]*)?>", re.IGNORECASE)
63 _CLOSE_CODE_RE = re.compile(r"</code\s*>", re.IGNORECASE)
64 _TEMPLATE_PLACEHOLDER_PATTERN = re.compile(r"__(?:TITLE|CSS|BODY|COLOPHON)__")
65
66 CSS = """
67 :root {
68 --bg: #0e0e10;
69 --bg-elev: #18181b;
70 --fg: #fafafa;
71 --fg-muted: #a1a1aa;
72 --fg-subtle: #71717a;
73 --accent: #a855f7;
74 --accent-soft: #c4b5fd;
75 --border: #27272a;
76 --code-bg: #1a1a1d;
77 --max-w: 720px;
78 }
79
80 @media (prefers-color-scheme: light) {
81 :root {
82 --bg: #ffffff;
83 --bg-elev: #fafafa;
84 --fg: #18181b;
85 --fg-muted: #52525b;
86 --fg-subtle: #71717a;
87 --accent: #7c3aed;
88 --accent-soft: #6d28d9;
89 --border: #e4e4e7;
90 --code-bg: #f4f4f5;
91 }
92 }
93
94 * { box-sizing: border-box; }
95
96 html, body {
97 margin: 0;
98 padding: 0;
99 background: var(--bg);
100 color: var(--fg);
101 font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, system-ui, sans-serif;
102 font-size: 17px;
103 line-height: 1.65;
104 -webkit-font-smoothing: antialiased;
105 -moz-osx-font-smoothing: grayscale;
106 text-rendering: optimizeLegibility;
107 }
108
109 body {
110 max-width: var(--max-w);
111 margin: 0 auto;
112 padding: 4rem 1.5rem 6rem;
113 }
114
115 .badge {
116 display: inline-block;
117 padding: 0.4rem 0.85rem;
118 margin-bottom: 2.5rem;
119 background: var(--bg-elev);
120 border: 1px solid var(--border);
121 border-radius: 999px;
122 font-family: 'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, Consolas, monospace;
123 font-size: 13px;
124 font-weight: 500;
125 color: var(--fg-muted);
126 letter-spacing: 0;
127 }
128
129 .badge .accent { color: var(--accent); }
130
131 .meta {
132 margin: -1.5rem 0 2.5rem;
133 color: var(--fg-subtle);
134 font-family: 'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, Consolas, monospace;
135 font-size: 13px;
136 letter-spacing: 0.01em;
137 }
138
139 h1 {
140 margin: 0 0 1.5rem;
141 color: var(--fg);
142 font-size: 30px;
143 font-weight: 700;
144 line-height: 1.2;
145 letter-spacing: 0;
146 }
147
148 h2,
149 .prose-label {
150 margin: 2.75rem 0 1.25rem;
151 color: var(--fg);
152 font-size: 20px;
153 font-weight: 600;
154 line-height: 1.35;
155 letter-spacing: 0;
156 }
157
158 .badge + h2,
159 .badge + .prose-label { margin-top: 0.5rem; }
160
161 h3 {
162 margin: 2rem 0 0.85rem;
163 color: var(--fg);
164 font-size: 17px;
165 font-weight: 600;
166 line-height: 1.4;
167 letter-spacing: 0;
168 }
169
170 p {
171 margin: 0 0 1.4rem;
172 color: var(--fg-muted);
173 }
174
175 p strong,
176 li strong,
177 td strong {
178 color: var(--fg);
179 font-weight: 600;
180 }
181
182 a {
183 color: var(--accent);
184 text-decoration: none;
185 border-bottom: 1px solid transparent;
186 transition: border-color 0.15s ease;
187 }
188
189 a:hover { border-bottom-color: var(--accent); }
190
191 ul,
192 ol {
193 margin: 0 0 1.6rem;
194 padding-left: 1.5rem;
195 color: var(--fg-muted);
196 }
197
198 li {
199 margin: 0.6rem 0;
200 padding-left: 0.4rem;
201 }
202
203 li::marker {
204 color: var(--accent);
205 font-weight: 600;
206 }
207
208 blockquote {
209 margin: 1.5rem 0;
210 padding-left: 1rem;
211 border-left: 3px solid var(--accent);
212 color: var(--fg-muted);
213 }
214
215 hr {
216 margin: 2.5rem 0;
217 border: 0;
218 border-top: 1px solid var(--border);
219 }
220
221 code {
222 font-family: 'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, Consolas, monospace;
223 font-size: 0.92em;
224 background: var(--code-bg);
225 padding: 0.15rem 0.4rem;
226 border-radius: 4px;
227 color: var(--accent-soft);
228 }
229
230 pre {
231 margin: 1.4rem 0;
232 background: var(--code-bg);
233 border: 1px solid var(--border);
234 border-radius: 8px;
235 padding: 1rem 1.25rem;
236 overflow-x: auto;
237 font-size: 14px;
238 line-height: 1.6;
239 }
240
241 pre code {
242 background: none;
243 padding: 0;
244 color: var(--fg);
245 }
246
247 table {
248 width: 100%;
249 border-collapse: collapse;
250 margin: 1.5rem 0;
251 font-size: 15px;
252 }
253
254 th,
255 td {
256 text-align: left;
257 padding: 0.75rem 1rem;
258 border-bottom: 1px solid var(--border);
259 vertical-align: top;
260 }
261
262 th {
263 color: var(--fg-muted);
264 font-weight: 600;
265 font-size: 13px;
266 letter-spacing: 0;
267 text-transform: uppercase;
268 }
269
270 td { color: var(--fg-muted); }
271 td:first-child { color: var(--fg); font-weight: 500; }
272
273 .engine-footer {
274 margin: 3rem 0 2.5rem;
275 padding: 1.25rem 1.5rem;
276 background: var(--bg-elev);
277 border: 1px solid var(--border);
278 border-radius: 8px;
279 color: var(--fg-muted);
280 }
281
282 .engine-footer pre {
283 margin: 0;
284 padding: 0;
285 background: transparent;
286 border: 0;
287 border-radius: 0;
288 font-family: 'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, Consolas, monospace;
289 font-size: 13.5px;
290 font-weight: 400;
291 line-height: 1.75;
292 color: inherit;
293 white-space: pre-wrap;
294 word-break: break-word;
295 }
296
297 .colophon {
298 margin-top: 4rem;
299 padding-top: 2rem;
300 border-top: 1px solid var(--border);
301 color: var(--fg-subtle);
302 font-size: 13px;
303 font-family: 'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, Consolas, monospace;
304 line-height: 1.7;
305 }
306
307 .colophon .rerun {
308 display: inline-block;
309 padding: 0.15rem 0.5rem;
310 margin-left: 0.25rem;
311 background: var(--code-bg);
312 border-radius: 4px;
313 color: var(--accent-soft);
314 font-size: 0.95em;
315 }
316
317 .library-hero {
318 padding: 1.5rem 0 2.5rem;
319 border-bottom: 1px solid var(--border);
320 }
321
322 .library-hero h1 { margin-bottom: 0.65rem; }
323 .library-hero p { max-width: 42rem; color: var(--fg-muted); }
324 .library-hero .subscribe { font-weight: 700; }
325
326 .library-topic { margin-top: 3rem; }
327
328 .library-topic-heading {
329 display: flex;
330 align-items: baseline;
331 justify-content: space-between;
332 gap: 1rem;
333 border-bottom: 1px solid var(--border);
334 }
335
336 .library-topic-heading h2 { margin-bottom: 0.65rem; }
337 .library-topic-heading a { font-size: 0.85rem; }
338
339 .library-entry {
340 display: grid;
341 grid-template-columns: 7rem minmax(0, 1fr);
342 column-gap: 1.25rem;
343 padding: 1.35rem 0;
344 border-bottom: 1px solid var(--border);
345 }
346
347 .library-entry time {
348 grid-row: 1 / span 2;
349 color: var(--fg-subtle);
350 font-family: 'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, monospace;
351 font-size: 0.8rem;
352 }
353
354 .library-entry h3 { margin: 0 0 0.35rem; font-size: 1.1rem; }
355 .library-entry p { margin: 0; color: var(--fg-muted); }
356 .library-empty { padding: 3rem 0; }
357
358 @media print {
359 :root {
360 --bg: #ffffff;
361 --bg-elev: #f5f5f5;
362 --fg: #000000;
363 --fg-muted: #1f2937;
364 --fg-subtle: #4b5563;
365 --accent: #6d28d9;
366 --accent-soft: #6d28d9;
367 --border: #d4d4d8;
368 --code-bg: #f4f4f5;
369 }
370
371 @page { size: A4; margin: 1.5cm 2cm; }
372
373 body {
374 max-width: none;
375 padding: 0;
376 font-size: 11pt;
377 }
378
379 a {
380 color: inherit;
381 border-bottom: 0;
382 text-decoration: underline;
383 }
384
385 a[href]::after {
386 content: " (" attr(href) ")";
387 font-size: 0.85em;
388 color: var(--fg-subtle);
389 }
390
391 .engine-footer { page-break-inside: avoid; }
392 }
393
394 @media (max-width: 600px) {
395 body {
396 padding: 2.5rem 1.25rem 4rem;
397 font-size: 16px;
398 }
399
400 h1 { font-size: 25px; }
401 .badge { font-size: 12px; }
402 th, td { padding: 0.65rem 0.5rem; }
403 .library-entry { grid-template-columns: 1fr; }
404 .library-entry time { grid-row: auto; margin-bottom: 0.5rem; }
405 }
406 """.strip()
407
408 HTML_TEMPLATE = """<!DOCTYPE html>
409 <html lang="en">
410 <head>
411 <meta charset="utf-8">
412 <meta name="viewport" content="width=device-width, initial-scale=1">
413 <title>last30days · __TITLE__</title>
414 <style>
415 __CSS__
416 </style>
417 </head>
418 <body>
419 __BODY__
420 __COLOPHON__
421 </body>
422 </html>
423 """
424
425
426 def render_html(
427 report: schema.Report,
428 *,
429 fun_level: str = "medium",
430 save_path: str | None = None,
431 synthesis_md: str | None = None,
432 register: str = "default",
433 ) -> str:
434 prepared_synthesis, synthesis_bounds = _wrap_untrusted_synthesis(synthesis_md)
435 md = render.render_for_html(
436 report,
437 synthesis_md=prepared_synthesis,
438 save_path=save_path,
439 fun_level=fun_level,
440 register=register,
441 )
442 md = _strip_evidence_block(md)
443 md = _strip_canonical_boundary(md)
444 md = _promote_prose_labels(md)
445 body = _markdown_to_html(md, untrusted_bounds=synthesis_bounds)
446 body = _promote_meta_marker(body)
447 colophon = _build_colophon(report)
448 return _wrap_in_template(body, colophon, report.topic)
449
450
451 def render_html_comparison(
452 entity_reports: list[tuple[str, schema.Report]],
453 *,
454 fun_level: str = "medium",
455 save_path: str | None = None,
456 synthesis_md: str | None = None,
457 ) -> str:
458 _ = fun_level
459 prepared_synthesis, synthesis_bounds = _wrap_untrusted_synthesis(synthesis_md)
460 md = render.render_for_html_comparison(
461 entity_reports,
462 synthesis_md=prepared_synthesis,
463 save_path=save_path,
464 )
465 md = _strip_evidence_block(md)
466 md = _strip_canonical_boundary(md)
467 md = _promote_prose_labels(md)
468 body = _markdown_to_html(md, untrusted_bounds=synthesis_bounds)
469 body = _promote_meta_marker(body)
470 topic = " vs ".join(label for label, _ in entity_reports)
471 colophon = _build_colophon(entity_reports[0][1], topic=topic)
472 return _wrap_in_template(body, colophon, topic)
473
474
475 LIBRARY_BRIEF_MARKER = "<!-- generated by last30days library feed -->"
476
477
478 def render_library_brief(entry: LibraryEntry, *, include_private: bool = True) -> str:
479 """Render a scanned Markdown or JSON briefing as a safe standalone page."""
480 md = entry.content if include_private else public_markdown(entry.content)
481 md = _strip_invitation(md)
482 md = _strip_canonical_boundary(md)
483 if entry.source_format == "finished-brief":
484 md = _promote_prose_labels(md)
485 body = _markdown_to_html(md)
486 colophon = (
487 '<footer class="colophon">'
488 f"Saved research · {html.escape(entry.published_date.isoformat())} · "
489 f"{html.escape(entry.topic)}"
490 "</footer>"
491 )
492 rendered = scrub_publishable_digit_runs(
493 _wrap_in_template(body, colophon, entry.headline)
494 )
495 # Ownership marker consumed by the library-feed prune: a generated-looking
496 # filename alone must never be grounds for deletion.
497 head, sep, tail = rendered.rpartition("</body>")
498 if sep:
499 return f"{head}{LIBRARY_BRIEF_MARKER}\n{sep}{tail}"
500 return rendered
501
502
503 def render_library_index(
504 entries: Sequence[LibraryEntry],
505 *,
506 entry_urls: Mapping[str, str] | None = None,
507 feed_url: str | None = "feed.xml",
508 ) -> str:
509 """Render the reverse-chronological, topic-grouped research index."""
510 urls = entry_urls or {}
511 grouped: OrderedDict[str, list[LibraryEntry]] = OrderedDict()
512 for entry in entries:
513 grouped.setdefault(entry.topic, []).append(entry)
514
515 parts = [
516 '<header class="library-hero">',
517 '<span class="badge">RESEARCH LIBRARY</span>',
518 '<h1>What the community is learning</h1>',
519 ]
520 safe_feed_url = _safe_library_href(feed_url) if feed_url is not None else None
521 if safe_feed_url is None:
522 parts.append('<p>Saved last30days briefs, newest first.</p>')
523 else:
524 parts.extend([
525 '<p>Saved last30days briefs, newest first. Follow the Atom feed to keep up.</p>',
526 f'<p><a class="subscribe" href="{safe_feed_url}">Subscribe via Atom</a></p>',
527 ])
528 parts.append('</header>')
529 if not entries:
530 parts.append('<section class="library-empty"><h2>No saved briefs yet</h2><p>Run last30days research and this library will fill itself.</p></section>')
531 for topic, topic_entries in grouped.items():
532 latest = topic_entries[0]
533 latest_url = urls.get(latest.entry_id, f"briefs/{latest.output_name}")
534 safe_latest_url = _safe_library_href(latest_url)
535 parts.extend([
536 '<section class="library-topic">',
537 '<div class="library-topic-heading">',
538 f'<h2>{html.escape(topic)}</h2>',
539 ])
540 if safe_latest_url is not None:
541 parts.append(f'<a href="{safe_latest_url}">Latest</a>')
542 parts.append('</div>')
543 for entry in topic_entries:
544 url = urls.get(entry.entry_id, f"briefs/{entry.output_name}")
545 safe_url = _safe_library_href(url)
546 headline_html = html.escape(entry.headline)
547 if safe_url is not None:
548 title_html = f'<h3><a href="{safe_url}">{headline_html}</a></h3>'
549 else:
550 title_html = f'<h3>{headline_html}</h3>'
551 parts.extend([
552 '<article class="library-entry">',
553 f'<time datetime="{entry.published_date.isoformat()}">{entry.published_date.isoformat()}</time>',
554 title_html,
555 f'<p>{html.escape(entry.summary)}</p>',
556 '</article>',
557 ])
558 parts.append('</section>')
559 colophon = '<footer class="colophon">Generated locally by <strong>last30days</strong>.</footer>'
560 rendered = _wrap_in_template("\n".join(parts), colophon, "Research library")
561 return scrub_publishable_digit_runs(rendered)
562
563
564 _HREF_PATTERN = re.compile(r'(?P<prefix>\bhref\s*=\s*)(?P<quote>["\'])(?P<url>.*?)(?P=quote)', re.IGNORECASE)
565 _LONG_DIGIT_RUN = re.compile(r"\d{13,19}")
566
567
568 def scrub_publishable_digit_runs(html_content: str) -> str:
569 """Defuse payment-card-shaped digit runs before hosted publishing.
570
571 ht-ml.app rejects pages containing 13-19 digit runs during its safety scan.
572 Social post IDs commonly have that shape. Link targets are percent-encoded
573 so they still resolve; visible occurrences are shortened for readability.
574 """
575 def scrub_href(match: re.Match[str]) -> str:
576 url = _LONG_DIGIT_RUN.sub(
577 lambda digits: "".join(f"%{ord(char):02X}" for char in digits.group(0)),
578 match.group("url"),
579 )
580 return f'{match.group("prefix")}{match.group("quote")}{url}{match.group("quote")}'
581
582 with_safe_hrefs = _HREF_PATTERN.sub(scrub_href, html_content)
583 return _LONG_DIGIT_RUN.sub(
584 lambda digits: f"{digits.group(0)[:6]}…{digits.group(0)[-4:]}",
585 with_safe_hrefs,
586 )
587
588
589 def _strip_evidence_block(md: str) -> str:
590 return EVIDENCE_BLOCK_PATTERN.sub("", md)
591
592
593 def _strip_invitation(md: str) -> str:
594 return INVITATION_PATTERN.sub("", md)
595
596
597 def _strip_synthesis_invitation(synthesis_md: str | None) -> str | None:
598 """Strip the invitation before the engine footer is appended after it."""
599 if synthesis_md is None:
600 return None
601 return _strip_invitation(synthesis_md)
602
603
604 def _prepare_synthesis_md(synthesis_md: str | None) -> str | None:
605 cleaned = _strip_synthesis_invitation(synthesis_md)
606 if cleaned is None:
607 return None
608 return _strip_canonical_boundary(cleaned)
609
610
611 def _wrap_untrusted_synthesis(
612 synthesis_md: str | None,
613 ) -> tuple[str | None, tuple[str, str] | None]:
614 cleaned = _prepare_synthesis_md(synthesis_md)
615 if cleaned is None or not cleaned.strip():
616 return cleaned, None
617 nonce = secrets.token_hex(16)
618 start_marker = f"__LAST30DAYS_SYNTHESIS_START_{nonce}__"
619 end_marker = f"__LAST30DAYS_SYNTHESIS_END_{nonce}__"
620 return f"{start_marker}\n{cleaned.strip()}\n{end_marker}", (start_marker, end_marker)
621
622
623 def _strip_canonical_boundary(md: str) -> str:
624 return CANONICAL_BOUNDARY_PATTERN.sub("", md)
625
626
627 def _promote_prose_labels(md: str) -> str:
628 for source, normalized in PROSE_LABELS:
629 md = re.sub(
630 # The terminal report ends the label line with a `\` hard break.
631 rf"^{re.escape(source)}[ \t]*\\?[ \t]*$",
632 f"## {normalized}",
633 md,
634 flags=re.MULTILINE,
635 )
636 return md
637
638
639 def _strip_non_meta_comments(text: str) -> str:
640 """Strip HTML comments except ``META:`` markers in strict O(N) time."""
641 out: list[str] = []
642 pos = 0
643 while True:
644 start = text.find("<!--", pos)
645 if start == -1:
646 out.append(text[pos:])
647 break
648 end = text.find("-->", start + 4)
649 if end == -1:
650 out.append(text[pos:])
651 break
652 inner = text[start + 4 : end]
653 if inner.lstrip().startswith("META:"):
654 out.append(text[pos : end + 3])
655 else:
656 out.append(text[pos:start])
657 pos = end + 3
658 return "".join(out)
659
660
661 def _strip_html_comments_outside_code(md: str) -> str:
662 lines = md.splitlines(keepends=True)
663 out: list[str] = []
664 prose_chunk: list[str] = []
665 in_code = False
666
667 def flush_prose() -> None:
668 if prose_chunk:
669 out.append(_strip_non_meta_comments("".join(prose_chunk)))
670 prose_chunk.clear()
671
672 for line in lines:
673 if line.strip().startswith("```"):
674 if not in_code:
675 flush_prose()
676 in_code = True
677 out.append(line)
678 else:
679 out.append(line)
680 in_code = False
681 continue
682 if in_code:
683 out.append(line)
684 else:
685 prose_chunk.append(line)
686 flush_prose()
687 return "".join(out)
688
689
690 def _markdown_to_html(
691 md: str,
692 *,
693 untrusted_bounds: tuple[str, str] | None = None,
694 allow_engine_footers: bool = True,
695 ) -> str:
696 if allow_engine_footers:
697 md, footers = _protect_engine_footers(md, untrusted_bounds=untrusted_bounds)
698 else:
699 footers = {}
700 md = _strip_html_comments_outside_code(md)
701 lines = md.splitlines()
702 out: list[str] = []
703 paragraph: list[str] = []
704 list_type: str | None = None
705 in_code = False
706 code_lines: list[str] = []
707 index = 0
708
709 def flush_paragraph() -> None:
710 nonlocal paragraph
711 if paragraph:
712 text = " ".join(part.strip() for part in paragraph).strip()
713 if text:
714 out.append(f"<p>{_inline_markdown(text)}</p>")
715 paragraph = []
716
717 def close_list() -> None:
718 nonlocal list_type
719 if list_type:
720 out.append(f"</{list_type}>")
721 list_type = None
722
723 while index < len(lines):
724 line = lines[index]
725 stripped = line.strip()
726
727 if in_code:
728 if stripped.startswith("```"):
729 out.append(f"<pre><code>{html.escape(chr(10).join(code_lines))}</code></pre>")
730 code_lines = []
731 in_code = False
732 else:
733 code_lines.append(line)
734 index += 1
735 continue
736
737 # A single trailing backslash is a markdown hard break: the Claude Code
738 # terminal report ends each pseudo-list line but the last with one.
739 if stripped.endswith("\\") and not stripped.endswith("\\\\"):
740 stripped = stripped[:-1].rstrip()
741 line = stripped
742
743 if stripped.startswith("```"):
744 flush_paragraph()
745 close_list()
746 in_code = True
747 code_lines = []
748 index += 1
749 continue
750
751 if stripped in footers:
752 flush_paragraph()
753 close_list()
754 footer = html.escape(footers[stripped], quote=False)
755 out.append(f'<div class="engine-footer"><pre>{footer}</pre></div>')
756 index += 1
757 continue
758
759 meta_match = _STANDALONE_META_RAW_PATTERN.fullmatch(stripped)
760 if meta_match:
761 flush_paragraph()
762 close_list()
763 meta_text = html.escape(html.unescape(meta_match.group(1).strip()))
764 out.append(f'<div class="meta">{meta_text}</div>')
765 index += 1
766 continue
767
768 if not stripped:
769 flush_paragraph()
770 close_list()
771 index += 1
772 continue
773
774 if stripped == "---":
775 flush_paragraph()
776 close_list()
777 out.append("<hr>")
778 index += 1
779 continue
780
781 if index + 1 < len(lines) and _is_table_row(stripped) and _is_table_separator(lines[index + 1].strip()):
782 flush_paragraph()
783 close_list()
784 table_lines = [stripped]
785 index += 2
786 while index < len(lines) and _is_table_row(lines[index].strip()):
787 table_lines.append(lines[index].strip())
788 index += 1
789 out.append(_render_table(table_lines))
790 continue
791
792 heading = re.match(r"^(#{1,4})\s+(.+)$", stripped)
793 if heading:
794 flush_paragraph()
795 close_list()
796 level = min(len(heading.group(1)), 3)
797 out.append(f"<h{level}>{_inline_markdown(heading.group(2))}</h{level}>")
798 index += 1
799 continue
800
801 if stripped.startswith(">"):
802 flush_paragraph()
803 close_list()
804 quote_lines = []
805 while index < len(lines) and lines[index].strip().startswith(">"):
806 quote_lines.append(lines[index].strip().lstrip(">").strip())
807 index += 1
808 out.append(f"<blockquote>{_inline_markdown(' '.join(quote_lines))}</blockquote>")
809 continue
810
811 # `•` and an escaped `1\.` are the list-free markers the skill writes
812 # in chat on Claude Code; an export copies that text and wants lists.
813 unordered = re.match(r"^[-*•]\s+(.+)$", stripped)
814 ordered = re.match(r"^\d+(?:[.)]|\\\.)\s+(.+)$", stripped)
815 if unordered or ordered:
816 flush_paragraph()
817 next_type = "ul" if unordered else "ol"
818 if list_type != next_type:
819 close_list()
820 out.append(f"<{next_type}>")
821 list_type = next_type
822 item = unordered.group(1) if unordered else ordered.group(1)
823 out.append(f"<li>{_inline_markdown(item)}</li>")
824 index += 1
825 continue
826
827 if stripped.startswith("🌐 last30days"):
828 flush_paragraph()
829 close_list()
830 badge_text = _inline_markdown(stripped.removeprefix("🌐").strip())
831 out.append(f'<div class="badge"><span class="accent">🌐</span> {badge_text}</div>')
832 index += 1
833 continue
834
835 close_list()
836 paragraph.append(line)
837 index += 1
838
839 if in_code:
840 out.append(f"<pre><code>{html.escape(chr(10).join(code_lines))}</code></pre>")
841 flush_paragraph()
842 close_list()
843 return "\n".join(out).strip()
844
845
846 def _protect_engine_footers(
847 md: str,
848 *,
849 untrusted_bounds: tuple[str, str] | None = None,
850 ) -> tuple[str, dict[str, str]]:
851 footers: dict[str, str] = {}
852 nonce = secrets.token_hex(16)
853 lines = md.splitlines()
854 out: list[str] = []
855 index = 0
856 in_code = False
857 in_untrusted = False
858 start_marker, end_marker = untrusted_bounds if untrusted_bounds is not None else (None, None)
859
860 def next_token(content: str) -> str:
861 token = f"__LAST30DAYS_ENGINE_FOOTER_{nonce}_{len(footers)}__"
862 footers[token] = content.strip("\n")
863 return token
864
865 while index < len(lines):
866 line = lines[index]
867 stripped = line.strip()
868
869 if start_marker is not None and stripped == start_marker:
870 in_untrusted = True
871 index += 1
872 continue
873 if end_marker is not None and stripped == end_marker:
874 in_untrusted = False
875 if in_code:
876 # Close any unclosed code fence left inside untrusted synthesis
877 # so it cannot swallow the real engine footer appended after it.
878 out.append("```")
879 in_code = False
880 index += 1
881 continue
882
883 if in_untrusted:
884 if stripped.startswith("```"):
885 in_code = not in_code
886 out.append(line)
887 index += 1
888 continue
889
890 if in_code:
891 out.append(line)
892 if stripped.startswith("```"):
893 in_code = False
894 index += 1
895 continue
896
897 if stripped == "```text":
898 end_index = index + 1
899 while end_index < len(lines) and not lines[end_index].strip().startswith("```"):
900 end_index += 1
901 if end_index < len(lines) and lines[end_index].strip() == "```":
902 block = "\n".join(lines[index : end_index + 1])
903 match = FENCED_ENGINE_FOOTER_PATTERN.fullmatch(block)
904 if match:
905 out.append("")
906 out.append(next_token(match.group(1)))
907 out.append("")
908 index = end_index + 1
909 continue
910 out.append(line)
911 in_code = True
912 index += 1
913 continue
914
915 if stripped.startswith("```"):
916 out.append(line)
917 in_code = True
918 index += 1
919 continue
920
921 if _PASS_THROUGH_FOOTER_START.fullmatch(line):
922 end_index = index + 1
923 while end_index < len(lines) and not _PASS_THROUGH_FOOTER_END.fullmatch(lines[end_index]):
924 end_index += 1
925 if end_index < len(lines):
926 body_text = "\n".join(lines[index + 1 : end_index])
927 if "All agents reported back!" in body_text:
928 out.append("")
929 out.append(next_token(body_text))
930 out.append("")
931 index = end_index + 1
932 continue
933
934 out.append(line)
935 index += 1
936
937 return "\n".join(out), footers
938
939
940 def _update_pre_code_depth(line: str, pre_depth: int, code_depth: int) -> tuple[int, int]:
941 pre_depth = max(0, pre_depth + len(_OPEN_PRE_RE.findall(line)) - len(_CLOSE_PRE_RE.findall(line)))
942 code_depth = max(0, code_depth + len(_OPEN_CODE_RE.findall(line)) - len(_CLOSE_CODE_RE.findall(line)))
943 return pre_depth, code_depth
944
945
946 def _wrap_engine_footer(body: str) -> str:
947 """Compatibility shim: ``_markdown_to_html`` now renders protected footers inline."""
948 return body
949
950
951 def _promote_meta_marker(body: str) -> str:
952 """Promote standalone ``<!-- META: ... -->`` markers into ``<div class="meta">``.
953
954 Only standalone block-level lines outside ``<pre>``/``<code>`` elements are
955 promoted so markers inside attributes (such as ``href="..."``), inline
956 text, or code blocks can never break out of their HTML context.
957 """
958 out: list[str] = []
959 pre_depth = 0
960 code_depth = 0
961 for line in body.splitlines():
962 if pre_depth == 0 and code_depth == 0:
963 stripped = line.strip()
964 promoted: str | None = None
965 for pattern in _STANDALONE_META_PROMOTE_PATTERNS:
966 match = pattern.fullmatch(stripped)
967 if match:
968 text = html.escape(html.unescape(match.group(1).strip()))
969 promoted = f'<div class="meta">{text}</div>'
970 break
971 if promoted is not None:
972 out.append(promoted)
973 continue
974 out.append(line)
975 pre_depth, code_depth = _update_pre_code_depth(line, pre_depth, code_depth)
976 return "\n".join(out)
977
978 # Schemes allowed in synthesized markdown links. The HTML artifact is opened in
979 # a browser, so a permissive link parser exposes a stored-XSS vector: a
980 # `[label](javascript:...)` or `[label](data:text/html,...)` link surviving the
981 # LLM synthesis would render as a clickable script payload in the saved file.
982 # Restrict link URLs to a small allowlist of schemes and accept relative URLs
983 # (no scheme, no `:` before the first `/` or `?`, and no protocol-relative `//`).
984 # Anything else is rendered as plain bracketed text so the label remains readable.
985 _SAFE_LINK_SCHEMES = frozenset({"http", "https", "mailto"})
986 _SAFE_LIBRARY_LINK_SCHEMES = frozenset({"http", "https"})
987 _INVALID_HOSTNAME_CHARS = frozenset(' "\'<>\\&;')
988
989
990 def _is_safe_url_candidate(
991 url: str,
992 allowed_schemes: frozenset[str],
993 ) -> bool:
994 # Reject any control characters (e.g. `java\x0Dscript:` or leading `\t`
995 # stripped by browser URL parsers before scheme detection).
996 if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in url):
997 return False
998 stripped = url.strip()
999 if not stripped:
1000 return False
1001 # Reject protocol-relative (`//evil.example`) and backslash-led URLs (`\\`,
1002 # `\/`, `/\`) that browsers can resolve against an external host.
1003 if stripped.startswith(("//", "\\", "/\\")):
1004 return False
1005 # No scheme — relative URL or fragment. Allow.
1006 colon = stripped.find(":")
1007 if colon == -1:
1008 return True
1009 slash = stripped.find("/")
1010 question = stripped.find("?")
1011 hash_ = stripped.find("#")
1012 # The first `:` that comes after a `/`, `?`, or `#` is path/query/fragment,
1013 # not a scheme separator. e.g. `/path:with:colons` is a relative URL.
1014 earlier = [pos for pos in (slash, question, hash_) if 0 <= pos < colon]
1015 if earlier:
1016 return True
1017 scheme = stripped[:colon].lower()
1018 if scheme not in allowed_schemes:
1019 return False
1020 if scheme in {"http", "https"}:
1021 if stripped[colon : colon + 3] != "://":
1022 return False
1023 try:
1024 parsed = urlsplit(stripped)
1025 hostname = parsed.hostname
1026 _ = parsed.port
1027 except ValueError:
1028 return False
1029 if not hostname or any(ch in _INVALID_HOSTNAME_CHARS for ch in hostname):
1030 return False
1031 return True
1032
1033
1034 def _is_safe_link_url(
1035 url: str,
1036 *,
1037 allowed_schemes: frozenset[str] = _SAFE_LINK_SCHEMES,
1038 ) -> bool:
1039 """Return True if a link URL is safe to render as an ``<a href>``.
1040
1041 A URL is safe if it either:
1042 - has no scheme (relative URL, fragment, or path-only, excluding
1043 protocol-relative ``//`` and backslash-led paths), or
1044 - uses a scheme in ``allowed_schemes`` (default: http, https, mailto).
1045
1046 The scheme check is case-insensitive and tolerant of surrounding ASCII
1047 spaces while rejecting all control characters.
1048
1049 Precondition: ``url`` must already have been through ``html.escape`` (as it
1050 is in ``_inline_markdown`` and ``_safe_library_href``). Checks the escaped
1051 string as well as up to two rounds of ``html.unescape`` so entity-encoded
1052 schemes like ``javascript&#58;alert(1)`` or ``&#106;avascript:alert(1)``
1053 are also rejected even if a downstream consumer decodes entities.
1054 """
1055 if not isinstance(url, str):
1056 return False
1057 candidate = url
1058 for _ in range(3):
1059 if not _is_safe_url_candidate(candidate, allowed_schemes):
1060 return False
1061 decoded = html.unescape(candidate)
1062 if decoded == candidate:
1063 break
1064 candidate = decoded
1065 return True
1066
1067
1068 def _safe_library_href(url: str) -> str | None:
1069 """Validate and HTML-escape a library index URL, or return None if unsafe."""
1070 if not isinstance(url, str):
1071 return None
1072 if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in url):
1073 return None
1074 stripped = url.strip()
1075 if not stripped:
1076 return None
1077 escaped = html.escape(stripped, quote=True)
1078 if not _is_safe_link_url(escaped, allowed_schemes=_SAFE_LIBRARY_LINK_SCHEMES):
1079 return None
1080 return escaped
1081
1082
1083 def _render_inline_links(escaped: str, code_prefix: str) -> str:
1084 if "](" not in escaped:
1085 return escaped
1086
1087 closing_parens: dict[int, int] = {}
1088 open_parens: list[int] = []
1089 # Pair delimiters once so unclosed destinations do not rescan the same suffix.
1090 for delimiter in re.finditer(r"[()]|\s+", escaped):
1091 if delimiter[0] == "(":
1092 open_parens.append(delimiter.start())
1093 elif delimiter[0] == ")":
1094 if open_parens:
1095 closing_parens[open_parens.pop()] = delimiter.start()
1096 else:
1097 open_parens.clear()
1098
1099 link_start = re.compile(r"\[([^\]]+)\]\(")
1100 parts: list[str] = []
1101 copied_until = search_from = 0
1102 while match := link_start.search(escaped, search_from):
1103 start = match.end()
1104 search_from = start
1105 end = closing_parens.get(start - 1)
1106 if end is None or end == start:
1107 continue
1108 search_from = end + 1
1109 url = escaped[start:end]
1110 # Never allow an inline code span to expand into markup inside href.
1111 if code_prefix in url or not _is_safe_link_url(url):
1112 continue
1113 parts.append(escaped[copied_until:match.start()])
1114 parts.append(f'<a href="{url}" rel="noopener noreferrer">{match[1]}</a>')
1115 copied_until = search_from
1116 parts.append(escaped[copied_until:])
1117 return "".join(parts)
1118
1119
1120 def _inline_markdown(text: str) -> str:
1121 escaped = html.escape(text, quote=True)
1122 nonce = secrets.token_hex(12)
1123 code_prefix = f"__CODE_{nonce}_"
1124 code_tokens: dict[str, str] = {}
1125
1126 def code_replace(match: re.Match[str]) -> str:
1127 token = f"{code_prefix}{len(code_tokens)}__"
1128 code_tokens[token] = f"<code>{match.group(1)}</code>"
1129 return token
1130
1131 escaped = re.sub(r"`([^`]+)`", code_replace, escaped)
1132 escaped = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", escaped)
1133 escaped = _render_inline_links(escaped, code_prefix)
1134 if code_tokens:
1135 token_re = re.compile(rf"{re.escape(code_prefix)}\d+__")
1136 escaped = token_re.sub(
1137 lambda match: code_tokens.get(match.group(0), match.group(0)),
1138 escaped,
1139 )
1140 return escaped
1141
1142
1143 def _is_table_row(line: str) -> bool:
1144 return "|" in line and len(_split_table_cells(line)) >= 2
1145
1146
1147 def _is_table_separator(line: str) -> bool:
1148 cells = _split_table_cells(line)
1149 return bool(cells) and all(re.fullmatch(r":?-{3,}:?", cell.strip()) for cell in cells)
1150
1151
1152 def _split_table_cells(line: str) -> list[str]:
1153 """Split a Markdown table row on unescaped ``|`` and unescape ``\\|`` and ``\\\\``."""
1154 stripped = line.strip()
1155 if not stripped:
1156 return []
1157 if stripped.startswith("|"):
1158 stripped = stripped[1:]
1159 cells: list[str] = []
1160 buf: list[str] = []
1161 i = 0
1162 n = len(stripped)
1163 ended_with_delimiter = False
1164 while i < n:
1165 ch = stripped[i]
1166 if ch == "\\" and i + 1 < n and stripped[i + 1] in ("|", "\\"):
1167 buf.append(stripped[i + 1])
1168 i += 2
1169 ended_with_delimiter = False
1170 elif ch == "|":
1171 cells.append("".join(buf).strip())
1172 buf = []
1173 i += 1
1174 ended_with_delimiter = True
1175 else:
1176 buf.append(ch)
1177 i += 1
1178 ended_with_delimiter = False
1179 if not ended_with_delimiter:
1180 cells.append("".join(buf).strip())
1181 return cells
1182
1183
1184 def _render_table(rows: list[str]) -> str:
1185 header = _split_table_cells(rows[0])
1186 body_rows = [_split_table_cells(row) for row in rows[1:]]
1187 out = ["<table>", "<thead>", "<tr>"]
1188 out.extend(f"<th>{_inline_markdown(cell)}</th>" for cell in header)
1189 out.extend(["</tr>", "</thead>", "<tbody>"])
1190 for row in body_rows:
1191 out.append("<tr>")
1192 out.extend(f"<td>{_inline_markdown(cell)}</td>" for cell in row)
1193 out.append("</tr>")
1194 out.extend(["</tbody>", "</table>"])
1195 return "\n".join(out)
1196
1197
1198 def _build_colophon(report: schema.Report, *, topic: str | None = None) -> str:
1199 display_topic = topic or report.topic
1200 generated = html.escape(_generated_date(report))
1201 version = render._skill_version()
1202 escaped_topic = html.escape(display_topic)
1203 rerun = html.escape(f"/last30days {display_topic}")
1204 return (
1205 '<div class="colophon">\n'
1206 f" Generated {generated} by /last30days v{html.escape(version)} · topic: {escaped_topic}<br>\n"
1207 f' Re-run for fresh data: <span class="rerun">{rerun}</span>\n'
1208 "</div>"
1209 )
1210
1211
1212 def _generated_date(report: schema.Report) -> str:
1213 if report.generated_at:
1214 return report.generated_at[:10]
1215 return date.today().strftime("%Y-%m-%d")
1216
1217
1218 def _wrap_in_template(body: str, colophon: str, title: str) -> str:
1219 replacements = {
1220 "__TITLE__": html.escape(title),
1221 "__CSS__": CSS,
1222 "__BODY__": body,
1223 "__COLOPHON__": colophon,
1224 }
1225 return _TEMPLATE_PLACEHOLDER_PATTERN.sub(
1226 lambda match: replacements[match.group(0)],
1227 HTML_TEMPLATE,
1228 )
1229
1229 lines PYTHON