---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import hashlib import html import ipaddress import json import os import re import socket import threading import time from datetime import datetime, timezone from."
resource: "https://capabilities.copecheck.com"
tags: ["copecheck", "capabilities", "source-file", "py"]
timestamp: "2026-10-24T17:25:06Z"
site: "capabilities"
source_path: "copecheck-capabilities/server.py"
---

# from __future__ import annotations

Source path: `copecheck-capabilities/server.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-10-24T17:25:06Z`

```py
from __future__ import annotations

import argparse
import hashlib
import html
import ipaddress
import json
import os
import re
import socket
import threading
import time
from datetime import datetime, timezone
from html.parser import HTMLParser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, urljoin, urlparse
from urllib.request import HTTPRedirectHandler, Request, build_opener, urlopen


BASE = Path(__file__).resolve().parent
DATA_DIR = BASE / "data"


def default_appendix_path() -> Path:
    candidates = [
        BASE.parent / "thesis" / "data" / "appendix-live.json",
        BASE.parent / "copecheck_thesis" / "data" / "appendix-live.json",
        BASE.parent / "copecheck-thesis" / "data" / "appendix-live.json",
        Path("/home/ben/infra/copecheck-thesis/data/appendix-live.json"),
    ]
    for candidate in candidates:
        if candidate.exists():
            return candidate.resolve()
    return candidates[0].resolve()


DEFAULT_APPENDIX_PATH = default_appendix_path()
APPENDIX_PATH = Path(os.getenv("CAPABILITIES_APPENDIX_PATH", str(DEFAULT_APPENDIX_PATH)))
SUBMISSIONS_FILE = Path(os.getenv("CAPABILITIES_SUBMISSIONS_FILE", str(DATA_DIR / "capability-submissions.jsonl")))
PUBLIC_BASE = os.getenv("COPECHECK_CAPABILITIES_PUBLIC_BASE", "https://capabilities.copecheck.com").rstrip("/")
THESIS_BASE = os.getenv("COPECHECK_THESIS_PUBLIC_BASE", "https://thesis.copecheck.com").rstrip("/")
FETCH_TIMEOUT = float(os.getenv("CAPABILITIES_FETCH_TIMEOUT", "12"))
SUBMIT_BODY_LIMIT = 18_000
SUBMIT_RATE_LIMIT = 12
SUBMIT_RATE_WINDOW = 3600
SUBMIT_LOCK = threading.Lock()
SUBMIT_RATE_STORE: dict[str, list[float]] = {}
ARTICLE_LIMIT = 220_000
MINIMAX_TIMEOUT = float(os.getenv("CAPABILITIES_MINIMAX_TIMEOUT", "7"))
ORGANIZATION_SCHEMA = {
    "@type": "Organization",
    "@id": "https://www.copecheck.com/#organization",
    "name": "CopeCheck",
    "url": "https://www.copecheck.com/",
}
DATASET_LICENSE_PATH = "/license"

CATEGORY_META = {
    "benchmark": {
        "label": "Benchmarks",
        "short": "model capability",
        "section": "Appendix III section one",
        "colour": "#235ebc",
    },
    "deployment": {
        "label": "Deployments",
        "short": "workflow proof",
        "section": "Appendix III section four",
        "colour": "#0f766e",
    },
    "vendor": {
        "label": "Vendor framing",
        "short": "threshold language",
        "section": "Appendix III section two",
        "colour": "#7c3aed",
    },
    "labour_market": {
        "label": "Labour market",
        "short": "employment signal",
        "section": "Appendix III sections five to seven",
        "colour": "#b4233a",
    },
    "layoff": {
        "label": "Layoffs",
        "short": "workforce cuts",
        "section": "Appendix III section six",
        "colour": "#a66a00",
    },
    "disconfirming": {
        "label": "Disconfirming — Attribution",
        "short": "attribution audit",
        "section": "Appendix III — audit register",
        "colour": "#9a3412",
    },
}


CSS = r"""
:root {
  color-scheme: light;
  --bg: #f7f8fa;
  --paper: #ffffff;
  --paper-2: #eef3f6;
  --ink: #16181d;
  --muted: #5d6673;
  --quiet: #7b8491;
  --line: #d9dee5;
  --line-strong: #c2cad4;
  --green: #0f766e;
  --blue: #235ebc;
  --red: #b4233a;
  --violet: #7c3aed;
  --amber: #a66a00;
  --shadow: 0 18px 42px rgba(32, 42, 54, .08);
  --radius: 8px;
  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* { box-sizing: border-box; }
body {
  margin: 0;
  background:
    linear-gradient(180deg, rgba(255,255,255,.82), rgba(247,248,250,.96) 34rem),
    var(--bg);
  color: var(--ink);
  line-height: 1.5;
}
a { color: inherit; text-decoration-thickness: .08em; text-underline-offset: .18em; }
.shell { width: min(1180px, calc(100% - 32px)); margin: 0 auto; }
.topbar {
  border-bottom: 1px solid var(--line);
  background: rgba(255,255,255,.84);
  backdrop-filter: blur(16px);
  position: sticky;
  top: 0;
  z-index: 5;
}
.topbar .shell {
  min-height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
}
.brand {
  display: inline-flex;
  gap: 10px;
  align-items: center;
  font-weight: 760;
  letter-spacing: 0;
}
.brand-mark {
  width: 30px;
  height: 30px;
  border: 2px solid var(--ink);
  display: grid;
  place-items: center;
  font-size: 13px;
  line-height: 1;
}
nav { display: flex; gap: 16px; flex-wrap: wrap; align-items: center; color: var(--muted); font-size: 14px; }
nav a { text-decoration: none; }
nav a:hover { color: var(--ink); }
.hero {
  padding: 54px 0 28px;
  display: grid;
  grid-template-columns: minmax(0, 1.02fr) minmax(320px, .78fr);
  gap: 34px;
  align-items: end;
}
h1 {
  font-size: clamp(42px, 6vw, 78px);
  line-height: .95;
  margin: 0 0 20px;
  letter-spacing: 0;
  max-width: 820px;
}
.lead {
  font-size: clamp(18px, 2vw, 22px);
  color: var(--muted);
  max-width: 760px;
  margin: 0;
}
.hero-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-top: 28px;
}
.button,
button,
.filter {
  min-height: 42px;
  border: 1px solid var(--line-strong);
  border-radius: var(--radius);
  background: var(--paper);
  color: var(--ink);
  padding: 10px 14px;
  font: inherit;
  font-size: 14px;
  font-weight: 690;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
}
.button.primary,
button.primary {
  background: var(--ink);
  color: #fff;
  border-color: var(--ink);
}
.button:hover,
button:hover,
.filter:hover { transform: translateY(-1px); box-shadow: 0 8px 20px rgba(32,42,54,.08); }
.submit-panel {
  background: var(--ink);
  color: #fff;
  border-radius: var(--radius);
  padding: clamp(20px, 4vw, 30px);
  margin: 8px auto 28px;
  box-shadow: var(--shadow);
}
.submit-panel h2 { color: #fff; }
.submit-panel p { color: rgba(255,255,255,.72); margin: 8px 0 0; max-width: 760px; }
.submit-form {
  display: grid;
  grid-template-columns: minmax(240px, 1.2fr) minmax(220px, .8fr) auto;
  gap: 12px;
  align-items: end;
  margin-top: 18px;
}
.submit-form label {
  display: grid;
  gap: 7px;
  color: rgba(255,255,255,.68);
  font-size: 12px;
  font-weight: 780;
  text-transform: uppercase;
  letter-spacing: .04em;
}
.submit-form input,
.submit-form textarea {
  width: 100%;
  min-height: 46px;
  border: 1px solid rgba(255,255,255,.2);
  border-radius: var(--radius);
  background: rgba(255,255,255,.08);
  color: #fff;
  padding: 10px 12px;
  font: inherit;
  font-weight: 650;
}
.submit-form textarea {
  min-height: 46px;
  resize: vertical;
}
.submit-form input::placeholder,
.submit-form textarea::placeholder { color: rgba(255,255,255,.44); }
.submit-form button {
  border-color: #fff;
  background: #fff;
  color: var(--ink);
}
.submit-result {
  margin-top: 14px;
}
.oracle-result {
  display: grid;
  gap: 16px;
  margin-top: 18px;
  padding: 18px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--paper);
  color: var(--ink);
}
.oracle-top {
  display: grid;
  grid-template-columns: auto minmax(0, 1fr);
  gap: 16px;
  align-items: center;
}
.oracle-status {
  display: grid;
  place-items: center;
  width: 106px;
  min-height: 86px;
  border-radius: var(--radius);
  background: #e8f8f3;
  color: var(--green);
  font-size: 13px;
  font-weight: 850;
  text-align: center;
  padding: 10px;
}
.oracle-status.reject {
  background: #fff1f1;
  color: var(--red);
}
.oracle-result h3 {
  font-size: 24px;
}
.oracle-result p { margin: 7px 0 0; color: var(--muted); }
.oracle-columns {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 14px;
}
.oracle-box {
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: #fbfcfd;
  padding: 14px;
}
.oracle-box ul {
  margin: 10px 0 0;
  padding-left: 18px;
}
.oracle-box li { margin: 5px 0; color: var(--muted); }
.oracle-entry {
  border-left: 3px solid var(--green);
  padding-left: 12px;
}
.oracle-entry dl {
  display: grid;
  gap: 8px;
  margin: 10px 0 0;
}
.oracle-entry dt { color: var(--quiet); font-size: 12px; text-transform: uppercase; letter-spacing: .08em; }
.oracle-entry dd { margin: 2px 0 0; font-weight: 700; }
.status-panel {
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--radius);
  padding: 18px;
  box-shadow: var(--shadow);
}
.status-panel dl {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 14px;
  margin: 0;
}
.status-panel dt {
  font-size: 12px;
  color: var(--quiet);
  text-transform: uppercase;
  letter-spacing: .08em;
}
.status-panel dd {
  margin: 4px 0 0;
  font-weight: 780;
  font-size: 24px;
}
.toolbar {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 14px;
  align-items: center;
  padding: 18px 0 24px;
}
.search {
  min-height: 46px;
  width: 100%;
  border: 1px solid var(--line-strong);
  border-radius: var(--radius);
  padding: 10px 14px;
  font: inherit;
  background: var(--paper);
}
.filters { display: flex; gap: 8px; flex-wrap: wrap; }
.filter[aria-current="true"] {
  background: var(--ink);
  color: #fff;
  border-color: var(--ink);
}
.section-grid {
  display: grid;
  grid-template-columns: minmax(0, .92fr) minmax(0, 1.08fr);
  gap: 22px;
  margin-bottom: 28px;
}
.map-panel,
.machine-panel {
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--radius);
  padding: 20px;
  min-width: 0;
}
.panel-head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 14px;
  margin-bottom: 14px;
}
h2, h3 { margin: 0; letter-spacing: 0; }
h2 { font-size: 28px; line-height: 1.08; }
h3 { font-size: 18px; line-height: 1.2; }
.muted { color: var(--muted); }
.cap-map {
  width: 100%;
  height: auto;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: #fbfcfd;
}
.machine-panel pre {
  max-height: 310px;
  overflow: auto;
  white-space: pre-wrap;
  word-break: break-word;
  background: #11151b;
  color: #edf3fb;
  border-radius: var(--radius);
  padding: 16px;
  font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  margin: 0 0 14px;
}
.feed {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px;
  margin: 0 0 48px;
}
.card {
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--radius);
  padding: 20px;
  display: grid;
  gap: 14px;
  min-height: 100%;
  box-shadow: 0 10px 28px rgba(32,42,54,.04);
}
.card:hover { border-color: var(--line-strong); }
.card-top {
  display: flex;
  align-items: start;
  justify-content: space-between;
  gap: 12px;
}
.card h2 {
  font-size: 24px;
  line-height: 1.12;
}
.card h2 a { text-decoration: none; }
.card h2 a:hover { text-decoration: underline; }
.score {
  width: 58px;
  height: 58px;
  flex: 0 0 auto;
  border-radius: 50%;
  display: grid;
  place-items: center;
  font-weight: 820;
  color: #fff;
  background: conic-gradient(var(--score-colour, var(--green)) calc(var(--score, 0) * 1%), #e5e9ef 0);
  position: relative;
}
.score::before {
  content: "";
  position: absolute;
  inset: 6px;
  background: var(--paper);
  border-radius: 50%;
}
.score span { position: relative; color: var(--ink); }
.meta-row {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}
.tag {
  border: 1px solid var(--line);
  border-radius: 999px;
  padding: 4px 9px;
  color: var(--muted);
  font-size: 12px;
  font-weight: 690;
  background: #fbfcfd;
}
.tag-confirm {
  background: #f0fdf4;
  border-color: #86efac;
  color: #166534;
}
.tag-disconfirm {
  background: #fff7ed;
  border-color: #fed7aa;
  color: #9a3412;
  font-style: italic;
}
.claim {
  font-size: 16px;
  margin: 0;
}
.verdict {
  border-left: 3px solid var(--score-colour, var(--green));
  padding-left: 12px;
  color: #2c3540;
  margin: 0;
}
.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: auto;
}
.detail {
  padding: 44px 0 64px;
}
.detail-article {
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--radius);
  padding: clamp(22px, 4vw, 42px);
  box-shadow: var(--shadow);
}
.detail h1 { font-size: clamp(38px, 5vw, 64px); max-width: 900px; }
.detail-grid {
  display: grid;
  grid-template-columns: 220px minmax(0, 1fr);
  gap: 26px;
  margin-top: 28px;
}
.fact-list {
  margin: 0;
  display: grid;
  gap: 12px;
}
.fact-list dt { color: var(--quiet); font-size: 12px; text-transform: uppercase; letter-spacing: .08em; }
.fact-list dd { margin: 2px 0 0; font-weight: 700; }
.prose {
  display: grid;
  gap: 18px;
  font-size: 18px;
}
.prose p { margin: 0; }
footer {
  border-top: 1px solid var(--line);
  padding: 26px 0 42px;
  color: var(--muted);
  font-size: 14px;
}
.toast {
  position: fixed;
  right: 16px;
  bottom: 16px;
  background: var(--ink);
  color: #fff;
  padding: 10px 14px;
  border-radius: var(--radius);
  opacity: 0;
  pointer-events: none;
  transition: opacity .18s ease, transform .18s ease;
  transform: translateY(8px);
}
.toast.is-visible { opacity: 1; transform: translateY(0); }
@media (max-width: 880px) {
  .hero,
  .section-grid,
  .feed,
  .detail-grid,
  .toolbar,
  .submit-form,
  .oracle-top,
  .oracle-columns {
    grid-template-columns: 1fr;
  }
  .topbar .shell { align-items: start; flex-direction: column; padding: 14px 0; }
  h1 { font-size: clamp(40px, 14vw, 62px); }
  .status-panel dl { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 520px) {
  .shell { width: min(100% - 22px, 1180px); }
  .card-top { display: grid; }
  .score { width: 52px; height: 52px; }
  .button, button, .filter { width: 100%; }
  .filters { display: grid; grid-template-columns: 1fr 1fr; }
  .status-panel dl { grid-template-columns: 1fr; }
}
"""

JS = r"""
const toast = document.querySelector('.toast');
function showToast(message) {
  if (!toast) return;
  toast.textContent = message;
  toast.classList.add('is-visible');
  setTimeout(() => toast.classList.remove('is-visible'), 1800);
}
document.addEventListener('click', async (event) => {
  const button = event.target.closest('[data-copy-target]');
  if (!button) return;
  const target = document.querySelector(button.dataset.copyTarget);
  if (!target) return;
  const text = target.value || target.textContent || '';
  try {
    await navigator.clipboard.writeText(text.trim());
    showToast(button.dataset.copyLabel || 'Copied');
  } catch {
    showToast('Copy failed');
  }
});
const search = document.querySelector('[data-search]');
if (search) {
  search.addEventListener('input', () => {
    const q = search.value.trim().toLowerCase();
    document.querySelectorAll('[data-capability-card]').forEach((card) => {
      const text = card.textContent.toLowerCase();
      card.hidden = q && !text.includes(q);
    });
  });
}
const submitForm = document.querySelector('[data-submit-article]');
const submitResult = document.querySelector('[data-submit-result]');
function esc(value) {
  const node = document.createElement('span');
  node.textContent = value == null ? '' : String(value);
  return node.innerHTML;
}
function renderList(values) {
  if (!values || !values.length) return '<li>None returned.</li>';
  return values.map((value) => `<li>${esc(value)}</li>`).join('');
}
function renderSubmission(verdict) {
  const suggested = verdict.suggested_entry || {};
  const shouldAdd = Boolean(verdict.should_add);
  submitResult.innerHTML = `
    <article class="oracle-result" aria-live="polite">
      <div class="oracle-top">
        <div class="oracle-status ${shouldAdd ? '' : 'reject'}">${shouldAdd ? 'Add to review' : 'Do not add yet'}</div>
        <div>
          <h3>${esc(verdict.source_title || 'Oracle verdict')}</h3>
          <p>${esc(verdict.oracle_verdict || '')}</p>
          <div class="meta-row">
            <span class="tag">${esc(verdict.category_label || verdict.category || 'capability')}</span>
            <span class="tag">confidence ${esc(verdict.confidence)}</span>
            <span class="tag">${esc(verdict.provider || 'rules')}</span>
          </div>
        </div>
      </div>
      <div class="oracle-columns">
        <div class="oracle-box">
          <h3>Why</h3>
          <ul>${renderList(verdict.reasons || [])}</ul>
        </div>
        <div class="oracle-box">
          <h3>Concerns</h3>
          <ul>${renderList(verdict.concerns || [])}</ul>
        </div>
      </div>
      <div class="oracle-entry">
        <h3>Suggested Appendix III entry</h3>
        <dl>
          <div><dt>Claim</dt><dd>${esc(suggested.claim || verdict.capability_claim || '')}</dd></div>
          <div><dt>Sector</dt><dd>${esc(suggested.sector || verdict.sector || '')}</dd></div>
          <div><dt>Capability</dt><dd>${esc(suggested.capability || verdict.capability || '')}</dd></div>
          <div><dt>Thesis implication</dt><dd>${esc(suggested.relevance || verdict.thesis_implication || '')}</dd></div>
          <div><dt>Source</dt><dd><a href="${esc(verdict.source_url || '#')}">${esc(verdict.publisher || verdict.source_url || 'source')}</a></dd></div>
        </dl>
      </div>
    </article>
  `;
}
if (submitForm && submitResult) {
  submitForm.addEventListener('submit', async (event) => {
    event.preventDefault();
    const button = submitForm.querySelector('button[type="submit"]');
    const url = submitForm.querySelector('[name="url"]').value.trim();
    const note = submitForm.querySelector('[name="note"]').value.trim();
    button.disabled = true;
    button.textContent = 'Asking Oracle...';
    submitResult.innerHTML = '<div class="oracle-result"><strong>Reading source and asking the Oracle...</strong><p>This usually takes a few seconds.</p></div>';
    try {
      const response = await fetch('/api/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url, note })
      });
      const data = await response.json();
      if (!response.ok || !data.ok) throw new Error(data.error || 'Submission failed.');
      localStorage.setItem('copecheckCapabilitiesLastSubmission', JSON.stringify(data.verdict));
      renderSubmission(data.verdict);
    } catch (error) {
      submitResult.innerHTML = `<div class="oracle-result"><strong>Oracle could not judge this URL</strong><p>${esc(error.message)}</p></div>`;
    } finally {
      button.disabled = false;
      button.textContent = 'Ask Oracle';
    }
  });
  const saved = localStorage.getItem('copecheckCapabilitiesLastSubmission');
  if (saved) {
    try { renderSubmission(JSON.parse(saved)); } catch { localStorage.removeItem('copecheckCapabilitiesLastSubmission'); }
  }
}
"""


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


def load_env_file(path: Path) -> None:
    if not path.exists():
        return
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))


def load_runtime_env() -> None:
    load_env_file(BASE / ".env")
    shared = os.getenv("COPECHECK_SHARED_ENV")
    if shared:
        load_env_file(Path(shared))


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


def clean_text(value: Any) -> str:
    text = html.unescape(str(value or ""))
    text = re.sub(r"<[^>]+>", " ", text)
    return re.sub(r"\s+", " ", text).strip()


def public_host_allowed(host: str) -> bool:
    cleaned = host.strip().strip("[]").lower()
    if not cleaned or cleaned in {"localhost", "0.0.0.0"} or cleaned.endswith(".local"):
        return False
    try:
        addresses = [ipaddress.ip_address(cleaned)]
    except ValueError:
        try:
            infos = socket.getaddrinfo(cleaned, None, type=socket.SOCK_STREAM)
            addresses = [ipaddress.ip_address(info[4][0]) for info in infos]
        except OSError:
            return False
    return bool(addresses) and all(address.is_global for address in addresses)


def normalise_public_url(raw_url: str) -> str:
    value = str(raw_url or "").strip()
    if not value:
        raise ValueError("Enter an article URL.")
    if not re.match(r"^https?://", value, flags=re.I):
        value = f"https://{value}"
    parsed = urlparse(value)
    if parsed.scheme.lower() not in {"http", "https"}:
        raise ValueError("Only http and https URLs can be submitted.")
    if not parsed.hostname:
        raise ValueError("That URL does not include a valid host.")
    try:
        host = parsed.hostname.encode("idna").decode("ascii")
    except UnicodeError as exc:
        raise ValueError("That host name is not valid.") from exc
    if not public_host_allowed(host):
        raise ValueError("That URL resolves to a private or non-public address.")
    netloc = host if parsed.port is None else f"{host}:{parsed.port}"
    return parsed._replace(scheme=parsed.scheme.lower(), netloc=netloc, path=parsed.path or "/", fragment="").geturl()


class PublicOnlyRedirectHandler(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        safe_url = normalise_public_url(urljoin(req.full_url, newurl))
        return super().redirect_request(req, fp, code, msg, headers, safe_url)


PUBLIC_URL_OPENER = build_opener(PublicOnlyRedirectHandler())


def request_url(url: str, timeout: float = FETCH_TIMEOUT) -> dict[str, Any]:
    req = Request(
        url,
        headers={
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36 CopeCheckCapabilities/1.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en-GB,en;q=0.9",
        },
    )
    started = time.perf_counter()
    try:
        with PUBLIC_URL_OPENER.open(req, timeout=timeout) as response:
            body = response.read(ARTICLE_LIMIT)
            return {
                "ok": 200 <= response.status < 400,
                "status": response.status,
                "url": response.url,
                "content_type": response.headers.get("content-type", ""),
                "body": body,
                "elapsed_ms": int((time.perf_counter() - started) * 1000),
                "error": "",
            }
    except HTTPError as exc:
        body = b""
        try:
            body = exc.read(60_000)
        except Exception:
            pass
        return {
            "ok": False,
            "status": exc.code,
            "url": url,
            "content_type": exc.headers.get("content-type", "") if exc.headers else "",
            "body": body,
            "elapsed_ms": int((time.perf_counter() - started) * 1000),
            "error": str(exc),
        }
    except (URLError, TimeoutError, OSError) as exc:
        return {
            "ok": False,
            "status": 0,
            "url": url,
            "content_type": "",
            "body": b"",
            "elapsed_ms": int((time.perf_counter() - started) * 1000),
            "error": str(exc),
        }


def reader_url_for(url: str) -> str:
    parsed = urlparse(url)
    target = parsed._replace(scheme="http").geturl()
    return f"https://r.jina.ai/{target}"


class ArticleParser(HTMLParser):
    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.title = ""
        self.metas: list[dict[str, str]] = []
        self.links: list[dict[str, str]] = []
        self.headings: list[str] = []
        self.paragraphs: list[str] = []
        self._capture_tag = ""
        self._capture_buffer: list[str] = []
        self._skip_depth = 0

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        tag = tag.lower()
        attr_map = {str(key).lower(): str(value or "") for key, value in attrs}
        if tag == "meta":
            self.metas.append(attr_map)
        elif tag == "link":
            self.links.append(attr_map)
        if tag in {"title", "h1", "h2", "p"}:
            self._capture_tag = tag
            self._capture_buffer = []
            return
        if tag in {"script", "style", "noscript", "template"}:
            self._skip_depth += 1

    def handle_endtag(self, tag: str) -> None:
        tag = tag.lower()
        if self._capture_tag == tag:
            text = clean_text(" ".join(self._capture_buffer))
            if text:
                if tag == "title" and not self.title:
                    self.title = text
                elif tag in {"h1", "h2"}:
                    self.headings.append(text)
                elif tag == "p":
                    self.paragraphs.append(text)
            self._capture_tag = ""
            self._capture_buffer = []
            return
        if tag in {"script", "style", "noscript", "template"} and self._skip_depth:
            self._skip_depth -= 1

    def handle_data(self, data: str) -> None:
        if self._capture_tag and not self._skip_depth:
            self._capture_buffer.append(data)


def decode_response(response: dict[str, Any]) -> str:
    body = response.get("body") or b""
    if not isinstance(body, bytes):
        return ""
    content_type = str(response.get("content_type") or "")
    charset_match = re.search(r"charset=([\w.-]+)", content_type, flags=re.I)
    charset = charset_match.group(1) if charset_match else "utf-8"
    try:
        return body.decode(charset, errors="ignore")
    except LookupError:
        return body.decode("utf-8", errors="ignore")


def first_meta(parser: ArticleParser, name: str = "", prop: str = "") -> str:
    target_name = name.lower()
    target_prop = prop.lower()
    for meta in parser.metas:
        if target_name and meta.get("name", "").lower() == target_name:
            return clean_text(meta.get("content", ""))
        if target_prop and meta.get("property", "").lower() == target_prop:
            return clean_text(meta.get("content", ""))
    return ""


def first_link(parser: ArticleParser, rel_name: str) -> str:
    needle = rel_name.lower()
    for link in parser.links:
        rel = link.get("rel", "").lower()
        if needle in {part.strip() for part in rel.split()}:
            return link.get("href", "").strip()
    return ""


def extract_article(raw_url: str) -> dict[str, Any]:
    url = normalise_public_url(raw_url)
    response = request_url(url)
    if not response["ok"]:
        fallback_response = request_url(reader_url_for(url), timeout=max(FETCH_TIMEOUT, 18))
        if fallback_response["ok"]:
            response = {**fallback_response, "reader_fallback": True, "original_status": response["status"]}
        else:
            raise ValueError(f"Could not fetch the article. HTTP {response['status'] or 'offline'}: {response['error']}")
    text = decode_response(response)
    parser = ArticleParser()
    try:
        parser.feed(text)
    except Exception:
        pass
    parsed = urlparse(url)
    reader_title_match = re.search(r"^Title:\s*(.+)$", text, flags=re.M)
    reader_source_match = re.search(r"^URL Source:\s*(.+)$", text, flags=re.M)
    reader_body_match = re.search(r"Markdown Content:\s*(.+)", text, flags=re.S)
    reader_body = reader_body_match.group(1) if reader_body_match else ""
    description = first_meta(parser, "description") or first_meta(parser, prop="og:description")
    title = (
        first_meta(parser, prop="og:title")
        or parser.title
        or (reader_title_match.group(1).strip() if reader_title_match else "")
        or (parser.headings[0] if parser.headings else parsed.hostname or "Submitted article")
    )
    publisher = first_meta(parser, prop="og:site_name") or (parsed.hostname or "Unknown publisher")
    published_at = (
        first_meta(parser, prop="article:published_time")
        or first_meta(parser, "date")
        or first_meta(parser, "publishdate")
    )
    canonical = first_link(parser, "canonical") or (url if response.get("reader_fallback") else "") or (reader_source_match.group(1).strip() if reader_source_match else "") or url
    body_text = clean_text(" ".join(parser.paragraphs))
    if response.get("reader_fallback"):
        body_text = clean_text(re.sub(r"[*_`#>\[\]\(\)]", " ", reader_body or text))
    if len(body_text) < 300:
        body_text = clean_text(re.sub(r"<[^>]+>", " ", text))
    excerpt = body_text[:2600]
    return {
        "url": url,
        "final_url": url if response.get("reader_fallback") else (canonical or url),
        "canonical": canonical,
        "status": response.get("original_status") or response["status"],
        "elapsed_ms": response["elapsed_ms"],
        "content_type": response.get("content_type") or "",
        "reader_fallback": bool(response.get("reader_fallback")),
        "title": title[:240],
        "description": description[:500],
        "publisher": publisher[:160],
        "published_at": published_at[:80],
        "host": parsed.hostname or "",
        "excerpt": excerpt,
        "word_count": len(re.findall(r"\b[\w'-]+\b", body_text)),
    }


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


