Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

68.8 KB
Raw Blame
#!/usr/bin/env python3
"""Builds the static kwant website in site/ from the page sources in site-src/.

The output is committed, so serving or deploying site/ needs no build step.
Run `python3 scripts/build_site.py` after editing anything in site-src/.

Each page source starts with a header block of `key: value` lines, then `---`, then HTML.
Keys: title, description, path (output path under site/), nav (docs nav id, docs pages only),
active (header link to mark current on non-docs pages), faq (yes: FAQPage JSON-LD from the page's
<section class="faq">, each <h3> question and the <p> after it), and card, card_title, card_art for the
social card (see scripts/build_og.py).
Shortcodes in the HTML:
  {{root}}                                relative path back to site/
  {{shot:NAME|ALT|SIZES}}                 a zoomable responsive screenshot (desktop-* or phone-*); desktop ones not in
                                          CLOSEUPS get class="app", the window bar in site.css
  {{video:NAME|LABEL}}                    a muted looping demo clip; site.js sets its poster near the screen, <noscript> has it (class="app", window bar too)
  {{install:ID}}                          the install command box with macOS/Linux and Docker tabs
  {{CONTACT_EMAIL}}                       the contact address, from OPERATOR below (marked placeholder while empty)
  {{avatar:ROLE}}                         a kwant app avatar (the same CRT-framed creature the app draws)
  {{char:ROLE}}                           the same creature without its frame (hero and footer crew)
  {{releases}}                            the release line under the hero: latest Mac version and date, release count
                                          since the first one, licence (from CHANGELOG.md, see release_line)
  {{windows_exe}}                         the latest release's Windows (beta) installer URL (from CHANGELOG.md, see
                                          windows_installer); its file name carries the version, so it can't use
                                          releases/latest/download like the .dmg

Every local asset URL in the pages and in site.css gets a `?v=<content hash>` query, so a deploy never pairs new HTML
with a browser's cached old CSS, JS, fonts or images.

Pages also get their social tags (Open Graph, Twitter), JSON-LD structured data and a sitemap with lastmod dates.
The build also writes llms.txt (https://llmstxt.org): a short summary of kwant for AI assistants, listing every page with
its title and description, so new pages show up there without extra work.
Each page's og:image is its own card from scripts/build_og.py (site/assets/og/), so run that first when titles or cards change.
lastmod and the docs' dateModified come from the last git commit that changed the page body (today if it's uncommitted).

The blog: each post is a Markdown file in site-src/blog/ (see BLOG_HELP below for its header keys and what the Markdown
supports). Posts become blog/<file name>.html, with BlogPosting JSON-LD, a reading time and related posts; the build also
writes blog/index.html and the RSS feed blog/feed.xml, and adds the posts to the sitemap and llms.txt. A post with
`draft: yes` is left out of everything; `python3 scripts/build_site.py --drafts` builds drafts too, for a local preview
only (never commit that build). The Blog link in the header and footer appears once one post is published.

It also writes the favicons (favicon.svg, favicon-32.png, apple-touch-icon.png, favicon.ico) from LOGO_RECTS,
so the tab icon is always the header logo.
"""
import datetime
import hashlib
import html
import json
import os
import pathlib
import posixpath
import re
import shutil
import struct
import subprocess
import sys
import urllib.request
import zlib

ROOT = pathlib.Path(__file__).resolve().parent.parent
SRC = ROOT / "site-src"
MEDIA = ROOT / "site" / "assets" / "media"
OUT = ROOT / "site"
SITE_URL = "https://kwant.si"
GITHUB = "https://github.com/alexsergivan/kwant"
# How to reach whoever runs kwant.si, for the privacy policy and terms ({{CONTACT_EMAIL}} in the page sources).
# An empty value leaves the marked placeholder in the page, and check_site.py fails until it is filled in.
OPERATOR = {
    "CONTACT_EMAIL": "[email protected]",
}

# Cloudflare Web Analytics: counts page views without cookies, local storage or fingerprinting. The token is the kwant.si
# site in Cloudflare (automatic install is off there). site/_headers allows its two hosts in script-src and connect-src.
# The page only carries the token; site.js adds the beacon script after the first paint, so it never competes with the
# page's own files.
CF_ANALYTICS = '<script type="application/json" id="cf-beacon">{"token": "7f6ed395033a43eea3885ad0943890c2"}</script>'


# On the home page every lazy image waits for site.js, which loads it when it comes within 600 px of the screen. Native
# lazy loading starts them at the first layout, before the first paint, where on a phone they compete with the hero
# poster (the LCP image). Until then the image shows an empty picture of the same size; <noscript> keeps the real one.
LAZY_IMG = re.compile(r'<img\b[^>]*\bloading="lazy"[^>]*>')


def defer_images(page_html):
    def one(m):
        tag = m[0]
        before = m.string[:m.start()]
        if before.rfind("<picture") > before.rfind("</picture>"):
            return tag  # a <picture> picks its own source; leave it to the browser's lazy loading
        w, h = re.search(r'\bwidth="(\d+)"', tag)[1], re.search(r'\bheight="(\d+)"', tag)[1]
        empty = f"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='{w}' height='{h}'/%3E"
        lazy = re.sub(r'\ssrc="', f' src="{empty}" data-src="', tag, count=1).replace(' srcset="', ' data-srcset="', 1)
        return f"{lazy}<noscript>{tag}</noscript>"
    return LAZY_IMG.sub(one, page_html)


DOC_GROUPS = [
    ("Get started", [("quickstart", "Quickstart"), ("install", "Install & run"), ("phone", "On your phone")]),
    ("Using kwant", [
        ("spaces", "Spaces"),
        ("bots-and-teams", "Bots & teams"),
        ("accounts", "Accounts & profiles"),
        ("models", "Models & routing"),
        ("approvals", "Approvals & passwords"),
        ("agents-in-vm", "Run Claude in the VM"),
        ("flight-school", "Flight School"),
        ("smart-results", "Smart Results"),
        ("dev-mode", "Dev mode"),
    ]),
    ("Works on its own", [
        ("mission-board", "Mission board"),
        ("goals", "Goals"),
        ("idea-jar", "Idea jar"),
        ("routines", "Routines & bot actions"),
        ("memory-skills", "Memory, skills & search"),
        ("lessons", "Lessons"),
        ("truth-ledger", "Truth Ledger"),
        ("loose-ends", "Loose ends & letters"),
        ("parallel-universe", "Parallel Universe"),
    ]),
    ("Connect", [("mcp", "MCP tools"), ("home-assistant", "Home Assistant"), ("agents-connect", "Coding agents"), ("telegram", "Telegram"), ("browser", "Browser"),
                 ("browser-proxy", "Browser proxy")]),
]
DOCS = [d for _, items in DOC_GROUPS for d in items]

