---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import hashlib import html import json import re import tempfile import sys import time import urllib.parse import urllib.request import xml.etree.ElementTree as ET."
resource: "https://codex.copecheck.com/tools/fetch_rss_stories.py"
tags: ["copecheck", "codex", "source-file", "py"]
timestamp: "2026-08-25T12:19:38Z"
site: "codex"
source_path: "copecheck-codex/tools/fetch_rss_stories.py"
---

# from __future__ import annotations

Source path: `copecheck-codex/tools/fetch_rss_stories.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-25T12:19:38Z`

```py
from __future__ import annotations

import argparse
import hashlib
import html
import json
import re
import tempfile
import sys
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from canonical_identity import canonical_url, canonical_url_hash, same_event, provenance_key  # noqa: E402
from story_state import (  # noqa: E402
    JobEventIndex,
    add_job_provenance,
    atomic_write_json,
    canonical_job_id,
    ensure_state_schema,
    ensure_job_identity,
    find_job_by_story_key,
    register_story_aliases,
    public_job_error,
    public_result_payload,
    state_file_lock,
    story_key,
)

DATA_DIR = ROOT / "data"
STATE_PATH = DATA_DIR / "jobs-state.json"
STORIES_JSON_PATH = DATA_DIR / "stories.json"
DEFAULT_FEEDS = [
    ROOT / "feeds" / "main-rss_feeds.json",
    ROOT / "feeds" / "uk-rss_feeds.json",
    ROOT / "feeds" / "layoffs-rss_feeds.json",
]
CHANNEL_ORDER = [
    "main",
    "uk",
    "layoffs",
    "countries",
    "eu",
    "policy",
    "cities",
    "data",
    "careers",
]
NS = {"atom": "http://www.w3.org/2005/Atom"}


@dataclass
class Story:
    channel: str
    feed: str
    title: str
    url: str
    source: str | None
    published: str | None
    summary: str | None
    provenance: list[dict] = field(default_factory=list)


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


def clean_google_alert_url(url: str) -> str:
    parsed = urllib.parse.urlparse(url)
    query = urllib.parse.parse_qs(parsed.query)
    for key in ("url", "q"):
        if query.get(key):
            candidate = query[key][0]
            if candidate.startswith(("http://", "https://")):
                return candidate
    return url


def channel_from_feed_file(path: Path) -> str:
    name = path.name
    if "uk-" in name:
        return "uk"
    if "layoffs" in name:
        return "layoffs"
    return "main"


def load_feed_files(paths: list[Path]) -> list[tuple[str, dict]]:
    feeds: list[tuple[str, dict]] = []
    for path in paths:
        data = json.loads(path.read_text(encoding="utf-8"))
        channel = channel_from_feed_file(path)
        for feed in data.get("feeds", []):
            feeds.append((channel, feed))
    return feeds


def fetch_url(url: str, timeout: int) -> bytes:
    request = urllib.request.Request(
        url,
        headers={
            "User-Agent": "CopeCheckCodex/0.2 (+https://codex.copecheck.com)",
            "Accept": "application/atom+xml, application/rss+xml, application/xml;q=0.9, */*;q=0.8",
        },
    )
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return response.read()


def parse_atom(raw: bytes, channel: str, feed_name: str) -> list[Story]:
    root = ET.fromstring(raw)
    entries = root.findall("atom:entry", NS)
    stories: list[Story] = []
    for entry in entries:
        title = clean_text(entry.findtext("atom:title", default="", namespaces=NS))
        if not title:
            continue
        link = ""
        for link_tag in entry.findall("atom:link", NS):
            href = link_tag.attrib.get("href")
            if href:
                link = href
                break
        if not link:
            continue
        source = entry.findtext("atom:source/atom:title", default="", namespaces=NS)
        summary = clean_text(entry.findtext("atom:content", default="", namespaces=NS))
        if not summary:
            summary = clean_text(entry.findtext("atom:summary", default="", namespaces=NS))
        stories.append(
            Story(
                channel=channel,
                feed=feed_name,
                title=title,
                url=clean_google_alert_url(link),
                source=clean_text(source) or None,
                published=entry.findtext("atom:published", default="", namespaces=NS)
                or entry.findtext("atom:updated", default="", namespaces=NS)
                or None,
                summary=summary[:280] if summary else None,
            )
        )
    return stories


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


def story_sort_key(story: Story) -> str:
    return normalize_date(story.published)


def _story_datetime(story: Story):
    try:
        value = datetime.fromisoformat(str(story.published or "").replace("Z", "+00:00"))
        return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
    except ValueError:
        return None


def story_observation(story: Story) -> dict:
    canonical = canonical_url(story.url)
    key_title = f"{story.title}\nsource:{story.source or ''}\nfeed:{story.feed}\nchannel:{story.channel}"
    return {
        "observation_key": provenance_key(canonical, key_title, story.summary or ""),
        "raw_url": story.url,
        "canonical_url": canonical,
        "source_title": story.title,
        "publisher": story.source,
        "source": "rss",
        "feed": story.feed,
        "channel": story.channel,
        "observed_at": story.published,
    }


def dedupe_story_events(stories: list[Story], event_window_days: int = 3) -> list[Story]:
    """Collapse publisher variants while retaining feed/source/channel captures."""
    groups: list[Story] = []
    for story in sorted(stories, key=story_sort_key, reverse=True):
        observation = story_observation(story)
        matched = None
        for candidate in groups:
            exact_url = canonical_url(story.url) == canonical_url(candidate.url)
            left_dt, right_dt = _story_datetime(story), _story_datetime(candidate)
            within_window = bool(
                left_dt and right_dt
                and abs((left_dt - right_dt).total_seconds()) <= event_window_days * 86400
            )
            if exact_url or (within_window and same_event(
                canonical_a=canonical_url(story.url),
                title_a=story.title,
                quote_a=story.summary or "",
                canonical_b=canonical_url(candidate.url),
                title_b=candidate.title,
                quote_b=candidate.summary or "",
            )):
                matched = candidate
                break
        if matched is None:
            story.provenance = [observation]
            groups.append(story)
        elif not any(item.get("observation_key") == observation["observation_key"] for item in matched.provenance):
            matched.provenance.append(observation)
    return groups


def story_to_dict(story: Story) -> dict[str, str | None]:
    provenance = story.provenance or [story_observation(story)]
    return {
        "channel": story.channel,
        "channels": sorted({str(item.get("channel")) for item in provenance if item.get("channel")}),
        "feed": story.feed,
        "title": story.title,
        "url": story.url,
        "canonical_url": canonical_url(story.url),
        "story_key": story_key(story.url),
        "source": story.source,
        "published": story.published,
        "summary": story.summary,
        "provenance": provenance,
    }


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


def read_state(path: Path) -> dict:
    if not path.exists():
        return ensure_state_schema({"updated_at": utc_now()})
    # A corrupt state file must stop the writer.  Silently renaming it and
    # starting from an empty queue would discard the complete audit history.
    return ensure_state_schema(json.loads(path.read_text(encoding="utf-8")))


def write_state(path: Path, state: dict) -> None:
    ensure_state_schema(state)
    state["updated_at"] = utc_now()
    atomic_write_json(path, state)


def public_result(result: dict | None) -> dict | None:
    return public_result_payload(result)


def public_job(job: dict | None) -> dict | None:
    if not isinstance(job, dict):
        return None
    result = public_result(job.get("result"))
    return {
        key: value
        for key, value in {
            "job_id": job.get("job_id"),
            "status": job.get("status"),
            "channel": job.get("channel"),
            "model_key": job.get("model_key"),
            "submitted_at": job.get("submitted_at"),
            "completed_at": job.get("completed_at"),
            "route_target": job.get("route_target") or job.get("channel"),
            "result": result,
            "error": public_job_error(job.get("error")),
        }.items()
        if value is not None
    }


def story_job_id(url: str) -> str:
    return canonical_job_id(url)


def merge_jobs(stories: list[Story], state: dict) -> list[dict]:
    merged = []
    for story in stories:
        item = story_to_dict(story)
        _job_id, job = find_job_by_story_key(state, story_key(story.url))
        if job:
            item["job"] = public_job(job)
        merged.append(item)
    return merged


def select_display_stories(stories: list[Story], limit: int, per_channel_min: int) -> list[Story]:
    limit = max(0, limit)
    if limit <= 0:
        return []
    selected: list[Story] = []
    selected_keys: set[str] = set()
    if per_channel_min > 0:
        observed = {
            str(item.get("channel"))
            for story in stories
            for item in (story.provenance or [story_observation(story)])
            if item.get("channel")
        }
        channels = [channel for channel in CHANNEL_ORDER if channel in observed]
        channels.extend(
            channel
            for channel in sorted(observed)
            if channel not in CHANNEL_ORDER
        )
        for channel in channels:
            channel_count = 0
            for story in stories:
                if len(selected) >= limit or channel_count >= per_channel_min:
                    break
                key = story_key(story.url)
                observed_channels = {
                    str(item.get("channel"))
                    for item in story.provenance
                    if item.get("channel")
                } or {story.channel}
                if channel not in observed_channels or key in selected_keys:
                    continue
                selected.append(story)
                selected_keys.add(key)
                channel_count += 1
    for story in stories:
        if len(selected) >= limit:
            break
        key = story_key(story.url)
        if key in selected_keys:
            continue
        selected.append(story)
        selected_keys.add(key)
    selected.sort(key=story_sort_key, reverse=True)
    return selected


def enqueue_stories(
    stories: list[Story],
    state_path: Path,
    queue_limit: int,
    model_key: str,
    per_channel_limit: int,
) -> dict[str, int]:
    queued_by_channel: dict[str, int] = {}
    changed = False
    with state_file_lock(state_path):
        state = read_state(state_path)
        jobs = state.setdefault("jobs", {})
        for existing_id, existing in jobs.items():
            if isinstance(existing, dict):
                changed = ensure_job_identity(existing, str(existing_id)) or changed
                register_story_aliases(state, str(existing_id), existing)
        event_index = JobEventIndex(state)
        for story in stories:
            channel = story.channel or "main"
            key = story_key(story.url)
            job_id = story_job_id(story.url)
            candidate = {
                "job_id": job_id,
                "url": story.url,
                "canonical_url": canonical_url(story.url),
                "story_key": key,
                "channel": story.channel,
                "status": "queued",
                "submitted_at": utc_now(),
                "model_key": model_key,
                "worker": "mac-openclaw",
                "attempts": 0,
                "source": "rss",
                "priority": 50,
                "feed": story.feed,
                "story_title": story.title,
                "story_summary": story.summary,
                "story_published": story.published,
                "route_target": story.channel,
                "provenance": story.provenance or [story_observation(story)],
            }
            # Populate canonical/event fields before lookup, but do not claim
            # the prospective job ID yet.  A syndicated candidate may merge
            # into an existing owner and therefore never become a state row.
            ensure_job_identity(candidate)
            existing_id, existing = event_index.find(candidate)
            if existing:
                for observation in story.provenance or [story_observation(story)]:
                    changed = add_job_provenance(existing, observation) or changed
                register_story_aliases(state, str(existing_id), existing)
                # Make the newly observed publisher URL an immediate alias so
                # later scans do not need fuzzy matching to find this event.
                if key and state.setdefault("story_aliases", {}).get(key) != existing_id:
                    state["story_aliases"][key] = existing_id
                    event_index.register_story_key(key, str(existing_id))
                    changed = True
                continue
            if sum(queued_by_channel.values()) >= queue_limit:
                continue
            if per_channel_limit > 0 and queued_by_channel.get(channel, 0) >= per_channel_limit:
                continue
            if job_id in jobs:
                raise RuntimeError(f"canonical job-id collision for {job_id}")
            # Only a candidate that is actually inserted owns this legacy ID.
            ensure_job_identity(candidate, job_id)
            candidate["provenance_count"] = len(candidate["provenance"])
            candidate["channels"] = sorted({item["channel"] for item in candidate["provenance"] if item.get("channel")})
            jobs[job_id] = candidate
            register_story_aliases(state, job_id, candidate)
            event_index.add(job_id, candidate)
            changed = True
            queued_by_channel[channel] = queued_by_channel.get(channel, 0) + 1
        if changed:
            write_state(state_path, state)
    return queued_by_channel


def write_outputs(js_path: Path, json_path: Path, stories: list[Story], state_path: Path) -> None:
    generated_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
    with state_file_lock(state_path, exclusive=False):
        state = read_state(state_path)
    body = {
        "generatedAt": generated_at,
        "count": len(stories),
        "stories": merge_jobs(stories, state),
    }
    atomic_write_json(json_path, body)
    js = (
        "export const storyFeed = "
        + json.dumps(body, ensure_ascii=False, indent=2, allow_nan=False)
        + ";\n"
    )
    js_path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=js_path.parent, delete=False) as handle:
        handle.write(js)
        tmp_name = handle.name
    Path(tmp_name).replace(js_path)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--feed-file", action="append", type=Path)
    parser.add_argument("--out", type=Path, default=ROOT / "data" / "stories.js")
    parser.add_argument("--json-out", type=Path, default=STORIES_JSON_PATH)
    parser.add_argument("--state", type=Path, default=STATE_PATH)
    parser.add_argument("--limit", type=int, default=24)
    parser.add_argument("--auto-queue", action="store_true")
    parser.add_argument("--queue-limit", type=int, default=8)
    parser.add_argument("--queue-scan-limit", type=int)
    parser.add_argument("--per-channel-limit", type=int, default=0)
    parser.add_argument("--display-per-channel-min", type=int, default=0)
    parser.add_argument("--model-key", default="minimax-quality")
    parser.add_argument("--timeout", type=int, default=15)
    args = parser.parse_args()

    feed_files = args.feed_file or [path for path in DEFAULT_FEEDS if path.exists()]
    feeds = load_feed_files(feed_files)
    stories: list[Story] = []
    errors: list[str] = []
    for channel, feed in feeds:
        name = str(feed.get("name") or channel)
        url = str(feed.get("url") or "")
        if not url:
            continue
        try:
            raw = fetch_url(url, timeout=args.timeout)
            feed_stories = parse_atom(raw, channel=channel, feed_name=name)
        except Exception as exc:
            errors.append(f"{name}: {type(exc).__name__}: {exc}")
            continue
        stories.extend(feed_stories)
        time.sleep(0.2)

    stories = dedupe_story_events(stories)
    stories.sort(key=story_sort_key, reverse=True)
    display_stories = select_display_stories(
        stories,
        limit=args.limit,
        per_channel_min=max(0, args.display_per_channel_min),
    )
    queue_scan_limit = args.queue_scan_limit if args.queue_scan_limit is not None else args.limit
    queue_candidates = stories[: max(0, queue_scan_limit)]
    queued_by_channel: dict[str, int] = {}
    if args.auto_queue:
        queued_by_channel = enqueue_stories(
            stories=queue_candidates,
            state_path=args.state,
            queue_limit=max(0, args.queue_limit),
            per_channel_limit=max(0, args.per_channel_limit),
            model_key=args.model_key,
        )
    write_outputs(args.out, args.json_out, display_stories, args.state)
    print(
        json.dumps(
            {
                "stories": len(display_stories),
                "scanned": len(queue_candidates),
                "queued": sum(queued_by_channel.values()),
                "queued_by_channel": queued_by_channel,
                "errors": errors[:8],
            },
            ensure_ascii=False,
            allow_nan=False,
        )
    )
    return 0 if display_stories else 1


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