def load_appendix() -> dict[str, Any]:
    try:
        data = json.loads(APPENDIX_PATH.read_text(encoding="utf-8"))
        if isinstance(data, dict):
            return data
    except (OSError, json.JSONDecodeError):
        pass
    return {
        "status": "missing_register",
        "updated_at": utc_now(),
        "summary": "The capabilities register is waiting for Appendix III data.",
        "items": [],
        "signals": [],
        "watchlist": [],
    }


def category_for(item: dict[str, Any]) -> str:
    category = str(item.get("category") or "deployment").lower()
    return category if category in CATEGORY_META else "deployment"


def score_for(item: dict[str, Any]) -> int:
    for key in ("cope_score", "pressure_score", "score"):
        try:
            return max(0, min(100, int(round(float(item.get(key))))))
        except (TypeError, ValueError):
            continue
    try:
        return max(0, min(100, int(round(float(item.get("confidence")) * 100))))
    except (TypeError, ValueError):
        return 50


def colour_for(category: str) -> str:
    return CATEGORY_META.get(category, CATEGORY_META["deployment"])["colour"]


def normalize_item(item: dict[str, Any], index: int = 0) -> dict[str, Any]:
    category = category_for(item)
    title = str(item.get("title") or item.get("publisher") or item.get("url") or "Capability claim")
    slug = str(item.get("slug") or slugify(title, f"capability-{index + 1}"))
    return {
        **item,
        "slug": slug,
        "title": title,
        "category": category,
        "category_label": CATEGORY_META[category]["label"],
        "category_short": CATEGORY_META[category]["short"],
        "category_section": CATEGORY_META[category]["section"],
        "colour": colour_for(category),
        "score": score_for(item),
        "observed_at": item.get("observed_at") or item.get("source_date") or item.get("published") or "",
        "publisher": item.get("publisher") or "Unknown source",
        "claim": item.get("claim") or item.get("note") or "",
        "oracle_verdict": item.get("oracle_verdict") or item.get("note") or item.get("claim") or "",
        "capability": item.get("capability") or CATEGORY_META[category]["short"],
        "sector": item.get("sector") or "General",
        "relevance": item.get("relevance") or CATEGORY_META[category]["section"],
        "confidence": item.get("confidence", "n/a"),
    }