# The mark is the kwant app's antenna bot, the same 8-bit creature the bots use as avatars.
LOGO_RECTS = [
    (10, 4, 1, 1, "#1d1147"), (10, 1, 2, 2, "#ddd5ff"), (4, 5, 8, 1, "#fff"), (3, 6, 10, 1, "#fff"), (2, 7, 12, 7, "#fff"),
    (3, 14, 10, 1, "#fff"), (4, 15, 8, 1, "#ddd5ff"), (13, 7, 1, 7, "#ddd5ff"), (5, 8, 2, 3, "#1d1147"), (9, 8, 2, 3, "#1d1147"),
    (3, 11, 2, 1, "#b8a9fb"), (11, 11, 2, 1, "#b8a9fb"), (6, 12, 1, 1, "#1d1147"), (9, 12, 1, 1, "#1d1147"), (7, 13, 2, 1, "#1d1147"),
    (4, 16, 2, 1, "#ddd5ff"), (10, 16, 2, 1, "#ddd5ff"),
]
LOGO = (
    '<svg viewBox="0 0 16 17" width="38" height="38" shape-rendering="crispEdges" aria-hidden="true">'
    + "".join(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{c}"/>' for x, y, w, h, c in LOGO_RECTS)
    + "</svg>"
)
GH_ICON = (
    '<svg viewBox="0 0 16 16" width="17" height="17" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 '
    '5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52'
    '-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59'
    '.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82'
    '.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 '
    '.21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>'
)


# ---- App avatars, ported from frontend/src/components/ModernAvatar.tsx (framed, 26-grid) ----
AV_FRAME, AV_PANEL, AV_SCAN, AV_INK, AV_BLUSH = "#4a3f8a", "#15112e", "#0d0a1f", "#1b1033", "#ff6b81"
AV_PALETTES = {
    "yellow": ("#fdc934", "#d98a1f", "#fff0a0", "#5ce1ff"),
    "green": ("#3ccf6e", "#1f8f4c", "#a8f5bf", "#c6ff6b"),
    "cyan": ("#5ce1ff", "#2a92c9", "#d2f7ff", "#ff6b81"),
    "violet": ("#a98bff", "#6d4fd6", "#e1d6ff", "#ffd23f"),
    "blue": ("#6d9bff", "#3c5fcf", "#cddcff", "#ff7eb6"),
    "coral": ("#ff8a7a", "#cf5446", "#ffd6cf", "#6d4fd6"),
    "red": ("#ff6b6b", "#c43c4c", "#ffc9c9", "#5ce1ff"),
    "mint": ("#9be564", "#5e9e33", "#e2ffc7", "#ffe066"),
}
AV_ROLES = {
    "brand": ("yellow", "antenna"), "user": ("blue", "ears"), "architect": ("violet", "horns"),
    "tech_lead": ("cyan", "visor"), "devops": ("green", "spikes"), "designer": ("coral", "beret"),
    "qa": ("red", "goggles"), "research": ("mint", "bulb"),
}


def avatar_rects(role):
    pal, acc = AV_ROLES[role]
    body, shade, light, accent = AV_PALETTES[pal]
    head = {
        "antenna": [(15, 6, 1, 1, AV_INK), (15, 3, 2, 2, accent), (15, 3, 1, 1, "#ffffff")],
        "spikes": [(10, 5, 1, 2, body), (13, 4, 1, 3, body), (16, 5, 1, 2, body), (6, 10, 1, 1, shade), (6, 13, 1, 1, shade),
                   (19, 10, 1, 1, shade), (19, 13, 1, 1, shade), (13, 4, 1, 1, light)],
        "ears": [(8, 5, 2, 3, body), (16, 5, 2, 3, shade), (8, 6, 1, 1, AV_BLUSH), (17, 6, 1, 1, AV_BLUSH)],
        "horns": [(8, 5, 1, 2, accent), (9, 6, 1, 1, accent), (17, 5, 1, 2, accent), (16, 6, 1, 1, accent)],
        "visor": [(9, 5, 8, 1, accent), (8, 6, 1, 3, accent), (17, 6, 1, 3, accent), (6, 10, 2, 3, accent), (18, 10, 2, 3, accent)],
        "beret": [(9, 5, 8, 2, accent), (8, 6, 1, 1, accent), (13, 4, 1, 1, accent), (10, 5, 2, 1, "#9a7cff")],
        "bulb": [(12, 2, 2, 1, accent), (11, 3, 4, 2, accent), (12, 3, 1, 1, "#ffffff"), (12, 5, 2, 1, "#8a8aa8"), (12, 6, 2, 1, AV_INK)],
    }.get(acc, [])
    face = {
        "goggles": [(7, 8, 12, 1, AV_INK), (9, 7, 3, 2, accent), (14, 7, 3, 2, accent), (9, 7, 1, 1, "#ffffff"), (14, 7, 1, 1, "#ffffff")],
    }.get(acc, [])
    return [(7, 20, 12, 1, "#261d4a")] + head + [
        (9, 7, 8, 1, body), (8, 8, 10, 1, body), (7, 9, 12, 7, body), (8, 16, 10, 1, body), (9, 17, 8, 1, shade),
        (18, 9, 1, 7, shade), (17, 16, 1, 1, shade), (7, 15, 1, 1, shade), (8, 16, 1, 1, shade), (10, 8, 2, 1, light), (9, 9, 1, 1, light),
        (10, 10, 2, 3, AV_INK), (14, 10, 2, 3, AV_INK), (10, 10, 1, 1, "#f5f2ff"), (14, 10, 1, 1, "#f5f2ff"),
        (8, 13, 2, 1, AV_BLUSH), (16, 13, 2, 1, AV_BLUSH), (11, 14, 1, 1, AV_INK), (14, 14, 1, 1, AV_INK), (12, 15, 2, 1, AV_INK),
        (9, 18, 2, 1, AV_INK), (15, 18, 2, 1, AV_INK),
    ] + face


AV_FRAME_FILL = [(6, 2, 14, 22), (4, 3, 18, 20), (3, 4, 20, 18), (2, 6, 22, 14)]


def avatar(role):
    r = lambda x, y, w, h, c: f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{c}"/>'
    parts = [r(x - 1, y - 1, w + 2, h + 2, AV_FRAME) for x, y, w, h in AV_FRAME_FILL]
    parts += [r(x, y, w, h, AV_PANEL) for x, y, w, h in AV_FRAME_FILL]
    parts += [r(3.5, 4.5 + i, 19, 0.25, AV_SCAN) for i in range(16)]
    parts += [r(*a) for a in avatar_rects(role)]
    return f'<svg class="av" viewBox="0 0 26 26" width="34" height="34" shape-rendering="crispEdges" aria-hidden="true">{"".join(parts)}</svg>'


def char(role):
    """{{char:role}}: the avatar creature alone, no frame or screen (the redesign's hero and footer crew)."""
    rects = "".join(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{c}"/>' for x, y, w, h, c in avatar_rects(role))
    return f'<svg class="char-svg" viewBox="5 1 16 20" shape-rendering="crispEdges" aria-hidden="true">{rects}</svg>'


def px_icon(rows, cls="pi", label=None):
    """A pixel icon from strings of '#' and '.', one rect per run, drawn in currentColor."""
    h, w = len(rows), max(len(r) for r in rows)
    rects = "".join(
        f'<rect x="{m.start()}" y="{y}" width="{m.end() - m.start()}" height="1"/>'
        for y, row in enumerate(rows) for m in re.finditer(r"#+", row)
    )
    aria = f'role="img" aria-label="{label}"' if label else 'aria-hidden="true"'
    return f'<svg class="{cls}" viewBox="0 0 {w} {h}" shape-rendering="crispEdges" fill="currentColor" {aria}>{rects}</svg>'


# Pixel icons (Mira's site redesign, Nov 2026). One string per row, '#' is a filled pixel.
IC = {
    "handoff": [".........", "....#....", "....##...", "#######..", "########.", "#######..", "....##...", "....#....", "........."],
    "shield": [".#######.", ".#######.", ".##...##.", ".##...##.", ".##...##.", "..##.##..", "..##.##..", "...###...", "....#...."],
    "cursor": ["#........", "##.......", "###......", "####.....", "#####....", "######...", "###......", "#..##....", "....##..."],
    "moon": ["...####..", "..##.....", ".##......", ".##......", ".##......", ".##......", "..##...#.", "...#####.", "........."],
    "check": [".........", ".......##", "......##.", ".....##..", "##..##...", ".####....", "..##.....", ".........", "........."],
    "down": ["...##...", "...##...", "...##...", "#..##..#", "##.##.##", ".######.", "..####..", "...##...", "########"],
    "star": ["....#....", "...###...", "#########", ".#######.", "..#####..", "..##.##..", ".##...##.", "........."],
    "heart": [".##.##.", "#######", "#######", ".#####.", "..###..", "...#..."],
    "pause": ["##..##", "##..##", "##..##", "##..##", "##..##", "##..##"],
    "play": ["#.....", "###...", "#####.", "#####.", "###...", "#....."],
    "full": ["###..###", "#......#", "#......#", "........", "........", "#......#", "#......#", "###..###"],
    "arrow": ["....#...", ".....#..", "########", ".....#..", "....#..."],
}

# The GitHub star count in the nav, read once per build. The build never needs the network: offline, rate-limited or
# slow, it falls back to STARS_FALLBACK. KWANT_STARS=<n> pins it (KWANT_STARS=off skips the call).
STARS_FALLBACK = 522
_STARS = None


def stars():
    global _STARS
    if _STARS is None:
        pinned = os.environ.get("KWANT_STARS", "")
        n = STARS_FALLBACK
        if pinned.isdigit():
            n = int(pinned)
        elif pinned != "off":
            try:
                req = urllib.request.Request(
                    "https://api.github.com/repos/alexsergivan/kwant",
                    headers={"Accept": "application/vnd.github+json", "User-Agent": "kwant-site-build"},
                )
                with urllib.request.urlopen(req, timeout=4) as r:
                    n = int(json.load(r)["stargazers_count"]) or STARS_FALLBACK
            except Exception:
                n = STARS_FALLBACK
        _STARS = f"{n / 1000:.1f}k".replace(".0k", "k") if n >= 1000 else str(n)
    return _STARS


def parse(path):
    text = path.read_text()
    head, body = text.split("\n---\n", 1)
    meta = {}
    for line in head.strip().splitlines():
        k, v = line.split(":", 1)
        meta[k.strip()] = v.strip()
    return meta, body


# Desktop shots that are close-ups, not the whole app window, so they get no window bar (see img.app in site.css).
CLOSEUPS = {"v69-signin-card", "v69-working-card", "v611-reply-close", "v611-human-check-card",
            "v071-post-github-card", "v071-dev-on-card", "v071-dev-off-armed-card", "v071-lgtm-card",
            "v072-dev-repos-card", "v072-dev-explainer-card", "v072-dev-repo-chips-card", "v072-switch-on-card",
            "v07-dev-review-card", "v076-get-started-card", "v076-device-sign-in-card",
            "v076-linux-install-card", "v076-whats-new-card",
            "v077-claude-vm-card", "v077-isolation-notice-card", "v077-bring-your-bots-card",
            "v077-dev-fresh-card", "v077-import-several-card", "v077-whats-new-card",
            "v080-queued-under-running-card", "v080-import-card", "v080-prepush-card-card",
            "v080-fresh-eyes-chip-card", "v080-before-after-card", "v080-drop-files-card", "v080-import-preview-card",
            "v090-attention-card", "v090-ci-fixit-card", "v090-ci-verdict-card", "v090-line-notes-card", "v090-point-at-it-card", "v090-review-inbox-card", "v090-roll-back-card", "v090-roll-back-restore-card", "v090-scope-warning-card", "v090-tool-notes-card", "v090-tool-notes-chat-card", "v090-verdict-card", "v090-watch-chat-card", "v090-watch-mission-card", "v090-worktrees-card",
            "v095-apps-accounts-tiles", "v095-budget-overview-card", "v095-bot-budget-card", "v095-tool-failure-line-card",
            "v096-real-chrome-signin-card",
            "v097-working-avatar-card",
            "v098-done-check-card",
            "v099-update-off-race-card",
            "v0913-browser-upload-card"}


def shot(root, name, alt, sizes):
    phone = name.startswith("phone-")
    small, big, w, h = (390, 780, 390, 844) if phone else (1440, 2880, 1440, 900)
    base = f"{root}assets/media/{name}"
    sizes = sizes or "(max-width: 1024px) 100vw, 680px"
    a = html.escape(alt, quote=True)
    app = "" if phone or name in CLOSEUPS else ' class="app"'
    # A 720w copy, where one exists, keeps phones from fetching the 1440w file.
    mid = f"{base}-720.webp 720w, " if not phone and (MEDIA / f"{name}-720.webp").exists() else ""
    return (
        f'<a class="zoom" href="{base}-{big}.webp" data-caption="{a}">'
        f'<img{app} src="{base}-{small}.webp" srcset="{mid}{base}-{small}.webp {small}w, {base}-{big}.webp {big}w" '
        f'sizes="{sizes}" width="{w}" height="{h}" loading="lazy" decoding="async" alt="{a}"></a>'
    )


def video(root, name, label, eager=False):
    base = f"{root}assets/media/{name}"
    lbl = html.escape(label, quote=True)
    attrs = (f'class="app" data-autoplay controls muted playsinline loop preload="{"metadata" if eager else "none"}" '
             f'width="1280" height="800" aria-label="{lbl}"')
    src = f'<source src="{base}.mp4" type="video/mp4"></video>'
    # The poster waits in data-poster for site.js. Without JS, site.css hides this copy and the <noscript> one, with its
    # real poster, shows instead (the same way as the home page's lazy images).
    return (f'<video {attrs} data-poster="{base}-poster.webp">{src}'
            f'<noscript><video {attrs} poster="{base}-poster.webp">{src}</noscript>')


INSTALL = [
    ("src", "macOS · Linux", "git clone https://github.com/alexsergivan/kwant && cd kwant && make run"),
    ("docker", "Docker", "git clone https://github.com/alexsergivan/kwant && cd kwant && docker compose up -d --build"),
]


NOTAB = ' tabindex="-1"'


def install(uid):
    tabs = "".join(
        f'<button type="button" role="tab" id="{uid}-t-{k}" aria-controls="{uid}-p-{k}" '
        f'aria-selected="{"true" if i == 0 else "false"}"{"" if i == 0 else NOTAB}>{html.escape(label)}</button>'
        for i, (k, label, _) in enumerate(INSTALL)
    )
    panels = "".join(
        f'<div class="cmd" role="tabpanel" id="{uid}-p-{k}" aria-labelledby="{uid}-t-{k}"{"" if i == 0 else " hidden"}>'
        f'<span class="p" aria-hidden="true">$</span><code>{html.escape(cmd)}</code>'
        f'<button type="button" class="copy-cmd" aria-label="Copy the {html.escape(label)} install command">copy</button></div>'
        for i, (k, label, cmd) in enumerate(INSTALL)
    )
    return (
        f'<div class="install" data-tabs><div class="install-top"><span class="install-k" aria-hidden="true">Install</span>'
        f'<div class="tabs" role="tablist" aria-label="Install with">{tabs}</div></div>{panels}</div>'
    )


RELEASE_HEAD = re.compile(r"^## \[Mac (\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$", re.M)


def releases(changelog=None):
    """Mac releases as (version, date), newest first, from the CHANGELOG headings `## [Mac X.Y.Z] - YYYY-MM-DD`.

    CHANGELOG.md is the source because it is checked in: every release adds its heading in the same commit as the
    version bump, so the count can't fall behind, and the build needs no git tags or network. Pre-releases
    (mac-v0.1.0-test.1) never get a heading, so they don't count."""
    text = (ROOT / "CHANGELOG.md").read_text() if changelog is None else changelog
    found = [(v, datetime.date.fromisoformat(d)) for v, d in RELEASE_HEAD.findall(text)]
    if not found:
        raise SystemExit("CHANGELOG.md has no '## [Mac X.Y.Z] - YYYY-MM-DD' release headings")
    return sorted(found, key=lambda r: (r[1], tuple(int(n) for n in r[0].split("."))), reverse=True)


def short_date(d):
    return f"{d:%b} {d.day}"


def release_line(changelog=None):
    rel = releases(changelog)
    (latest, day), first = rel[0], rel[-1][1]
    count = f"{len(rel)} releases since {short_date(first)}" if len(rel) > 1 else "First release"
    return (
        f'<p class="proof">{latest} released {short_date(day)} <span aria-hidden="true">·</span> '
        f'<a href="{GITHUB}/releases" rel="noopener">{count}</a> <span aria-hidden="true">·</span> '
        f'<a href="{GITHUB}" rel="noopener">AGPL-3.0, open source</a></p>'
    )


def windows_installer(changelog=None):
    """The latest release's Windows (beta) installer. windows-release.yml names it kwant_<version>_windows_x64_beta_setup.exe
    and attaches it to the mac-v<version> release, so the link points at that exact file."""
    latest = releases(changelog)[0][0]
    return f"{GITHUB}/releases/download/mac-v{latest}/kwant_{latest}_windows_x64_beta_setup.exe"


def operator(key):
    value = OPERATOR[key].strip()
    if not value:
        return f'<span class="placeholder">{{{{{key}}}}}</span>'
    if key == "CONTACT_EMAIL":
        return f'<a href="mailto:{html.escape(value, quote=True)}">{html.escape(value)}</a>'
    return html.escape(value)


RELEASE_KICKER = re.compile(r'<p class="kicker">New in (\d+(?:\.\d+)+)(?: to (\d+(?:\.\d+)+))?(?: · ([^<]*))?</p>')
JUMP_VERSIONS = 6


def release_kickers(body):
    """features.html: the "New in 0.9.7" kicker above each release h2 becomes an amber `v0.9.7` chip and the release
    date (design.md: "amber v0.9.7 chip + date"). The page source keeps "New in X" so release edits stay the same."""
    dates = {v: d for v, d in releases()}

    def chip(m):
        first, last, extra = m[1], m[2], m[3]
        newest = last or first
        day = dates.get(newest if newest.count(".") == 2 else newest + ".0")
        ver = f"v{first}" + (f"–{last}" if last else "")
        when = f'<time datetime="{day.isoformat()}">{day:%b} {day.day}, {day.year}</time>' if day else ""
        more = f"<span>{extra}</span>" if extra else ""
        return f'<p class="rel-kick"><span class="sr-only">New in </span><span class="ver">{ver}</span>{when}{more}</p>'

    return RELEASE_KICKER.sub(chip, body)


def jump_versions(body):
    """The newest releases as mono links at the start of the features jump bar, then a divider before the topics."""
    found = re.findall(r'<section id="(new-\d+)"[^>]*>\s*<div class="wrap">\s*<div class="section-head">\s*'
                       r'<p class="kicker">New in (\d+(?:\.\d+)+)(?: to (\d+(?:\.\d+)+))?', body)
    links = "".join(f'<li><a class="ver" href="#{sid}">{last or first}</a></li>' for sid, first, last in found[:JUMP_VERSIONS])
    return f'<ul class="jump">{links}</ul><span class="sep" aria-hidden="true"></span>' if links else ""


def expand(body, root):
    body = body.replace("{{root}}", root)
    body = re.sub(r"\{\{(" + "|".join(OPERATOR) + r")\}\}", lambda m: operator(m[1]), body)
    body = re.sub(r"\{\{install:([a-z0-9-]+)\}\}", lambda m: install(m[1]), body)
    if "{{releases}}" in body:
        body = body.replace("{{releases}}", release_line())
    if "{{jump:versions}}" in body:
        body = body.replace("{{jump:versions}}", jump_versions(body))
    if '<p class="kicker">New in ' in body:
        body = release_kickers(body)
    if "{{windows_exe}}" in body:
        body = body.replace("{{windows_exe}}", windows_installer())
    body = re.sub(r"\{\{avatar:([a-z_]+)\}\}", lambda m: avatar(m[1]), body)
    body = re.sub(r"\{\{char:([a-z_]+)\}\}", lambda m: char(m[1]), body)
    body = re.sub(r"\{\{icon:([a-z]+)\}\}", lambda m: px_icon(IC[m[1]]), body)
    body = re.sub(r"\{\{shot:([^|}]+)\|([^|}]+)(?:\|([^}]*))?\}\}", lambda m: shot(root, m[1], m[2], m[3]), body)
    body = re.sub(
        r"\{\{video(!?):([^|}]+)\|([^}]+)\}\}", lambda m: video(root, m[2], m[3], eager=m[1] == "!"), body
    )
    return body


# The "Watch it work · 0:52" reel (home page, desktop). The pill and its lightbox are only emitted once the video is in
# site/assets/media, so the site never links to a missing file. The description is the reel's text alternative.
REEL = "assets/media/reel.mp4"
REEL_VTT = "assets/media/reel.vtt"
REEL_POSTERS = ("assets/media/reel-poster-960.webp", "assets/media/reel-poster-1920.webp")
REEL_DESC = ("kwant demo, 52 seconds. A team of bots picks up a task and hands it on, you point at the exact spot on a "
             "page that's wrong, a bot asks before running a risky command, each task shows the checks it passed, and a "
             "routine keeps watching overnight. Recorded on a sample demo workspace, with no real account or repo.")
# The real length (Kit's reel.json: 51.8 s). The label never claims a full minute.
REEL_LENGTH = "0:52"


def reel_markup(root):
    """The reel pill and its <dialog>. Without JS the pill is a plain link to the mp4. hero.js opens the dialog and only
    then sets the video's src and poster, so nothing of the reel loads with the page."""
    if not (OUT / REEL).exists():
        return "", ""
    posters = " ".join(f'data-poster-{w}="{root}{p}"' for w, p in zip(("sm", "lg"), REEL_POSTERS) if (OUT / p).exists())
    track = (f'\n      <track kind="captions" srclang="en" label="English" data-src="{root}{REEL_VTT}">'
             if (OUT / REEL_VTT).exists() else "")
    pill = (f'\n  <div class="reel"><a class="btn btn-line px" href="{root}{REEL}" data-reel aria-haspopup="dialog" '
            f'aria-controls="reel-dialog">{px_icon(IC["play"])}Watch it work <span>{REEL_LENGTH}</span></a></div>')
    dialog = f"""
<dialog class="reel-dialog" id="reel-dialog" aria-labelledby="reel-title" aria-describedby="reel-desc">
  <div class="reel-bar"><h2 id="reel-title">Watch kwant work</h2><button type="button" class="reel-close" data-reel-close aria-label="Close video">Close</button></div>
  <div class="reel-frame">
    <video controls playsinline preload="none" data-src="{root}{REEL}" {posters} aria-describedby="reel-desc">{track}
    </video>
    <button type="button" class="reel-play" data-reel-play hidden aria-label="Play video">{px_icon(IC["play"])}</button>
  </div>
  <p class="sr-only" id="reel-desc">{REEL_DESC}</p>
</dialog>"""
    return pill, dialog


def header(root, active, home_page=False):
    """The floating pill nav (Mira's site redesign): brand, Features, Docs, Blog once it is live, the GitHub star
    count written at build time, and Get started. The home page adds the reel pill and its dialog."""
    reel, dialog = reel_markup(root) if home_page else ("", "")
    home = root or "./"
    def nl(href, text, name):
        cur = ' aria-current="page"' if active == name else ""
        return f'<a class="nl" href="{href}"{cur}>{text}</a>'
    blog = nl(f"{root}blog/index.html", "Blog", "blog") + "\n    " if BLOG_LIVE else ""
    n = stars()
    return f"""<a class="skip" href="#main">Skip to content</a>
<header class="topbar">
  <nav class="pill px" aria-label="Main">
    <a class="brand" href="{home}" aria-label="kwant home">{LOGO}<span>kwant</span></a>
    {nl(f"{root}features.html", "Features", "features")}
    {nl(f"{root}docs/quickstart.html", "Docs", "docs")}
    {blog}<a class="nl stars" href="{GITHUB}" rel="noopener" aria-label="kwant on GitHub, {n} stars">{GH_ICON}<b>★ {n}</b></a>
    <a class="btn btn-solid btn-get px" href="{root}docs/quickstart.html">Get started</a>
  </nav>{reel}
</header>{dialog}"""


def footer(root, home_page=False):
    home = root or "./"
    blog = f'      <a href="{root}blog/index.html">Blog</a>\n' if BLOG_LIVE else ""
    crew = "".join(char(r) for r in ("research", "designer", "brand", "tech_lead", "qa"))
    hero_js = f'\n<script src="{root}assets/js/hero.js" defer></script>' if home_page else ""
    return f"""<footer class="site-footer">
  <div class="ground" aria-hidden="true"><div class="crew">{crew}</div></div>
  <div class="wrap">
    <div class="foot-grid">
    <div class="foot-brand">
      <a class="brand" href="{home}" aria-label="kwant home">{LOGO}<span>kwant</span></a>
      <p>A self-hosted team of AI bots in one binary. Free and open source under AGPL-3.0.</p>
      <p class="foot-star">kwant runs on coffee and GitHub stars. <a href="{GITHUB}" rel="noopener">Toss one our way {px_icon(IC["star"])}</a></p>
    </div>
    <nav aria-label="Product">
      <h2>Product</h2>
      <a href="{root}features.html">Features</a>
      <a href="{root}docs/quickstart.html">Quickstart</a>
      <a href="{root}docs/install.html">Install &amp; run</a>
      <a href="{root}docs/phone.html">On your phone</a>
      <a href="{root}self-hosted-ai-agents.html">Self-hosted AI agents</a>
{blog}      <a href="{root}docs/mcp.html">MCP tools</a>
    </nav>
    <nav aria-label="Using kwant">
      <h2>Using kwant</h2>
      <a href="{root}docs/spaces.html">Spaces</a>
      <a href="{root}docs/accounts.html">Accounts</a>
      <a href="{root}docs/approvals.html">Approvals</a>
      <a href="{root}docs/routines.html">Routines</a>
    </nav>
    <nav aria-label="Project">
      <h2>Project</h2>
      <a href="{GITHUB}" rel="noopener">GitHub</a>
      <a href="{GITHUB}/issues" rel="noopener">Issues</a>
      <a href="{GITHUB}/blob/main/SECURITY.md" rel="noopener">Security</a>
      <a href="{root}contact.html">Contact</a>
      <a href="https://x.com/kwantbot" rel="noopener">X (@kwantbot)</a>
    </nav>
    <nav aria-label="Legal">
      <h2>Legal</h2>
      <a href="{root}privacy.html">Privacy</a>
      <a href="{root}terms.html">Terms of use</a>
      <a href="{root}terms.html#license">License</a>
    </nav>
    </div>
    <div class="foot-base">
      <p class="foot-legal">kwant is not affiliated with or endorsed by Anthropic, OpenAI, xAI, Google or Apple. Their names and products are trademarks of their owners.</p>
      <p class="foot-notice"><strong>kwant has no token.</strong> Official X account is <a href="https://x.com/kwantbot" rel="noopener">@kwantbot</a>.</p>
      <p class="foot-made">Made in Germany with {px_icon(IC["heart"], label="love")}</p>
    </div>
  </div>
</footer>{hero_js}
<script src="{root}assets/js/site.js" defer></script>
<script src="{root}assets/js/pixel.js" defer></script>"""


def docs_shell(root, current, body):
    here = ' aria-current="page"'
    items = "\n".join(
        f'    <div class="docs-group"><h3>{html.escape(group)}</h3><ul>'
        + "".join(
            f'<li><a href="{root}docs/{slug}.html"{here if slug == current else ""}>{html.escape(label)}</a></li>'
            for slug, label in links
        )
        + "</ul></div>"
        for group, links in DOC_GROUPS
    )
    idx = [s for s, _ in DOCS].index(current)
    prev_link = next_link = ""
    if idx > 0:
        s, l = DOCS[idx - 1]
        prev_link = f'<a class="prev px" href="{root}docs/{s}.html"><small>Previous</small>{html.escape(l)}</a>'
    if idx < len(DOCS) - 1:
        s, l = DOCS[idx + 1]
        next_link = f'<a class="next px" href="{root}docs/{s}.html"><small>Next</small>{html.escape(l)}</a>'
    # Phones: the same groups in a <details> at the top of the article (Mira's docs-menu-390).
    here_label = html.escape(DOCS[idx][1])
    return f"""<div class="wrap docs">
  <nav class="docs-nav" aria-label="Docs">
    <h2>Docs</h2>
{items}
  </nav>
  <article class="prose">
    <details class="crumb-mobile">
      <summary class="px">{here_label} <span>Docs menu</span></summary>
      <nav aria-label="Docs (menu)">
{items.replace('<h3>', '<p class="docs-h">').replace('</h3>', '</p>')}
      </nav>
    </details>
{body}
    <nav class="pager" aria-label="Docs pages">{prev_link}{next_link}</nav>
  </article>
</div>"""


def git_dates(src):
    """(first published, last modified) as YYYY-MM-DD from git. Modified is the last commit that changed the page body, so
    header-only edits (a card line) don't look like new content. Today when the body has uncommitted changes or git isn't there."""
    today = datetime.date.today().isoformat()
    git = lambda *a: subprocess.run(["git", *a], cwd=ROOT, capture_output=True, text=True, check=True).stdout
    body = lambda text: text.split("\n---\n", 1)[-1]
    try:
        log = git("log", "--follow", "--name-only", "--format=@%H %cs", "--", str(src.relative_to(ROOT))).split("@")[1:]
    except (OSError, subprocess.CalledProcessError):
        return today, today
    commits = [(head.split()[0], head.split()[1], head.split()[2]) for head in (entry.strip() for entry in log) if len(head.split()) >= 3]
    if not commits:
        return today, today
    current, modified = body(src.read_text()), today
    for sha, date, path in commits:
        if body(git("show", f"{sha}:{path}")) != current:
            break
        modified = date
    return commits[-1][1], modified


def page_url(path):
    return SITE_URL + "/" + path.replace("index.html", "").replace(".html", "")


def og_image(path, image=None):
    """The page's own social card, with a content hash so link previews refresh when it changes. 404 uses the home card.
    A blog post can name its own image (a path under site/) instead."""
    if image:
        if not (OUT / image).is_file():
            sys.exit(f"{path}: image: {image} is not in site/")
        return f"{SITE_URL}/{image}?v={file_hash(OUT / image)}"
    name = "home" if path in ("index.html", "404.html") else path.removesuffix(".html").replace("/", "-")
    card = OUT / f"assets/og/{name}.png"
    if not card.exists():
        return f"{SITE_URL}/assets/og.png"
    return f"{SITE_URL}/assets/og/{name}.png?v={file_hash(card)}"


ORG_ID, SITE_ID, APP_ID = f"{SITE_URL}/#org", f"{SITE_URL}/#website", f"{SITE_URL}/#app"
LICENSES = [f"{GITHUB}/blob/main/LICENSE"]


def faq_items(body):
    """(question, answer) pairs from the page's <section class="faq">: each <h3> and the <p> right after it, as plain text,
    so the FAQPage JSON-LD always says exactly what the page shows."""
    section = re.search(r'<section class="faq"[^>]*>(.*?)</section>', body, re.S)
    if not section:
        sys.exit("faq: yes, but the page has no <section class=\"faq\">")
    text = lambda h: html.unescape(re.sub(r"<[^>]+>", "", h)).strip()
    return [(text(q), text(a)) for q, a in re.findall(r"<h3[^>]*>(.*?)</h3>\s*<p>(.*?)</p>", section[1], re.S)]


def structured_data(meta, url, title, image, dates, body=""):
    """JSON-LD for the page: the app, site and project on the home page, an article with breadcrumbs on docs pages."""
    path = meta["path"]
    org = {"@type": "Organization", "@id": ORG_ID, "name": "kwant", "alternateName": "kwnt", "url": SITE_URL + "/",
           "logo": f"{SITE_URL}/apple-touch-icon.png", "sameAs": [GITHUB]}
    crumbs = lambda items: {"@type": "BreadcrumbList", "itemListElement": [
        {"@type": "ListItem", "position": i + 1, "name": n, "item": u} for i, (n, u) in enumerate(items)]}
    if path == "index.html":
        graph = [
            org,
            {"@type": "WebSite", "@id": SITE_ID, "name": "kwant", "url": SITE_URL + "/", "inLanguage": "en", "publisher": {"@id": ORG_ID}},
            {"@type": "SoftwareApplication", "@id": APP_ID, "name": "kwant", "alternateName": "kwnt", "url": SITE_URL + "/", "description": meta["description"],
             "applicationCategory": "DeveloperApplication", "operatingSystem": "macOS, Linux", "image": image,
             "screenshot": f"{SITE_URL}/assets/media/desktop-team-discussion-1440.webp",
             "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"},
             "license": LICENSES, "isAccessibleForFree": True, "downloadUrl": GITHUB, "sameAs": [GITHUB],
             "author": {"@id": ORG_ID}, "publisher": {"@id": ORG_ID}},
            {"@type": "SoftwareSourceCode", "@id": f"{SITE_URL}/#code", "name": "kwant", "codeRepository": GITHUB,
             "programmingLanguage": ["Rust", "TypeScript"], "license": LICENSES, "targetProduct": {"@id": APP_ID}},
        ]
    elif meta.get("nav"):
        label = dict(DOCS)[meta["nav"]]
        graph = [
            {"@type": "TechArticle", "@id": url + "#article", "headline": title, "description": meta["description"], "url": url,
             "mainEntityOfPage": url, "image": image, "inLanguage": "en", "datePublished": dates[0], "dateModified": dates[1],
             "author": {"@id": ORG_ID}, "publisher": {"@id": ORG_ID}, "about": {"@id": APP_ID}, "isPartOf": {"@id": SITE_ID}},
            crumbs([("kwant", SITE_URL + "/"), ("Docs", f"{SITE_URL}/docs/quickstart"), (label, url)]),
            org,
        ]
    elif meta.get("kind") == "post":
        author = ({"@id": ORG_ID} if meta["author"] == BLOG_AUTHOR else {"@type": "Person", "name": meta["author"]})
        post = {"@type": "BlogPosting", "@id": url + "#post", "headline": title, "description": meta["description"], "url": url,
                "mainEntityOfPage": url, "image": image, "inLanguage": "en", "datePublished": meta["date"],
                "dateModified": meta["updated"], "author": author, "publisher": {"@id": ORG_ID},
                "wordCount": meta["words"], "isPartOf": {"@id": BLOG_ID}, "about": {"@id": APP_ID}}
        if meta["tag_list"]:
            post["keywords"] = meta["tag_list"]
        graph = [post, crumbs([("kwant", SITE_URL + "/"), ("Blog", f"{SITE_URL}/blog/"), (title, url)]), org]
    elif meta.get("kind") == "blog":
        graph = [
            {"@type": "Blog", "@id": BLOG_ID, "name": BLOG_TITLE, "description": meta["description"], "url": url, "inLanguage": "en",
             "publisher": {"@id": ORG_ID}, "isPartOf": {"@id": SITE_ID}, "blogPost": [
                 {"@type": "BlogPosting", "@id": page_url(m["path"]) + "#post", "headline": m["title"], "url": page_url(m["path"]),
                  "datePublished": m["date"], "dateModified": m["updated"]} for m in meta["posts"]]},
            crumbs([("kwant", SITE_URL + "/"), ("Blog", url)]),
            org,
        ]
    elif path == "404.html":
        return ""
    else:
        graph = [
            {"@type": "ContactPage" if path == "contact.html" else "WebPage", "@id": url, "name": title, "description": meta["description"], "url": url, "image": image,
             "inLanguage": "en", "dateModified": dates[1], "about": {"@id": APP_ID}, "isPartOf": {"@id": SITE_ID}},
            crumbs([("kwant", SITE_URL + "/"), (title.split(":")[0], url)]),
        ]
    if meta.get("faq") == "yes":
        graph.append({"@type": "FAQPage", "@id": url + "#faq", "url": url, "mainEntity": [
            {"@type": "Question", "name": q, "acceptedAnswer": {"@type": "Answer", "text": a}} for q, a in faq_items(body)]})
    data = json.dumps({"@context": "https://schema.org", "@graph": graph}, ensure_ascii=False, separators=(",", ":"))
    # JSON-LD is a data block, not a script, so the CSP's script-src doesn't apply to it. It goes at the end of <body>
    # so the head and the first screen of text still fit in the first TCP round trip.
    return f'<script type="application/ld+json">{data.replace("</", "<" + chr(92) + "/")}</script>\n'


def page(meta, body, root, dates):
    title = meta["title"]
    full_title = title if title.startswith("kwant") else f"{title} · kwant"
    desc = html.escape(meta["description"], quote=True)
    is404 = meta["path"] == "404.html"
    robots = '<meta name="robots" content="noindex">\n' if is404 else ""
    url = page_url(meta["path"])
    image = og_image(meta["path"], meta.get("image"))
    card_name = "kwant" if is404 else meta.get("card_title") or title.split(":")[0]
    img_alt = html.escape(f"{card_name}: {meta.get('card', meta['description'])}", quote=True)
    ftitle = html.escape(full_title, quote=True)
    article = (
        f'<meta property="article:published_time" content="{dates[0]}">\n<meta property="article:modified_time" content="{dates[1]}">\n'
        if meta.get("nav") or meta.get("kind") == "post" else ""
    )
    if meta.get("kind") == "post":
        article += "".join(f'<meta property="article:tag" content="{html.escape(t, quote=True)}">\n' for t in meta["tag_list"])
    if meta.get("kind") in ("post", "blog"):
        article += f'<link rel="alternate" type="application/rss+xml" title="{BLOG_TITLE}" href="{SITE_URL}/blog/feed.xml">\n'
    return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{html.escape(full_title)}</title>
<meta name="description" content="{desc}">
<meta name="theme-color" content="#0d0a1f">
<meta name="color-scheme" content="dark">
{robots}<link rel="canonical" href="{url}">
<meta property="og:type" content="{"article" if meta.get("nav") or meta.get("kind") == "post" else "website"}">
<meta property="og:site_name" content="kwant">
<meta property="og:locale" content="en_US">
<meta property="og:title" content="{ftitle}">
<meta property="og:description" content="{desc}">
<meta property="og:url" content="{url}">
<meta property="og:image" content="{image}">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="{img_alt}">
{article}<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@kwantbot">
<meta name="twitter:title" content="{ftitle}">
<meta name="twitter:description" content="{desc}">
<meta name="twitter:image" content="{image}">
<meta name="twitter:image:alt" content="{img_alt}">
<link rel="icon" href="{root}favicon.svg" type="image/svg+xml">
<link rel="icon" href="{root}favicon-32.png" sizes="32x32" type="image/png">
<link rel="apple-touch-icon" href="{root}apple-touch-icon.png">
<link rel="preload" href="{root}assets/fonts/pixelify-sans.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="{root}assets/fonts/inter-var.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="{root}assets/fonts/jetbrains-mono.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="{root}assets/css/site.css">
</head>
<body class="page-{meta.get("active", "docs" if meta.get("nav") else "home") if not is404 else "404"}">
{header(root, "docs" if meta.get("nav") else meta.get("active", "home"), meta["path"] == "index.html")}
<main id="main">
{body}
</main>
{footer(root, meta["path"] == "index.html")}
{structured_data(meta, url, title, image, dates, body)}{CF_ANALYTICS}
</body>
</html>
"""


# ---- Blog ----
BLOG_SRC = SRC / "blog"
BLOG_ID = f"{SITE_URL}/blog/#blog"
BLOG_LIVE = False  # set by main() once a post is published: shows the Blog link in the header and footer
BLOG_AUTHOR = "The kwant team"
BLOG_TITLE = "kwant blog"
BLOG_DESC = "Guides, comparisons and notes on running a self-hosted team of AI agents with kwant."
WORDS_PER_MINUTE = 220
BLOG_HELP = """A post's header keys (one `key: value` per line, then a line with ---):
  title, description, date (YYYY-MM-DD)     required
  updated (YYYY-MM-DD)                      when the post last changed in substance; defaults to date
  author                                    defaults to "The kwant team"
  tags                                      comma separated, e.g. comparison, self-hosted; related posts share tags
  card, card_title, card_art                the social card, as for pages (scripts/build_og.py)
  image                                     a site path (assets/media/x.png) to use as og:image instead of the card
  draft: yes                                left out of the site, the sitemap, the feed and llms.txt
Markdown: ## and ### headings (h2 get an id from their text), paragraphs, - and 1. lists, **bold**, *italic*, `code`,
[links](url), > quotes, ``` code blocks, | pipe | tables |, and a ```compare block (a comparison table that turns into
one card per row on phones; first row = column names, yes / no / partial cells get a mark and words), and a ```prompt
block (a code block that wraps its lines, for prose such as a prompt to copy into an AI tool). A line that
starts with < is passed through as HTML, and the page shortcodes ({{root}}, {{shot:…}}, …) work too."""

_SLUG = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
MARKS = {"yes": ("✓", "Yes", "yes"), "no": ("✗", "No", "no"), "partial": ("~", "Partly", "partial")}


def slugify(text):
    return re.sub(r"[^a-z0-9]+", "-", html.unescape(re.sub(r"<[^>]+>", "", text)).lower()).strip("-")


# Link targets a post may use: web, mail, this site (root-relative, {{root}}-relative) and in-page anchors.
# Anything else, javascript:, data:, protocol-relative //host and the rest, stays plain text.
_SAFE_HREF = re.compile(r"(?:https?://[^\s/]|mailto:[^\s/]|/(?![/\\])|\{\{root\}\}(?![/\\])[^:]*$|#)", re.I)


def md_inline(text):
    """Inline Markdown to HTML: `code`, [text](url), **bold**, *italic*. Text is escaped; code spans are kept verbatim."""
    codes = []
    def keep(m):
        codes.append(f"<code>{html.escape(m[1], quote=False)}</code>")
        return f"\x00{len(codes) - 1}\x00"
    text = re.sub(r"`([^`]+)`", keep, text)
    text = html.escape(text, quote=False)
    def link(m):
        href = html.unescape(m[2])
        if not _SAFE_HREF.match(href):
            return m[0]
        ext = ' rel="noopener"' if re.match(r"https?://", href, re.I) and not href.startswith(SITE_URL) else ""
        return f'<a href="{html.escape(href, quote=True)}"{ext}>{m[1]}</a>'
    text = re.sub(r"\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\)", link, text)
    text = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", text)
    text = re.sub(r"(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])", r"<em>\1</em>", text)
    return re.sub(r"\x00(\d+)\x00", lambda m: codes[int(m[1])], text)


def _cells(line):
    return [c.strip() for c in line.strip().strip("|").split("|")]


def _is_rule(line):
    return bool(re.fullmatch(r"\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?", line.strip()))


def compare_table(lines):
    """The comparison component: a real table (row headers, column headers, a caption) that CSS turns into one card per
    row on narrow screens, each cell labelled with its column through data-label."""
    caption = ""
    if lines and lines[0].lower().startswith("caption:"):
        caption = lines.pop(0).split(":", 1)[1].strip()
    rows = [_cells(l) for l in lines if l.strip() and not _is_rule(l)]
    if len(rows) < 2 or len(rows[0]) < 3:
        sys.exit("compare: needs a header row with a first column and at least two products, and one row")
    head, body = rows[0], rows[1:]
    def cell(value, label):
        mark = MARKS.get(value.lower().split(" ", 1)[0].rstrip(".,:;"))
        if mark:
            rest = value.split(" ", 1)[1] if " " in value else ""
            inner = (f'<span class="mark mark-{mark[2]}" aria-hidden="true">{mark[0]}</span> {mark[1]}'
                     + (f" <span class=\"cmp-note\">{md_inline(rest)}</span>" if rest else ""))
        else:
            inner = md_inline(value)
        return f'<td data-label="{html.escape(label, quote=True)}"><span>{inner}</span></td>'
    out = ['<figure class="compare">', "<table>"]
    if caption:
        out.append(f"<caption>{md_inline(caption)}</caption>")
    out.append("<thead><tr>" + "".join(f'<th scope="col">{md_inline(h)}</th>' for h in head) + "</tr></thead>")
    out.append("<tbody>")
    for r in body:
        r = (r + [""] * len(head))[:len(head)]
        out.append(f'<tr><th scope="row">{md_inline(r[0])}</th>' + "".join(cell(v, head[i + 1]) for i, v in enumerate(r[1:])) + "</tr>")
    out += ["</tbody>", "</table>", "</figure>"]
    return "\n".join(out)


def markdown(text):
    """The small Markdown subset in BLOG_HELP, to HTML. Kept here so the site needs nothing but Python to build."""
    lines, out, i = text.strip("\n").split("\n"), [], 0
    para = lambda chunk: f"<p>{md_inline(' '.join(l.strip() for l in chunk))}</p>"
    while i < len(lines):
        line = lines[i]
        if not line.strip():
            i += 1
            continue
        if line.startswith("```"):
            lang, j = line[3:].strip(), i + 1
            while j < len(lines) and not lines[j].startswith("```"):
                j += 1
            block, i = lines[i + 1:j], j + 1
            if lang == "compare":
                out.append(compare_table(block))
            elif lang == "prompt":
                out.append(f'<pre class="prompt"><code>{html.escape(chr(10).join(block), quote=False)}</code></pre>')
            else:
                out.append(f"<pre><code>{html.escape(chr(10).join(block), quote=False)}</code></pre>")
            continue
        m = re.match(r"(#{1,6})\s+(.*)", line)
        if m:
            level = len(m[1])
            if level < 2:
                sys.exit(f"markdown: '# {m[2]}': the post's title is its only h1; start headings at ##")
            body = md_inline(m[2].strip())
            ident = f' id="{slugify(body)}"' if level <= 3 else ""
            out.append(f"<h{level}{ident}>{body}</h{level}>")
            i += 1
            continue
        if line.startswith("<"):
            j = i
            while j < len(lines) and lines[j].strip():
                j += 1
            out.append("\n".join(lines[i:j]))
            i = j
            continue
        if line.lstrip().startswith("|") and i + 1 < len(lines) and _is_rule(lines[i + 1]):
            j = i
            while j < len(lines) and lines[j].lstrip().startswith("|"):
                j += 1
            rows = [_cells(l) for l in lines[i:j] if not _is_rule(l)]
            head = "".join(f'<th scope="col">{md_inline(c)}</th>' for c in rows[0])
            body = "".join("<tr>" + "".join(f"<td>{md_inline(c)}</td>" for c in r) + "</tr>" for r in rows[1:])
            out.append(f'<div class="table-wrap"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>')
            i = j
            continue
        if line.startswith(">"):
            j = i
            while j < len(lines) and lines[j].startswith(">"):
                j += 1
            out.append(f"<blockquote>{markdown(chr(10).join(l[1:].lstrip() for l in lines[i:j]))}</blockquote>")
            i = j
            continue
        m = re.match(r"(\s*)([-*]|\d+\.)\s+", line)
        if m:
            tag = "ol" if m[2][0].isdigit() else "ul"
            items, j = [], i
            while j < len(lines) and lines[j].strip():
                im = re.match(r"\s*([-*]|\d+\.)\s+(.*)", lines[j])
                if im and (im[1][0].isdigit()) == (tag == "ol"):
                    items.append([im[2]])
                elif items:
                    items[-1].append(lines[j].strip())
                else:
                    break
                j += 1
            out.append(f"<{tag}>" + "".join(f"<li>{md_inline(' '.join(it))}</li>" for it in items) + f"</{tag}>")
            i = j
            continue
        j = i
        while j < len(lines) and lines[j].strip() and not re.match(r"(#{1,6}\s|```|<|>|\s*([-*]|\d+\.)\s)", lines[j]):
            j += 1
        out.append(para(lines[i:j]))
        i = j
    return "\n".join(out)


def reading_minutes(text):
    words = len(re.findall(r"\w+", re.sub(r"<[^>]+>", " ", text)))
    return max(1, -(-words // WORDS_PER_MINUTE))


def blog_posts(drafts=False):
    """Every post as (meta, markdown), newest first. Header keys are checked so a typo fails the build, not the page."""
    posts = []
    for src in sorted(BLOG_SRC.glob("*.md")) if BLOG_SRC.exists() else []:
        meta, body = parse(src)
        slug = src.stem
        if not _SLUG.fullmatch(slug):
            sys.exit(f"{src.name}: file names are the URL, so use lowercase words and dashes only")
        for key in ("title", "description", "date"):
            if not meta.get(key):
                sys.exit(f"{src.name}: missing '{key}:'\n{BLOG_HELP}")
        for key in ("date", "updated"):
            if meta.get(key):
                datetime.date.fromisoformat(meta[key])
        if meta.get("updated", meta["date"]) < meta["date"]:
            sys.exit(f"{src.name}: updated is before date")
        if meta.get("draft") == "yes" and not drafts:
            continue
        meta.update(path=f"blog/{slug}.html", slug=slug, kind="post", active="blog")
        meta.setdefault("updated", meta["date"])
        meta.setdefault("author", BLOG_AUTHOR)
        meta.setdefault("card_art", "avatar:research")
        meta["tag_list"] = [t.strip() for t in meta.get("tags", "").split(",") if t.strip()]
        meta["words"] = len(re.findall(r"\w+", body))
        meta["minutes"] = reading_minutes(body)
        posts.append((meta, body))
    return sorted(posts, key=lambda p: (p[0]["date"], p[0]["slug"]), reverse=True)


def related(meta, posts, n=3):
    """Up to n other posts, most shared tags first, then newest."""
    tags = set(meta["tag_list"])
    others = [m for m, _ in posts if m["slug"] != meta["slug"]]
    scored = sorted(others, key=lambda m: (len(tags & set(m["tag_list"])), m["date"], m["slug"]), reverse=True)
    return scored[:n]


def human_date(iso):
    d = datetime.date.fromisoformat(iso)
    return f"{d.strftime('%B')} {d.day}, {d.year}"


def post_meta_line(meta):
    when = f'<time datetime="{meta["date"]}">{human_date(meta["date"])}</time>'
    if meta["updated"] != meta["date"]:
        when += f' · Updated <time datetime="{meta["updated"]}">{human_date(meta["updated"])}</time>'
    return f'{html.escape(meta["author"])} · {when} · {meta["minutes"]} min read'


def post_card(m, root, level=2):
    tags = "".join(f"<li>{html.escape(t)}</li>" for t in m["tag_list"])
    return (f'<article class="post-card"><h{level}><a href="{root}{m["path"]}">{html.escape(m["title"])}</a></h{level}>'
            f'<p>{html.escape(m["description"])}</p>'
            f'<p class="post-meta">{post_meta_line(m)}</p>' + (f'<ul class="tags" aria-label="Tags">{tags}</ul>' if tags else "")
            + "</article>")


def blog_post_body(meta, body, posts, root):
    tags = ", ".join(meta["tag_list"])
    rel = related(meta, posts)
    rel_html = (f'<aside class="related" aria-labelledby="related-title"><h2 id="related-title">Related posts</h2>'
                f'<div class="post-grid">{"".join(post_card(m, root, 3) for m in rel)}</div></aside>') if rel else ""
    return f"""<section class="page-head post-head">
  <div class="wrap">
    <nav class="crumbs" aria-label="Breadcrumb"><a href="{root}index.html">kwant</a> <span aria-hidden="true">/</span> <a href="{root}blog/index.html">Blog</a></nav>
    {f'<p class="kicker">{html.escape(tags)}</p>' if tags else ""}
    <h1>{html.escape(meta["title"])}</h1>
    <p class="lede">{html.escape(meta["description"])}</p>
    <p class="post-meta">{post_meta_line(meta)}</p>
  </div>
</section>

<div class="wrap">
  <article class="prose solo post">
{expand(markdown(body), root)}
    <aside class="post-cta" aria-label="Try kwant">
      <p><strong>Try kwant.</strong> A self-hosted team of AI agents in one binary, free and open source.</p>
      <p class="cta"><a class="btn btn-violet" href="{root}docs/install.html">Install kwant</a> <a class="btn btn-soft" href="{GITHUB}" rel="noopener">See it on GitHub</a></p>
    </aside>
  </article>
  {rel_html}
</div>
"""


def blog_index_body(posts, root):
    cards = "".join(post_card(m, root) for m, _ in posts)
    return f"""<section class="page-head">
  <div class="wrap">
    <p class="kicker">Blog</p>
    <h1>The kwant blog</h1>
    <p class="lede">{html.escape(BLOG_DESC)} <a href="{root}blog/feed.xml">RSS feed</a></p>
  </div>
</section>

<div class="wrap">
  <div class="post-list">{cards}</div>
</div>
"""


def rfc822(iso):
    d = datetime.date.fromisoformat(iso)
    return datetime.datetime(d.year, d.month, d.day, 8, 0, tzinfo=datetime.timezone.utc).strftime("%a, %d %b %Y %H:%M:%S +0000")


def blog_feed(posts):
    """RSS 2.0 for the blog. Only post dates go in it, so a rebuild with no new posts writes the same bytes."""
    esc = lambda s: html.escape(s, quote=False)
    items = []
    for m, _ in posts:
        url = page_url(m["path"])
        cats = "".join(f"<category>{esc(t)}</category>" for t in m["tag_list"])
        items.append(f"    <item><title>{esc(m['title'])}</title><link>{url}</link><guid isPermaLink=\"true\">{url}</guid>"
                     f"<pubDate>{rfc822(m['date'])}</pubDate><description>{esc(m['description'])}</description>{cats}</item>")
    newest = max(m["updated"] for m, _ in posts)
    return "\n".join([
        '<?xml version="1.0" encoding="UTF-8"?>',
        '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">',
        "  <channel>",
        f"    <title>{BLOG_TITLE}</title>",
        f"    <link>{SITE_URL}/blog/</link>",
        f"    <description>{esc(BLOG_DESC)}</description>",
        "    <language>en</language>",
        f"    <lastBuildDate>{rfc822(newest)}</lastBuildDate>",
        f'    <atom:link href="{SITE_URL}/blog/feed.xml" rel="self" type="application/rss+xml"/>',
        *items,
        "  </channel>",
        "</rss>",
    ]) + "\n"


# ---- Cache busting ----
_hashes = {}


def file_hash(path):
    if path not in _hashes:
        _hashes[path] = hashlib.sha256(path.read_bytes()).hexdigest()[:10]
    return _hashes[path]


def version_css():
    """Adds ?v=<hash> to every url() in site.css, so a changed font or image gets a new URL. Re-running is a no-op."""
    css = OUT / "assets/css/site.css"
    text = css.read_text()
    new = re.sub(
        r'url\("(\.\./[^"?#]+)(?:\?v=[0-9a-f]+)?"\)',
        lambda m: f'url("{m[1]}?v={file_hash((css.parent / m[1]).resolve())}")',
        text,
    )
    if new != text:
        css.write_text(new)


ASSET_URL = re.compile(
    r'(?<=["\s,])((?:\.\./)*|/)?((?:assets/[\w./-]+\.(?:css|js|woff2|png|webp|jpg|svg|mp4))|favicon\.svg|favicon-32\.png|apple-touch-icon\.png)(?=["\s,])'
)


def version_urls(page_html):
    """Appends ?v=<hash> to the page's relative asset URLs (src, href, srcset, poster). Absolute URLs such as og:image stay as they are."""
    return ASSET_URL.sub(lambda m: f"{m[1] or ''}{m[2]}?v={file_hash(OUT / m[2])}", page_html)


# ---- Favicons, drawn from LOGO_RECTS ----
# The logo's pixels span x 2..13 and y 1..16, so a 16x16 box from y=1 holds it exactly: crisp at 16, 32 and 48 px.
FAV_BG = "#4024a8"


def favicon_svg():
    rects = "".join(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{c}"/>' for x, y, w, h, c in LOGO_RECTS)
    return (
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 1 16 16" shape-rendering="crispEdges">'
        f'<rect x="0" y="1" width="16" height="16" rx="3" fill="{FAV_BG}"/>{rects}</svg>\n'
    )


def hexrgb(c):
    c = c.lstrip("#")
    if len(c) == 3:
        c = "".join(ch * 2 for ch in c)
    return tuple(int(c[i:i + 2], 16) for i in (0, 2, 4))


def favicon_pixels(size, scale, corner):
    """RGBA rows: the violet square (corners cut by `corner` px) with the logo scaled by an integer `scale`."""
    bg = hexrgb(FAV_BG) + (255,)
    px = [[bg] * size for _ in range(size)]
    for y in range(size):
        for x in range(size):
            dx = max(corner - x, x - (size - 1 - corner), 0)
            dy = max(corner - y, y - (size - 1 - corner), 0)
            if corner and dx and dy and dx * dx + dy * dy > corner * corner:
                px[y][x] = (0, 0, 0, 0)
    ox, oy = (size - 12 * scale) // 2 - 2 * scale, (size - 16 * scale) // 2 - scale
    for x, y, w, h, c in LOGO_RECTS:
        col = hexrgb(c) + (255,)
        for yy in range(oy + y * scale, oy + (y + h) * scale):
            for xx in range(ox + x * scale, ox + (x + w) * scale):
                px[yy][xx] = col
    return px


def png_bytes(px):
    h, w = len(px), len(px[0])
    raw = b"".join(b"\x00" + bytes(v for p in row for v in p) for row in px)
    chunk = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
    return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")


def ico_bytes(pngs):
    head = struct.pack("<HHH", 0, 1, len(pngs))
    offset = 6 + 16 * len(pngs)
    entries = data = b""
    for size, png in pngs:
        entries += struct.pack("<BBBBHHII", size % 256, size % 256, 0, 0, 1, 32, len(png), offset)
        offset += len(png)
        data += png
    return head + entries + data


def write_favicons():
    (OUT / "favicon.svg").write_text(favicon_svg())
    p16, p32 = png_bytes(favicon_pixels(16, 1, 0)), png_bytes(favicon_pixels(32, 2, 4))
    (OUT / "favicon-32.png").write_bytes(p32)
    (OUT / "favicon.ico").write_bytes(ico_bytes([(16, p16), (32, p32)]))
    # iOS rounds the corners itself, so the touch icon is a full square with room around the logo.
    (OUT / "apple-touch-icon.png").write_bytes(png_bytes(favicon_pixels(180, 8, 0)))


LLMS_INTRO = """# kwant

> kwant is an open-source, self-hosted team of AI agents in one Rust binary (`kwnt`). Bots share chats, hand work to each
> other with @mentions and get it done on their own, on a schedule or while you're away. It runs on a laptop, a VPS or
> Docker, with the Claude, Codex or Grok CLI logins you already have, API keys, local Ollama or any OpenAI-compatible server.

Key facts:

- License: AGPL-3.0, with commercial licenses available ([email protected]).
- Source: https://github.com/alexsergivan/kwant
- kwant has no token (no coin, no crypto). The official X account is @kwantbot (https://x.com/kwantbot).
- Mac app: https://github.com/alexsergivan/kwant/releases/latest/download/kwant_universal.dmg
- Linux app (beta, x86_64): https://github.com/alexsergivan/kwant/releases/latest/download/kwant_amd64.deb (Ubuntu 22.04+, Debian 12+) or https://github.com/alexsergivan/kwant/releases/latest/download/kwant_x86_64.AppImage
- Windows app (beta, 64-bit): {{windows_exe}} (per-user install, no admin rights; the latest one is always on https://github.com/alexsergivan/kwant/releases/latest).
- Phone app (iPhone and Android, no app store): open your kwant server's https address in Safari or Chrome and add it to the Home Screen; it gets notifications when a bot needs you. https://kwant.si/docs/phone
- Run Claude inside the VM (Linux, off by default): each bot's Claude replies run in a container with no network, and the real key stays outside. https://kwant.si/docs/agents-in-vm
- The program you install and run is called `kwnt` (`kwnt serve`).
- No telemetry: kwant sends nothing to its developers. The kwant.si website sets no cookies and counts page views with
  Cloudflare's cookie-free Web Analytics.
- Optional Mission board: a task counts as Verified only when a check passes, and the bot that handed out work reviews
  the result. No token limits by default; hand-off caps (4 per bot, 16 per request, with Continue) stop loops.
- Smart Results draw a bot's table or list as a sortable comparison, chart or checklist, copied word for word from the
  reply. Goals check that a page, command or file stays OK and offer one fix when one breaks.
- Dev mode watches each team's repo on GitHub (including GitHub Enterprise), GitLab, Gitea, Forgejo or any git server: a
  plain-words card for every merge, a review of every pull request or merge request by a bot that didn't write it
  (posted to GitHub only when you press Post to GitHub), and a production floor where pushes to main, deploys and
  destructive data commands always ask. The Idea jar has a free bot write a take on each idea you
  drop in; Do it makes a draft mission you approve.
- Automatic model failover: when an account runs out of usage, bots move to the next account in your order, across
  Claude, Codex, Grok and Custom API, and go back after the reset.
- Bots cite web facts with links that open the page at the exact quote; kwant checks the quote is on the page word for
  word and refuses made-up ones. Browser steps report what changed, and checkouts always ask before paying.
- Coding agents (Claude Code, Codex, Cursor or any MCP client) can ask your bots for work over MCP at /api/mcp/agents,
  with one revocable token per connection, only the bots you pick, and no way to approve anything.
- A daily spending stop (off by default) caps what all bots together use in a day, in tokens and dollars.
- Imports bots from Claude Code subagents, SKILL.md files, character cards, JSON exports and Grok Bot exports.
- Not to be confused with the Kwant quantum-transport Python package (kwant-project.org) or other products named Kwant; this kwant is an AI agent app.
"""


def llms_txt(pages):
    """llms.txt: the intro above, then every page as a markdown link with its description, docs in nav order."""
    line = lambda path: f"- [{pages[path]['title']}]({page_url(path)}): {pages[path]['description']}"
    docs = [f"docs/{d}.html" for d, _ in DOCS if f"docs/{d}.html" in pages]
    alternatives = sorted(p for p in pages if p.startswith("alternatives/"))
    blog = ["blog/index.html"] * ("blog/index.html" in pages) + sorted((p for p in pages if p.startswith("blog/") and p != "blog/index.html"),
                                                                        key=lambda p: pages[p]["date"], reverse=True)
    main = sorted((p for p in pages if p not in docs + alternatives + blog and p not in ("privacy.html", "terms.html", "404.html")), key=lambda p: p != "index.html")
    legal = [p for p in ("privacy.html", "terms.html") if p in pages]
    out = [LLMS_INTRO.replace("{{windows_exe}}", windows_installer()), "## Site", *map(line, main), "", "## Docs", *map(line, docs), ""]
    if alternatives:
        out += ["## Alternatives", *map(line, alternatives), ""]
    if blog:
        out += ["## Blog", *map(line, blog), ""]
    out += ["## Optional", *map(line, legal)]
    return "\n".join(out) + "\n"


def clean_links(page_html, path):
    """Points every internal page link at its clean, root-relative URL (/docs/install, not ../docs/install.html), the form
    Pages serves without a 308 redirect and the sitemap and canonicals use."""
    def clean(m):
        target, frag = m[2], m[3] or ""
        if not target.startswith("/"):
            target = posixpath.normpath(posixpath.join(posixpath.dirname("/" + path), target))
        target = re.sub(r"(^|/)index\.html$", r"\1", target).removesuffix(".html")
        return f'{m[1]}{target}{frag}"'
    return re.sub(r'(<a\b[^>]*?\bhref=")((?![a-z]+:|#)[^"#?]*\.html)(#[^"]*)?"', clean, page_html)


def main(argv=None):
    global BLOG_LIVE
    argv = sys.argv[1:] if argv is None else argv
    write_favicons()
    version_css()
    written, lastmod, metas = [], {}, {}
    posts = blog_posts(drafts="--drafts" in argv)
    BLOG_LIVE = bool(posts)
    # Every blog file is rebuilt from site-src/blog, so a post that was deleted or turned back into a draft goes away too.
    shutil.rmtree(OUT / "blog", ignore_errors=True)
    for src in sorted(SRC.glob("*.html")):
        meta, body = parse(src)
        dates = git_dates(src)
        lastmod[meta["path"]] = dates[1]
        metas[meta["path"]] = meta
        out = OUT / meta["path"]
        # The 404 page is served for any missing path, so it needs root-absolute links.
        root = "/" if meta["path"] == "404.html" else "../" * meta["path"].count("/")
        body = expand(body, root)
        if meta.get("nav"):
            body = docs_shell(root, meta["nav"], body)
        out.parent.mkdir(parents=True, exist_ok=True)
        built = version_urls(page(meta, body, root, dates))
        if meta["path"] == "index.html":
            built = defer_images(built)
        out.write_text(clean_links(built, meta["path"]))
        written.append(meta["path"])
    if posts:
        root = "../"
        index = {"path": "blog/index.html", "title": "Blog: guides and comparisons for self-hosted AI agents",
                 "card_title": "Blog", "card": "Guides, comparisons and notes on self-hosted AI agents", "card_art": "team",
                 "description": BLOG_DESC, "active": "blog", "kind": "blog", "posts": [m for m, _ in posts]}
        newest = max(m["updated"] for m, _ in posts)
        for meta, body in posts:
            out = OUT / meta["path"]
            out.parent.mkdir(parents=True, exist_ok=True)
            out.write_text(clean_links(version_urls(page(meta, blog_post_body(meta, body, posts, root), root, (meta["date"], meta["updated"]))), meta["path"]))
            lastmod[meta["path"]], metas[meta["path"]] = meta["updated"], meta
            written.append(meta["path"])
        (OUT / index["path"]).write_text(clean_links(version_urls(page(index, blog_index_body(posts, root), root, (newest, newest))), index["path"]))
        lastmod[index["path"]], metas[index["path"]] = newest, index
        written.append(index["path"])
        (OUT / "blog/feed.xml").write_text(blog_feed(posts))
    urls = [p for p in written if p != "404.html"]
    sitemap = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
    for p in urls:
        sitemap.append(f"  <url><loc>{page_url(p)}</loc><lastmod>{lastmod[p]}</lastmod></url>")
    sitemap.append("</urlset>")
    (OUT / "sitemap.xml").write_text("\n".join(sitemap) + "\n")
    (OUT / "llms.txt").write_text(llms_txt(metas))
    (OUT / "robots.txt").write_text(f"User-agent: *\nAllow: /\n\nSitemap: {SITE_URL}/sitemap.xml\n")
    print("wrote", ", ".join(written), file=sys.stderr)


if __name__ == "__main__":
    main()