---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import copy import html as html_lib import importlib.util import ipaddress import json import math import os import re import sqlite3 import socket import sys import."
resource: "https://codex.copecheck.com/codex_server.py"
tags: ["copecheck", "codex", "source-file", "py"]
timestamp: "2026-09-25T22:01:57Z"
site: "codex"
source_path: "copecheck-codex/codex_server.py"
---

# from __future__ import annotations

Source path: `copecheck-codex/codex_server.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-25T22:01:57Z`

```py
from __future__ import annotations

import argparse
import copy
import html as html_lib
import importlib.util
import ipaddress
import json
import math
import os
import re
import sqlite3
import socket
import sys
import threading
import time
import uuid
from datetime import datetime, timezone
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, unquote, urlparse

from canonical_identity import canonical_url
from story_state import (
    add_job_provenance,
    atomic_write_json,
    canonical_job_id,
    ensure_state_schema,
    ensure_job_identity,
    find_job_by_story_key,
    provenance_observation,
    public_job_error,
    public_result_payload,
    register_story_aliases,
    resolve_job,
    state_file_lock,
    story_key,
    valid_public_score,
)


BASE = Path(__file__).resolve().parent
DATA_DIR = BASE / "data"
STATE_PATH = DATA_DIR / "jobs-state.json"
STORIES_PATH = DATA_DIR / "stories.json"
DOOM_MARKETS_PATH = DATA_DIR / "doom-markets.json"
STATE_LOCK = threading.Lock()
_STATE_CACHE: dict[str, Any] | None = None
_STATE_CACHE_MTIME_NS: int | None = None
PUBLIC_CHANNELS = {
    "main",
    "uk",
    "countries",
    "eu",
    "policy",
    "cities",
    "data",
    "careers",
    "layoffs",
}
QUEUE_CHANNEL_ORDER = [
    "main",
    "uk",
    "layoffs",
    "countries",
    "eu",
    "policy",
    "cities",
    "data",
    "careers",
]
RATE_LIMIT_WINDOW = 3600
RATE_LIMIT_MAX = 12
RATE_STORE: dict[str, list[float]] = {}
PUBLIC_BASE_URL = os.getenv("COPECHECK_PUBLIC_BASE_URL", "https://codex.copecheck.com").rstrip("/")
AI_DISCLOSURE_TEXT = (
    "This Oracle entry contains AI-generated analysis. Model outputs may contain errors; "
    "verify the score against the linked source."
)
AUTO_PUBLISH_ATTRIBUTION = {"direct_quote", "named_paraphrase", "institutional_report"}
MAIN_DB_PATH = Path(os.getenv("COPECHECK_MAIN_DB", "/home/ben/infra/copecheck/data/copecheck.db"))
MAIN_DB_MODULE_PATH = Path(os.getenv(
    "COPECHECK_MAIN_DB_MODULE",
    str(MAIN_DB_PATH.parent.parent / "db.py"),
))
UK_DB_PATH = Path(os.getenv("COPECHECK_UK_DB", "/home/ben/infra/copecheck-uk/data/copecheck_uk.db"))
LAYOFFS_ORACLE_PATH = Path(
    os.getenv("COPECHECK_LAYOFFS_ORACLE_JSON", "/home/ben/infra/copecheck-layoffs/data/codex_oracle.json")
)
UK_HOST_HINTS = {
    "bbc.co.uk",
    "bbc.com",
    "theguardian.com",
    "telegraph.co.uk",
    "independent.co.uk",
    "gov.uk",
    "parliament.uk",
    "ons.gov.uk",
    "ft.com",
    "standard.co.uk",
    "mirror.co.uk",
    "express.co.uk",
    "dailymail.co.uk",
    "politics.co.uk",
}
UK_TEXT_HINTS = {
    "uk",
    "britain",
    "british",
    "england",
    "scotland",
    "wales",
    "westminster",
    "parliament",
    "nhs",
    "ons",
    "labour",
    "conservative",
    "reform uk",
    "starmer",
    "reeves",
}
LAYOFF_TEXT_HINTS = {
    "layoff",
    "layoffs",
    "laid off",
    "redundancy",
    "redundancies",
    "job cuts",
    "cuts jobs",
    "cut jobs",
    "headcount reduction",
    "workforce reduction",
    "restructuring",
    "severance",
}


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


def load_env() -> None:
    env_path = BASE / ".env"
    if not env_path.exists():
        return
    for line in env_path.read_text(encoding="utf-8").splitlines():
        line = 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())


def _read_state_unlocked() -> dict[str, Any]:
    global _STATE_CACHE, _STATE_CACHE_MTIME_NS
    if not STATE_PATH.exists():
        return ensure_state_schema({"updated_at": utc_now()})
    mtime_ns = STATE_PATH.stat().st_mtime_ns
    if _STATE_CACHE is not None and _STATE_CACHE_MTIME_NS == mtime_ns:
        return _STATE_CACHE
    state = ensure_state_schema(json.loads(STATE_PATH.read_text(encoding="utf-8")))
    _STATE_CACHE = state
    _STATE_CACHE_MTIME_NS = mtime_ns
    return state


def read_state() -> dict[str, Any]:
    with state_file_lock(STATE_PATH, exclusive=False):
        return _read_state_unlocked()


def _write_state_unlocked(state: dict[str, Any]) -> None:
    global _STATE_CACHE, _STATE_CACHE_MTIME_NS
    ensure_state_schema(state)
    state["updated_at"] = utc_now()
    atomic_write_json(STATE_PATH, state)
    _STATE_CACHE = state
    _STATE_CACHE_MTIME_NS = STATE_PATH.stat().st_mtime_ns


def write_state(state: dict[str, Any]) -> None:
    with state_file_lock(STATE_PATH):
        _write_state_unlocked(state)


def short_words(value: Any, limit: int = 24) -> str:
    text = re.sub(r"\s+", " ", str(value or "")).strip()
    if not text:
        return ""
    words = text.split(" ")
    if len(words) <= limit:
        return text
    return " ".join(words[:limit]).rstrip(".,;:") + "..."


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


def first_claim(result: dict[str, Any] | None) -> dict[str, Any] | None:
    if not isinstance(result, dict):
        return None
    claims = result.get("claims")
    if isinstance(claims, list) and claims and isinstance(claims[0], dict):
        return claims[0]
    return None


def source_for(job: dict[str, Any], result: dict[str, Any] | None) -> dict[str, Any]:
    source = result.get("source") if isinstance(result, dict) else None
    if not isinstance(source, dict):
        source = {}
    return {
        "url": source.get("url") or job.get("url"),
        "canonical_url": source.get("canonical_url"),
        "publisher": source.get("publisher"),
        "title": source.get("title") or job.get("story_title") or job.get("url"),
        "date_published": source.get("date_published") or job.get("story_published"),
    }


def route_for(job: dict[str, Any]) -> str:
    channel = str(job.get("route_target") or job.get("channel") or "main").lower()
    return channel if channel in PUBLIC_CHANNELS else "main"


def route_text_for(job: dict[str, Any] | None = None, result: dict[str, Any] | None = None) -> str:
    job = job or {}
    result = result if isinstance(result, dict) else job.get("result") if isinstance(job.get("result"), dict) else {}
    source = source_for(job, result if isinstance(result, dict) else None)
    claims = result.get("claims") if isinstance(result, dict) else []
    claim_text = " ".join(
        " ".join(
            str(claim.get(key) or "")
            for key in (
                "claim_summary",
                "attributed_claim",
                "rationale_short",
                "structural_issue_ignored",
                "party_or_org",
                "person",
            )
        )
        for claim in claims or []
        if isinstance(claim, dict)
    )
    return " ".join(
        str(part or "")
        for part in [
            job.get("url"),
            job.get("story_title"),
            job.get("feed"),
            source.get("url"),
            source.get("title"),
            source.get("publisher"),
            claim_text,
        ]
    ).lower()


def detect_route(url: str, result: dict[str, Any] | None = None, job: dict[str, Any] | None = None) -> tuple[str, str]:
    parsed = urlparse(url)
    host = parsed.netloc.lower().removeprefix("www.")
    path = parsed.path.lower()
    probe_job = dict(job or {})
    probe_job.setdefault("url", url)
    text = route_text_for(probe_job, result)
    if any(hint in text for hint in LAYOFF_TEXT_HINTS):
        return "layoffs", "layoff language"
    if any(host == item or host.endswith(f".{item}") for item in UK_HOST_HINTS):
        return "uk", f"UK source: {host}"
    if "/uk" in path or any(hint in text for hint in UK_TEXT_HINTS):
        return "uk", "UK/public-institution language"
    return "main", "general AI/workforce claim"


def queue_priority(job: dict[str, Any]) -> int:
    default_priority = 50 if str(job.get("source") or "") == "rss" else 0
    try:
        return int(job.get("priority", default_priority))
    except (TypeError, ValueError):
        return default_priority


def queue_sort_key(job: dict[str, Any]) -> tuple[int, str]:
    return (queue_priority(job), str(job.get("submitted_at") or ""))


def is_manual_priority(job: dict[str, Any]) -> bool:
    return str(job.get("source") or "") == "manual" or queue_priority(job) <= 10


def is_manual_submission(job: dict[str, Any]) -> bool:
    return str(job.get("source") or "") == "manual"


def publication_path_for(job: dict[str, Any]) -> str:
    job_id = str(job.get("job_id") or "")
    return f"/oracle/{route_for(job)}/{job_id}"


def subdomain_target_for(job: dict[str, Any]) -> dict[str, str]:
    result = job.get("result") if isinstance(job.get("result"), dict) else {}
    claim = first_claim(result) or {}
    job_id = str(job.get("job_id") or "")
    short_id = job_id.replace("cc_", "")[:8] or "entry"
    slug = str(job.get("subdomain_slug") or f"{slugify(claim.get('claim_summary'), 'oracle')}-{short_id}")
    channel = route_for(job)
    if channel == "uk":
        path = f"/analysis/{slug}"
        return {"host": "uk.copecheck.com", "path": path, "url": f"https://uk.copecheck.com{path}"}
    if channel == "layoffs":
        path = f"/oracle/{job_id}/"
        return {"host": "layoffs.copecheck.com", "path": path, "url": f"https://layoffs.copecheck.com{path}"}
    path = f"/v/{slug}"
    return {"host": "www.copecheck.com", "path": path, "url": f"https://www.copecheck.com{path}"}


def valid_cope_score(value: Any) -> bool:
    """Accept only finite scores in the public 0–100 contract."""
    return valid_public_score(value)


def result_has_invalid_cope_score(result: Any) -> bool:
    """Reject any worker claim that supplies a score outside the contract."""
    if not isinstance(result, dict):
        return False
    payload = result.get("result") if isinstance(result.get("result"), dict) else result
    claims = payload.get("claims") if isinstance(payload, dict) else None
    return isinstance(claims, list) and any(
        isinstance(claim, dict)
        and "cope_score" in claim
        and not valid_cope_score(claim.get("cope_score"))
        for claim in claims
    )


def private_diagnostic_snapshot(value: Any) -> Any:
    """Keep rejected worker evidence JSON-safe without publishing it."""
    if isinstance(value, float) and not math.isfinite(value):
        if math.isnan(value):
            return "NaN"
        return "Infinity" if value > 0 else "-Infinity"
    if isinstance(value, dict):
        return {
            str(key): private_diagnostic_snapshot(child)
            for key, child in value.items()
        }
    if isinstance(value, list):
        return [private_diagnostic_snapshot(child) for child in value]
    if isinstance(value, tuple):
        return [private_diagnostic_snapshot(child) for child in value]
    return copy.deepcopy(value)


def is_auto_publishable(job: dict[str, Any]) -> bool:
    result = job.get("result")
    if job.get("status") != "complete" or not isinstance(result, dict):
        return False
    claim = first_claim(result)
    if not claim:
        return False
    source = source_for(job, result)
    try:
        confidence = float(claim.get("confidence") or 0)
    except (TypeError, ValueError):
        confidence = 0
    return all(
        [
            result.get("status", "complete") == "complete",
            claim.get("needs_review") is False,
            confidence >= 0.78,
            valid_cope_score(claim.get("cope_score")),
            claim.get("attribution_strength") in AUTO_PUBLISH_ATTRIBUTION,
            bool(source.get("url")),
            bool(claim.get("relevant_excerpt")),
            bool(claim.get("evidence_used")),
        ]
    )


def is_publication_candidate(job: dict[str, Any]) -> bool:
    if is_auto_publishable(job):
        return True
    result = job.get("result")
    if not is_manual_submission(job) or job.get("status") not in {"complete", "needs_review"}:
        return False
    if not isinstance(result, dict) or str(result.get("status") or job.get("status")) not in {"complete", "needs_review"}:
        return False
    claim = first_claim(result)
    if not claim:
        return False
    source = source_for(job, result)
    return all(
        [
            bool(source.get("url")),
            valid_cope_score(claim.get("cope_score")),
            bool(claim.get("claim_summary")),
            bool(claim.get("rationale_short")),
        ]
    )


def apply_publication_state(job: dict[str, Any], now: str | None = None) -> bool:
    previous = {
        key: job.get(key)
        for key in ("publication_status", "publication_path", "publication_url", "published_at")
    }
    if is_publication_candidate(job):
        target = subdomain_target_for(job)
        job["subdomain_slug"] = target["path"].rstrip("/").rsplit("/", 1)[-1]
        job["publication_host"] = target["host"]
        job["publication_status"] = "published"
        job["publication_path"] = target["path"]
        job["publication_url"] = target["url"]
        job.setdefault("published_at", job.get("completed_at") or now or utc_now())
    elif job.get("status") in {"needs_review", "complete", "discarded", "failed"} or isinstance(job.get("result"), dict):
        job["publication_status"] = "review" if job.get("status") == "needs_review" else "unpublished"
        for key in ("publication_path", "publication_url", "published_at"):
            job.pop(key, None)
    return previous != {
        key: job.get(key)
        for key in ("publication_status", "publication_path", "publication_url", "published_at")
    }


def oracle_summary(job: dict[str, Any], result: dict[str, Any], claim: dict[str, Any]) -> str:
    person = claim.get("person") or claim.get("party_or_org") or "The claim"
    score = claim.get("cope_score")
    band = str(claim.get("band") or "unclassified").replace("_", " ")
    mode = str(claim.get("primary_mode") or "unknown").replace("_", " ")
    rationale = str(claim.get("rationale_short") or "").strip()
    base = f"{person} lands at {score}/100 ({band}) for {mode}."
    if rationale:
        return f"{base} {rationale}"
    source = source_for(job, result)
    return f"{base} Source: {source.get('publisher') or source.get('title') or 'captured article'}."


def publication_entry(job: dict[str, Any], compact: bool = False) -> dict[str, Any] | None:
    if not is_publication_candidate(job):
        return None
    result = sanitize_public_result(job.get("result")) or {}
    claim = first_claim(result)
    if not claim:
        return None
    source = source_for(job, result)
    path = job.get("publication_path") or publication_path_for(job)
    entry = {
        "job_id": job.get("job_id"),
        "channel": route_for(job),
        "published_at": job.get("published_at") or job.get("completed_at") or job.get("submitted_at"),
        "path": path,
        "url": job.get("publication_url") or PUBLIC_BASE_URL + path,
        "source_url": source.get("url"),
        "source_title": source.get("title"),
        "publisher": source.get("publisher"),
        "date_published": source.get("date_published"),
        "claim_summary": claim.get("claim_summary"),
        "oracle_summary": oracle_summary(job, result, claim),
        "score": claim.get("cope_score"),
        "band": claim.get("band"),
        "mode": claim.get("primary_mode"),
        "confidence": claim.get("confidence"),
        "needs_review": claim.get("needs_review"),
        "review_reason": claim.get("review_reason"),
        "person": claim.get("person"),
        "role": claim.get("role"),
        "party_or_org": claim.get("party_or_org"),
        "attribution_strength": claim.get("attribution_strength"),
        "rationale_short": claim.get("rationale_short"),
        "relevant_excerpt": short_words(claim.get("relevant_excerpt"), 24),
        "evidence_used": claim.get("evidence_used") or [],
    }
    if compact:
        keep = {
            "job_id",
            "channel",
            "published_at",
            "path",
            "url",
            "claim_summary",
            "oracle_summary",
            "score",
            "band",
            "mode",
            "needs_review",
        }
        entry = {key: value for key, value in entry.items() if key in keep}
    return {key: value for key, value in entry.items() if value is not None}


def published_entries(state: dict[str, Any], limit: int | None = None) -> list[dict[str, Any]]:
    entries = [
        entry
        for job in state.get("jobs", {}).values()
        if isinstance(job, dict)
        for entry in [publication_entry(job)]
        if entry
    ]
    entries.sort(key=lambda item: str(item.get("published_at") or ""), reverse=True)
    if limit is not None:
        entries = entries[:limit]
    return entries


def oracle_markdown(entry: dict[str, Any]) -> str:
    evidence = "\n".join(f"- {item}" for item in entry.get("evidence_used", [])[:5])
    excerpt = entry.get("relevant_excerpt")
    review_note = (
        "## Publication Note\n\nThis manual submission was published after scoring, "
        "but the attribution/review flag should still be checked before treating it as final."
        if entry.get("needs_review")
        else ""
    )
    return "\n\n".join(
        part
        for part in [
            f"## Oracle Summary\n\n{entry.get('oracle_summary')}",
            review_note,
            (
                "## Attributed Claim\n\n"
                f"> {entry.get('claim_summary')}\n\n"
                f"**Score:** {entry.get('score')}/100 ({entry.get('band')})  \n"
                f"**Mode:** {entry.get('mode')}  \n"
                f"**Attribution:** {entry.get('attribution_strength')}  \n"
                f"**Confidence:** {round(float(entry.get('confidence') or 0) * 100)}%"
            ),
            f"## Rationale\n\n{entry.get('rationale_short')}",
            f"## Evidence Used\n\n{evidence}" if evidence else "",
            f"## Source Excerpt\n\n> {excerpt}" if excerpt else "",
            f"[Open original source]({entry.get('source_url')})",
        ]
        if part
    )


_MAIN_DB_API = None


def main_db_api():
    """Load Main's canonical writer without importing Codex as `db`."""
    global _MAIN_DB_API
    if _MAIN_DB_API is None:
        if not MAIN_DB_MODULE_PATH.exists():
            raise FileNotFoundError(f"Main DB API is missing: {MAIN_DB_MODULE_PATH}")
        module_dir = str(MAIN_DB_MODULE_PATH.parent)
        if module_dir not in sys.path:
            sys.path.insert(0, module_dir)
        spec = importlib.util.spec_from_file_location(
            "_copecheck_main_db_api",
            MAIN_DB_MODULE_PATH,
        )
        if spec is None or spec.loader is None:
            raise RuntimeError("Could not load Main canonical DB API")
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        _MAIN_DB_API = module
    _MAIN_DB_API.DB_PATH = str(MAIN_DB_PATH)
    return _MAIN_DB_API


# --- full-article body extraction for Main publications -------------------
# Historical bug: Main publications stored `relevant_excerpt` (a 100-300 char
# quote) in articles.body, so 503 curated rows shipped with truncated bodies.
# We now fetch the real article text first and fall back to the excerpt.
HOME_SCRAPER_URL = os.getenv("FIRECRAWL_URL", "http://100.70.233.73:3002").rstrip("/")
CODEX_BODY_MIN_CHARS = int(os.getenv("CODEX_BODY_MIN_CHARS", "500"))
CODEX_BODY_TIMEOUT = float(os.getenv("CODEX_BODY_TIMEOUT", "25"))


def fetch_full_body(url: str) -> str:
    """Return extracted article text, or "" when extraction is not possible."""
    if not url:
        return ""
    import urllib.request
    payload = json.dumps({"url": url, "formats": ["markdown"]}).encode("utf-8")
    req = urllib.request.Request(
        f"{HOME_SCRAPER_URL}/v1/scrape",
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=CODEX_BODY_TIMEOUT) as resp:
            data = json.loads(resp.read().decode("utf-8", "replace"))
    except Exception as exc:  # network, timeout, bad JSON
        print(f"[codex] body extraction failed for {url}: {exc}", flush=True)
        return ""
    if not data.get("success"):
        return ""
    return str((data.get("data") or {}).get("markdown") or "").strip()


def publication_body(entry: dict[str, Any]) -> str:
    """Full article text when we can get it, excerpt as a documented fallback."""
    excerpt = str(entry.get("relevant_excerpt") or "")
    full = fetch_full_body(str(entry.get("source_url") or ""))
    if len(full) >= CODEX_BODY_MIN_CHARS and len(full) > len(excerpt):
        return full
    return excerpt


def write_main_publication(job: dict[str, Any], entry: dict[str, Any]) -> str:
    if not MAIN_DB_PATH.exists():
        raise FileNotFoundError(f"Main database is missing: {MAIN_DB_PATH}")
    title = str(entry.get("claim_summary") or entry.get("source_title") or "Oracle summary")
    raw_url = str(entry.get("source_url") or "")
    canonical = canonical_url(raw_url)
    if not canonical:
        raise ValueError("Main publication requires a canonical source URL")
    api = main_db_api()
    api.insert_pending(
        raw_url,
        title,
        entry.get("publisher") or "CopeCheck Codex",
        entry.get("date_published") or entry.get("published_at"),
        entry.get("oracle_summary") or "",
        publication_body(entry),
        channel="codex",
    )
    article = api.by_url_hash(raw_url)
    if not article:
        raise RuntimeError("Main canonical writer did not resolve the article")
    slug = str(article["slug"])
    api.set_verdict(
        slug,
        oracle_markdown(entry),
        short_words(entry.get("oracle_summary"), 28),
        job.get("model_key") or "codex",
        0.0,
        relevance=100.0,
    )
    return slug


def write_uk_publication(job: dict[str, Any], entry: dict[str, Any]) -> None:
    if not UK_DB_PATH.exists():
        return
    claim = first_claim(job.get("result") if isinstance(job.get("result"), dict) else {}) or {}
    slug = job["subdomain_slug"]
    evidence = "\n".join(f"- {item}" for item in entry.get("evidence_used", [])[:5])
    explanation = "\n\n".join(
        part
        for part in [
            entry.get("oracle_summary"),
            entry.get("rationale_short"),
            f"Evidence:\n{evidence}" if evidence else "",
        ]
        if part
    )
    with sqlite3.connect(UK_DB_PATH, timeout=30) as con:
        con.execute("PRAGMA journal_mode=WAL")
        con.execute(
            """
            INSERT INTO analyses
              (input_text, input_url, extracted_title, cope_score, cope_type, scapegoats,
[redacted secret-like line]
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'codex')
            ON CONFLICT(slug) DO UPDATE SET
              input_text=excluded.input_text,
              input_url=excluded.input_url,
              extracted_title=excluded.extracted_title,
              cope_score=excluded.cope_score,
              cope_type=excluded.cope_type,
              scapegoats=excluded.scapegoats,
              structural_reality=excluded.structural_reality,
              what_data_says=excluded.what_data_says,
              verdict=excluded.verdict,
              explanation=excluded.explanation,
              model=excluded.model
            """,
            (
                "\n\n".join(
                    part
                    for part in [claim.get("attributed_claim"), entry.get("relevant_excerpt")]
                    if part
                )[:2000],
                entry.get("source_url"),
                entry.get("claim_summary"),
                int(entry.get("score") or 0),
                entry.get("mode"),
                json.dumps([claim.get("scapegoat_target")] if claim.get("scapegoat_target") else []),
                claim.get("structural_issue_ignored") or entry.get("rationale_short") or "",
                evidence,
                str(entry.get("band") or "").replace("_", " ").title(),
                explanation,
                job.get("model_key") or "codex",
                slug,
            ),
        )


def write_layoffs_publication(job: dict[str, Any], entry: dict[str, Any]) -> None:
    with state_file_lock(LAYOFFS_ORACLE_PATH):
        try:
            data = json.loads(LAYOFFS_ORACLE_PATH.read_text(encoding="utf-8"))
        except FileNotFoundError:
            data = {}
        if not isinstance(data, dict):
            raise ValueError("Layoffs Oracle state must be a JSON object")
        data[str(job.get("job_id"))] = entry
        atomic_write_json(LAYOFFS_ORACLE_PATH, data)


def publish_to_subdomain(job: dict[str, Any]) -> bool:
    if not is_publication_candidate(job):
        return False
    apply_publication_state(job)
    entry = publication_entry(job)
    if not entry:
        return False
    try:
        channel = route_for(job)
        if channel == "uk":
            write_uk_publication(job, entry)
        elif channel == "layoffs":
            write_layoffs_publication(job, entry)
        else:
            actual_slug = write_main_publication(job, entry)
            job["subdomain_slug"] = actual_slug
            job["publication_host"] = "www.copecheck.com"
            job["publication_path"] = f"/v/{actual_slug}"
            job["publication_url"] = f"https://www.copecheck.com/v/{actual_slug}"
        job.pop("publication_error", None)
        return True
    except Exception as exc:
        job["publication_status"] = "publish_failed"
        job["publication_error"] = f"{type(exc).__name__}: {exc}"
        return False


def publish_all_to_subdomains(state: dict[str, Any]) -> int:
    count = 0
    for job in state.get("jobs", {}).values():
        if isinstance(job, dict) and is_auto_publishable(job):
            if publish_to_subdomain(job):
                count += 1
    return count


def backfill_publications(state: dict[str, Any]) -> int:
    changed = 0
    now = utc_now()
    for job in state.get("jobs", {}).values():
        if isinstance(job, dict) and apply_publication_state(job, now=now):
            changed += 1
    return changed


def public_job(job: dict[str, Any]) -> dict[str, Any]:
    result = job.get("result")
    if isinstance(result, dict):
        result = sanitize_public_result(result)
    publication = publication_entry(job, compact=True)
    public = {
        "job_id": job.get("job_id"),
        "url": job.get("url"),
        "channel": job.get("channel"),
        "status": job.get("status"),
        "submitted_at": job.get("submitted_at"),
        "claimed_at": job.get("claimed_at"),
        "completed_at": job.get("completed_at"),
        "model_key": job.get("model_key"),
        "worker": job.get("worker"),
        "route_target": job.get("route_target") or job.get("channel"),
        "route_auto": job.get("route_auto"),
        "route_reason": job.get("route_reason"),
        "publication_status": job.get("publication_status"),
        "publication": publication,
        "result": result,
        "error": public_job_error(job.get("error")),
    }
    return {key: value for key, value in public.items() if value is not None}


def sanitize_result(result: dict[str, Any], excerpt_word_limit: int | None = 24) -> dict[str, Any]:
    clean = copy.deepcopy(result)
    if isinstance(clean.get("result"), dict):
        clean = clean["result"]
    clean.pop("raw_output", None)
    source = clean.get("source")
    if isinstance(source, dict):
        source.pop("text", None)
        # Extraction gateways sometimes report an intermediate asset URL with
[redacted secret-like line]
        # submitted article URL is already public; the internal canonical
        # extraction target is not part of the public API contract.
        source.pop("canonical_url", None)
    for claim in clean.get("claims") or []:
        if isinstance(claim, dict):
            excerpt = claim.get("relevant_excerpt")
            if isinstance(excerpt, str) and excerpt_word_limit is not None:
                claim["relevant_excerpt"] = short_words(excerpt, excerpt_word_limit)
    return clean


def sanitize_public_result(
    result: dict[str, Any], excerpt_word_limit: int | None = 24,
) -> dict[str, Any] | None:
    """Apply the shared public boundary, then the Codex excerpt limit."""
    clean = public_result_payload(result)
    if not isinstance(clean, dict):
        return None
    for claim in clean.get("claims") or []:
        if isinstance(claim, dict):
            excerpt = claim.get("relevant_excerpt")
            if isinstance(excerpt, str) and excerpt_word_limit is not None:
                claim["relevant_excerpt"] = short_words(excerpt, excerpt_word_limit)
    return clean


def allowed_path(path: str) -> Path | None:
    route = "/" if path == "/" else unquote(path)
    if route == "/":
        target = BASE / "index.html"
    elif route in {"/ai-disclosure", "/ai-disclosure/"}:
        target = BASE / "ai-disclosure.html"
    elif route in {
        "/data/seed.js",
        "/data/stories.js",
        "/data/stories.json",
        "/data/doom-markets.js",
        "/data/doom-markets.json",
        "/robots.txt",
        "/sitemap.xml",
        "/fixtures/scoring-smoke.html",
    }:
        target = (BASE / route.lstrip("/")).resolve()
    elif route.startswith("/assets/"):
        target = (BASE / route.lstrip("/")).resolve()
        try:
            target.relative_to((BASE / "assets").resolve())
        except ValueError:
            return None
        if target.suffix.lower() not in {
            ".css", ".js", ".png", ".ico", ".svg", ".jpg", ".jpeg",
            ".webp", ".woff", ".woff2",
        }:
            return None
    else:
        return None
    try:
        target.relative_to(BASE)
    except ValueError:
        return None
    if any(part.startswith(".") for part in target.relative_to(BASE).parts):
        return None
    if not target.is_file():
        return None
    return target


def content_type(path: Path) -> str:
    suffix = path.suffix.lower()
    if suffix == ".html":
        return "text/html; charset=utf-8"
    if suffix == ".css":
        return "text/css; charset=utf-8"
    if suffix == ".js":
        return "text/javascript; charset=utf-8"
    if suffix == ".json":
        return "application/json; charset=utf-8"
    if suffix == ".xml":
        return "application/xml; charset=utf-8"
    if suffix == ".svg":
        return "image/svg+xml"
    if suffix == ".ico":
        return "image/x-icon"
    if suffix == ".png":
        return "image/png"
    if suffix in {".jpg", ".jpeg"}:
        return "image/jpeg"
    return "application/octet-stream"


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", ".localhost")):
        return False
    try:
        cleaned = cleaned.encode("idna").decode("ascii")
    except UnicodeError:
        return False
    try:
        addresses = [ipaddress.ip_address(cleaned)]
    except ValueError:
        try:
            infos = socket.getaddrinfo(cleaned, None, type=socket.SOCK_STREAM)
        except OSError:
            return False
        addresses = []
        for info in infos:
            try:
                addresses.append(ipaddress.ip_address(info[4][0]))
            except ValueError:
                return False
    return bool(addresses) and all(address.is_global for address in addresses)


def valid_url(url: str) -> bool:
    if len(url) > 2000:
        return False
    parsed = urlparse(url)
    if parsed.scheme not in {"http", "https"} or not parsed.hostname:
        return False
    return public_host_allowed(parsed.hostname)


def client_id(headers: Any, remote: str | None) -> str:
    forwarded = headers.get("CF-Connecting-IP") or headers.get("X-Forwarded-For")
    if forwarded:
        return forwarded.split(",", 1)[0].strip()
    return remote or "unknown"


def rate_limited(key: str) -> bool:
    now = time.time()
    bucket = RATE_STORE.setdefault(key, [])
    bucket[:] = [stamp for stamp in bucket if now - stamp < RATE_LIMIT_WINDOW]
    if len(bucket) >= RATE_LIMIT_MAX:
        return True
    bucket.append(now)
    return False


def read_stories() -> dict[str, Any]:
    if not STORIES_PATH.exists():
        return {"generatedAt": utc_now(), "count": 0, "stories": []}
    try:
        return json.loads(STORIES_PATH.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return {"generatedAt": utc_now(), "count": 0, "stories": []}


def read_doom_markets() -> dict[str, Any]:
    if not DOOM_MARKETS_PATH.exists():
        return {
            "generatedAt": utc_now(),
            "summary": {
                "doom_index": 0,
                "market_pressure": 0,
                "official_pressure": 0,
                "market_count": 0,
                "oracle_verdict": "No market signal snapshot has been generated yet.",
            },
            "signals": [],
            "official_indicators": [],
            "poll_watchlist": [],
            "source_notes": [],
            "errors": [],
        }
    try:
        return json.loads(DOOM_MARKETS_PATH.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return {
            "generatedAt": utc_now(),
            "summary": {
                "doom_index": 0,
                "market_pressure": 0,
                "official_pressure": 0,
                "market_count": 0,
                "oracle_verdict": "The market signal snapshot is temporarily unreadable.",
            },
            "signals": [],
            "official_indicators": [],
            "poll_watchlist": [],
            "source_notes": [],
            "errors": ["doom-markets.json could not be decoded"],
        }


def stories_with_jobs() -> dict[str, Any]:
    body = read_stories()
    stories = body.get("stories")
    if not isinstance(stories, list):
        stories = []
    state = read_state()
    merged = []
    for story in stories:
        if not isinstance(story, dict):
            continue
        clean = dict(story)
        _job_id, job = find_job_by_story_key(state, story_key(clean.get("url")))
        if job:
            clean["job"] = public_job(job)
        merged.append(clean)
    body["stories"] = merged
    body["count"] = len(merged)
    return body


def html_escape(value: Any) -> str:
    return html_lib.escape(str(value or ""), quote=True)


def json_ld(data: dict[str, Any]) -> str:
    return json.dumps(data, ensure_ascii=False, allow_nan=False).replace("</", "<\\/")


def render_oracle_page(entry: dict[str, Any]) -> str:
    evidence_items = "".join(
        f"<li>{html_escape(item)}</li>"
        for item in entry.get("evidence_used", [])[:4]
    )
    excerpt = entry.get("relevant_excerpt")
    excerpt_markup = f"<blockquote>{html_escape(excerpt)}</blockquote>" if excerpt else ""
    title = entry.get("claim_summary") or "Oracle entry"
    source_title = entry.get("source_title") or entry.get("source_url") or "Source"
    canonical_url = entry.get("url") or f"{PUBLIC_BASE_URL}{entry.get('path') or ''}"
    schema = {
        "@context": "https://schema.org",
        "@type": "Article",
        "headline": title,
        "description": entry.get("oracle_summary"),
        "url": canonical_url,
        "datePublished": entry.get("published_at"),
        "isBasedOn": entry.get("source_url"),
        "publisher": {
            "@type": "Organization",
            "name": "CopeCheck",
            "url": "https://www.copecheck.com/",
        },
        "mainEntityOfPage": canonical_url,
    }
    return f"""<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{html_escape(title)} - CopeCheck Oracle</title>
    <meta name="description" content="{html_escape(entry.get('oracle_summary'))}">
    <meta property="og:title" content="{html_escape(title)}">
    <meta property="og:description" content="{html_escape(entry.get('oracle_summary'))}">
    <meta property="og:type" content="article">
    <meta property="og:url" content="{html_escape(canonical_url)}">
    <link rel="canonical" href="{html_escape(canonical_url)}">
    <link rel="icon" href="data:,">
    <link rel="stylesheet" href="/assets/styles.css?v=20260509-oracle">
    <script type="application/ld+json">{json_ld(schema)}</script>
  </head>
  <body class="oracle-page">
    <header class="site-header">
      <a class="brand" href="/" aria-label="CopeCheck Codex home">
        <span class="brand-mark">CC</span>
        <span class="brand-copy"><strong>CopeCheck</strong><small>Oracle</small></span>
      </a>
      <nav class="top-nav" aria-label="Oracle navigation">
        <a href="/#oracle">Oracle</a>
        <a href="/#stories">Stories</a>
        <a href="/#submit">Score URL</a>
      </nav>
      <a class="header-action" href="{html_escape(entry.get('source_url'))}" target="_blank" rel="noreferrer">Open Source</a>
    </header>
    <main>
      <article class="oracle-detail">
        <aside class="cc-ai-label" role="note"><strong>AI-generated analysis</strong> This score and summary were produced by an AI model. <a href="/ai-disclosure">How CopeCheck uses AI</a>.</aside>
        <div class="oracle-detail-score {html_escape(score_class_name(entry.get('score')))}">
          <strong>{html_escape(entry.get('score'))}</strong>
          <span>{html_escape(entry.get('band'))}</span>
        </div>
        <div class="oracle-detail-copy">
          <p class="overline">{html_escape(entry.get('channel'))} / {html_escape(entry.get('mode'))}</p>
          <h1>{html_escape(title)}</h1>
          <p class="hero-lede">{html_escape(entry.get('oracle_summary'))}</p>
          <div class="oracle-facts">
            <span>{html_escape(entry.get('publisher') or 'Source captured')}</span>
            <span>{html_escape(entry.get('person') or 'Attributed claim')}</span>
            <span>{round(float(entry.get('confidence') or 0) * 100)}% confidence</span>
          </div>
          <section>
            <h2>Source</h2>
            <p><a href="{html_escape(entry.get('source_url'))}" target="_blank" rel="noreferrer">{html_escape(source_title)}</a></p>
          </section>
          <section>
            <h2>Oracle Rationale</h2>
            <p>{html_escape(entry.get('rationale_short'))}</p>
            {excerpt_markup}
          </section>
          <section>
            <h2>Evidence Used</h2>
            <ul>{evidence_items}</ul>
          </section>
        </div>
      </article>
    </main>
    <footer class="site-footer"><p class="cc-ai-footer"><strong>AI disclosure:</strong> This analysis is AI-generated and may contain errors. <a href="/ai-disclosure">Full disclosure</a>.</p></footer>
  </body>
</html>"""


def score_class_name(score: Any) -> str:
    try:
        score_value = int(score)
    except (TypeError, ValueError):
        score_value = 0
    if score_value >= 80:
        return "terminal"
    if score_value >= 60:
        return "heavy"
    if score_value >= 40:
        return "partial"
    if score_value >= 20:
        return "somewhat"
    return "lucid"


class CodexHandler(BaseHTTPRequestHandler):
    server_version = "CopeCheckCodex/0.2"

    def log_message(self, fmt: str, *args: object) -> None:
        if os.getenv("COPECHECK_CODEX_VERBOSE"):
            super().log_message(fmt, *args)

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

    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_html(self, status: int, body: str, head_only: bool = False) -> None:
        raw = body.encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(raw)))
        self.send_header("Cache-Control", "public, max-age=60, stale-while-revalidate=300")
        self.send_security_headers()
        self.end_headers()
        if head_only:
            return
        self.wfile.write(raw)

    def send_static(self, target: Path, head_only: bool = False) -> None:
        raw = target.read_bytes()
        self.send_response(200)
        self.send_header("Content-Type", content_type(target))
        self.send_header("Content-Length", str(len(raw)))
        if target.parts[-2:-1] == ("assets",) or target.suffix in {".css", ".js"}:
            self.send_header("Cache-Control", "public, max-age=300, stale-while-revalidate=3600")
        else:
            self.send_header("Cache-Control", "public, max-age=60, stale-while-revalidate=300")
        self.send_security_headers()
        self.end_headers()
        if head_only:
            return
        self.wfile.write(raw)

    def read_json(self) -> dict[str, Any]:
        length = int(self.headers.get("Content-Length", "0"))
        if length <= 0:
            return {}
        return json.loads(self.rfile.read(length).decode("utf-8"))

    def authorized(self) -> bool:
[redacted secret-like line]
[redacted secret-like line]
            return False
[redacted secret-like line]

    def do_OPTIONS(self) -> None:
        self.send_response(204)
        self.send_header("Access-Control-Allow-Origin", "https://codex.copecheck.com")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
[redacted secret-like line]
        self.send_header("Access-Control-Max-Age", "86400")
        self.end_headers()

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

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

    def handle_read(self, head_only: bool = False) -> None:
        parsed = urlparse(self.path)
        if parsed.path == "/healthz":
            try:
                state = read_state()
                jobs = state.get("jobs")
                if not isinstance(jobs, dict):
                    raise ValueError("jobs state is not an object")
            except (OSError, json.JSONDecodeError, ValueError):
                self.send_json(
                    503,
                    {"ok": False, "service": "copecheck-codex", "error": "state_unreadable"},
                    head_only=head_only,
                )
                return
            self.send_json(
                200,
                {"ok": True, "service": "copecheck-codex", "jobs": len(jobs)},
                head_only=head_only,
            )
            return
        if parsed.path == "/api/stories":
            self.send_json(200, {"ok": True, "feed": stories_with_jobs()}, head_only=head_only)
            return
        if parsed.path in {"/api/doom-markets", "/api/doom-markets.json"}:
            self.send_json(200, {"ok": True, "feed": read_doom_markets()}, head_only=head_only)
            return
        if parsed.path == "/api/oracle":
            self.get_oracle_list(parse_qs(parsed.query), head_only=head_only)
            return
        oracle_api_match = re.fullmatch(r"/api/oracle/(cc_[a-f0-9]{16})", parsed.path)
        if oracle_api_match:
            self.get_oracle_entry(oracle_api_match.group(1), head_only=head_only)
            return
        if parsed.path == "/api/jobs/pending":
            self.get_pending(parse_qs(parsed.query), head_only=head_only)
            return
        if parsed.path.startswith("/api/jobs/"):
            self.get_job(parsed.path.rsplit("/", 1)[-1], head_only=head_only)
            return
        oracle_page_match = re.fullmatch(r"/oracle/(?:[a-z0-9_-]+/)?(cc_[a-f0-9]{16})", parsed.path)
        if oracle_page_match:
            self.get_oracle_page(oracle_page_match.group(1), head_only=head_only)
            return
        target = allowed_path(parsed.path)
        if not target:
            self.send_error(HTTPStatus.NOT_FOUND)
            return
        self.send_static(target, head_only=head_only)

    def do_POST(self) -> None:
        parsed = urlparse(self.path)
        if parsed.path == "/api/jobs":
            self.create_job()
            return
        match = re.fullmatch(r"/api/jobs/([^/]+)/result", parsed.path)
        if match:
            self.save_result(match.group(1))
            return
        self.send_json(404, {"ok": False, "error": "not_found"})

    def create_job(self) -> None:
        ip = client_id(self.headers, self.client_address[0] if self.client_address else None)
        if rate_limited(ip):
            self.send_json(429, {"ok": False, "error": "rate_limited"})
            return
        try:
            payload = self.read_json()
        except json.JSONDecodeError:
            self.send_json(400, {"ok": False, "error": "invalid_json"})
            return
        url = str(payload.get("url") or "").strip()
        if not valid_url(url):
            self.send_json(400, {"ok": False, "error": "invalid_url"})
            return
        requested_channel = str(payload.get("channel") or "auto").strip().lower()
        route_auto = requested_channel in {"", "auto", "detect"}
        if route_auto:
            channel, route_reason = detect_route(url)
        else:
            channel = requested_channel if requested_channel in PUBLIC_CHANNELS else "main"
            route_reason = "selected channel"
        model_key = str(payload.get("model_key") or os.getenv("COPECHECK_PUBLIC_MODEL_KEY") or "minimax-quality")
        job_id = canonical_job_id(url) or f"cc_{uuid.uuid4().hex[:16]}"
        job = {
            "job_id": job_id,
            "url": url,
            "channel": channel,
            "status": "queued",
            "submitted_at": utc_now(),
            "model_key": model_key,
            "worker": "mac-openclaw",
            "attempts": 0,
            "source": "manual",
            "priority": 0,
            "route_target": channel,
            "route_auto": route_auto,
            "route_reason": route_reason,
        }
        ensure_job_identity(job, job_id)
        with STATE_LOCK, state_file_lock(STATE_PATH):
            state = _read_state_unlocked()
            existing_id, existing = find_job_by_story_key(state, story_key(url))
            if existing_id and existing:
                changed = add_job_provenance(
                    existing,
                    # This is another discovery of the existing state row,
                    # not a second historic job row.
                    provenance_observation(job, include_legacy_id=False),
                )
                register_story_aliases(state, existing_id, existing)
                if changed:
                    _write_state_unlocked(state)
                self.send_json(200, {
                    "ok": True,
                    "deduplicated": True,
                    "job": public_job(existing),
                })
                return
            if job_id in state.setdefault("jobs", {}):
                job_id = f"cc_{uuid.uuid4().hex[:16]}"
                job["job_id"] = job_id
                ensure_job_identity(job, job_id)
            state.setdefault("jobs", {})[job_id] = job
            register_story_aliases(state, job_id, job)
            _write_state_unlocked(state)
        self.send_json(201, {"ok": True, "job": public_job(job)})

    def get_job(self, job_id: str, head_only: bool = False) -> None:
        if not re.fullmatch(r"cc_[a-f0-9]{16}", job_id):
            self.send_json(404, {"ok": False, "error": "not_found"}, head_only=head_only)
            return
        with STATE_LOCK:
            _resolved_id, job = resolve_job(read_state(), job_id)
        if not job:
            self.send_json(404, {"ok": False, "error": "not_found"}, head_only=head_only)
            return
        self.send_json(200, {"ok": True, "job": public_job(job)}, head_only=head_only)

    def get_oracle_list(self, query: dict[str, list[str]], head_only: bool = False) -> None:
        limit = 18
        if query.get("limit"):
            try:
                limit = max(1, min(80, int(query["limit"][0])))
            except ValueError:
                limit = 18
        with STATE_LOCK:
            entries = published_entries(read_state(), limit=limit)
        for entry in entries:
            entry["ai_disclosure"] = AI_DISCLOSURE_TEXT
        self.send_json(200, {"ok": True, "count": len(entries), "ai_disclosure": AI_DISCLOSURE_TEXT, "entries": entries}, head_only=head_only)

    def get_oracle_entry(self, job_id: str, head_only: bool = False) -> None:
        with STATE_LOCK:
            _resolved_id, job = resolve_job(read_state(), job_id)
        if not isinstance(job, dict):
            self.send_json(404, {"ok": False, "error": "not_found"}, head_only=head_only)
            return
        entry = publication_entry(job)
        if not entry:
            self.send_json(404, {"ok": False, "error": "not_published"}, head_only=head_only)
            return
        entry["ai_disclosure"] = AI_DISCLOSURE_TEXT
        self.send_json(200, {"ok": True, "ai_disclosure": AI_DISCLOSURE_TEXT, "entry": entry}, head_only=head_only)

    def get_oracle_page(self, job_id: str, head_only: bool = False) -> None:
        with STATE_LOCK:
            _resolved_id, job = resolve_job(read_state(), job_id)
        if not isinstance(job, dict):
            self.send_error(HTTPStatus.NOT_FOUND)
            return
        entry = publication_entry(job)
        if not entry:
            self.send_error(HTTPStatus.NOT_FOUND)
            return
        self.send_html(200, render_oracle_page(entry), head_only=head_only)

    def get_pending(self, query: dict[str, list[str]], head_only: bool = False) -> None:
        if not self.authorized():
            self.send_json(401, {"ok": False, "error": "unauthorized"}, head_only=head_only)
            return
        if head_only:
            self.send_json(200, {"ok": True, "jobs": []}, head_only=True)
            return
        limit = 3
        if query.get("limit"):
            try:
                limit = max(1, min(10, int(query["limit"][0])))
            except ValueError:
                limit = 3
        now = utc_now()
        claimed: list[dict[str, Any]] = []
        with STATE_LOCK, state_file_lock(STATE_PATH):
            state = _read_state_unlocked()
            claimable_by_channel: dict[str, list[dict[str, Any]]] = {}
            manual_claims: list[dict[str, Any]] = []
            for job in state.setdefault("jobs", {}).values():
                status = job.get("status")
                stale_claim = False
                if status == "claimed" and job.get("claimed_at"):
                    try:
                        claimed_at = datetime.fromisoformat(str(job["claimed_at"]).replace("Z", "+00:00"))
                        stale_claim = time.time() - claimed_at.timestamp() > 900
                    except ValueError:
                        stale_claim = True
                if status == "queued" or stale_claim:
                    channel = str(job.get("route_target") or job.get("channel") or "main")
                    if is_manual_priority(job):
                        manual_claims.append(job)
                    else:
                        claimable_by_channel.setdefault(channel, []).append(job)

            def claim(job: dict[str, Any]) -> None:
                job["status"] = "claimed"
                job["claimed_at"] = now
                job["attempts"] = int(job.get("attempts") or 0) + 1
                claimed.append(job.copy())

            manual_claims.sort(key=queue_sort_key)
            while manual_claims and len(claimed) < limit:
                claim(manual_claims.pop(0))

            for jobs in claimable_by_channel.values():
                jobs.sort(key=queue_sort_key)

            channels = [channel for channel in QUEUE_CHANNEL_ORDER if channel in claimable_by_channel]
            channels.extend(channel for channel in claimable_by_channel if channel not in QUEUE_CHANNEL_ORDER)
            base_order = QUEUE_CHANNEL_ORDER + [channel for channel in channels if channel not in QUEUE_CHANNEL_ORDER]
            while channels and len(claimed) < limit:
                try:
                    cursor = int(state.get("queue_cursor") or 0) % max(1, len(base_order))
                except (TypeError, ValueError):
                    cursor = 0
                ordered = base_order[cursor:] + base_order[:cursor]
                progressed = False
                for channel in ordered:
                    jobs = claimable_by_channel.get(channel) or []
                    if not jobs:
                        continue
                    job = jobs.pop(0)
                    claim(job)
                    state["queue_cursor"] = (base_order.index(channel) + 1) % len(base_order)
                    progressed = True
                    if len(claimed) >= limit:
                        break
                if not progressed:
                    break
            _write_state_unlocked(state)
        self.send_json(200, {"ok": True, "jobs": claimed}, head_only=head_only)

    def save_result(self, job_id: str) -> None:
        if not self.authorized():
            self.send_json(401, {"ok": False, "error": "unauthorized"})
            return
        try:
            payload = self.read_json()
        except json.JSONDecodeError:
            self.send_json(400, {"ok": False, "error": "invalid_json"})
            return
        with STATE_LOCK, state_file_lock(STATE_PATH):
            state = _read_state_unlocked()
            resolved_id, job = resolve_job(state, job_id)
            if not job:
                self.send_json(404, {"ok": False, "error": "not_found"})
                return
            if resolved_id != job_id:
                self.send_json(200, {
                    "ok": True,
                    "deduplicated": True,
                    "ignored": "archived_alias_callback",
                    "job": public_job(job),
                })
                return
            result = payload.get("result")
            invalid_score = result_has_invalid_cope_score(result)
            failed_callback = (
                payload.get("ok") is False
                or not isinstance(result, dict)
                or invalid_score
            )
            terminal_success = (
                job.get("status") in {"complete", "needs_review", "discarded"}
                and isinstance(job.get("result"), dict)
            )
            if terminal_success:
                # Terminal representatives are immutable until a future
[redacted secret-like line]
                self.send_json(200, {
                    "ok": True,
                    "deduplicated": True,
                    "ignored": "terminal_result_immutable",
                    "job": public_job(job),
                })
                return
            if failed_callback:
                job["status"] = "failed"
                job["error"] = (
                    "invalid_cope_score"
                    if invalid_score
                    else payload.get("error") or "worker_failed"
                )
                if invalid_score:
                    job["rejected_result"] = private_diagnostic_snapshot(result)
                job.pop("result", None)
            else:
                result_status = str(result.get("status") or "complete")
                job["status"] = "needs_review" if result_status == "needs_review" else result_status
                job["result"] = sanitize_result(result, excerpt_word_limit=None)
                job.pop("rejected_result", None)
                job.pop("error", None)
                job["processed_by"] = payload.get("worker") or "mac-openclaw"
                if job.get("route_auto"):
                    route_target, route_reason = detect_route(str(job.get("url") or ""), job["result"], job)
                    job["channel"] = route_target
                    job["route_target"] = route_target
                    job["route_reason"] = route_reason
            job["completed_at"] = utc_now()
            ensure_job_identity(job, resolved_id)
            # The discovery capture already represents this job's legacy ID.
            # Keep result-derived publisher/quote metadata as a separate audit
            # observation without claiming the same legacy row twice.
            add_job_provenance(
                job,
                provenance_observation(job, include_legacy_id=False),
            )
            register_story_aliases(state, resolved_id, job)
            apply_publication_state(job)
            publish_to_subdomain(job)
            _write_state_unlocked(state)
        self.send_json(200, {"ok": True, "job": public_job(job)})


def main() -> None:
    load_env()
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default=os.getenv("COPECHECK_CODEX_HOST", "127.0.0.1"))
    parser.add_argument("--port", type=int, default=int(os.getenv("COPECHECK_CODEX_PORT", "8105")))
    args = parser.parse_args()
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    server = ThreadingHTTPServer((args.host, args.port), CodexHandler)
    print(json.dumps({"service": "copecheck-codex", "host": args.host, "port": args.port}), flush=True)
    server.serve_forever()


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