def load_items() -> tuple[dict[str, Any], list[dict[str, Any]]]:
    appendix = load_appendix()
    raw_items = appendix.get("items") if isinstance(appendix.get("items"), list) else []
    items = [normalize_item(item, i) for i, item in enumerate(raw_items) if isinstance(item, dict)]
    items.sort(key=lambda item: str(item.get("observed_at") or ""), reverse=True)
    return appendix, items


def classify_category(text: str) -> str:
    lower = text.lower()
    if any(term in lower for term in ["layoff", "laid off", "redundanc", "job cuts", "workforce reduction"]):
        return "layoff"
    if any(term in lower for term in ["deployed", "deployment", "rollout", "case study", "customer", "workflow", "production"]):
        return "deployment"
    if any(term in lower for term in ["benchmark", "evaluation", "evals", "sota", "frontier", "leaderboard"]):
        return "benchmark"
    if any(term in lower for term in ["pricing", "api", "model release", "launches", "announces", "vendor"]):
        return "vendor"
    if any(term in lower for term in ["hiring", "wages", "employment", "labour", "labor", "jobs", "salary"]):
        return "labour_market"
    return "deployment"


def infer_sector(text: str) -> str:
    lower = text.lower()
    sectors = [
        ("Financial services", ["bank", "finance", "insurance", "trading", "risk", "loan", "payment"]),
        ("Software engineering", ["developer", "coding", "software", "github", "programming", "engineer"]),
        ("Customer operations", ["call centre", "contact center", "support", "customer service", "agent assist"]),
        ("Legal and compliance", ["legal", "law firm", "contract", "compliance", "regulatory"]),
        ("Healthcare", ["health", "hospital", "clinical", "patient", "medical"]),
        ("Education", ["school", "student", "teacher", "university", "learning"]),
        ("Media and marketing", ["marketing", "advertising", "content", "copywriting", "media"]),
        ("Public sector", ["government", "public sector", "civil service", "council"]),
        ("Manufacturing and logistics", ["factory", "manufacturing", "warehouse", "logistics", "supply chain"]),
    ]
    for label, terms in sectors:
        if any(term in lower for term in terms):
            return label
    return "General"


