---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Import official OpenAI and Anthropic releases into Appendix III. The capabilities site reads ``CopeCheck/thesis/data/appendix-live.json``. This script keeps the import deterministic and cheap."
resource: "https://capabilities.copecheck.com"
tags: ["copecheck", "capabilities", "source-file", "py"]
timestamp: "2026-10-24T17:25:06Z"
site: "capabilities"
source_path: "copecheck-capabilities/tools/import_vendor_releases.py"
---

# !/usr/bin/env python3

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

```py
#!/usr/bin/env python3
"""Import official OpenAI and Anthropic releases into Appendix III.

The capabilities site reads ``CopeCheck/thesis/data/appendix-live.json``. This
script keeps the import deterministic and cheap: no model calls, no API keys,
just official RSS/sitemap/news pages plus rule-based scoring.
"""

from __future__ import annotations

import argparse
import datetime as dt
import email.utils
import html
import json
import re
import sys
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any


WORKSPACE = Path(__file__).resolve().parents[2]
DEFAULT_APPENDIX = WORKSPACE / "thesis" / "data" / "appendix-live.json"
GPT5_LAUNCH_DATE = dt.date(2025, 8, 7)
OPENAI_RSS = "https://openai.com/news/rss.xml"
ANTHROPIC_SITEMAP = "https://www.anthropic.com/sitemap.xml"
USER_AGENT = "CopeCheck capability importer (+https://capabilities.copecheck.com)"
DEFAULT_MIN_SCORE = 60


CATEGORY_SECTIONS = {
    "benchmark": "Appendix III, section one: model and benchmark capability evidence",
    "deployment": "Appendix III, section four: enterprise deployment evidence",
    "vendor": "Appendix III, section two: vendor threshold and platform capability evidence",
    "labour_market": "Appendix III, section five: labour-market and adoption evidence",
    "layoff": "Appendix III, section five: labour-market displacement evidence",
}


LOW_SIGNAL_TERMS = [
    "board",
    "appoints",
    "appointed",
    "office",
    "opens",
    "hiring plans",
    "terms",
    "policy update",
    "principles",
    "foundation",
    "fellowship",
    "grant",
    "grants",
    "contest",
    "pledge",
    "benefit trust",
    "campus",
    "student club",
    "wellbeing",
    "feed philosophy",
    "privacy",
    "constitution",
]

SAFETY_POLICY_TERMS = [
    "system card",
    "safety",
    "safeguard",
    "misalignment",
    "monitor",
    "policy",
    "compliance framework",
    "responsible ai",
    "transparency",
    "privacy",
    "wellbeing",
    "constitution",
]


def fetch_text(url: str, timeout: int = 15) -> str:
    request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return response.read().decode("utf-8", "replace")


def clean_text(value: Any) -> str:
    text = html.unescape(str(value or ""))
    text = re.sub(r"<script\b.*?</script>", " ", text, flags=re.I | re.S)
    text = re.sub(r"<style\b.*?</style>", " ", text, flags=re.I | re.S)
    text = re.sub(r"<[^>]+>", " ", text)
    text = re.sub(r"\s+", " ", text)
    return text.strip()


def short_text(value: str, limit: int = 360) -> str:
    text = clean_text(value)
    if len(text) <= limit:
        return text
    cut = text[: limit - 1].rsplit(" ", 1)[0].rstrip(".,;:")
    return f"{cut}."


def normalise_url(url: str) -> str:
    parsed = urllib.parse.urlsplit(url.strip())
    path = re.sub(r"/+$", "", parsed.path)
    return urllib.parse.urlunsplit((parsed.scheme.lower(), parsed.netloc.lower(), path, "", ""))


def slugify(value: str, prefix: str = "") -> str:
    slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
    slug = slug[:82].strip("-") or "release"
    if prefix:
        slug = f"{prefix}-{slug}"
    return slug[:96].strip("-")


def unique_slug(base_slug: str, used: set[str]) -> str:
    slug = base_slug
    counter = 2
    while slug in used:
        suffix = f"-{counter}"
        slug = f"{base_slug[:96 - len(suffix)]}{suffix}".strip("-")
        counter += 1
    used.add(slug)
    return slug


def parse_rss_date(value: str) -> dt.date | None:
    if not value:
        return None
    try:
        return email.utils.parsedate_to_datetime(value).date()
    except (TypeError, ValueError, IndexError, AttributeError):
        return None


def parse_article_date(value: str) -> dt.date | None:
    value = clean_text(value)
    for fmt in ("%b %d, %Y", "%B %d, %Y", "%Y-%m-%d"):
        try:
            return dt.datetime.strptime(value, fmt).date()
        except ValueError:
            continue
    return None


def parse_iso_date(value: str) -> dt.date | None:
    if not value:
        return None
    try:
        return dt.datetime.fromisoformat(value.replace("Z", "+00:00")).date()
    except ValueError:
        return None


def is_model_launch(title: str) -> bool:
    """Recognise release families without pinning detection to one generation."""
    return bool(re.match(
        r"^(?:introducing\s+)?(?:gpt-\d+(?:\.\d+)?|"
        r"claude\s+(?:opus|sonnet|haiku|mythos|fable)\s+\d|"
        r"gemini\s+\d|kimi\s+k?\d|muse\s+(?:wonder|spark))\b",
        title.lower(),
    ))


def infer_category(title: str, description: str, source_category: str = "") -> str:
    text = f"{title} {description} {source_category}".lower()
    title_lower = title.lower()
    if any(term in text for term in SAFETY_POLICY_TERMS):
        return "vendor"
    if is_model_launch(title) and "system card" not in text:
        return "benchmark"
    if any(term in text for term in ["layoff", "laid off", "redundanc", "job cut", "workforce reduction"]):
        return "layoff"
    if any(term in text for term in ["economic index", "economic futures", "jobs", "employment", "worker", "workforce", "wage", "compensation", "education report"]):
        return "labour_market"
    if any(term in text for term in ["funding", "raises", "raise", "grant", "grants"]):
        return "vendor"
    if any(term in text for term in ["benchmark", "eval", "sota", "state of the art", "science", "research", "mathematical", "reasoning model"]):
        return "benchmark"
    if any(term in text for term in ["deploy", "deployment", "customer", "case study", "uses", "use claude", "use openai", "powered by", "partnership", "workflow", "enterprise", "bank", "pwc", "deloitte", "accenture", "cognizant", "infosys"]):
        return "deployment"
    if any(term in text for term in ["introducing", "launch", "available", "api", "model", "agent", "codex", "claude", "chatgpt", "pricing", "sdk"]):
        return "vendor"
    return "vendor"


def infer_sector(title: str, description: str) -> str:
    text = f"{title} {description}".lower()
    sectors = [
        ("Software engineering", ["codex", "coding", "developer", "xcode", "github", "software", "terminal", "web development"]),
        ("Financial services", ["bank", "finance", "financial", "trading", "payment", "cfo", "insurance"]),
        ("Healthcare and life sciences", ["health", "clinician", "life sciences", "drug", "genomics", "protein", "medical", "cms"]),
        ("Cybersecurity", ["cyber", "security", "vulnerability", "safeguard", "misuse", "attack"]),
        ("Education", ["education", "student", "teacher", "school", "university", "campus", "educator"]),
        ("Public sector", ["government", "federal", "public sector", "fedramp", "national security", "department"]),
        ("Customer operations", ["customer service", "contact center", "support", "service agents", "call centre"]),
        ("Commerce and marketplace", ["shopping", "commerce", "marketplace", "retail", "product discovery", "food distribution"]),
        ("Media and content", ["news", "media", "writing", "creative", "sora", "image", "video", "voice"]),
        ("Scientific research", ["science", "research", "math", "mathematical", "physics", "protein", "genesis"]),
        ("Enterprise operations", ["enterprise", "business", "work", "operations", "workflow", "productivity", "pwc", "deloitte", "accenture", "cognizant"]),
        ("AI infrastructure", ["compute", "data center", "infrastructure", "tpu", "aws", "cloud", "bedrock", "vertex", "nvidia", "microsoft"]),
    ]
    for sector, terms in sectors:
        if any(term in text for term in terms):
            return sector
    return "General AI capability"


def infer_capability(title: str, description: str, category: str) -> str:
    text = f"{title} {description}".lower()
    capabilities = [
        ("Frontier model release and benchmark movement", ["gpt-", "claude opus", "claude sonnet", "claude haiku", "mythos", "fable", "gemini", "kimi", "muse wonder", "frontier", "benchmark"]),
        ("Autonomous software engineering and computer-use agents", ["codex", "coding", "software engineering", "computer use", "terminal", "xcode"]),
        ("Enterprise workflow automation", ["workflow", "enterprise", "business", "productivity", "office", "operations"]),
        ("Financial workflow automation", ["finance", "bank", "cfo", "financial", "trading", "payment"]),
        ("Healthcare and life-sciences reasoning", ["health", "clinician", "life sciences", "drug", "protein", "medical"]),
        ("Cyber defence and misuse monitoring", ["cyber", "security", "vulnerability", "attack", "misuse"]),
        ("Education and workforce adoption", ["education", "student", "teacher", "worker", "workforce", "jobs", "economic"]),
        ("Multimodal content generation and media workflows", ["sora", "image", "video", "voice", "creative", "writing"]),
        ("Agent platform and API infrastructure", ["api", "sdk", "agents", "mcp", "model context protocol", "bedrock", "vertex", "cloud"]),
    ]
    for capability, terms in capabilities:
        if any(term in text for term in terms):
            return capability
    fallback = {
        "benchmark": "Model and benchmark capability movement",
        "deployment": "Production AI deployment signal",
        "vendor": "Vendor platform capability signal",
        "labour_market": "Labour-market adoption signal",
        "layoff": "Labour displacement signal",
    }
    return fallback.get(category, "AI capability signal")


def score_release(title: str, description: str, category: str) -> int:
    text = f"{title} {description}".lower()
    title_lower = title.lower()
    score = {
        "benchmark": 76,
        "deployment": 78,
        "vendor": 64,
        "labour_market": 72,
        "layoff": 80,
    }.get(category, 60)
    model_launch = is_model_launch(title)
    if model_launch and "system card" not in text:
        score += 20
    elif any(term in text for term in ["gpt-5.5", "gpt-5.4", "gpt-5.3", "gpt-5.2", "gpt-5.1", "gpt-5", "claude opus", "claude sonnet", "claude haiku", "mythos"]):
        score += 12
    if any(term in text for term in ["codex", "agent", "agents", "computer use", "autonomously", "workflow", "automate", "automation"]):
        score += 10
    if any(term in text for term in ["customer", "case study", "deploy", "partnership", "roll out", "rollout", "enterprise"]):
        score += 7
    if any(term in text for term in ["saves", "reduced", "faster", "productivity", "minutes", "hours", "1b", "million", "billion"]):
        score += 4
    if any(term in text for term in ["system card", "safety", "safeguard", "policy", "terms", "board", "office", "appointed", "funding", "raises"]):
        score -= 12
    if any(term in text for term in SAFETY_POLICY_TERMS):
        score -= 16
    if any(term in text for term in LOW_SIGNAL_TERMS):
        score -= 10
    return max(25, min(96, score))


def oracle_verdict(publisher: str, title: str, category: str, score: int) -> str:
    if score < 60:
        return (
            "This is a low-signal vendor radar item. Keep it as context only unless a later benchmark, deployment, "
            "procurement change, or labour-market datapoint turns it into direct Appendix III evidence."
        )
    if score >= 86:
        return (
            f"{publisher} is describing a frontier or production capability that pushes directly on the thesis. "
            "The important signal is not the marketing language; it is the widening set of tasks now being routed through model-driven execution rather than ordinary software or headcount."
        )
    if category == "deployment":
        return (
            f"This is useful evidence because it moves AI from demo space into an actual organisational workflow. "
            "Treat it as a displacement-pressure signal where the near-term effect is task compression, supervision thinning, and fewer handoffs."
        )
    if category == "benchmark":
        return (
            f"This belongs in the register because benchmark and model-release claims set the ceiling for the next wave of deployment stories. "
            "The labour-market effect is indirect today, but it becomes direct when these gains are packaged into agents, APIs, and enterprise tools."
        )
    if category == "labour_market":
        return (
            f"This is a labour-market context signal rather than a single workflow proof point. "
            "It helps the thesis track whether adoption, education, wages, and institutional behaviour are moving in the same direction as the capability curve."
        )
    return (
        f"This is a lower-to-mid strength vendor signal for the capability register. "
        "It does not prove displacement on its own, but it records another platform step that can later show up as workflow automation, procurement change, or organisational dependency."
    )


def build_item(raw: dict[str, Any], used_slugs: set[str]) -> dict[str, Any]:
    title = clean_text(raw["title"])
    description = short_text(raw.get("description") or f"Official {raw['publisher']} release: {title}.")
    category = infer_category(title, description, raw.get("source_category", ""))
    score = score_release(title, description, category)
    slug = unique_slug(slugify(title, raw["slug_prefix"]), used_slugs)
    publisher = raw["publisher"]
    claim = description.rstrip(".")
    if not claim:
        claim = f"{publisher} announced {title}"
    claim = f"{claim}."
    return {
        "slug": slug,
        "url": raw["url"],
        "title": title,
        "publisher": publisher,
        "category": category,
        "sector": infer_sector(title, description),
        "capability": infer_capability(title, description, category),
        "claim": short_text(claim, 420),
        "relevance": CATEGORY_SECTIONS.get(category, CATEGORY_SECTIONS["vendor"]),
        "cope_score": score,
        "confidence": 0.9 if publisher == "OpenAI" else 0.88,
        "note": (
            f"Imported from the official {publisher} release stream because it was published on or after "
            f"the GPT-5 launch date ({GPT5_LAUNCH_DATE.isoformat()})."
        ),
        "oracle_verdict": oracle_verdict(publisher, title, category, score),
        "observed_at": raw["observed_at"],
        "source_family": "official_vendor_release",
        "source_provider": publisher.lower(),
    }


def refresh_vendor_item(item: dict[str, Any]) -> bool:
    # A scoring refresh must never erase a reviewed correction or its verdict.
    if item.get("correction") or item.get("reviewed_at"):
        return False
    title = clean_text(item.get("title") or "")
    description = clean_text(item.get("claim") or item.get("note") or title)
    publisher = clean_text(item.get("publisher") or item.get("source_provider") or "Vendor")
    old = {
        "category": item.get("category"),
        "sector": item.get("sector"),
        "capability": item.get("capability"),
        "cope_score": item.get("cope_score"),
        "relevance": item.get("relevance"),
        "oracle_verdict": item.get("oracle_verdict"),
    }
    category = infer_category(title, description, "")
    score = score_release(title, description, category)
    item["category"] = category
    item["sector"] = infer_sector(title, description)
    item["capability"] = infer_capability(title, description, category)
    item["relevance"] = CATEGORY_SECTIONS.get(category, CATEGORY_SECTIONS["vendor"])
    item["cope_score"] = score
    item["oracle_verdict"] = oracle_verdict(publisher, title, category, score)
    item["score_method"] = "deterministic_vendor_release_v3"
    return any(item.get(key) != value for key, value in old.items())


def openai_releases(start_date: dt.date) -> list[dict[str, Any]]:
    xml = fetch_text(OPENAI_RSS)
    root = ET.fromstring(xml)
    out: list[dict[str, Any]] = []
    for item in root.findall("./channel/item"):
        title = item.findtext("title") or ""
        link = item.findtext("link") or ""
        published = parse_rss_date(item.findtext("pubDate") or "")
        parsed = urllib.parse.urlsplit(link)
        if not published or published < start_date:
            continue
        if parsed.netloc.lower() != "openai.com" or not parsed.path.startswith("/index/"):
            continue
        categories = [clean_text(c.text or "") for c in item.findall("category")]
        description = clean_text(item.findtext("description") or "")
        out.append(
            {
                "publisher": "OpenAI",
                "slug_prefix": "openai",
                "title": title,
                "url": link,
                "observed_at": published.isoformat(),
                "description": description,
                "source_category": ", ".join(categories),
            }
        )
    return out


def anthropic_page(url: str, fallback_date: dt.date | None) -> dict[str, Any] | None:
    page = ""
    last_error: Exception | None = None
    for timeout in (12, 20):
        try:
            page = fetch_text(url, timeout=timeout)
            break
        except Exception as exc:  # noqa: BLE001 - keep imports resilient.
            last_error = exc
            time.sleep(0.25)
    if not page:
        print(f"warn: could not fetch {url}: {last_error}", file=sys.stderr)
        return None
    title_match = re.search(r"<h1[^>]*>(.*?)</h1>", page, flags=re.I | re.S)
    date_match = re.search(r'<div class="body-3 agate">([^<]+)</div>', page, flags=re.I)
    title = clean_text(title_match.group(1) if title_match else urllib.parse.urlsplit(url).path.rsplit("/", 1)[-1])
    published = parse_article_date(date_match.group(1) if date_match else "") or fallback_date
    paragraphs = [
        clean_text(match.group(1))
        for match in re.finditer(r'<p[^>]*class="[^"]*post-text[^"]*"[^>]*>(.*?)</p>', page, flags=re.I | re.S)
    ]
    paragraphs = [p for p in paragraphs if p]
    description = " ".join(paragraphs[:2])
    if not description:
        meta = re.search(r'<meta[^>]+(?:name|property)="(?:description|og:description)"[^>]+content="([^"]+)"', page, flags=re.I)
        description = clean_text(meta.group(1) if meta else "")
    if not published:
        return None
    return {
        "publisher": "Anthropic",
        "slug_prefix": "anthropic",
        "title": title,
        "url": url,
        "observed_at": published.isoformat(),
        "description": description,
        "source_category": "",
    }


def anthropic_releases(start_date: dt.date, max_workers: int = 5) -> list[dict[str, Any]]:
    xml = fetch_text(ANTHROPIC_SITEMAP)
    root = ET.fromstring(xml)
    ns = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
    candidates: list[tuple[str, dt.date | None]] = []
    for url_node in root.findall(".//sm:url", ns):
        loc = url_node.findtext("sm:loc", default="", namespaces=ns)
        lastmod = parse_iso_date(url_node.findtext("sm:lastmod", default="", namespaces=ns))
        if "/news/" not in loc:
            continue
        if lastmod and lastmod < start_date:
            continue
        candidates.append((loc, lastmod))

    out: list[dict[str, Any]] = []
    with ThreadPoolExecutor(max_workers=max_workers) as pool:
        futures = {pool.submit(anthropic_page, loc, lastmod): loc for loc, lastmod in candidates}
        for future in as_completed(futures):
            item = future.result()
            if item and dt.date.fromisoformat(item["observed_at"]) >= start_date:
                out.append(item)
    out.sort(key=lambda row: (row["observed_at"], row["url"]), reverse=True)
    return out


def load_appendix(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))


def write_appendix(path: Path, data: dict[str, Any]) -> None:
    path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def refresh_existing(path: Path, dry_run: bool) -> int:
    appendix = load_appendix(path)
    items = appendix.get("items") if isinstance(appendix.get("items"), list) else []
    changed = 0
    for item in items:
        if not isinstance(item, dict) or item.get("source_family") != "official_vendor_release":
            continue
        changed += int(refresh_vendor_item(item))

    print(f"official vendor entries refreshed: {changed}")
    if dry_run:
        return changed

    now = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
    appendix["updated_at"] = now
    scanner = appendix.setdefault("scanner", {})
    vendor_import = scanner.setdefault("vendor_release_import", {})
    vendor_import["last_score_refresh_at"] = now
    vendor_import["score_refresh_mode"] = "deterministic_vendor_release_v3"
    write_appendix(path, appendix)
    return changed


def import_releases(path: Path, start_date: dt.date, dry_run: bool, min_score: int) -> int:
    appendix = load_appendix(path)
    items = appendix.setdefault("items", [])
    existing_urls = {normalise_url(str(item.get("url", ""))) for item in items if isinstance(item, dict)}
    used_slugs = {str(item.get("slug", "")) for item in items if isinstance(item, dict)}

    raw_releases = openai_releases(start_date) + anthropic_releases(start_date)
    new_items: list[dict[str, Any]] = []
    for raw in raw_releases:
        if normalise_url(raw["url"]) in existing_urls:
            continue
        built = build_item(raw, used_slugs)
        if built["cope_score"] < min_score:
            continue
        existing_urls.add(normalise_url(raw["url"]))
        new_items.append(built)

    print(f"official releases discovered: {len(raw_releases)}")
    print(f"new releases after dedupe: {len(new_items)}")
    by_provider: dict[str, int] = {}
    by_category: dict[str, int] = {}
    for item in new_items:
        by_provider[item["publisher"]] = by_provider.get(item["publisher"], 0) + 1
        by_category[item["category"]] = by_category.get(item["category"], 0) + 1
    print("by provider:", by_provider)
    print("by category:", by_category)
    for sample in new_items[:12]:
        print(f"- {sample['observed_at']} [{sample['publisher']}/{sample['category']}/{sample['cope_score']}] {sample['title']}")

    if dry_run:
        return len(new_items)

    items.extend(new_items)
    appendix["updated_at"] = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
    scanner = appendix.setdefault("scanner", {})
    scanner["vendor_release_import"] = {
        "last_run_at": appendix["updated_at"],
        "start_date": start_date.isoformat(),
        "sources": [OPENAI_RSS, ANTHROPIC_SITEMAP],
        "added": len(new_items),
        "total_discovered": len(raw_releases),
        "mode": "deterministic_no_model_call",
        "min_score": min_score,
    }
    write_appendix(path, appendix)
    return len(new_items)


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--appendix", type=Path, default=DEFAULT_APPENDIX)
    parser.add_argument("--start-date", default=GPT5_LAUNCH_DATE.isoformat())
    parser.add_argument("--min-score", default=DEFAULT_MIN_SCORE, type=int, help="Skip newly discovered releases below this deterministic evidence score.")
    parser.add_argument("--refresh-existing", action="store_true", help="Recompute category, score, relevance and verdict for existing official vendor release entries.")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()
    start_date = dt.date.fromisoformat(args.start_date)
    if args.refresh_existing:
        refresh_existing(args.appendix, args.dry_run)
    else:
        import_releases(args.appendix, start_date, args.dry_run, args.min_score)
    return 0


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