---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import html import io import json import mimetypes import os import re import zipfile from datetime import datetime, timezone from http.server import."
resource: "https://thesis.copecheck.com"
tags: ["copecheck", "thesis", "source-file", "py"]
timestamp: "2026-09-26T10:09:14Z"
site: "thesis"
source_path: "copecheck-thesis/server.py"
---

# from __future__ import annotations

Source path: `copecheck-thesis/server.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-26T10:09:14Z`

```py
from __future__ import annotations

import argparse
import html
import io
import json
import mimetypes
import os
import re
import zipfile
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import urlparse


BASE = Path(__file__).resolve().parent
DATA_DIR = BASE / "data"
ASSET_DIR = BASE / "assets"
PUBLIC_BASE = os.getenv("COPECHECK_THESIS_PUBLIC_BASE", "https://thesis.copecheck.com").rstrip("/")
CAPABILITIES_BASE = os.getenv("COPECHECK_CAPABILITIES_PUBLIC_BASE", "https://capabilities.copecheck.com").rstrip("/")

LIVE_SIGNAL_CATEGORIES = {
    "Benchmark trajectory updates": {"benchmark"},
    "Vendor threshold framing": {"vendor"},
    "Enterprise deployment evidence": {"deployment"},
    "CEO language and labour-market evidence": {"labour_market", "layoff"},
}

INFOGRAPHICS = [
    {
        "number": "01",
        "essay": "1. Unit Cost Dominance",
        "title": "The Cost Threshold",
        "anchor": "1-unit-cost-dominance",
        "tone": "#235ebc",
        "visual": "cost",
        "claim": "AI plus verification becomes substitutive when it is cheaper than human-only production at equivalent quality.",
        "pattern": "Capability parity is no longer the decisive question. The decisive question is verification and integration cost.",
    },
    {
        "number": "02",
        "essay": "2. Interface Collapse",
        "title": "Task Wins Become Workflow Wins",
        "anchor": "2-interface-collapse",
        "tone": "#0f766e",
        "visual": "interface",
        "claim": "Once AI can operate software interfaces, isolated task dominance propagates upward into whole workflows.",
        "pattern": "The worker does not lose one task at a time. The workflow is recomposed around agents, APIs, and verification layers.",
    },
    {
        "number": "03",
        "essay": "3. The Multiplayer Prisoner's Dilemma",
        "title": "Nobody Can Pause Alone",
        "anchor": "3-the-multiplayer-prisoner-s-dilemma",
        "tone": "#b4233a",
        "visual": "dilemma",
        "claim": "Restraint is dominated at worker, firm, sector, and state level once competitors deploy.",
        "pattern": "Every actor may prefer a slower transition, but each is punished for being the one that slows first.",
    },
    {
        "number": "04",
        "essay": "4. The Sorites Collapse Principle",
        "title": "No Clean Assistance Line",
        "anchor": "4-the-sorites-collapse-principle",
        "tone": "#7c3aed",
        "visual": "sorites",
        "claim": "Assistance and replacement sit on a continuous gradient, not in separable policy boxes.",
        "pattern": "The boundary exists nowhere and everywhere: each small step is defensible, but the endpoint is substitution.",
    },
    {
        "number": "05",
        "essay": "5. Categorical Recursion",
        "title": "Capital Routes Around Labels",
        "anchor": "5-categorical-recursion",
        "tone": "#a66a00",
        "visual": "categories",
        "claim": "Regulation that depends on stable categories is outpaced by reclassification, outsourcing, and recomposition.",
        "pattern": "The protected category becomes a map for avoidance unless the intervention targets value flow directly.",
    },
    {
        "number": "06",
        "essay": "6. The Successor System",
        "title": "Consumption Without Wages",
        "anchor": "6-the-successor-system",
        "tone": "#0f4c81",
        "visual": "successor",
        "claim": "A successor can preserve consumption while ending the wage-demand mechanism that made work necessary.",
        "pattern": "The question shifts from saving jobs to deciding how purchasing power, ownership, and legitimacy are rebuilt.",
    },
    {
        "number": "07",
        "essay": "7. Drag Is Not Rescue",
        "title": "Friction Changes Timing",
        "anchor": "7-drag-is-not-rescue",
        "tone": "#6b7280",
        "visual": "drag",
        "claim": "Liability, culture, regulation, and integration slow adoption, but do not reverse the competitive direction.",
        "pattern": "Drag stretches the curve. It does not create a stable equilibrium where substitution stops.",
    },
]


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def escape(value: Any) -> str:
    if value is None:
        return ""
    return html.escape(str(value), quote=True)


def load_json(path: Path, fallback: dict[str, Any]) -> dict[str, Any]:
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        return data if isinstance(data, dict) else fallback
    except (OSError, json.JSONDecodeError):
        return fallback


def load_thesis() -> dict[str, Any]:
    return load_json(
        DATA_DIR / "thesis.json",
        {
            "title": "The Discontinuity Thesis",
            "subtitle": "A Sequence of Seven Essays on Why Postwar Capitalism Ends",
            "author": "Ben Luong",
            "version": "v1.1.2 final",
            "publication_date": "May 2026",
            "source_pdf": "/assets/The_Discontinuity_Thesis_v1_1_2.pdf",
            "generated_at": utc_now(),
            "word_count": 0,
            "blocks": [],
            "toc": [],
            "references": [],
            "reference_count": 0,
            "full_text": "",
        },
    )


def load_live_appendix() -> dict[str, Any]:
    return load_json(
        DATA_DIR / "appendix-live.json",
        {
            "status": "awaiting_scanner",
            "updated_at": None,
            "summary": "Appendix III live evidence is ready for scanner output.",
            "watchlist": [],
            "signals": [],
            "items": [],
        },
    )


def format_number(value: Any) -> str:
    try:
        return f"{int(value):,}"
    except (TypeError, ValueError):
        return escape(value)


def nav_items(toc: list[dict[str, Any]]) -> list[dict[str, str]]:
    allowed = []
    for item in toc:
        text = str(item.get("text") or "")
        level = str(item.get("level") or "")
        if level == "h2" or text.startswith("Section ") or text in {"How to Read This Sequence", "Scope, claims, and measurement"}:
            allowed.append({"id": str(item.get("id") or ""), "text": text, "level": level})
    return allowed[:48]


def live_item_date(item: dict[str, Any]) -> str:
    return str(item.get("observed_at") or item.get("source_date") or item.get("published") or item.get("updated_at") or "")


def live_items(live: dict[str, Any]) -> list[dict[str, Any]]:
    raw_items = live.get("items") if isinstance(live.get("items"), list) else []
    items = [item for item in raw_items if isinstance(item, dict)]
    items.sort(key=lambda item: (live_item_date(item), str(item.get("title") or "")), reverse=True)
    return items


def live_signal_count(signal: dict[str, Any], items: list[dict[str, Any]]) -> int:
    categories = LIVE_SIGNAL_CATEGORIES.get(str(signal.get("label") or ""))
    if categories:
        return sum(1 for item in items if str(item.get("category") or "").lower() in categories)

    target = str(signal.get("target_section") or "").split(":", 1)[0].lower()
    if not target:
        return int(signal.get("open_items") or 0)
    return sum(1 for item in items if target in str(item.get("relevance") or "").lower())


def render_live_appendix(live: dict[str, Any]) -> str:
    items = live_items(live)
    newest_source_date = live_item_date(items[0]) if items else "not yet populated"
    signals = live.get("signals") if isinstance(live.get("signals"), list) else []
    signal_html = "\n".join(
        f"""
        <li>
          <strong>{escape(item.get("label"))}</strong>
          <span>{escape(item.get("target_section"))}</span>
          <em>{escape(live_signal_count(item, items))} published items</em>
        </li>
        """
        for item in signals
        if isinstance(item, dict)
    )
    watchlist = live.get("watchlist") if isinstance(live.get("watchlist"), list) else []
    watch_html = "".join(f"<li>{escape(item)}</li>" for item in watchlist[:12])
    item_html = "\n".join(
        f"""
        <article>
          <a href="{escape(item.get("url"))}">{escape(item.get("title") or item.get("publisher") or item.get("url"))}</a>
          <p>{escape(item.get("claim") or item.get("note") or "")}</p>
          <small>{escape(item.get("publisher") or "Unknown source")} / {escape(live_item_date(item) or "undated")} / {escape(item.get("category") or "evidence")} / score {escape(item.get("cope_score", "n/a"))}</small>
        </article>
        """
        for item in items[:12]
        if isinstance(item, dict)
    )
    if not item_html:
        item_html = """
        <article>
          <strong>Scanner lane is ready</strong>
          <p>No OpenClaw additions have been written yet. The page will render new evidence here as soon as the worker updates the JSON register.</p>
          <small>Baseline Appendix III remains the fixed v1.1.2 text below.</small>
        </article>
        """
    return f"""
    <section class="live-appendix" id="appendix-iii-live" aria-labelledby="appendix-live-title">
      <div class="section-kicker">Curated Appendix III</div>
      <div class="live-head">
        <div>
          <h2 id="appendix-live-title">Frontier evidence register</h2>
          <p>{escape(live.get("summary"))}</p>
        </div>
        <span>{escape(str(live.get("status", "unknown")).replace("_", " "))}</span>
      </div>
      <div class="live-grid">
        <div>
          <h3>Coverage lanes</h3>
          <ul class="signal-list">{signal_html}</ul>
        </div>
        <div>
          <h3>Watched sources</h3>
          <ul class="watch-list">{watch_html}</ul>
        </div>
      </div>
      <div class="evidence-list">{item_html}</div>
      <p class="live-meta">{escape(live.get("cadence") or "Curated; updated in reviewed batches, not a continuous feed.")} Register metadata updated {escape(live.get("updated_at") or "unknown")}; newest source dated {escape(newest_source_date)}. Full console: <a href="{escape(CAPABILITIES_BASE)}">CopeCheck Capabilities</a>.</p>
    </section>
"""


def render_appendix_table(table: dict[str, Any]) -> str:
    columns = table.get("columns") if isinstance(table.get("columns"), list) else []
    rows = table.get("rows") if isinstance(table.get("rows"), list) else []
    if not columns or not rows:
        return ""
    head = "".join(f"<th scope=\"col\">{escape(column)}</th>" for column in columns)
    body_rows = []
    for row in rows:
        if not isinstance(row, dict):
            continue
        cells = "".join(f"<td>{escape(row.get(str(column), ''))}</td>" for column in columns)
        body_rows.append(f"<tr>{cells}</tr>")
    if not body_rows:
        return ""
    return f"""
    <figure class="appendix-table">
      <figcaption>{escape(table.get("title") or "Appendix evidence table")}</figcaption>
      <div class="appendix-table-scroll" tabindex="0">
        <table>
          <thead><tr>{head}</tr></thead>
          <tbody>{''.join(body_rows)}</tbody>
        </table>
      </div>
    </figure>
"""


def link_urls(value: str) -> str:
    parts = []
    last = 0
    for match in re.finditer(r"https?://[^\s)>,]+", value):
        parts.append(escape(value[last : match.start()]))
        url = match.group(0).rstrip(".,;")
        trailing = match.group(0)[len(url) :]
        parts.append(f'<a href="{escape(url)}">{escape(url)}</a>{escape(trailing)}')
        last = match.end()
    parts.append(escape(value[last:]))
    return "".join(parts)


def reference_items(thesis: dict[str, Any]) -> list[dict[str, Any]]:
    references = thesis.get("references") if isinstance(thesis.get("references"), list) else []
    return [reference for reference in references if isinstance(reference, dict)]


def okf_slug(value: Any, fallback: str = "item") -> str:
    slug = re.sub(r"[^a-z0-9]+", "-", str(value or "").lower()).strip("-")
    return slug[:96].strip("-") or fallback


def okf_value(value: Any) -> str:
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        return str(value)
    if isinstance(value, list):
        return "[" + ", ".join(okf_value(item) for item in value if item not in (None, "")) + "]"
    return json.dumps(str(value), ensure_ascii=False)


def okf_frontmatter(fields: dict[str, Any]) -> str:
    lines = ["---"]
    for key, value in fields.items():
        if value is None or value == "" or value == []:
            continue
        lines.append(f"{key}: {okf_value(value)}")
    lines.append("---")
    return "\n".join(lines) + "\n\n"


def okf_doc(fields: dict[str, Any], body: str) -> str:
    return okf_frontmatter(fields) + body.strip() + "\n"


def okf_excerpt(value: Any, limit: int = 180) -> str:
    text = re.sub(r"\s+", " ", str(value or "")).strip()
    if len(text) <= limit:
        return text
    return text[: limit - 1].rsplit(" ", 1)[0].rstrip(".,;:") + "."


def okf_table(table: dict[str, Any]) -> str:
    columns = table.get("columns") if isinstance(table.get("columns"), list) else []
    rows = table.get("rows") if isinstance(table.get("rows"), list) else []
    if not columns or not rows:
        return ""
    header = "| " + " | ".join(str(column) for column in columns) + " |"
    divider = "| " + " | ".join("---" for _ in columns) + " |"
    body = []
    for row in rows:
        if not isinstance(row, dict):
            continue
        values = [str(row.get(str(column), "")).replace("\n", " ") for column in columns]
        body.append("| " + " | ".join(values) + " |")
    return "\n".join([header, divider, *body])


def okf_sections(thesis: dict[str, Any]) -> list[dict[str, str]]:
    blocks = thesis.get("blocks") if isinstance(thesis.get("blocks"), list) else []
    table_items = thesis.get("appendix_tables") if isinstance(thesis.get("appendix_tables"), list) else []
    tables = {str(table.get("key")): table for table in table_items if isinstance(table, dict)}
    sections: list[dict[str, Any]] = []
    current: dict[str, Any] | None = None
    for block in blocks:
        if not isinstance(block, dict):
            continue
        block_type = str(block.get("type") or "p")
        text = str(block.get("text") or "")
        if block_type == "h2":
            current = {
                "id": str(block.get("id") or okf_slug(text, "section")),
                "title": text,
                "parts": [f"# {text}"],
                "first_paragraph": "",
            }
            sections.append(current)
        elif current:
            if block_type == "h3":
                current["parts"].append(f"\n## {text}")
            elif block_type == "appendix_table":
                table = tables.get(str(block.get("key"))) or {}
                rendered = okf_table(table)
                if rendered:
                    current["parts"].append(f"\n## {table.get('title') or 'Appendix table'}\n\n{rendered}")
            elif text:
                if not current["first_paragraph"]:
                    current["first_paragraph"] = text
                current["parts"].append(text)
    return [
        {
            "id": str(section["id"]),
            "title": str(section["title"]),
            "description": okf_excerpt(section.get("first_paragraph") or section.get("title")),
            "body": "\n\n".join(str(part) for part in section["parts"]),
        }
        for section in sections
    ]


def render_okf_bundle() -> dict[str, bytes]:
    thesis = load_thesis()
    live = load_live_appendix()
    sections = okf_sections(thesis)
    live_register = live_items(live)
    references = reference_items(thesis)
    timestamp = live.get("updated_at") or thesis.get("generated_at") or utc_now()
    docs: dict[str, str] = {}

    docs["index.md"] = f"""---
okf_version: "0.1"
---

# The Discontinuity Thesis OKF Bundle

This is the Open Knowledge Format mirror of [{thesis.get("title")}]({PUBLIC_BASE}/). It exposes the thesis, sections, references, and live Appendix III evidence register as Markdown concept files with YAML frontmatter.

# Concepts

* [Thesis](thesis.md) - Core publication metadata, access routes, and section index.
* [Sections](sections/) - One concept document for each major thesis section.
* [Live Evidence](evidence/) - Appendix III evidence items sourced from the live register.
* [References](references/) - Extracted thesis references as citation concepts.
* [Update Log](log.md) - Bundle-generation and evidence-register history.

# Human Browser

* [OKF bridge page]({PUBLIC_BASE}/okf-browser/) - HTML view of every generated OKF concept.
"""

    docs["log.md"] = f"""# OKF Bundle Update Log

## {datetime.now(timezone.utc).date().isoformat()}
* **Update**: Generated the OKF bundle from the thesis JSON and live Appendix III register.
* **Evidence**: Bundle contains {len(live_register)} live evidence concepts and {len(references)} reference concepts.

## {str(live.get("updated_at") or thesis.get("generated_at") or "")[:10] or datetime.now(timezone.utc).date().isoformat()}
* **Source**: Live Appendix III register timestamp `{live.get("updated_at") or "unknown"}`.
"""

    section_links = "\n".join(
        f"* [{section['title']}](sections/{section['id']}.md) - {section['description']}"
        for section in sections
    )
    docs["thesis.md"] = okf_doc(
        {
            "type": "CreativeWork",
            "title": thesis.get("title"),
            "description": thesis.get("subtitle"),
            "resource": PUBLIC_BASE + "/",
            "tags": ["discontinuity-thesis", "ai", "labour-market", "postwar-capitalism"],
            "timestamp": thesis.get("generated_at") or timestamp,
            "version": thesis.get("version"),
            "author": thesis.get("author"),
        },
        f"""# {thesis.get("title")}

{thesis.get("subtitle")}

# Access Routes

* Canonical HTML: [{PUBLIC_BASE}/]({PUBLIC_BASE}/)
* Plain text: [{PUBLIC_BASE}/full.txt]({PUBLIC_BASE}/full.txt)
* Structured JSON: [{PUBLIC_BASE}/data.json]({PUBLIC_BASE}/data.json)
* Live Appendix III JSON: [{PUBLIC_BASE}/appendix-live.json]({PUBLIC_BASE}/appendix-live.json)
* OKF zip bundle: [{PUBLIC_BASE}/okf.zip]({PUBLIC_BASE}/okf.zip)
* PDF: [{PUBLIC_BASE}{thesis.get("source_pdf")}]({PUBLIC_BASE}{thesis.get("source_pdf")})
* EPUB: [{PUBLIC_BASE}/assets/discontinuity-thesis.epub]({PUBLIC_BASE}/assets/discontinuity-thesis.epub)

# Sections

{section_links}

# Related Concepts

* [Live evidence register](evidence/index.md)
* [References](references/index.md)
""",
    )

    docs["sections/index.md"] = "# Thesis Sections\n\n" + "\n".join(
        f"* [{section['title']}]({section['id']}.md) - {section['description']}"
        for section in sections
    ) + "\n"
    for index, section in enumerate(sections, start=1):
        docs[f"sections/{section['id']}.md"] = okf_doc(
            {
                "type": "Thesis Section",
                "title": section["title"],
                "description": section["description"],
                "resource": f"{PUBLIC_BASE}/#{section['id']}",
                "tags": ["discontinuity-thesis", "section"],
                "timestamp": thesis.get("generated_at") or timestamp,
                "order": index,
            },
            section["body"] + "\n\n# Related Concepts\n\n* [Thesis](../thesis.md)\n* [Section index](index.md)",
        )

    docs["evidence/index.md"] = f"""# Live Appendix III Evidence

Live register status: `{live.get("status")}`  
Updated: `{live.get("updated_at")}`  
Items: `{len(live_register)}`

""" + "\n".join(
        f"* [{item.get('title') or item.get('publisher') or item.get('url')}]({okf_slug(item.get('slug') or item.get('title') or item.get('url'), f'evidence-{idx}')}.md) - {okf_excerpt(item.get('claim') or item.get('note'))}"
        for idx, item in enumerate(live_register, start=1)
        if isinstance(item, dict)
    ) + "\n"
    for idx, item in enumerate(live_register, start=1):
        if not isinstance(item, dict):
            continue
        slug = okf_slug(item.get("slug") or item.get("title") or item.get("url"), f"evidence-{idx}")
        title = item.get("title") or item.get("publisher") or item.get("url") or f"Evidence {idx}"
        source_url = item.get("url")
        body = f"""# {title}

# Claim

{item.get("claim") or item.get("note") or ""}

# Relevance

{item.get("relevance") or ""}

# Oracle Verdict

{item.get("oracle_verdict") or item.get("note") or ""}

# Metadata

* Publisher: {item.get("publisher") or "Unknown"}
* Category: {item.get("category") or "evidence"}
* Sector: {item.get("sector") or ""}
* Capability: {item.get("capability") or ""}
* Cope score: {item.get("cope_score", "n/a")}
* Confidence: {item.get("confidence", "n/a")}

# Related Concepts

* [Live evidence index](index.md)
* [Thesis](../thesis.md)

# Citations

"""
        if source_url:
            body += f"[1] [{title}]({source_url})\n"
        docs[f"evidence/{slug}.md"] = okf_doc(
            {
                "type": "Evidence Item",
                "title": title,
                "description": okf_excerpt(item.get("claim") or item.get("note")),
                "resource": source_url,
                "tags": ["appendix-iii", str(item.get("category") or "evidence"), okf_slug(item.get("publisher") or "source")],
                "timestamp": item.get("observed_at") or item.get("source_date") or item.get("updated_at") or timestamp,
                "category": item.get("category"),
                "publisher": item.get("publisher"),
                "cope_score": item.get("cope_score"),
                "confidence": item.get("confidence"),
            },
            body,
        )

    docs["references/index.md"] = "# Thesis References\n\n" + "\n".join(
        f"* [Reference {reference.get('number') or idx}](reference-{reference.get('number') or idx}.md) - {okf_excerpt(reference.get('text'))}"
        for idx, reference in enumerate(references, start=1)
    ) + "\n"
    for idx, reference in enumerate(references, start=1):
        number = reference.get("number") or idx
        text = str(reference.get("text") or "")
        urls = re.findall(r"https?://[^\s)>,]+", text)
        citations = "\n".join(f"[{i}] [{url}]({url})" for i, url in enumerate(urls, start=1)) or "No external URL extracted from this reference."
        docs[f"references/reference-{number}.md"] = okf_doc(
            {
                "type": "Reference",
                "title": f"Reference {number}",
                "description": okf_excerpt(text),
                "resource": urls[0] if urls else None,
                "tags": ["reference", "discontinuity-thesis"],
                "timestamp": thesis.get("generated_at") or timestamp,
                "number": number,
            },
            f"""# Reference {number}

{text}

# Related Concepts

* [Thesis](../thesis.md)
* [References index](index.md)

# Citations

{citations}
""",
        )

    return {path: body.encode("utf-8") for path, body in docs.items()}


def render_okf_path(path: str) -> bytes | None:
    clean = path.removeprefix("/okf/").strip("/")
    if not clean:
        clean = "index.md"
    elif clean.endswith("/"):
        clean += "index.md"
    elif "." not in Path(clean).name:
        clean = clean.rstrip("/") + "/index.md"
    docs = render_okf_bundle()
    return docs.get(clean)


def render_okf_zip() -> bytes:
    buffer = io.BytesIO()
    docs = render_okf_bundle()
    with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
        for path, body in sorted(docs.items()):
            archive.writestr(path, body)
    return buffer.getvalue()


def render_okf_bridge() -> bytes:
    thesis = load_thesis()
    live = load_live_appendix()
    sections = okf_sections(thesis)
    live_register = live_items(live)
    references = reference_items(thesis)
    docs = render_okf_bundle()

    section_rows = "\n".join(
        f"""
        <article class="okf-row">
          <a href="/okf/sections/{escape(section['id'])}.md">{escape(section['title'])}</a>
          <p>{escape(section['description'])}</p>
        </article>
        """
        for section in sections
    )
    evidence_rows = "\n".join(
        f"""
        <article class="okf-row">
          <a href="/okf/evidence/{escape(okf_slug(item.get('slug') or item.get('title') or item.get('url'), f'evidence-{idx}'))}.md">{escape(item.get('title') or item.get('publisher') or item.get('url'))}</a>
          <small>{escape(item.get('publisher') or 'Unknown source')} / {escape(item.get('category') or 'evidence')} / score {escape(item.get('cope_score', 'n/a'))}</small>
          <p>{escape(okf_excerpt(item.get('claim') or item.get('note'), 240))}</p>
        </article>
        """
        for idx, item in enumerate(live_register, start=1)
        if isinstance(item, dict)
    )
    reference_rows = "\n".join(
        f"""
        <article class="okf-row">
          <a href="/okf/references/reference-{escape(reference.get('number') or idx)}.md">Reference {escape(reference.get('number') or idx)}</a>
          <p>{escape(okf_excerpt(reference.get('text'), 260))}</p>
        </article>
        """
        for idx, reference in enumerate(references, start=1)
    )
    body = f"""
<header class="topbar">
  <a class="brand" href="/">
    <span class="mark">DT</span>
    <span><strong>The Discontinuity Thesis</strong><small>OKF browser</small></span>
  </a>
  <nav>
    <a href="/">Thesis</a>
    <a href="/okf/">OKF root</a>
    <a href="/okf/thesis.md">Thesis concept</a>
    <a href="/okf.zip">Download zip</a>
    <a href="/data.json">JSON</a>
  </nav>
</header>
<main class="okf-bridge">
  <section class="hero okf-hero">
    <div class="hero-copy">
      <p class="section-kicker">Open Knowledge Format</p>
      <h1>OKF bundle browser</h1>
      <p class="subtitle">A human-readable bridge for the full Markdown concept bundle behind The Discontinuity Thesis.</p>
      <div class="actions">
        <a href="/okf/">Open OKF root</a>
        <a href="/okf.zip">Download ZIP</a>
        <a href="/okf/evidence/">Evidence index</a>
      </div>
    </div>
  </section>
  <section class="machine-note okf-counts">
    <div><strong>{escape(len(docs))}</strong><p>Markdown files in the generated OKF bundle.</p></div>
    <div><strong>{escape(len(sections))}</strong><p>Major thesis section concepts.</p></div>
    <div><strong>{escape(len(live_register))}</strong><p>Live Appendix III evidence concepts.</p></div>
    <div><strong>{escape(len(references))}</strong><p>Reference concepts extracted from the thesis.</p></div>
  </section>
  <section class="okf-panel">
    <div class="okf-panel-head">
      <h2>Core bundle files</h2>
      <p>Reserved index and bundle-level files.</p>
    </div>
    <div class="okf-list">
      <article class="okf-row"><a href="/okf/">index.md</a><p>Bundle root with OKF version and concept map.</p></article>
      <article class="okf-row"><a href="/okf/thesis.md">thesis.md</a><p>Publication metadata, canonical routes, and section links.</p></article>
      <article class="okf-row"><a href="/okf/log.md">log.md</a><p>Generated bundle update log.</p></article>
    </div>
  </section>
  <section class="okf-panel">
    <div class="okf-panel-head">
      <h2>Sections</h2>
      <p>Every major thesis section rendered as a Markdown concept file.</p>
    </div>
    <div class="okf-list">{section_rows}</div>
  </section>
  <section class="okf-panel">
    <div class="okf-panel-head">
      <h2>Live Appendix III evidence</h2>
      <p>Every live evidence item currently present in the appendix register.</p>
    </div>
    <div class="okf-list okf-evidence-list">{evidence_rows}</div>
  </section>
  <section class="okf-panel">
    <div class="okf-panel-head">
      <h2>References</h2>
      <p>Extracted thesis references rendered as citation concepts.</p>
    </div>
    <div class="okf-list">{reference_rows}</div>
  </section>
</main>
"""
    return render_layout(
        "OKF Bundle Browser | The Discontinuity Thesis",
        "Human-readable bridge page for the Open Knowledge Format bundle behind The Discontinuity Thesis.",
        body,
        thesis,
        "/okf-browser/",
    )


def render_references(thesis: dict[str, Any], *, reader: bool = False) -> str:
    references = reference_items(thesis)
    if not references:
        return ""
    items = "\n".join(
        f"""
        <li>
          <span class="reference-number">{escape(reference.get("number"))}</span>
          <p>{link_urls(str(reference.get("text") or ""))}</p>
        </li>
        """
        for reference in references
    )
    class_name = "reader-section reader-references" if reader else "thesis-section references-section"
    return f"""
    <section class="{class_name}" id="references">
      <h2>References</h2>
      <ol class="references-list">{items}</ol>
    </section>
"""


def render_article(thesis: dict[str, Any], live: dict[str, Any]) -> str:
    blocks = thesis.get("blocks") if isinstance(thesis.get("blocks"), list) else []
    table_items = thesis.get("appendix_tables") if isinstance(thesis.get("appendix_tables"), list) else []
    tables = {str(table.get("key")): table for table in table_items if isinstance(table, dict)}
    output = []
    for block in blocks:
        if not isinstance(block, dict):
            continue
        block_type = str(block.get("type") or "p")
        text = str(block.get("text") or "")
        block_id = str(block.get("id") or "")
        if block_type == "h2":
            if output:
                output.append("</section>")
            section_class = "thesis-section appendix-section" if text.startswith("Appendix III:") else "thesis-section"
            output.append(f'<section class="{section_class}" id="{escape(block_id)}">')
            output.append(f"<h2>{escape(text)}</h2>")
            if text.startswith("Appendix III:"):
                output.append(render_live_appendix(live))
        elif block_type == "h3":
            output.append(f'<h3 id="{escape(block_id)}">{escape(text)}</h3>' if block_id else f"<h3>{escape(text)}</h3>")
        elif block_type == "appendix_table":
            output.append(render_appendix_table(tables.get(str(block.get("key"))) or {}))
        else:
            output.append(f"<p>{escape(text)}</p>")
    if output:
        output.append("</section>")
    references_html = render_references(thesis)
    if references_html:
        output.append(references_html)
    return "\n".join(output)


def render_infographic_visual(kind: str) -> str:
    if kind == "cost":
        return """
          <div class="cost-bars">
            <div class="cost-bar human"><span>Human-only</span></div>
            <div class="cost-bar ai"><span>AI + verifier</span></div>
            <div class="cost-threshold"><span>Dominance threshold</span></div>
          </div>
        """
    if kind == "interface":
        return """
          <div class="flow-strip">
            <span>Task</span>
            <span>Tool</span>
            <span>Flow</span>
            <span>Role</span>
          </div>
        """
    if kind == "dilemma":
        return """
          <div class="dilemma-map">
            <span>Worker</span>
            <span>Firm</span>
            <strong>Deploy</strong>
            <span>Sector</span>
            <span>State</span>
          </div>
        """
    if kind == "sorites":
        return """
          <div class="sorites-scale">
            <div class="sorites-track"></div>
            <div class="sorites-points">
              <span>Assist</span>
              <span>Co-draft</span>
              <span>Verify</span>
              <span>Replace</span>
            </div>
            <strong>No clean boundary</strong>
          </div>
        """
    if kind == "categories":
        return """
          <div class="category-map">
            <span>Employee</span>
            <span>Contractor</span>
            <span>Vendor</span>
            <span>Agent</span>
            <strong>Value flow</strong>
          </div>
        """
    if kind == "successor":
        return """
          <div class="successor-loop">
            <span>Output</span>
            <span>Ownership</span>
            <strong>Transfers</strong>
            <span>Demand</span>
            <span>Legitimacy</span>
          </div>
        """
    if kind == "drag":
        return """
          <div class="drag-chart">
            <span class="drag-curve"></span>
            <span class="drag-gate gate-one">law</span>
            <span class="drag-gate gate-two">culture</span>
            <span class="drag-gate gate-three">integration</span>
          </div>
        """
    return ""


def render_infographics_section(standalone: bool = False) -> str:
    heading_tag = "h1" if standalone else "h2"
    cards = "\n".join(
        f"""
        <a class="infographic-card" href="/#{escape(item["anchor"])}" style="--card-accent: {escape(item["tone"])}">
          <span class="infographic-number">{escape(item["number"])}</span>
          <div class="infographic-visual" aria-hidden="true">{render_infographic_visual(str(item["visual"]))}</div>
          <div class="infographic-copy">
            <p class="infographic-essay">{escape(item["essay"])}</p>
            <h3>{escape(item["title"])}</h3>
            <p>{escape(item["claim"])}</p>
            <small>{escape(item["pattern"])}</small>
          </div>
        </a>
        """
        for item in INFOGRAPHICS
    )
    return f"""
  <section class="infographics-section" id="infographics" aria-labelledby="infographics-title">
    <div class="infographics-head">
      <div>
        <div class="section-kicker">Infographics</div>
        <{heading_tag} id="infographics-title">Seven essays, seven structural diagrams</{heading_tag}>
        <p>Each card compresses one essay into its core mechanism, then links into the full argument for bots and human readers.</p>
      </div>
      <a href="/infographics/" class="section-link">Standalone view</a>
    </div>
    <div class="infographic-grid">{cards}</div>
  </section>
"""


def reader_excerpt(value: str, limit: int = 180) -> str:
    value = " ".join(value.split())
    return value if len(value) <= limit else value[: limit - 1].rstrip() + "..."


def render_note_button(target: str, excerpt: str) -> str:
    return f'<button class="note-marker" type="button" data-note-target="{escape(target)}" data-note-excerpt="{escape(excerpt)}" aria-label="Add note">Note</button>'


def render_reader_article(thesis: dict[str, Any], live: dict[str, Any]) -> str:
    blocks = thesis.get("blocks") if isinstance(thesis.get("blocks"), list) else []
    table_items = thesis.get("appendix_tables") if isinstance(thesis.get("appendix_tables"), list) else []
    tables = {str(table.get("key")): table for table in table_items if isinstance(table, dict)}
    output = []
    for index, block in enumerate(blocks):
        if not isinstance(block, dict):
            continue
        block_type = str(block.get("type") or "p")
        text = str(block.get("text") or "")
        block_id = str(block.get("id") or f"reader-block-{index}")
        target = block_id if block_type in {"h2", "h3"} else f"reader-block-{index}"
        if block_type == "h2":
            if output:
                output.append("</section>")
            output.append(f'<section class="reader-section" id="{escape(block_id)}">')
            output.append(f"<h2>{escape(text)}</h2>")
            if text.startswith("Appendix III:"):
                output.append(render_live_appendix(live))
        elif block_type == "h3":
            output.append(
                f'<div class="reader-block has-note-button" id="{escape(target)}" data-reader-block><h3>{escape(text)}</h3>{render_note_button(target, reader_excerpt(text))}</div>'
            )
        elif block_type == "appendix_table":
            table = render_appendix_table(tables.get(str(block.get("key"))) or {})
            if table:
                output.append(f'<div class="reader-block reader-table-block" id="{escape(target)}" data-reader-block>{table}</div>')
        else:
            output.append(
                f'<div class="reader-block has-note-button" id="{escape(target)}" data-reader-block><p>{escape(text)}</p>{render_note_button(target, reader_excerpt(text))}</div>'
            )
    if output:
        output.append("</section>")
    references_html = render_references(thesis, reader=True)
    if references_html:
        output.append(references_html)
    return "\n".join(output)


def render_layout(title: str, description: str, body: str, thesis: dict[str, Any], canonical_path: str = "/") -> bytes:
    canonical = PUBLIC_BASE + canonical_path
    live = load_live_appendix()
    date_modified = max(
        str(thesis.get("generated_at") or ""),
        str(live.get("updated_at") or ""),
    ) or None
    creative_work = {
        "@context": "https://schema.org",
        "@type": "CreativeWork",
        "name": thesis.get("title"),
        "headline": thesis.get("title"),
        "alternativeHeadline": thesis.get("subtitle"),
        "author": {"@type": "Person", "name": thesis.get("author")},
        "datePublished": "2026-05",
        "dateModified": date_modified,
        "url": canonical,
        "citation": [str(reference.get("text") or "") for reference in reference_items(thesis)],
        "encoding": [
            {"@type": "MediaObject", "encodingFormat": "application/pdf", "contentUrl": PUBLIC_BASE + "/assets/The_Discontinuity_Thesis_v1_1_2.pdf"},
            {"@type": "MediaObject", "encodingFormat": "application/epub+zip", "contentUrl": PUBLIC_BASE + "/assets/discontinuity-thesis.epub"},
            {"@type": "MediaObject", "encodingFormat": "text/plain", "contentUrl": PUBLIC_BASE + "/full.txt"},
            {"@type": "MediaObject", "encodingFormat": "application/json", "contentUrl": PUBLIC_BASE + "/data.json"},
            {"@type": "MediaObject", "encodingFormat": "text/markdown", "contentUrl": PUBLIC_BASE + "/okf/"},
            {"@type": "MediaObject", "encodingFormat": "application/zip", "contentUrl": PUBLIC_BASE + "/okf.zip"},
        ],
    }
    html_doc = f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{escape(title)}</title>
  <meta name="description" content="{escape(description)}">
  <meta name="robots" content="index,follow,max-snippet:-1,max-image-preview:large">
  <link rel="canonical" href="{escape(canonical)}">
  <meta property="og:title" content="{escape(title)}">
  <meta property="og:description" content="{escape(description)}">
  <meta property="og:url" content="{escape(canonical)}">
  <meta property="og:type" content="article">
  <meta property="og:image" content="{escape(PUBLIC_BASE)}/assets/cover.png">
  <script type="application/ld+json">{json.dumps(creative_work, ensure_ascii=False)}</script>
  <style>{CSS}.oracle-float {{
  position: fixed;
  left: max(1rem, env(safe-area-inset-left));
  bottom: max(1rem, env(safe-area-inset-bottom));
  z-index: 9998;
  display: inline-flex;
  flex-direction: column;
  gap: 0.15rem;
  padding: 0.72rem 0.92rem;
  border: 1px solid rgba(255, 255, 255, 0.22);
  border-radius: 0.75rem;
  background: rgba(12, 16, 24, 0.9);
  color: #fff;
  text-decoration: none;
  box-shadow: 0 18px 42px rgba(0, 0, 0, 0.28);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  transition: transform 160ms ease, box-shadow 160ms ease, border-color 160ms ease;
}}

.oracle-float:hover,
.oracle-float:focus-visible {{
  transform: translateY(-2px);
  border-color: rgba(255, 255, 255, 0.42);
  box-shadow: 0 22px 54px rgba(0, 0, 0, 0.36);
  color: #fff;
}}

.oracle-float-kicker {{
  font-size: 0.64rem;
  font-weight: 700;
  line-height: 1;
  letter-spacing: 0.08em;
  opacity: 0.72;
  text-transform: uppercase;
}}

.oracle-float-title {{
  font-size: 0.95rem;
  font-weight: 800;
  line-height: 1.1;
}}

@media (max-width: 640px) {{
  .oracle-float {{
    left: 0.75rem;
    right: 0.75rem;
    bottom: 0.75rem;
    width: auto;
    align-items: center;
    text-align: center;
  }}

  .oracle-float-kicker {{
    display: none;
  }}
}}
</style>
</head>
<body>
{body}
  <a class="oracle-float" href="https://chatgpt.com/g/[redacted]" target="_blank" rel="noopener" aria-label="Ask the Oracle custom GPT">
    <span class="oracle-float-kicker">Custom GPT</span>
    <span class="oracle-float-title">Ask the Oracle</span>
  </a>
</body>
</html>
"""
    return html_doc.encode("utf-8")


def render_home() -> bytes:
    thesis = load_thesis()
    live = load_live_appendix()
    toc = nav_items(thesis.get("toc") if isinstance(thesis.get("toc"), list) else [])
    toc_html = "\n".join(
        f'<a class="{escape(item["level"])}" href="#{escape(item["id"])}">{escape(item["text"])}</a>'
        for item in toc
        if item.get("id")
    )
    if reference_items(thesis):
        toc_html += '\n<a class="h2" href="#references">References</a>'
    copy_text = str(thesis.get("full_text") or "")
    live_count = len(live.get("items") if isinstance(live.get("items"), list) else [])
    body = f"""
<header class="topbar">
  <a class="brand" href="/">
    <span class="mark">DT</span>
    <span><strong>The Discontinuity Thesis</strong><small>CopeCheck edition</small></span>
  </a>
  <nav>
    <a href="#read">Read</a>
    <a href="#infographics">Infographics</a>
    <a href="/reader/">Reader</a>
    <a href="#appendix-iii-live">Appendix III register</a>
    <a href="{escape(CAPABILITIES_BASE)}">Capabilities</a>
    <a href="/okf/">OKF</a>
    <a href="/okf-browser/">OKF Browser</a>
    <a href="/assets/discontinuity-thesis.epub">EPUB</a>
    <a href="/full.txt">Full text</a>
    <a href="/data.json">JSON</a>
  </nav>
</header>
<main>
  <section class="hero">
    <div class="hero-copy">
      <h1>{escape(thesis.get("title"))}</h1>
      <p class="subtitle">{escape(thesis.get("subtitle"))}</p>
      <p class="standfirst">A one-page, bot-readable web edition of Ben Luong's May 2026 thesis, with Appendix III maintained as a curated frontier-evidence register.</p>
      <div class="actions">
        <button id="copy-all" type="button">Copy all text</button>
        <a href="/reader/">Open reader</a>
        <a href="/assets/discontinuity-thesis.epub">Download EPUB</a>
        <a href="{escape(thesis.get("source_pdf"))}">Open PDF</a>
      </div>
      <p id="copy-status" class="copy-status" role="status" aria-live="polite"></p>
    </div>
    <aside class="cover-card" aria-label="PDF cover">
      <img src="/assets/cover.png" alt="Cover of The Discontinuity Thesis PDF">
      <div>
        <span>{escape(thesis.get("version"))}</span>
        <strong>{format_number(thesis.get("word_count"))} words</strong>
        <span>{escape(thesis.get("publication_date"))}</span>
      </div>
    </aside>
  </section>
  <section class="machine-note">
    <div>
      <strong>Bot-readable by design</strong>
      <p>The full thesis is rendered in this HTML, exposed as <a href="/full.txt">plain text</a>, mirrored as <a href="/data.json">structured JSON</a>, and published as an <a href="/okf/">Open Knowledge Format bundle</a>. The Copy All button uses the same source text.</p>
    </div>
    <div>
      <strong>Appendix III evidence register</strong>
      <p>{escape(str(live.get("status", "unknown")).replace("_", " "))}; {escape(live_count)} reviewed additions currently published. {escape(live.get("cadence") or "Updated in reviewed batches.")} <a href="{escape(CAPABILITIES_BASE)}">Open capabilities console</a>.</p>
    </div>
    <div>
      <strong>Reader edition</strong>
      <p><a href="/reader/">Browser reader</a> with local notes and progress, plus a <a href="/assets/discontinuity-thesis.epub">Kindle-ready EPUB</a>.</p>
    </div>
  </section>
  {render_infographics_section()}
  <div class="reader-shell" id="read">
    <aside class="toc" aria-label="Document navigation">
      <strong>On this page</strong>
      {toc_html}
    </aside>
    <article class="thesis" id="copy-source">
      {render_article(thesis, live)}
    </article>
  </div>
</main>
<footer>
  <strong>CopeCheck thesis edition</strong>
  <p>Canonical PDF: <a href="{escape(thesis.get("source_pdf"))}">{escape(Path(str(thesis.get("source_pdf"))).name)}</a>. Generated {escape(thesis.get("generated_at"))}.</p>
</footer>
<textarea id="copy-buffer" aria-hidden="true" readonly tabindex="-1">{escape(copy_text)}</textarea>
<script>
(() => {{
  const button = document.getElementById("copy-all");
  const buffer = document.getElementById("copy-buffer");
  const status = document.getElementById("copy-status");
  async function copyAll() {{
    const text = buffer.value;
    try {{
      await navigator.clipboard.writeText(text);
      status.textContent = `Copied ${{new Intl.NumberFormat("en-GB").format(text.length)}} characters.`;
    }} catch (error) {{
      buffer.hidden = false;
      buffer.focus();
      buffer.select();
      document.execCommand("copy");
      buffer.hidden = true;
      status.textContent = "Copied using fallback selection.";
    }}
  }}
  button.addEventListener("click", copyAll);
}})();
</script>
"""
    return render_layout(
        "The Discontinuity Thesis | CopeCheck",
        "A one-page, bot-readable web edition of The Discontinuity Thesis with a curated Appendix III evidence register.",
        body,
        thesis,
    )


def render_infographics_page() -> bytes:
    thesis = load_thesis()
    body = f"""
<header class="topbar">
  <a class="brand" href="/">
    <span class="mark">DT</span>
    <span><strong>The Discontinuity Thesis</strong><small>Infographics</small></span>
  </a>
  <nav>
    <a href="/">Home</a>
    <a href="/#read">Read</a>
    <a href="/reader/">Reader</a>
    <a href="/assets/discontinuity-thesis.epub">EPUB</a>
    <a href="/full.txt">Full text</a>
  </nav>
</header>
<main class="infographics-page">
  {render_infographics_section(standalone=True)}
</main>
<footer>
  <strong>Seven-essay infographic edition</strong>
  <p>Each diagram links back to the source essay in the canonical one-page thesis.</p>
</footer>
"""
    return render_layout(
        "Seven Infographics | The Discontinuity Thesis",
        "Seven one-card infographics summarising the essay sequence in The Discontinuity Thesis.",
        body,
        thesis,
        "/infographics/",
    )


def render_reader() -> bytes:
    thesis = load_thesis()
    live = load_live_appendix()
    toc = nav_items(thesis.get("toc") if isinstance(thesis.get("toc"), list) else [])
    toc_html = "\n".join(
        f'<a class="{escape(item["level"])}" href="#{escape(item["id"])}">{escape(item["text"])}</a>'
        for item in toc
        if item.get("id")
    )
    if reference_items(thesis):
        toc_html += '\n<a class="h2" href="#references">References</a>'
    body = f"""
<header class="reader-topbar">
  <a class="brand" href="/">
    <span class="mark">DT</span>
    <span><strong>The Discontinuity Thesis</strong><small>Reader edition</small></span>
  </a>
  <nav>
    <a href="/">Home</a>
    <a href="/assets/discontinuity-thesis.epub">EPUB</a>
    <a href="{escape(thesis.get("source_pdf"))}">PDF</a>
    <a href="/full.txt">Text</a>
  </nav>
</header>
<main class="reader-page">
  <aside class="reader-tools" aria-label="Reader tools">
    <section class="reader-toolbox">
      <strong>Progress</strong>
      <div class="reader-progress"><span id="reader-progress-bar"></span></div>
      <p id="reader-progress-label">0%</p>
    </section>
    <section class="reader-toolbox reader-nav">
      <strong>Sections</strong>
      {toc_html}
    </section>
    <section class="reader-toolbox">
      <div class="tool-head">
        <strong>Notes</strong>
        <span id="note-count">0</span>
      </div>
      <div id="notes-list" class="notes-list"></div>
      <textarea id="reader-note-text" rows="6" placeholder="Note"></textarea>
      <div class="reader-buttons">
        <button id="save-note" type="button">Save note</button>
        <button id="delete-note" type="button">Delete</button>
        <button id="copy-notes" type="button">Copy notes</button>
      </div>
      <p id="note-status" class="reader-status" role="status" aria-live="polite"></p>
    </section>
    <section class="reader-toolbox">
      <strong>Feedback</strong>
      <textarea id="feedback-text" rows="5" placeholder="Feedback"></textarea>
      <div class="reader-buttons">
        <a id="feedback-mail" class="reader-button-link" href="mailto:btl101@gmail.com?subject=Discontinuity%20Thesis%20feedback">Email</a>
        <button id="copy-feedback" type="button">Copy</button>
      </div>
      <p id="feedback-status" class="reader-status" role="status" aria-live="polite"></p>
    </section>
  </aside>
  <article class="reader-article" id="reader-article">
    <header class="reader-title">
      <h1>{escape(thesis.get("title"))}</h1>
      <p>{escape(thesis.get("subtitle"))}</p>
    </header>
    {render_reader_article(thesis, live)}
  </article>
</main>
<script>{READER_SCRIPT}</script>
"""
    return render_layout(
        "The Discontinuity Thesis Reader | CopeCheck",
        "A cookie-free online reader for The Discontinuity Thesis with local progress, local notes, feedback draft tools, and EPUB download.",
        body,
        thesis,
        "/reader/",
    )


def render_data() -> bytes:
    return json.dumps({
        "human_review": "The thesis text, claims and citations are hand-checked by the author. AI assists web presentation and evidence triage, not final thesis approval.",
        "thesis": load_thesis(),
        "appendix_live": load_live_appendix(),
    }, ensure_ascii=False, indent=2).encode("utf-8")


def render_llms(full: bool = False) -> bytes:
    thesis = load_thesis()
    live = load_live_appendix()
    live_items = live.get("items") if isinstance(live.get("items"), list) else []
    lines = [
        f"# {thesis.get('title')}",
        "",
        f"> {thesis.get('subtitle')}",
        "",
        f"Author: {thesis.get('author')}",
        f"Version: {thesis.get('version')}",
        f"Publication date: {thesis.get('publication_date')}",
        f"References: {thesis.get('reference_count') or len(reference_items(thesis))}",
        f"Canonical HTML: {PUBLIC_BASE}/",
        f"Plain text: {PUBLIC_BASE}/full.txt",
        f"Structured JSON: {PUBLIC_BASE}/data.json",
        f"Open Knowledge Format bundle: {PUBLIC_BASE}/okf/",
        f"Open Knowledge Format browser: {PUBLIC_BASE}/okf-browser/",
        f"Open Knowledge Format zip: {PUBLIC_BASE}/okf.zip",
        f"PDF: {PUBLIC_BASE}{thesis.get('source_pdf')}",
        "",
        "## Purpose",
        "",
        "This is the CopeCheck one-page web edition of The Discontinuity Thesis. The complete thesis text is present in the HTML and is also exposed as plain text and JSON for agents.",
        "",
        "## Appendix III live register",
        "",
        f"Status: {live.get('status')}",
        f"Updated: {live.get('updated_at')}",
        f"Summary: {live.get('summary')}",
        "",
    ]
    for item in live_items[:24]:
        if not isinstance(item, dict):
            continue
        lines.extend(
            [
                f"- {item.get('title') or item.get('publisher') or item.get('url')}",
                f"  URL: {item.get('url')}",
                f"  Publisher: {item.get('publisher')}",
                f"  Category: {item.get('category')}",
                f"  Claim: {item.get('claim') or item.get('note') or ''}",
                f"  Relevance: {item.get('relevance') or ''}",
                "",
            ]
        )
    lines.extend(
        [
        "## Use",
        "",
        "Use `/full.txt` when a single plain-text copy is needed. Use `/data.json` when headings, blocks, source PDF metadata, and the live Appendix III register are needed.",
        "Use `/okf/` or `/okf.zip` when an agent wants the same knowledge as linked Markdown concepts with YAML frontmatter.",
        "References extracted from the canonical PDF footnotes are available in `/data.json` under `thesis.references` and appended to `/full.txt`.",
        ]
    )
    if full:
        lines.extend(["", "## Full thesis text", "", str(thesis.get("full_text") or "")])
    return ("\n".join(lines).rstrip() + "\n").encode("utf-8")


def render_sitemap() -> bytes:
    today = datetime.now(timezone.utc).date().isoformat()
    return f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url><loc>{escape(PUBLIC_BASE)}/</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/infographics/</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/reader/</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/assets/discontinuity-thesis.epub</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/full.txt</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/data.json</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/okf/</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/okf-browser/</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/okf.zip</loc><lastmod>{today}</lastmod></url>
  <url><loc>{escape(PUBLIC_BASE)}/llms.txt</loc><lastmod>{today}</lastmod></url>
</urlset>
""".encode("utf-8")


# CopeCheck Network footer, matching the markup used by the Jinja-templated
# sites (careers/eu/policy/quiz). Appended to the injected disclosure footer
# below so every HTML response on this host carries it.
NETWORK_FOOTER = (
    "<p class=\"network-links\" style=\"margin-top:0.8rem;font-size:0.8rem;opacity:0.5;text-align:center;\">CopeCheck Network: <a href=\"https://copecheck.com\" style=\"color:inherit;\">Main</a> &middot; "
    "<a href=\"https://uk.copecheck.com\" style=\"color:inherit;\">UK</a> &middot; "
    "<a href=\"https://countries.copecheck.com\" style=\"color:inherit;\">Countries</a> &middot; "
    "<a href=\"https://eu.copecheck.com\" style=\"color:inherit;\">EU</a> &middot; "
    "<a href=\"https://policy.copecheck.com\" style=\"color:inherit;\">Policy</a> &middot; "
    "<a href=\"https://cities.copecheck.com\" style=\"color:inherit;\">Cities</a> &middot; "
    "<a href=\"https://layoffs.copecheck.com\" style=\"color:inherit;\">Layoffs</a> &middot; "
    "<a href=\"https://careers.copecheck.com\" style=\"color:inherit;\">Careers</a> &middot; "
    "<a href=\"https://quiz.copecheck.com\" style=\"color:inherit;\">Quiz</a> &middot; "
    "<a href=\"https://copecheck.com/contact?from=https://thesis.copecheck.com\" style=\"color:inherit;\">Feedback</a></p>"
)


def ai_disclosure_page() -> bytes:
    return b'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>AI and Human Review Disclosure | The Discontinuity Thesis</title></head><body><main><article style="max-width:52rem;margin:3rem auto;line-height:1.65"><h1>AI assistance and human review</h1><p><strong>The Discontinuity Thesis is hand-checked by its author.</strong> Its arguments, final prose, claims, references and published revisions are not automatically approved or published by an AI system.</p><h2>Where AI is used</h2><p>AI tools may assist with web presentation, formatting, indexing, summaries, infographics, machine-readable exports and triage of possible evidence for the live appendix. Suggested evidence or wording is reviewed before it becomes part of the thesis.</p><h2>Models</h2><p>Site-maintenance and evidence workflows may use OpenAI Codex/GPT-family models, currently gpt-5.6-luna with maximum reasoning in the main CopeCheck scoring path, and MiniMax models in specialist or fallback pipelines. Model output is treated as assistance, not authority.</p><h2>Corrections</h2><p>Send the page or section, disputed text and supporting evidence to <a href="mailto:btl101@gmail.com?subject=Discontinuity%20Thesis%20correction">btl101@gmail.com</a>.</p></article></main><footer></footer></body></html>'''


def inject_human_review_disclosure(body: bytes, content_type: str) -> bytes:
    if not content_type.startswith("text/html"):
        return body
    text = body.decode("utf-8", errors="replace")
    if "cc-ai-label" in text:
        return body
    label = '''<style>.cc-ai-label,.cc-ai-footer{box-sizing:border-box;border:1px solid rgba(34,197,94,.42);border-radius:.65rem;background:rgba(34,197,94,.08);color:inherit;padding:.75rem 1rem;line-height:1.5}.cc-ai-label{margin:1rem auto;max-width:72rem}.cc-ai-label strong{margin-right:.4rem;text-transform:uppercase;letter-spacing:.04em}.cc-ai-label a,.cc-ai-footer a{color:inherit;text-decoration:underline}.cc-ai-footer{margin:1rem;font-size:.85rem}</style><aside class="cc-ai-label" role="note"><strong>Human-checked thesis</strong> The thesis text, claims and citations are checked by the author; AI assists presentation and evidence triage. <a href="/ai-disclosure">Full disclosure</a>.</aside>'''
    footer = '''<p class="cc-ai-footer"><strong>Human-review disclosure:</strong> The thesis is hand-checked by the author. AI may assist formatting, presentation and evidence triage but does not approve the published argument. <a href="/ai-disclosure">Full disclosure</a>.</p>'''
    main_at = text.find("<main")
    if main_at >= 0:
        main_end = text.find(">", main_at)
        text = text[:main_end + 1] + label + text[main_end + 1:]
    footer += NETWORK_FOOTER
    footer_at = text.find("<footer")
    if footer_at >= 0:
        footer_end = text.find(">", footer_at)
        text = text[:footer_end + 1] + footer + text[footer_end + 1:]
    else:
        text = text.replace("</body>", f"<footer>{footer}</footer></body>", 1)
    return text.encode("utf-8")


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt: str, *args: Any) -> None:
        print(f"{self.address_string()} - {fmt % args}")

    def send_security_headers(self) -> None:
        self.send_header("X-Content-Type-Options", "nosniff")
        self.send_header("X-Frame-Options", "DENY")
        self.send_header("Referrer-Policy", "strict-origin-when-cross-origin")
        self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=(), interest-cohort=()")

    def send_bytes(self, status: int, body: bytes, content_type: str, head_only: bool = False) -> None:
        body = inject_human_review_disclosure(body, content_type)
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "public, max-age=300, stale-while-revalidate=900")
        self.send_security_headers()
        self.end_headers()
        if not head_only:
            self.wfile.write(body)

    def do_HEAD(self) -> None:
        self.route(head_only=True)

    def do_GET(self) -> None:
        self.route(head_only=False)

    def route(self, head_only: bool = False) -> None:
        path = urlparse(self.path).path
        if path == "/":
            return self.send_bytes(200, render_home(), "text/html; charset=utf-8", head_only)
        if path in {"/ai-disclosure", "/ai-disclosure/"}:
            return self.send_bytes(200, ai_disclosure_page(), "text/html; charset=utf-8", head_only)
        if path in {"/infographics", "/infographics/"}:
            return self.send_bytes(200, render_infographics_page(), "text/html; charset=utf-8", head_only)
        if path in {"/reader", "/reader/"}:
            return self.send_bytes(200, render_reader(), "text/html; charset=utf-8", head_only)
        if path == "/healthz":
            return self.send_bytes(200, b"ok\n", "text/plain; charset=utf-8", head_only)
        if path == "/discontinuity-thesis.epub":
            epub = ASSET_DIR / "discontinuity-thesis.epub"
            if epub.exists():
                return self.send_bytes(200, epub.read_bytes(), "application/epub+zip", head_only)
        if path == "/full.txt":
            text = (DATA_DIR / "full.txt").read_text(encoding="utf-8") if (DATA_DIR / "full.txt").exists() else ""
            return self.send_bytes(200, text.encode("utf-8"), "text/plain; charset=utf-8", head_only)
        if path == "/data.json":
            return self.send_bytes(200, render_data(), "application/json; charset=utf-8", head_only)
        if path in {"/okf-browser", "/okf-browser/"}:
            return self.send_bytes(200, render_okf_bridge(), "text/html; charset=utf-8", head_only)
        if path == "/okf.zip":
            return self.send_bytes(200, render_okf_zip(), "application/zip", head_only)
        if path == "/okf" or path.startswith("/okf/"):
            body = render_okf_path(path)
            if body is not None:
                return self.send_bytes(200, body, "text/markdown; charset=utf-8", head_only)
            return self.send_bytes(404, b"OKF concept not found\n", "text/plain; charset=utf-8", head_only)
        if path == "/llms.txt":
            return self.send_bytes(200, render_llms(False), "text/plain; charset=utf-8", head_only)
        if path == "/llms-full.txt":
            return self.send_bytes(200, render_llms(True), "text/plain; charset=utf-8", head_only)
        if path == "/appendix-live.json":
            return self.send_bytes(
                200,
                json.dumps(load_live_appendix(), ensure_ascii=False, indent=2).encode("utf-8"),
                "application/json; charset=utf-8",
                head_only,
            )
        if path == "/robots.txt":
            body = f"""User-agent: GPTBot
Allow: /

User-agent: OAI-SearchBot
Allow: /

User-agent: ChatGPT-User
Allow: /

User-agent: ClaudeBot
Allow: /

User-agent: anthropic-ai
Allow: /

User-agent: PerplexityBot
Allow: /

User-agent: Google-Extended
Allow: /

User-agent: *
Allow: /

Sitemap: {PUBLIC_BASE}/sitemap.xml
""".encode("utf-8")
            return self.send_bytes(200, body, "text/plain; charset=utf-8", head_only)
        if path == "/sitemap.xml":
            return self.send_bytes(200, render_sitemap(), "application/xml; charset=utf-8", head_only)
        if path.startswith("/assets/"):
            candidate = (ASSET_DIR / path.removeprefix("/assets/")).resolve()
            if ASSET_DIR.resolve() in candidate.parents and candidate.exists() and candidate.is_file():
                content_type = "application/epub+zip" if candidate.suffix == ".epub" else mimetypes.guess_type(candidate.name)[0] or "application/octet-stream"
                return self.send_bytes(200, candidate.read_bytes(), content_type, head_only)
        return self.send_bytes(404, b"Not found\n", "text/plain; charset=utf-8", head_only)


READER_SCRIPT = r"""
(() => {
  const keys = {
    progress: "copecheck.thesis.reader.progress.v1",
    notes: "copecheck.thesis.reader.notes.v1",
    feedback: "copecheck.thesis.reader.feedback.v1"
  };
  const article = document.getElementById("reader-article");
  const progressBar = document.getElementById("reader-progress-bar");
  const progressLabel = document.getElementById("reader-progress-label");
  const noteText = document.getElementById("reader-note-text");
  const noteStatus = document.getElementById("note-status");
  const noteCount = document.getElementById("note-count");
  const notesList = document.getElementById("notes-list");
  const feedbackText = document.getElementById("feedback-text");
  const feedbackMail = document.getElementById("feedback-mail");
  const feedbackStatus = document.getElementById("feedback-status");
  let selectedTarget = "";
  let ticking = false;

  function readJson(key, fallback) {
    try {
      const value = localStorage.getItem(key);
      return value ? JSON.parse(value) : fallback;
    } catch (error) {
      return fallback;
    }
  }

  function writeJson(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
  }

  function notes() {
    const value = readJson(keys.notes, []);
    return Array.isArray(value) ? value : [];
  }

  function setNotes(value) {
    writeJson(keys.notes, value);
    paintNotes();
  }

  function percentRead() {
    const max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
    return Math.min(100, Math.max(0, Math.round((window.scrollY / max) * 100)));
  }

  function currentSectionId() {
    const sections = [...document.querySelectorAll(".reader-section[id]")];
    let current = sections[0]?.id || "";
    for (const section of sections) {
      if (section.getBoundingClientRect().top <= 120) current = section.id;
    }
    return current;
  }

  function saveProgress() {
    const percent = percentRead();
    progressBar.style.width = `${percent}%`;
    progressLabel.textContent = `${percent}%`;
    writeJson(keys.progress, {
      scrollY: Math.round(window.scrollY),
      percent,
      section: currentSectionId(),
      updatedAt: new Date().toISOString()
    });
  }

  function restoreProgress() {
    const progress = readJson(keys.progress, null);
    if (!location.hash && progress && Number.isFinite(progress.scrollY)) {
      window.scrollTo(0, progress.scrollY);
    }
    saveProgress();
  }

  function selectTarget(target, excerpt = "") {
    selectedTarget = target;
    const existing = notes().find(item => item.target === target);
    noteText.value = existing?.text || "";
    noteText.dataset.target = target;
    noteText.dataset.excerpt = existing?.excerpt || excerpt;
    document.querySelectorAll(".reader-block.is-selected").forEach(item => item.classList.remove("is-selected"));
    const node = document.getElementById(target);
    if (node) node.classList.add("is-selected");
    noteText.focus();
  }

  function paintNoteMarkers() {
    const savedTargets = new Set(notes().map(item => item.target));
    document.querySelectorAll("[data-reader-block]").forEach(block => {
      block.classList.toggle("has-saved-note", savedTargets.has(block.id));
    });
  }

  function paintNotes() {
    const saved = notes().sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)));
    noteCount.textContent = String(saved.length);
    notesList.innerHTML = saved.map(item => `
      <button type="button" class="note-list-item" data-note-target="${escapeHtml(item.target)}">
        <strong>${escapeHtml(item.excerpt || item.target)}</strong>
        <span>${escapeHtml(item.text || "")}</span>
      </button>
    `).join("");
    paintNoteMarkers();
  }

  function escapeHtml(value) {
    return String(value || "").replace(/[&<>"']/g, character => ({
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      "\"": "&quot;",
      "'": "&#039;"
    }[character]));
  }

  function saveSelectedNote() {
    const target = selectedTarget || noteText.dataset.target;
    const text = noteText.value.trim();
    if (!target || !text) {
      noteStatus.textContent = "Select text first.";
      return;
    }
    const saved = notes();
    const now = new Date().toISOString();
    const existing = saved.find(item => item.target === target);
    if (existing) {
      existing.text = text;
      existing.updatedAt = now;
    } else {
      saved.push({
        id: crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`,
        target,
        excerpt: noteText.dataset.excerpt || target,
        text,
        createdAt: now,
        updatedAt: now
      });
    }
    setNotes(saved);
    noteStatus.textContent = "Saved.";
  }

  function deleteSelectedNote() {
    const target = selectedTarget || noteText.dataset.target;
    if (!target) return;
    setNotes(notes().filter(item => item.target !== target));
    noteText.value = "";
    noteStatus.textContent = "Deleted.";
  }

  function updateFeedbackLink() {
    const value = feedbackText.value.trim();
    localStorage.setItem(keys.feedback, value);
    feedbackMail.href = `mailto:btl101@gmail.com?subject=Discontinuity%20Thesis%20feedback&body=${encodeURIComponent(value)}`;
  }

  window.addEventListener("scroll", () => {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(() => {
      saveProgress();
      ticking = false;
    });
  }, { passive: true });

  article.addEventListener("click", event => {
    const button = event.target.closest(".note-marker");
    if (!button) return;
    selectTarget(button.dataset.noteTarget, button.dataset.noteExcerpt || "");
  });

  notesList.addEventListener("click", event => {
    const button = event.target.closest("[data-note-target]");
    if (!button) return;
    const target = button.dataset.noteTarget;
    const note = notes().find(item => item.target === target);
    const block = document.getElementById(target);
    if (block) block.scrollIntoView({ block: "center" });
    selectTarget(target, note?.excerpt || "");
  });

  document.getElementById("save-note").addEventListener("click", saveSelectedNote);
  document.getElementById("delete-note").addEventListener("click", deleteSelectedNote);
  document.getElementById("copy-notes").addEventListener("click", async () => {
    await navigator.clipboard.writeText(JSON.stringify(notes(), null, 2));
    noteStatus.textContent = "Copied.";
  });
  document.getElementById("copy-feedback").addEventListener("click", async () => {
    await navigator.clipboard.writeText(feedbackText.value);
    feedbackStatus.textContent = "Copied.";
  });
  feedbackText.addEventListener("input", updateFeedbackLink);

  feedbackText.value = localStorage.getItem(keys.feedback) || "";
  updateFeedbackLink();
  paintNotes();
  setTimeout(restoreProgress, 60);
})();
"""


CSS = r"""
:root {
  color-scheme: light;
  --bg: #f5f7fa;
  --ink: #10141b;
  --muted: #5d6878;
  --panel: #ffffff;
  --line: #d9e0ea;
  --blue: #235ebc;
  --green: #0f766e;
  --red: #b4233a;
  --gold: #a66a00;
  --shadow: 0 18px 60px rgba(16, 20, 27, 0.12);
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
  margin: 0;
  background: var(--bg);
  color: var(--ink);
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
  letter-spacing: 0;
}
a { color: inherit; text-decoration: none; }
p { color: var(--muted); line-height: 1.72; }
.topbar {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
  padding: 14px clamp(16px, 4vw, 54px);
  background: rgba(245, 247, 250, 0.92);
  border-bottom: 1px solid rgba(217, 224, 234, 0.9);
  backdrop-filter: blur(16px);
}
.brand {
  display: inline-flex;
  align-items: center;
  gap: 12px;
  min-width: max-content;
}
.mark {
  display: grid;
  place-items: center;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: var(--ink);
  color: white;
  font-weight: 900;
  font-size: 13px;
}
.brand strong,
.brand small {
  display: block;
}
.brand small {
  color: var(--muted);
  font-size: 12px;
}
nav {
  display: flex;
  align-items: center;
  gap: 5px;
  flex-wrap: wrap;
  justify-content: flex-end;
}
nav a {
  padding: 9px 11px;
  border-radius: 8px;
  color: var(--muted);
  font-size: 14px;
  font-weight: 800;
}
nav a:hover {
  background: var(--panel);
  color: var(--ink);
  box-shadow: inset 0 0 0 1px var(--line);
}
main {
  width: min(1240px, calc(100% - 32px));
  margin: 0 auto;
}
.hero {
  min-height: 660px;
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(300px, 390px);
  align-items: center;
  gap: clamp(34px, 6vw, 86px);
  padding: clamp(52px, 8vw, 90px) 0 56px;
}
h1 {
  max-width: 780px;
  margin: 0;
  font-size: clamp(54px, 8vw, 108px);
  line-height: 0.94;
  letter-spacing: 0;
}
.subtitle {
  max-width: 680px;
  margin: 22px 0 0;
  color: var(--ink);
  font-size: clamp(22px, 3vw, 34px);
  line-height: 1.14;
  font-weight: 750;
}
.standfirst {
  max-width: 720px;
  font-size: 19px;
}
.actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
  margin-top: 24px;
}
button,
.actions a {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 46px;
  padding: 0 18px;
  border: 1px solid var(--ink);
  border-radius: 8px;
  background: var(--ink);
  color: white;
  font: inherit;
  font-size: 14px;
  font-weight: 850;
  cursor: pointer;
}
.actions a {
  background: var(--panel);
  color: var(--ink);
  border-color: var(--line);
}
.copy-status {
  min-height: 24px;
  margin: 12px 0 0;
  color: var(--green);
  font-weight: 750;
}
.cover-card {
  display: grid;
  gap: 14px;
  align-self: center;
}
.cover-card img {
  width: 100%;
  aspect-ratio: 0.707;
  object-fit: cover;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: white;
  box-shadow: var(--shadow);
}
.cover-card div,
.machine-note,
.infographics-section,
.live-appendix,
.toc,
.thesis-section {
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
}
.cover-card div {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  padding: 13px;
  color: var(--muted);
  font-size: 13px;
  font-weight: 800;
}
.cover-card strong {
  color: var(--ink);
}
.machine-note {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 18px;
  padding: 24px;
  margin-bottom: 42px;
  box-shadow: 0 10px 34px rgba(16, 20, 27, 0.05);
}
.machine-note strong {
  display: block;
  font-size: 18px;
}
.machine-note p {
  margin-bottom: 0;
}
.machine-note a,
.thesis a,
footer a {
  color: var(--blue);
  font-weight: 800;
}
.infographics-page {
  padding: 36px 0 56px;
}
.infographics-section {
  scroll-margin-top: 92px;
  padding: clamp(24px, 4vw, 42px);
  margin-bottom: 42px;
  box-shadow: 0 10px 34px rgba(16, 20, 27, 0.05);
}
.infographics-head {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 18px;
  margin-bottom: 24px;
}
.infographics-head h2,
.infographics-head h1 {
  max-width: 720px;
  margin: 8px 0 0;
  color: var(--ink);
  font-size: clamp(32px, 5vw, 58px);
  line-height: 1;
  letter-spacing: 0;
}
.infographics-head p {
  max-width: 680px;
  margin: 12px 0 0;
  font-size: 17px;
}
.section-link {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 42px;
  padding: 0 14px;
  border: 1px solid var(--line);
  border-radius: 8px;
  color: var(--ink);
  font-size: 13px;
  font-weight: 900;
  white-space: nowrap;
}
.section-link:hover {
  border-color: var(--ink);
}
.infographic-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(270px, 1fr));
  gap: 16px;
}
.infographic-card {
  position: relative;
  display: grid;
  grid-template-rows: auto auto 1fr;
  min-height: 438px;
  padding: 16px;
  border: 1px solid var(--line);
  border-top: 5px solid var(--card-accent);
  border-radius: 8px;
  background: #ffffff;
  color: inherit;
  box-shadow: 0 10px 24px rgba(16, 20, 27, 0.04);
  transition: transform 160ms ease, box-shadow 160ms ease, border-color 160ms ease;
}
.infographic-card:hover {
  transform: translateY(-3px);
  border-color: color-mix(in srgb, var(--card-accent) 48%, var(--line));
  box-shadow: 0 18px 36px rgba(16, 20, 27, 0.1);
}
.infographic-number {
  width: max-content;
  padding: 5px 8px;
  border-radius: 8px;
  background: color-mix(in srgb, var(--card-accent) 14%, #ffffff);
  color: var(--card-accent);
  font-size: 12px;
  font-weight: 950;
}
.infographic-visual {
  position: relative;
  height: 164px;
  min-height: 164px;
  margin: 14px 0 16px;
  overflow: hidden;
  border: 1px solid #e5ebf4;
  border-radius: 8px;
  background:
    linear-gradient(90deg, rgba(16, 20, 27, 0.035) 1px, transparent 1px),
    linear-gradient(0deg, rgba(16, 20, 27, 0.035) 1px, transparent 1px),
    #f8fafc;
  background-size: 28px 28px;
}
.infographic-copy {
  display: grid;
  align-content: start;
  gap: 8px;
}
.infographic-essay {
  margin: 0;
  color: var(--card-accent);
  font-size: 13px;
  font-weight: 900;
  line-height: 1.3;
}
.infographic-copy h3 {
  margin: 0;
  color: var(--ink);
  font-size: 24px;
  line-height: 1.05;
  letter-spacing: 0;
}
.infographic-copy p {
  margin: 0;
  color: #2d3747;
  font-size: 15px;
  line-height: 1.55;
}
.infographic-copy small {
  display: block;
  color: var(--muted);
  font-size: 13px;
  line-height: 1.45;
}
.cost-bars {
  position: relative;
  display: flex;
  align-items: flex-end;
  gap: 14px;
  height: 100%;
  padding: 22px 18px;
}
.cost-bar {
  position: relative;
  flex: 1;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  padding: 0 8px 10px;
  border-radius: 8px 8px 4px 4px;
  color: #ffffff;
  font-size: 12px;
  font-weight: 900;
  text-align: center;
}
.cost-bar.human {
  height: 82%;
  background: #10141b;
}
.cost-bar.ai {
  height: 48%;
  background: var(--card-accent);
}
.cost-threshold {
  position: absolute;
  right: 14px;
  bottom: 54%;
  left: 14px;
  border-top: 2px dashed rgba(16, 20, 27, 0.45);
}
.cost-threshold span {
  position: absolute;
  right: 0;
  top: -24px;
  padding: 2px 4px;
  border-radius: 4px;
  background: #f8fafc;
  color: #2d3747;
  font-size: 11px;
  font-weight: 900;
  text-transform: uppercase;
}
.flow-strip {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  align-items: center;
  gap: 8px;
  height: 100%;
  padding: 18px;
}
.flow-strip span {
  position: relative;
  display: grid;
  place-items: center;
  min-height: 74px;
  padding: 8px;
  border: 2px solid color-mix(in srgb, var(--card-accent) 55%, #ffffff);
  border-radius: 8px;
  background: #ffffff;
  color: #162032;
  font-size: 12px;
  font-weight: 900;
  white-space: nowrap;
  text-align: center;
}
.flow-strip span:not(:last-child)::after {
  content: "";
  position: absolute;
  right: -11px;
  width: 12px;
  height: 2px;
  background: var(--card-accent);
}
.dilemma-map {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 8px;
  height: 100%;
  padding: 14px;
}
.dilemma-map span,
.dilemma-map strong {
  display: grid;
  place-items: center;
  border-radius: 8px;
  text-align: center;
  font-size: 12px;
  font-weight: 900;
}
.dilemma-map span {
  border: 1px solid color-mix(in srgb, var(--card-accent) 35%, #ffffff);
  background: #ffffff;
}
.dilemma-map strong {
  grid-column: 2;
  grid-row: 2;
  background: var(--card-accent);
  color: #ffffff;
}
.dilemma-map span:nth-child(1) {
  grid-column: 2;
  grid-row: 1;
}
.dilemma-map span:nth-child(2) {
  grid-column: 1;
  grid-row: 2;
}
.dilemma-map span:nth-child(4) {
  grid-column: 3;
  grid-row: 2;
}
.dilemma-map span:nth-child(5) {
  grid-column: 2;
  grid-row: 3;
}
.sorites-scale {
  display: grid;
  align-content: center;
  gap: 14px;
  height: 100%;
  padding: 22px 16px;
}
.sorites-track {
  height: 24px;
  border-radius: 999px;
  background: linear-gradient(90deg, #e2e8f0, #94a3b8, var(--card-accent), #111827);
}
.sorites-points {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 7px;
}
.sorites-points span {
  padding-top: 12px;
  border-top: 2px solid color-mix(in srgb, var(--card-accent) 50%, #cbd5e1);
  color: #2d3747;
  font-size: 11px;
  font-weight: 900;
  text-align: center;
}
.sorites-scale strong {
  justify-self: center;
  padding: 7px 10px;
  border-radius: 8px;
  background: #ffffff;
  color: var(--card-accent);
  font-size: 12px;
  font-weight: 950;
}
.category-map,
.successor-loop {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 9px;
  height: 100%;
  padding: 15px;
}
.category-map span,
.category-map strong,
.successor-loop span,
.successor-loop strong {
  display: grid;
  place-items: center;
  min-height: 44px;
  padding: 8px;
  border-radius: 8px;
  text-align: center;
  font-size: 12px;
  font-weight: 900;
}
.category-map span,
.successor-loop span {
  border: 1px solid #d9e0ea;
  background: #ffffff;
}
.category-map strong,
.successor-loop strong {
  grid-column: 1 / -1;
  border: 2px dashed var(--card-accent);
  background: color-mix(in srgb, var(--card-accent) 10%, #ffffff);
  color: var(--card-accent);
}
.drag-chart {
  position: relative;
  height: 100%;
  padding: 18px;
}
.drag-curve {
  position: absolute;
  right: 16px;
  bottom: 40px;
  left: 16px;
  height: 5px;
  border-radius: 999px;
  background: var(--card-accent);
  transform: rotate(-18deg);
  transform-origin: left center;
}
.drag-gate {
  position: absolute;
  display: grid;
  place-items: center;
  width: 66px;
  min-height: 34px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  background: #ffffff;
  color: #28303c;
  font-size: 11px;
  font-weight: 900;
  text-transform: uppercase;
}
.gate-one {
  left: 20px;
  bottom: 28px;
}
.gate-two {
  left: calc(50% - 33px);
  bottom: 62px;
}
.gate-three {
  right: 18px;
  top: 22px;
}
.reader-shell {
  display: grid;
  grid-template-columns: minmax(220px, 290px) minmax(0, 1fr);
  gap: 24px;
  align-items: start;
}
.toc {
  position: sticky;
  top: 84px;
  max-height: calc(100vh - 108px);
  overflow: auto;
  padding: 18px;
}
.toc strong {
  display: block;
  margin-bottom: 12px;
}
.toc a {
  display: block;
  padding: 8px 0;
  color: var(--muted);
  border-top: 1px solid #eef2f7;
  font-size: 13px;
  line-height: 1.3;
}
.toc a.h2 {
  color: var(--ink);
  font-weight: 850;
}
.toc a.h3 {
  padding-left: 10px;
}
.thesis {
  min-width: 0;
}
.thesis-section {
  padding: clamp(24px, 5vw, 54px);
  margin-bottom: 22px;
  box-shadow: 0 10px 34px rgba(16, 20, 27, 0.05);
}
.thesis h2 {
  margin: 0 0 22px;
  max-width: 820px;
  font-size: clamp(34px, 5vw, 60px);
  line-height: 1;
  letter-spacing: 0;
}
.thesis h3 {
  margin: 30px 0 10px;
  max-width: 780px;
  font-size: clamp(22px, 3vw, 32px);
  line-height: 1.12;
  letter-spacing: 0;
}
.thesis p {
  max-width: 820px;
  margin: 0 0 18px;
  color: #28303c;
  font-family: ui-serif, Georgia, Cambria, "Times New Roman", serif;
  font-size: 19px;
  line-height: 1.74;
  overflow-wrap: break-word;
  hyphens: none;
}
.appendix-section p {
  max-width: 880px;
}
.appendix-section h3 {
  margin-top: 38px;
  padding-top: 8px;
  border-top: 1px solid #edf1f6;
  color: #172033;
  font-size: clamp(21px, 2.6vw, 28px);
}
.appendix-table {
  max-width: 100%;
  margin: 22px 0 28px;
}
.appendix-table figcaption {
  margin: 0 0 10px;
  color: var(--ink);
  font-size: 15px;
  font-weight: 900;
}
.appendix-table-scroll {
  overflow-x: auto;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #ffffff;
}
.appendix-table table {
  width: 100%;
  min-width: 680px;
  border-collapse: collapse;
  font-size: 14px;
  line-height: 1.35;
}
.appendix-table th,
.appendix-table td {
  padding: 12px 13px;
  text-align: left;
  vertical-align: top;
  border-bottom: 1px solid #e8eef6;
}
.appendix-table th {
  background: #f4f7fb;
  color: #3a4657;
  font-size: 12px;
  font-weight: 900;
  text-transform: uppercase;
}
.appendix-table td:first-child {
  color: var(--ink);
  font-weight: 850;
  white-space: nowrap;
}
.appendix-table tbody tr:last-child td {
  border-bottom: 0;
}
.references-section {
  scroll-margin-top: 92px;
  margin-top: 30px;
}
.references-section h2,
.reader-references h2 {
  color: var(--ink);
}
.references-list {
  display: grid;
  gap: 0;
  margin: 16px 0 0;
  padding: 0;
  list-style: none;
}
.references-list li {
  display: grid;
  grid-template-columns: 46px minmax(0, 1fr);
  gap: 12px;
  padding: 14px 0;
  border-top: 1px solid var(--line);
}
.reference-number {
  display: grid;
  place-items: center;
  width: 34px;
  height: 34px;
  border-radius: 8px;
  background: #eef2f7;
  color: var(--ink);
  font-size: 13px;
  font-weight: 900;
}
.references-list p {
  margin: 0;
  color: #28303c;
  font-size: 15px;
  line-height: 1.58;
  overflow-wrap: anywhere;
}
.references-list a {
  color: var(--blue);
  font-weight: 800;
}
.thesis h2,
.thesis h3,
.toc a,
.live-appendix {
  overflow-wrap: anywhere;
}
.section-kicker {
  color: var(--red);
  font-size: 13px;
  font-weight: 900;
  text-transform: uppercase;
}
.live-appendix {
  margin: 22px 0 30px;
  padding: clamp(20px, 4vw, 34px);
  background: #fbfcff;
}
.live-head {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-top: 8px;
}
.live-head h2 {
  margin-bottom: 8px;
  font-size: clamp(30px, 4vw, 46px);
}
.live-head span {
  align-self: flex-start;
  padding: 8px 10px;
  border-radius: 999px;
  background: #dff8ee;
  color: #066148;
  font-size: 12px;
  font-weight: 900;
  white-space: nowrap;
}
.live-grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 0.9fr);
  gap: 18px;
  margin: 18px 0;
}
.signal-list,
.watch-list {
  display: grid;
  gap: 10px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.signal-list li,
.watch-list li,
.evidence-list article {
  padding: 14px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: white;
}
.signal-list strong,
.signal-list span,
.signal-list em {
  display: block;
}
.signal-list span,
.signal-list em,
.live-meta,
.evidence-list small {
  color: var(--muted);
  font-style: normal;
  font-size: 13px;
}
.evidence-list {
  display: grid;
  gap: 10px;
}
.evidence-list p {
  margin: 8px 0;
  font-family: inherit;
  font-size: 15px;
  line-height: 1.6;
}
.reader-topbar {
  position: sticky;
  top: 0;
  z-index: 12;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
  padding: 14px clamp(16px, 4vw, 48px);
  background: rgba(245, 247, 250, 0.95);
  border-bottom: 1px solid var(--line);
  backdrop-filter: blur(16px);
}
.reader-page {
  width: min(1380px, calc(100% - 28px));
  display: grid;
  grid-template-columns: minmax(260px, 340px) minmax(0, 820px);
  align-items: start;
  justify-content: center;
  gap: clamp(18px, 4vw, 54px);
  padding: 28px 0 70px;
}
.reader-tools {
  position: sticky;
  top: 88px;
  display: grid;
  gap: 14px;
  max-height: calc(100vh - 110px);
  overflow: auto;
}
.reader-toolbox {
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  padding: 16px;
  box-shadow: 0 10px 34px rgba(16, 20, 27, 0.05);
}
.reader-toolbox strong,
.tool-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  color: var(--ink);
}
.reader-progress {
  height: 10px;
  margin-top: 12px;
  border-radius: 999px;
  background: #e7edf5;
  overflow: hidden;
}
.reader-progress span {
  display: block;
  width: 0;
  height: 100%;
  background: var(--green);
}
#reader-progress-label,
.reader-status {
  min-height: 20px;
  margin: 8px 0 0;
  color: var(--muted);
  font-size: 13px;
  font-weight: 750;
}
.reader-nav {
  display: grid;
  gap: 6px;
}
.reader-nav a {
  display: block;
  padding: 7px 0;
  color: var(--muted);
  border-top: 1px solid #eef2f7;
  font-size: 13px;
  line-height: 1.25;
}
.reader-nav a.h2 {
  color: var(--ink);
  font-weight: 850;
}
.reader-nav a.h3 {
  padding-left: 10px;
}
.notes-list {
  display: grid;
  gap: 8px;
  margin: 12px 0;
}
.note-list-item {
  min-height: 0;
  display: block;
  width: 100%;
  padding: 10px;
  border: 1px solid var(--line);
  background: #fbfcff;
  color: var(--ink);
  text-align: left;
  white-space: normal;
}
.note-list-item strong,
.note-list-item span {
  display: block;
}
.note-list-item span {
  margin-top: 4px;
  color: var(--muted);
  font-size: 12px;
  line-height: 1.35;
}
.reader-toolbox textarea {
  width: 100%;
  min-width: 0;
  resize: vertical;
  padding: 11px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: white;
  color: var(--ink);
  font: inherit;
  font-size: 14px;
  line-height: 1.45;
}
.reader-buttons {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 8px;
  margin-top: 9px;
}
.reader-buttons button,
.reader-button-link {
  min-height: 40px;
  padding: 0 10px;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 850;
}
.reader-buttons button:nth-child(3) {
  grid-column: 1 / -1;
}
.reader-button-link {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--line);
  background: white;
  color: var(--ink);
}
.reader-article {
  min-width: 0;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  padding: clamp(28px, 6vw, 76px);
  box-shadow: 0 10px 34px rgba(16, 20, 27, 0.05);
}
.reader-title {
  margin-bottom: 42px;
  padding-bottom: 24px;
  border-bottom: 1px solid var(--line);
}
.reader-title h1 {
  max-width: 720px;
  font-size: clamp(42px, 7vw, 78px);
}
.reader-title p {
  max-width: 620px;
  color: var(--ink);
  font-size: clamp(19px, 3vw, 28px);
  font-weight: 800;
  line-height: 1.16;
}
.reader-section {
  scroll-margin-top: 90px;
}
.reader-section h2 {
  margin: 48px 0 22px;
  color: var(--ink);
  font-size: clamp(30px, 4vw, 52px);
  line-height: 1.04;
}
.reader-references {
  margin-top: 56px;
  padding-top: 24px;
  border-top: 1px solid var(--line);
}
.reader-references .references-list p {
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
  font-size: 14px;
  line-height: 1.55;
}
.reader-block {
  position: relative;
  margin-bottom: 18px;
  padding-right: 78px;
  scroll-margin-top: 100px;
}
.reader-block p {
  margin: 0;
  color: #202938;
  font-family: ui-serif, Georgia, Cambria, "Times New Roman", serif;
  font-size: clamp(19px, 2.2vw, 22px);
  line-height: 1.72;
  overflow-wrap: break-word;
  hyphens: none;
}
.reader-block h3 {
  margin: 34px 0 10px;
  color: #172033;
  font-size: clamp(23px, 3vw, 32px);
  line-height: 1.12;
}
.note-marker {
  position: absolute;
  top: 2px;
  right: 0;
  min-height: 32px;
  min-width: 58px;
  padding: 0 10px;
  border: 1px solid var(--line);
  background: #fbfcff;
  color: var(--muted);
  font-size: 12px;
}
.reader-block.has-saved-note .note-marker,
.reader-block.is-selected .note-marker {
  border-color: #83d4bf;
  background: #dff8ee;
  color: #066148;
}
.reader-block.is-selected {
  outline: 2px solid #bcebdc;
  outline-offset: 8px;
  border-radius: 8px;
}
.reader-table-block {
  padding-right: 0;
}
footer {
  width: min(1240px, calc(100% - 32px));
  margin: 62px auto 0;
  padding: 30px 0 44px;
  border-top: 1px solid var(--line);
}
#copy-buffer {
  position: fixed;
  left: 0;
  top: 0;
  width: 0;
  height: 0;
  padding: 0;
  border: 0;
  opacity: 0;
  overflow: hidden;
}
.okf-bridge {
  width: min(100% - 32px, 1320px);
}
.okf-hero {
  min-height: 0;
}
.okf-counts {
  grid-template-columns: repeat(4, minmax(0, 1fr));
}
.okf-counts strong {
  color: var(--blue);
  display: block;
  font-family: "Cormorant Garamond", serif;
  font-size: clamp(36px, 6vw, 64px);
  line-height: 0.95;
  margin-bottom: 8px;
}
.okf-panel {
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: 30px;
  box-shadow: var(--shadow);
  margin: 26px 0;
  padding: clamp(22px, 4vw, 44px);
}
.okf-panel-head {
  border-bottom: 1px solid var(--line);
  margin-bottom: 18px;
  padding-bottom: 16px;
}
.okf-panel-head h2 {
  font-size: clamp(32px, 4vw, 54px);
  margin: 0 0 8px;
}
.okf-panel-head p {
  color: var(--muted);
  margin: 0;
}
.okf-list {
  display: grid;
  gap: 12px;
}
.okf-evidence-list {
  max-height: 980px;
  overflow: auto;
  padding-right: 8px;
}
.okf-row {
  background: rgba(255, 255, 255, 0.72);
  border: 1px solid rgba(35, 94, 188, 0.10);
  border-radius: 18px;
  padding: 16px 18px;
}
.okf-row a {
  color: var(--blue);
  display: inline-block;
  font-family: Inter, sans-serif;
  font-weight: 850;
  line-height: 1.35;
  overflow-wrap: anywhere;
  text-decoration: none;
}
.okf-row small {
  color: var(--muted);
  display: block;
  font-family: Inter, sans-serif;
  font-size: 12px;
  letter-spacing: 0.02em;
  margin-top: 5px;
  text-transform: uppercase;
}
.okf-row p {
  color: var(--ink);
  font-size: 16px;
  line-height: 1.55;
  margin: 8px 0 0;
}
@media (max-width: 980px) {
  .hero,
  .reader-shell,
  .machine-note,
  .live-grid,
  .reader-page {
    grid-template-columns: 1fr;
  }
  .hero {
    min-height: 0;
  }
  .infographics-head {
    align-items: flex-start;
    flex-direction: column;
  }
  .cover-card {
    max-width: 360px;
  }
  .okf-counts {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
  .toc {
    position: static;
    max-height: none;
  }
  .reader-tools {
    position: static;
    max-height: none;
    order: 1;
    overflow: visible;
  }
  .reader-article {
    order: 2;
  }
}
@media (max-width: 640px) {
  main,
  footer {
    width: min(100% - 22px, 1240px);
  }
  .topbar {
    position: static;
    align-items: flex-start;
    flex-direction: column;
  }
  .reader-topbar {
    position: static;
    align-items: flex-start;
    flex-direction: column;
  }
  nav {
    justify-content: flex-start;
  }
  h1 {
    font-size: 48px;
    line-height: 1;
  }
  .subtitle {
    font-size: 23px;
  }
  .thesis-section {
    padding: 22px;
  }
  .thesis p {
    font-size: 18px;
  }
  .live-head {
    flex-direction: column;
  }
  .infographics-section {
    padding: 20px;
  }
  .infographic-grid {
    grid-template-columns: 1fr;
  }
  .infographic-card {
    grid-template-rows: auto auto 1fr;
    min-height: 0;
  }
  .infographic-visual {
    height: 150px;
    min-height: 150px;
  }
  .infographics-head h2,
  .infographics-head h1 {
    font-size: 34px;
  }
  .section-link {
    width: 100%;
  }
  .flow-strip {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
  .flow-strip span:not(:last-child)::after {
    display: none;
  }
  .reader-page {
    width: min(100% - 18px, 1380px);
    padding-top: 12px;
  }
  .reader-tools {
    max-height: 420px;
    overflow: auto;
  }
  .reader-article {
    padding: 22px;
  }
  .reader-block {
    padding-right: 0;
  }
  .note-marker {
    position: static;
    min-width: 0;
    margin-top: 8px;
  }
  .actions,
  .actions a,
  button {
    width: 100%;
  }
  .references-list li {
    grid-template-columns: 1fr;
  }
  .reference-number {
    width: max-content;
    padding: 0 10px;
  }
  .okf-counts {
    grid-template-columns: 1fr;
  }
  .okf-panel {
    border-radius: 22px;
    padding: 20px;
  }
}
"""


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", default=8107, type=int)
    args = parser.parse_args()
    server = ThreadingHTTPServer((args.host, args.port), Handler)
    print(f"CopeCheck thesis server running on http://{args.host}:{args.port}")
    server.serve_forever()


if __name__ == "__main__":
    main()
```