def infer_capability(text: str, category: str) -> str:
    lower = text.lower()
    capability_terms = [
        ("Autonomous workflow execution", ["agent", "autonomous", "end-to-end", "workflow"]),
        ("Code generation and software maintenance", ["coding", "code generation", "software", "developer"]),
        ("Document analysis and knowledge work", ["document", "contract", "summar", "analysis", "research"]),
        ("Customer support automation", ["customer", "support", "call centre", "contact center"]),
        ("Decision support and risk analysis", ["risk", "forecast", "decision", "validation", "compliance"]),
        ("Multimodal content generation", ["image", "video", "voice", "multimodal", "creative"]),
        ("Labour-market displacement signal", ["layoff", "job cuts", "hiring", "workforce"]),
    ]
    for label, terms in capability_terms:
        if any(term in lower for term in terms):
            return label
    return CATEGORY_META.get(category, CATEGORY_META["deployment"])["short"].title()


def rule_oracle_verdict(article: dict[str, Any], note: str = "") -> dict[str, Any]:
    text = " ".join(
        [
            article.get("title", ""),
            article.get("description", ""),
            article.get("excerpt", ""),
            note,
        ]
    )
    lower = text.lower()
    ai_terms = ["ai", "artificial intelligence", "llm", "language model", "agent", "automation", "machine learning", "copilot"]
    evidence_terms = [
        "minutes",
        "hours",
        "%",
        "percent",
        "benchmark",
        "deployed",
        "rollout",
        "case study",
        "customer",
        "workflow",
        "production",
        "reduced",
        "automated",
        "replaced",
        "saves",
    ]
    relevance_hits = sum(1 for term in ai_terms if term in lower)
    evidence_hits = sum(1 for term in evidence_terms if term in lower)
    category = classify_category(text)
    sector = infer_sector(text)
    capability = infer_capability(text, category)
    enough_article = article.get("word_count", 0) >= 120 or bool(article.get("description"))
    should_add = relevance_hits > 0 and evidence_hits > 0 and enough_article
    confidence = min(0.92, 0.36 + relevance_hits * 0.12 + evidence_hits * 0.07 + (0.12 if enough_article else 0))
    concerns: list[str] = []
    if relevance_hits == 0:
        concerns.append("The source does not clearly describe an AI capability or automation claim.")
    if evidence_hits == 0:
        concerns.append("The source lacks a concrete deployment, benchmark, metric or labour-market signal.")
    if not enough_article:
        concerns.append("The extracted source text is thin, so the claim may need manual review.")
    reasons = []
    if relevance_hits:
        reasons.append("It contains AI or automation language relevant to the capabilities register.")
    if evidence_hits:
        reasons.append("It contains at least one concrete signal such as a deployment, metric, benchmark or workflow change.")
    if category in {"deployment", "benchmark", "layoff", "labour_market"}:
        reasons.append(f"It maps cleanly to the {CATEGORY_META[category]['label']} lane.")
    if not reasons:
        reasons.append("The source can still be reviewed manually, but the automatic signal is weak.")
    claim = article.get("description") or article.get("title") or "Submitted source describes a possible AI capability claim."
    thesis_implication = (
        "This belongs in Appendix III if the source shows a measurable expansion of what AI systems can do in production, benchmarks, or labour-market substitution."
        if should_add
        else "This should stay out of the live register until there is a clearer measurable capability, deployment, benchmark, or labour-market implication."
    )
    oracle_verdict = (
        f"Add this to the capabilities review queue. The source appears to describe {capability.lower()} in {sector.lower()}, which is evidence for the thesis if the claim is attributable and measurable."
        if should_add
        else "Do not add this directly to the live capabilities register yet. The source does not currently provide enough clear capability evidence for Appendix III without manual interpretation."
    )
    score = int(round(confidence * 100 if should_add else min(58, confidence * 100)))
    return {
        "should_add": should_add,
        "status": "review" if should_add else "not_recommended",
        "confidence": round(confidence, 2),
        "category": category,
        "category_label": CATEGORY_META[category]["label"],
        "sector": sector,
        "capability": capability,
        "capability_claim": claim,
        "oracle_verdict": oracle_verdict,
        "thesis_implication": thesis_implication,
        "reasons": reasons,
        "concerns": concerns,
        "provider": "rules",
        "suggested_entry": {
            "title": article.get("title"),
            "url": article.get("final_url") or article.get("url"),
            "publisher": article.get("publisher"),
            "source_date": article.get("published_at"),
            "category": category,
            "sector": sector,
            "capability": capability,
            "claim": claim,
            "cope_score": score,
            "confidence": round(confidence, 2),
            "oracle_verdict": oracle_verdict,
            "relevance": thesis_implication,
            "status": "review",
        },
    }


def minimax_oracle_verdict(article: dict[str, Any], note: str = "") -> tuple[dict[str, Any], str]:
    load_runtime_env()
[redacted secret-like line]
    fallback = rule_oracle_verdict(article, note)
    if not key:
        return fallback, "rules"
    prompt = {
        "task": "Decide whether this source should be added to the CopeCheck capabilities register, which supports The Discontinuity Thesis Appendix III.",
        "rules": [
            "Recommend add only when the source has a clear AI capability, deployment, benchmark, workflow, labour-market, layoff, pricing, or vendor-threshold signal.",
            "Do not recommend adding generic AI opinion, vague marketing, weak attribution, or unrelated tech news.",
            "Return strict JSON only.",
        ],
        "article": {
            "title": article.get("title"),
            "publisher": article.get("publisher"),
            "url": article.get("final_url") or article.get("url"),
            "description": article.get("description"),
            "excerpt": article.get("excerpt", "")[:1800],
            "word_count": article.get("word_count"),
        },
        "user_note": note[:600],
        "schema": {
            "should_add": True,
            "confidence": 0.0,
            "category": "benchmark|deployment|vendor|labour_market|layoff",
            "sector": "short sector",
            "capability": "short capability",
            "capability_claim": "one sentence",
            "oracle_verdict": "two concise sentences",
            "thesis_implication": "one concise sentence",
            "reasons": ["2-4 reasons"],
            "concerns": ["0-3 concerns"],
        },
    }
    payload = {
        "model": os.getenv("MINIMAX_MODEL", "MiniMax-M2.7"),
        "messages": [
            {"role": "system", "content": "You are the CopeCheck Oracle for AI capability evidence. Return JSON only."},
            {"role": "user", "content": json.dumps(prompt, ensure_ascii=False)},
        ],
        "temperature": 0.1,
[redacted secret-like line]
        "stream": False,
        "reasoning_split": True,
    }
    endpoint = os.getenv("MINIMAX_CHAT_ENDPOINT", "https://api.minimax.io/v1/text/chatcompletion_v2")
    try:
        req = Request(
            endpoint,
            data=json.dumps(payload).encode("utf-8"),
[redacted secret-like line]
            method="POST",
        )
        with urlopen(req, timeout=MINIMAX_TIMEOUT) as response:
            data = json.loads(response.read(400_000).decode("utf-8", errors="ignore"))
        content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
        if not content:
            content = data.get("reply") or data.get("text") or data.get("output_text") or ""
        if isinstance(content, list):
            content = "\n".join(str(item.get("text", item)) for item in content)
        clean = re.sub(r"^```(?:json)?", "", str(content).strip(), flags=re.I).removesuffix("```").strip()
        if "{" in clean and "}" in clean:
            clean = clean[clean.find("{") : clean.rfind("}") + 1]
        parsed = json.loads(clean)
        if isinstance(parsed, dict):
            category = str(parsed.get("category") or fallback["category"]).lower()
            if category not in CATEGORY_META:
                category = fallback["category"]
            should_add = bool(parsed.get("should_add"))
            confidence = max(0.0, min(1.0, float(parsed.get("confidence") or fallback["confidence"])))
            score = int(round(confidence * 100 if should_add else min(58, confidence * 100)))
            merged = {
                **fallback,
                **parsed,
                "should_add": should_add,
                "status": "review" if should_add else "not_recommended",
                "confidence": round(confidence, 2),
                "category": category,
                "category_label": CATEGORY_META[category]["label"],
                "provider": f"MiniMax {payload['model']}",
            }
            merged["suggested_entry"] = {
                **fallback["suggested_entry"],
                "category": category,
                "sector": merged.get("sector") or fallback["sector"],
                "capability": merged.get("capability") or fallback["capability"],
                "claim": merged.get("capability_claim") or fallback["capability_claim"],
                "cope_score": score,
                "confidence": round(confidence, 2),
                "oracle_verdict": merged.get("oracle_verdict") or fallback["oracle_verdict"],
                "relevance": merged.get("thesis_implication") or fallback["thesis_implication"],
                "status": "review",
            }
            return merged, merged["provider"]
    except Exception as exc:
        fallback["diagnostic"] = f"MiniMax fallback used: {exc}"
    return fallback, "rules"


def rate_limit_ok(client_id: str) -> tuple[bool, int]:
    now = time.time()
    with SUBMIT_LOCK:
        recent = [stamp for stamp in SUBMIT_RATE_STORE.get(client_id, []) if stamp > now - SUBMIT_RATE_WINDOW]
        allowed = len(recent) < SUBMIT_RATE_LIMIT
        if allowed:
            recent.append(now)
        SUBMIT_RATE_STORE[client_id] = recent
    return allowed, max(0, SUBMIT_RATE_LIMIT - len(SUBMIT_RATE_STORE.get(client_id, [])))


def save_submission(article: dict[str, Any], verdict: dict[str, Any], client_id: str, note: str = "") -> str:
    SUBMISSIONS_FILE.parent.mkdir(parents=True, exist_ok=True)
    submit_id = hashlib.sha1(f"{article.get('final_url')}|{time.time()}".encode("utf-8")).hexdigest()[:12]
    record = {
        "id": submit_id,
        "submitted_at": utc_now(),
        "client_id_hash": hashlib.sha1(client_id.encode("utf-8")).hexdigest()[:12],
        "note": note[:1000],
        "article": article,
        "verdict": verdict,
    }
    with SUBMIT_LOCK:
        with SUBMISSIONS_FILE.open("a", encoding="utf-8") as handle:
            handle.write(json.dumps(record, ensure_ascii=False) + "\n")
    return submit_id


def judge_submission(raw_url: str, note: str = "", client_id: str = "") -> dict[str, Any]:
    article = extract_article(raw_url)
    verdict, provider = minimax_oracle_verdict(article, note)
    verdict.update(
        {
            "provider": provider,
            "source_title": article.get("title"),
            "source_url": article.get("final_url") or article.get("url"),
            "publisher": article.get("publisher"),
            "published_at": article.get("published_at"),
            "fetched_at": utc_now(),
            "article_status": article.get("status"),
            "article_word_count": article.get("word_count"),
        }
    )
    verdict["submission_id"] = save_submission(article, verdict, client_id or "unknown", note)
    return verdict


def category_counts(items: list[dict[str, Any]]) -> dict[str, int]:
    counts = {key: 0 for key in CATEGORY_META}
    for item in items:
        counts[item["category"]] = counts.get(item["category"], 0) + 1
    return counts


def machine_brief(items: list[dict[str, Any]], appendix: dict[str, Any]) -> str:
    lines = [
        "# CopeCheck Capabilities Register",
        "",
        f"Updated: {appendix.get('updated_at') or utc_now()}",
        f"Status: {appendix.get('status') or 'unknown'}",
        "",
        "Question to ask a model: What do these capability claims mean for The Discontinuity Thesis?",
        "",
        "Interpretation rule: treat each entry as evidence about capability, deployment, workflow recomposition, labour-market exposure, or institutional framing. Do not treat vendor optimism as neutral; separate the measurable capability claim from the comfort language around it.",
        "",
    ]
    for item in items:
        lines.extend(
            [
                f"## {item['title']}",
                f"Source: {item.get('url') or ''}",
                f"Publisher: {item['publisher']}",
                f"Category: {item['category_label']}",
                f"Sector: {item['sector']}",
                f"Capability: {item['capability']}",
                f"Score: {item['score']}/100",
                f"Claim: {item['claim']}",
                *([f"Evidence status: {item['evidence_status']}"] if item.get("evidence_status") else []),
                *([f"Availability: {item['availability']}"] if item.get("availability") else []),
                f"Oracle verdict: {item['oracle_verdict']}",
                f"Thesis relevance: {item['relevance']}",
                "",
            ]
        )
    return "\n".join(lines).strip() + "\n"


def page(title: str, description: str, body: str, canonical_path: str = "/") -> bytes:
    canonical = PUBLIC_BASE + canonical_path
    json_ld = {
        "@context": "https://schema.org",
        "@type": "Dataset",
        "@id": f"{PUBLIC_BASE}/#capabilities-register",
        "name": "CopeCheck Capabilities Register",
        "description": description,
        "url": canonical,
        "creator": ORGANIZATION_SCHEMA,
        "publisher": ORGANIZATION_SCHEMA,
        "license": PUBLIC_BASE + DATASET_LICENSE_PATH,
        "isAccessibleForFree": True,
        "isPartOf": f"{THESIS_BASE}/#appendix-iii-live",
        "includedInDataCatalog": {
            "@type": "DataCatalog",
            "name": "CopeCheck Network",
            "url": "https://www.copecheck.com/",
        },
        "distribution": [
            {
                "@type": "DataDownload",
                "encodingFormat": "application/json",
                "contentUrl": f"{PUBLIC_BASE}/feed.json",
            },
            {
                "@type": "DataDownload",
                "encodingFormat": "application/json",
                "contentUrl": f"{PUBLIC_BASE}/appendix-live.json",
            },
        ],
        "about": ["AI capability", "workflow automation", "labour market exposure", "Discontinuity Thesis"],
    }
    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="website">
  <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>
  <script type="application/ld+json">{json.dumps(json_ld, ensure_ascii=False)}</script>
</head>
<body>
  <header class="topbar">
    <div class="shell">
      <a class="brand" href="/" aria-label="CopeCheck Capabilities home">
        <span class="brand-mark">CC</span>
        <span>Capabilities</span>
      </a>
      <nav aria-label="Network">
        <a href="https://www.copecheck.com">CopeCheck</a>
        <a href="{escape(THESIS_BASE)}">Thesis</a>
        <a href="/feed.json">feed.json</a>
        <a href="/llms.txt">llms.txt</a>
      </nav>
    </div>
  </header>
  {body}
  <footer>
    <div class="shell">
      CopeCheck Capabilities is a curated evidence layer for The Discontinuity Thesis. It is updated in reviewed batches and exposes the Appendix III register as HTML, JSON, and agent-readable text.
    </div>
  </footer>
  <div class="toast" role="status" aria-live="polite"></div>
  <script>{JS}</script>
  <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_license() -> bytes:
    canonical = PUBLIC_BASE + DATASET_LICENSE_PATH
    description = (
        "Reuse terms for the CopeCheck Capabilities Register dataset and its "
        "machine-readable feeds."
    )
    json_ld = {
        "@context": "https://schema.org",
        "@type": "WebPage",
        "name": "CopeCheck Capabilities Register license",
        "description": description,
        "url": canonical,
        "publisher": ORGANIZATION_SCHEMA,
    }
    html_doc = f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>License | CopeCheck Capabilities</title>
  <meta name="description" content="{escape(description)}">
  <meta name="robots" content="index,follow">
  <link rel="canonical" href="{escape(canonical)}">
  <style>{CSS}</style>
  <script type="application/ld+json">{json.dumps(json_ld, ensure_ascii=False)}</script>
</head>
<body>
  <header class="topbar">
    <div class="shell">
      <a class="brand" href="/" aria-label="CopeCheck Capabilities home">
        <span class="brand-mark">CC</span>
        <span>Capabilities</span>
      </a>
      <nav aria-label="Network">
        <a href="https://www.copecheck.com">CopeCheck</a>
        <a href="{escape(THESIS_BASE)}">Thesis</a>
        <a href="/feed.json">feed.json</a>
      </nav>
    </div>
  </header>
  <main class="shell detail">
    <article class="detail-article">
      <p class="muted"><a href="/">Capabilities</a> / License</p>
      <h1>CopeCheck Capabilities Register license</h1>
      <div class="prose">
        <p>The CopeCheck-authored summaries, scoring fields and metadata in the Capabilities Register may be cited with attribution and a link back to the source page.</p>
        <p>The register links to third-party source material. Those underlying source pages remain governed by their original publishers' terms and are not relicensed by CopeCheck.</p>
        <p>For bulk reuse, commercial redistribution, or republication of substantial portions of the dataset, contact CopeCheck first.</p>
      </div>
    </article>
  </main>
  <script>{JS}</script>
</body>
</html>"""
    return html_doc.encode("utf-8")


def render_map(items: list[dict[str, Any]]) -> str:
    counts = category_counts(items)
    lanes = [key for key in CATEGORY_META if counts.get(key)]
    if not lanes:
        lanes = ["deployment", "labour_market"]
    lane_height = 64
    height = 40 + lane_height * len(lanes)
    width = 720
    rows = []
    for index, category in enumerate(lanes):
        y = 32 + index * lane_height
        meta = CATEGORY_META[category]
        category_items = [item for item in items if item["category"] == category]
        avg_score = int(round(sum(item["score"] for item in category_items) / max(1, len(category_items))))
        x = 220 + int((width - 270) * (avg_score / 100))
        rows.append(
            f"""
            <g>
              <text x="22" y="{y + 5}" fill="#16181d" font-size="16" font-weight="700">{escape(meta["label"])}</text>
              <text x="22" y="{y + 25}" fill="#5d6673" font-size="12">{escape(meta["section"])}</text>
              <line x1="220" y1="{y}" x2="{width - 46}" y2="{y}" stroke="#d9dee5" stroke-width="8" stroke-linecap="round"/>
              <line x1="220" y1="{y}" x2="{x}" y2="{y}" stroke="{meta["colour"]}" stroke-width="8" stroke-linecap="round"/>
              <circle cx="{x}" cy="{y}" r="13" fill="#fff" stroke="{meta["colour"]}" stroke-width="5"/>
              <text x="{width - 28}" y="{y + 5}" text-anchor="end" fill="#16181d" font-size="15" font-weight="800">{avg_score}</text>
              <text x="{width - 28}" y="{y + 24}" text-anchor="end" fill="#7b8491" font-size="12">{counts[category]} items</text>
            </g>
            """
        )
    return f"""<svg class="cap-map" viewBox="0 0 {width} {height}" role="img" aria-label="Capability categories and average pressure scores">
      <rect width="{width}" height="{height}" fill="#fbfcfd"/>
      {''.join(rows)}
    </svg>"""


def render_filters(active: str | None) -> str:
    links = [("all", "All")]
    links.extend((key, meta["label"]) for key, meta in CATEGORY_META.items())
    return "".join(
        f'<a class="filter" href="{"/" if key == "all" else "/?category=" + key}" aria-current="{str((not active and key == "all") or active == key).lower()}">{escape(label)}</a>'
        for key, label in links
    )


def render_card(item: dict[str, Any]) -> str:
    brief = "\n".join(
        [
            f"{item['title']}",
            f"Source: {item.get('url') or ''}",
            f"Claim: {item['claim']}",
            *([f"Availability: {item['availability']}"] if item.get("availability") else []),
            f"Oracle verdict: {item['oracle_verdict']}",
            f"Thesis relevance: {item['relevance']}",
        ]
    )
    return f"""
    <article class="card" data-capability-card data-category="{escape(item['category'])}" style="--score:{item['score']};--score-colour:{escape(item['colour'])}">
      <div class="card-top">
        <h2><a href="/c/{escape(item['slug'])}">{escape(item['title'])}</a></h2>
        <div class="score" aria-label="Oracle pressure score {item['score']} out of 100"><span>{item['score']}</span></div>
      </div>
      <div class="meta-row">
        <span class="tag">{escape(item['category_label'])}</span>
        <span class="tag">{escape(item['sector'])}</span>
        <span class="tag">{escape(item['capability'])}</span>
        <span class="tag {'tag-disconfirm' if item['category'] == 'disconfirming' else 'tag-confirm'}">[{'DISCONFIRMING — ATTRIBUTION' if item['category'] == 'disconfirming' else 'CONFIRMING'}]</span>
      </div>
      <p class="claim">{escape(item['claim'])}</p>
      {render_evidence_context(item)}
      <p class="verdict">{escape(item['oracle_verdict'])}</p>
      <div class="card-actions">
        <a class="button" href="/c/{escape(item['slug'])}">Read verdict</a>
        <a class="button" href="{escape(item.get('url') or '#')}">Source</a>
        <button type="button" data-copy-target="#brief-{escape(item['slug'])}" data-copy-label="Capability brief copied">Copy brief</button>
      </div>
      <template id="brief-{escape(item['slug'])}">{escape(brief)}</template>
    </article>
    """


def render_evidence_context(item: dict[str, Any]) -> str:
    parts = []
    if item.get("evidence_status"):
        label = str(item["evidence_status"]).replace("_", " ")
        parts.append(f'<p class="muted">Evidence: {escape(label)} · Reviewed {escape(item.get("reviewed_at") or "unknown")}</p>')
    if item.get("availability"):
        parts.append(f'<p class="muted"><strong>Access:</strong> {escape(item["availability"])}</p>')
    return "\n".join(parts)



def render_home(query: dict[str, list[str]]) -> bytes:
    appendix, items = load_items()
    active = (query.get("category") or [""])[0].strip().lower() or None
    visible = [item for item in items if not active or item["category"] == active]
    counts = category_counts(items)
    brief = machine_brief(items, appendix)
    description = "A curated CopeCheck evidence register mapping sourced AI capability claims to their implications for The Discontinuity Thesis."
    latest = max((str(item.get("observed_at") or "") for item in items), default="none")
    cards = "\n".join(render_card(item) for item in visible) or "<p>No capability items match this filter yet.</p>"
    body = f"""
    <main>
      <section class="shell hero">
        <div>
          <h1>What can AI demonstrably do now?</h1>
          <p class="lead">A curated capabilities register for press releases, case studies, research papers, benchmarks, and labour-market signals. It is updated in reviewed batches rather than continuously; each item keeps the claim, source, and Oracle verdict.</p>
          <div class="hero-actions">
            <a class="button primary" href="#feed">Read latest capabilities</a>
            <a class="button" href="#submit">Submit article</a>
            <button type="button" data-copy-target="#machine-brief" data-copy-label="Machine brief copied">Copy machine brief</button>
          </div>
        </div>
        <aside class="status-panel" aria-label="Register status">
          <dl>
            <div><dt>items</dt><dd>{len(items)}</dd></div>
            <div><dt>newest source</dt><dd>{escape(latest)}</dd></div>
            <div><dt>deployments</dt><dd>{counts.get("deployment", 0)}</dd></div>
            <div><dt>labour signals</dt><dd>{counts.get("labour_market", 0) + counts.get("layoff", 0)}</dd></div>
          </dl>
        </aside>
      </section>
      <section class="shell submit-panel" id="submit">
        <h2>Submit a capability article</h2>
        <p>Paste a source URL and the Oracle will decide whether it belongs in the capabilities register. Recommended items are saved to the Appendix III review queue rather than published blindly.</p>
        <form class="submit-form" data-submit-article>
          <label>
            <span>Article URL</span>
            <input name="url" type="url" placeholder="https://example.com/ai-case-study" required>
          </label>
          <label>
            <span>Optional note</span>
            <textarea name="note" placeholder="Why this might matter"></textarea>
          </label>
          <button type="submit">Ask Oracle</button>
        </form>
        <div class="submit-result" data-submit-result></div>
      </section>
      <section class="shell section-grid" aria-label="Capability map and machine brief">
        <div class="map-panel">
          <div class="panel-head">
            <h2>Capability map</h2>
            <span class="muted">average pressure score</span>
          </div>
          {render_map(items)}
        </div>
        <div class="machine-panel">
          <div class="panel-head">
            <h2>Machine brief</h2>
            <button type="button" data-copy-target="#machine-brief" data-copy-label="Machine brief copied">Copy</button>
          </div>
          <pre id="machine-brief">{escape(brief)}</pre>
        </div>
      </section>
      <section class="shell toolbar" id="feed" aria-label="Feed controls">
        <input class="search" data-search type="search" placeholder="Search sources, sectors, claims, verdicts" aria-label="Search capabilities">
        <div class="filters" aria-label="Category filters">{render_filters(active)}</div>
      </section>
      <section class="shell feed" aria-label="Capability feed">
        {cards}
      </section>
    </main>
    """
    return page("Capabilities | CopeCheck", description, body, "/")


def render_detail(slug: str) -> bytes:
    appendix, items = load_items()
    item = next((entry for entry in items if entry["slug"] == slug), None)
    if not item:
        return page(
            "Capability not found | CopeCheck",
            "The requested capability item was not found.",
            '<main class="shell detail"><article class="detail-article"><h1>Capability not found</h1><p><a href="/">Return to the capabilities register</a></p></article></main>',
            "/",
        )
    brief = machine_brief([item], appendix)
    body = f"""
    <main class="shell detail">
      <article class="detail-article" style="--score-colour:{escape(item['colour'])}">
        <p class="muted"><a href="/">Capabilities</a> / {escape(item['category_label'])}</p>
        <h1>{escape(item['title'])}</h1>
        <div class="meta-row">
          <span class="tag">{escape(item['publisher'])}</span>
          <span class="tag">{escape(item['sector'])}</span>
          <span class="tag">score {item['score']}/100</span>
          <span class="tag">confidence {escape(item['confidence'])}</span>
        </div>
        <div class="detail-grid">
          <dl class="fact-list">
            <div><dt>Category</dt><dd>{escape(item['category_label'])}</dd></div>
            <div><dt>Capability</dt><dd>{escape(item['capability'])}</dd></div>
            <div><dt>Observed</dt><dd>{escape(item['observed_at'] or 'unknown')}</dd></div>
            <div><dt>Thesis section</dt><dd>{escape(item['relevance'])}</dd></div>
          </dl>
          <div class="prose">
            <h2>Claim</h2>
            <p>{escape(item['claim'])}</p>
            {render_evidence_context(item)}
            <h2>Oracle verdict</h2>
            <p class="verdict">{escape(item['oracle_verdict'])}</p>
            <h2>Why it matters</h2>
            <p>{escape(item.get('note') or item['relevance'])}</p>
            <div class="card-actions">
              <a class="button primary" href="{escape(item.get('url') or '#')}">Open source</a>
              <a class="button" href="{escape(THESIS_BASE)}/#appendix-iii-live">Read thesis appendix</a>
              <button type="button" data-copy-target="#single-brief" data-copy-label="Capability brief copied">Copy brief</button>
            </div>
            <pre id="single-brief" hidden>{escape(brief)}</pre>
          </div>
        </div>
      </article>
    </main>
    """
    return page(f"{item['title']} | Capabilities | CopeCheck", item["claim"], body, f"/c/{item['slug']}")


def render_feed() -> bytes:
    appendix, items = load_items()
    payload = {
        "status": appendix.get("status"),
        "updated_at": appendix.get("updated_at"),
        "source_register": THESIS_BASE + "/appendix-live.json",
        "public_base": PUBLIC_BASE,
        "count": len(items),
        "ai_disclosure": "Oracle verdicts and summaries are AI-generated and may contain errors; verify against each linked source.",
        "items": [dict(item, ai_disclosure="AI-generated analysis; verify against the linked source.") for item in items],
    }
    return json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")


def render_llms() -> bytes:
    appendix, items = load_items()
    text = machine_brief(items, appendix)
    text += "\nRoutes:\n"
    text += f"- HTML: {PUBLIC_BASE}/\n"
    text += f"- JSON feed: {PUBLIC_BASE}/feed.json\n"
    text += f"- Thesis: {THESIS_BASE}/\n"
    return text.encode("utf-8")


def render_sitemap() -> bytes:
    _, items = load_items()
    today = datetime.now(timezone.utc).date().isoformat()
    urls = ["/", "/feed.json", "/llms.txt", DATASET_LICENSE_PATH]
    urls.extend(f"/c/{item['slug']}" for item in items)
    body = "\n".join(
        f"  <url><loc>{escape(PUBLIC_BASE + path)}</loc><lastmod>{today}</lastmod></url>"
        for path in urls
    )
    return f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{body}
</urlset>
""".encode("utf-8")


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 Disclosure | CopeCheck Capabilities</title></head><body><main><article style="max-width:52rem;margin:3rem auto;line-height:1.65"><h1>How CopeCheck Capabilities uses AI</h1><p><strong>Oracle verdicts, implications and some capability summaries are generated by artificial intelligence.</strong> Source titles, URLs and quoted claims remain attributable to their publishers.</p><h2>Models and method</h2><p>The network uses OpenAI Codex with gpt-5.6-luna at maximum reasoning for the main scoring path and MiniMax models, including M3 or M2.7, in specialist and fallback pipelines. Entries separate the attributable capability claim from the Oracle interpretation and apply the Discontinuity Thesis tests.</p><h2>Limits and corrections</h2><p>Generated outputs may omit context or overstate an implication. Verify against the linked source. Send corrections to <a href="mailto:btl101@gmail.com?subject=CopeCheck%20Capabilities%20correction">btl101@gmail.com</a>.</p></article></main><footer></footer></body></html>'''


def inject_ai_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(245,158,11,.45);border-radius:.65rem;background:rgba(245,158,11,.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 0;font-size:.85rem}</style><aside class="cc-ai-label" role="note"><strong>AI-generated analysis</strong> Oracle verdicts and implications may be generated by AI. <a href="/ai-disclosure">How CopeCheck uses AI</a>.</aside>'''
    footer = '''<p class="cc-ai-footer"><strong>AI disclosure:</strong> Analytical summaries and verdicts may be AI-generated and may contain errors. <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_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_ai_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=180, stale-while-revalidate=900")
        self.send_security_headers()
        self.end_headers()
        if not head_only:
            self.wfile.write(body)

    def send_json(self, status: int, payload: dict[str, Any], head_only: bool = False) -> None:
        body = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.send_security_headers()
        self.end_headers()
        if not head_only:
            self.wfile.write(body)

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

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

    def do_POST(self) -> None:
        parsed = urlparse(self.path)
        path = parsed.path.rstrip("/") or "/"
        if path == "/api/submit":
            return self.handle_submit(False)
        return self.send_json(405, {"ok": False, "error": "Method not allowed."})

    def client_identifier(self) -> str:
        return (
            self.headers.get("CF-Connecting-IP")
            or self.headers.get("X-Forwarded-For", "").split(",", 1)[0].strip()
            or self.client_address[0]
        )

    def read_payload(self) -> dict[str, str]:
        content_length = int(self.headers.get("Content-Length") or "0")
        if content_length > SUBMIT_BODY_LIMIT:
            raise ValueError("Request body is too large.")
        raw = self.rfile.read(content_length) if content_length else b"{}"
        content_type = self.headers.get("Content-Type", "")
        if "application/json" in content_type:
            data = json.loads(raw.decode("utf-8", errors="ignore") or "{}")
            if not isinstance(data, dict):
                raise ValueError("JSON body must be an object.")
            return {str(key): str(value) for key, value in data.items()}
        params = parse_qs(raw.decode("utf-8", errors="ignore"))
        return {key: values[0] for key, values in params.items() if values}

    def handle_submit(self, head_only: bool = False) -> None:
        allowed, remaining = rate_limit_ok(self.client_identifier())
        if not allowed:
            return self.send_json(
                429,
                {"ok": False, "error": f"Rate limit reached. Try again later. Limit is {SUBMIT_RATE_LIMIT} submissions per hour."},
                head_only,
            )
        try:
            payload = self.read_payload()
            verdict = judge_submission(payload.get("url", ""), payload.get("note", ""), self.client_identifier())
        except json.JSONDecodeError:
            return self.send_json(400, {"ok": False, "error": "Could not parse JSON body."}, head_only)
        except ValueError as exc:
            return self.send_json(400, {"ok": False, "error": str(exc)}, head_only)
        except Exception as exc:
            return self.send_json(502, {"ok": False, "error": f"Oracle submission failed: {exc}"}, head_only)
        return self.send_json(200, {"ok": True, "remaining": remaining, "verdict": verdict}, head_only)

    def route(self, head_only: bool = False) -> None:
        parsed = urlparse(self.path)
        path = parsed.path.rstrip("/") or "/"
        query = parse_qs(parsed.query)
        if path == "/api/submit":
            return self.handle_submit(head_only)
        if path == "/ai-disclosure":
            return self.send_bytes(200, ai_disclosure_page(), "text/html; charset=utf-8", head_only)
        if path == "/":
            return self.send_bytes(200, render_home(query), "text/html; charset=utf-8", head_only)
        if path.startswith("/c/"):
            return self.send_bytes(200, render_detail(path.removeprefix("/c/")), "text/html; charset=utf-8", head_only)
        if path == "/feed.json":
            return self.send_bytes(200, render_feed(), "application/json; charset=utf-8", head_only)
        if path == "/appendix-live.json":
            return self.send_bytes(
                200,
                json.dumps(load_appendix(), ensure_ascii=False, indent=2).encode("utf-8"),
                "application/json; charset=utf-8",
                head_only,
            )
        if path == "/llms.txt":
            return self.send_bytes(200, render_llms(), "text/plain; charset=utf-8", head_only)
        if path == DATASET_LICENSE_PATH:
            return self.send_bytes(200, render_license(), "text/html; charset=utf-8", head_only)
        if path == "/robots.txt":
            body = f"""User-agent: *
Allow: /

User-agent: GPTBot
Allow: /

User-agent: OAI-SearchBot
Allow: /

User-agent: ClaudeBot
Allow: /

Sitemap: {PUBLIC_BASE}/sitemap.xml
"""
            return self.send_bytes(200, body.encode("utf-8"), "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 == "/healthz":
            return self.send_bytes(200, b"ok\n", "text/plain; charset=utf-8", head_only)
        return self.send_bytes(404, b"Not found\n", "text/plain; charset=utf-8", head_only)


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


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