---
type: "Source File"
title: "\"\"\"CopeCheck v2 ingestion pipeline."
description: "\"\"\"CopeCheck v2 ingestion pipeline. Two modes: --news : Pull RSS feeds, filter, fetch articles, run through Oracle --cope : Scan for tracked figure quotes, score cope levels (no args) : Run both sequentially \"\"\" import."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-26T20:50:03Z"
site: "main"
source_path: "copecheck/pipeline.py"
---

# """CopeCheck v2 ingestion pipeline.

Source path: `copecheck/pipeline.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-26T20:50:03Z`

```py
"""CopeCheck v2 ingestion pipeline.

Two modes:
  --news    : Pull RSS feeds, filter, fetch articles, run through Oracle
  --cope    : Scan for tracked figure quotes, score cope levels
  (no args) : Run both sequentially
"""
import hashlib
import json
import logging
import os
import re
import signal
import sys
import time
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urljoin, urlsplit, urlunsplit

import feedparser
import requests
import trafilatura
import yaml
from dateutil import parser as dateparser

import db
import oracle
import sources
from content_quality import extraction_quality_issue

HOME_SCRAPER_URL = os.environ.get("FIRECRAWL_URL", "http://100.70.233.73:3002").rstrip("/")


def _short_words(value, limit=24):
    """Truncate text to limit words (Codex excerpt sanitisation)."""
    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 _score_relevance(title, snippet, one_liner, verdict_md):
    """Score 0-100 how relevant an article is to AI cope discourse."""
    import re as _re
    text = " ".join(filter(None, [title, snippet, one_liner])).lower()
    verdict = (verdict_md or "")[:2000].lower()
    score = 20
    high_kw = [
        r"\bcope\b", r"\bcoping\b", r"\bcopium\b", r"\bdenial\b",
        r"\bdeflect", r"\bdownplay", r"\bminimis", r"\bminimiz", r"\breassur",
        r"\bdisplac", r"\bobsolet", r"\breplace.*(?:job|work|human)",
        r"\bai.*(?:job|work|employ|labour|labor|layoff|replac|automa)",
        r"\b(?:job|work|employ|labour|labor|layoff).*\bai\b",
        r"\bautomation\b.*\b(?:job|work|employ|threat|risk|replac)",
        r"\bubi\b", r"\buniversal basic income\b",
        r"\bfuture of work\b", r"\bpost.?work\b", r"\bjobless\b",
        r"\bdiscontinuity\b", r"\bagent(?:ic|s)\b.*\b(?:replac|job|work|automa)",
        r"\bwhite.?collar\b", r"\bknowledge work",
        r"\blayoff", r"\bhiring freeze\b",
        r"\bwage.*(?:declin|stagna|collaps|pressur)",
        r"\bworker.*(?:displac|replac|threat|obsole)",
    ]
    med_kw = [
        r"\bartificial intelligence\b", r"\bllm\b", r"\blarge language model",
        r"\bgenerative ai\b", r"\bchatgpt\b", r"\bgpt\b",
        r"\bautomation\b", r"\bautomat",
        r"\bjob(?:s)?\b", r"\bemploy", r"\bunemploy",
        r"\blabou?r\b", r"\bworkforce\b", r"\bworker",
        r"\bwage(?:s)?\b", r"\bproductivity\b",
        r"\bagi\b", r"\bsuperintelligence\b",
    ]
    low_kw = [
        r"\bgame\b", r"\bgaming\b", r"\bsports?\b", r"\brecipe\b",
        r"\bweather\b", r"\bcelebrit", r"\bentertainment\b",
        r"\bmovie\b", r"\bfilm\b", r"\bmusic\b",
    ]
    for pat in high_kw:
        if _re.search(pat, text, _re.IGNORECASE):
            score += 8
    for pat in high_kw:
        if _re.search(pat, verdict, _re.IGNORECASE):
            score += 3
    for pat in med_kw:
        if _re.search(pat, text, _re.IGNORECASE):
            score += 3
    for pat in med_kw:
        if _re.search(pat, verdict, _re.IGNORECASE):
            score += 1
    for pat in low_kw:
        if _re.search(pat, text, _re.IGNORECASE):
            score -= 5
    if verdict:
        if _re.search(r"tangential|not.*relevant|off.?topic|puff piece|human.?interest", verdict):
            score -= 15
        if _re.search(r"cope.*score|cope.*level|discontinuity thesis|dt lens|oracle.*verdict", verdict):
            score += 10
    return max(0, min(100, score))

log = logging.getLogger("pipeline")

MAX_NEW_PER_RUN = int(os.environ.get("COPECHECK_MAX_NEW", "30"))
MAX_ANALYSE_PER_RUN = int(os.environ.get("COPECHECK_MAX_ANALYSE", "12"))
MAX_COPE_SCAN_PER_FIGURE = int(os.environ.get("COPECHECK_MAX_COPE_SCAN", "3"))
MIN_BODY_CHARS = 350
CONNECT_TIMEOUT = float(os.environ.get("COPECHECK_CONNECT_TIMEOUT", "5"))
FETCH_TIMEOUT = float(os.environ.get("COPECHECK_FETCH_TIMEOUT", "15"))
FEED_TIMEOUT = float(os.environ.get("COPECHECK_FEED_TIMEOUT", "15"))
ARTICLE_TIMEOUT = float(os.environ.get("COPECHECK_ARTICLE_TIMEOUT", "20"))
MAX_ARTICLE_BYTES = int(os.environ.get("COPECHECK_MAX_ARTICLE_BYTES", str(5 * 1024 * 1024)))
MAX_FEED_BYTES = int(os.environ.get("COPECHECK_MAX_FEED_BYTES", str(2 * 1024 * 1024)))
MAX_REDIRECTS = int(os.environ.get("COPECHECK_MAX_REDIRECTS", "5"))
MAX_ARTICLE_FETCHES_PER_RUN = int(os.environ.get("COPECHECK_MAX_ARTICLE_FETCHES", "20"))
MAX_RSS_ARTICLE_FETCHES = int(os.environ.get("COPECHECK_MAX_RSS_ARTICLE_FETCHES", "15"))
MAX_GNEWS_ARTICLE_FETCHES = int(os.environ.get("COPECHECK_MAX_GNEWS_ARTICLE_FETCHES", "1"))
HTTP_USER_AGENT = os.environ.get(
    "COPECHECK_HTTP_USER_AGENT",
    "CopeCheck/2.0 (+https://www.copecheck.com/about)",
)
RUN_STATUS_PATH = Path(__file__).parent / "logs" / "pipeline-status.json"

# Quality gate constants (ported from Codex)
AUTO_PUBLISH_ATTRIBUTION = {"direct_quote", "named_paraphrase", "contextual_attribution", "institutional_report"}
MIN_CONFIDENCE = 0.6

FIGURES_PATH = Path(__file__).parent / "figures.yaml"

RSS_FEEDS_PATH = Path(__file__).parent / "rss_feeds.json"


class DownloadLimitError(RuntimeError):
    """Raised when a remote response exceeds the configured byte limit."""


class OperationDeadlineExceeded(TimeoutError):
    """Raised when a full fetch/extraction operation exceeds its wall clock."""


@contextmanager
def _wall_clock_deadline(seconds: float, label: str):
    """Bound Python and native-library work on the pipeline's main thread."""
    if seconds <= 0 or not hasattr(signal, "setitimer"):
        yield
        return
    try:
        previous_handler = signal.getsignal(signal.SIGALRM)
        started = time.monotonic()

        def _deadline_handler(_signum, _frame):
            raise OperationDeadlineExceeded(
                f"{label} exceeded {seconds:.1f}s wall-clock deadline"
            )

        signal.signal(signal.SIGALRM, _deadline_handler)
        previous_timer = signal.setitimer(signal.ITIMER_REAL, seconds)
    except (AttributeError, ValueError):
        # Signal timers are unavailable outside the main thread. Network calls
        # remain bounded by connect/read deadlines in that unusual context.
        yield
        return
    try:
        yield
    finally:
        elapsed = time.monotonic() - started
        signal.setitimer(signal.ITIMER_REAL, 0)
        signal.signal(signal.SIGALRM, previous_handler)
        if previous_timer[0] > 0:
            remaining = max(0.001, previous_timer[0] - elapsed)
            signal.setitimer(signal.ITIMER_REAL, remaining, previous_timer[1])


class ArticleFetchBudget:
    """Shared run budget for page downloads across ingestion channels."""

    def __init__(self, limit: int):
        self.limit = max(0, int(limit))
        self.used = 0

    @property
    def remaining(self) -> int:
        return max(0, self.limit - self.used)

    def claim(self) -> bool:
        if self.used >= self.limit:
            return False
        self.used += 1
        return True


def _safe_url_for_log(url: str) -> str:
    """Return a diagnostic URL without query parameters or credentials."""
    try:
        parts = urlsplit(url or "")
        hostname = parts.hostname or ""
        if not hostname:
            return "unknown"
        port = f":{parts.port}" if parts.port else ""
        return urlunsplit((parts.scheme or "https", hostname + port, parts.path, "", ""))
    except Exception:
        return "unknown"


def _set_phase(phase: str, source: str = "", **details) -> None:
    """Persist the current phase so a hard timeout remains diagnosable."""
    payload = {
        "phase": phase,
        "source": source,
        "updated_at": datetime.now(timezone.utc).isoformat(),
        "pid": os.getpid(),
        **details,
    }
    try:
        RUN_STATUS_PATH.parent.mkdir(parents=True, exist_ok=True)
        tmp = RUN_STATUS_PATH.with_name(f".{RUN_STATUS_PATH.name}.{os.getpid()}.tmp")
        tmp.write_text(json.dumps(payload, sort_keys=True) + "\n", encoding="utf-8")
        os.replace(tmp, RUN_STATUS_PATH)
    except Exception as exc:
        log.warning("could not persist pipeline phase=%s: %s", phase, exc)


def _bounded_download(url: str, *, phase: str, source: str, timeout: float,
                      max_bytes: int) -> bytes:
    """Download a response with connect/read deadlines and a byte ceiling."""
    safe_url = _safe_url_for_log(url)
    started = time.monotonic()
    deadline = started + timeout
    _set_phase(
        phase,
        source=source,
        url=safe_url,
        timeout_seconds=timeout,
        max_bytes=max_bytes,
    )
    log.info(
        "network start phase=%s source=%s url=%s timeout=%.1fs",
        phase, source, safe_url, timeout,
    )
    current_url = url
    response = None
    for redirect_count in range(MAX_REDIRECTS + 1):
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise requests.Timeout(f"download exceeded {timeout:.1f}s deadline")
        connect_timeout = max(0.5, min(CONNECT_TIMEOUT, remaining))
        read_timeout = max(0.5, min(5.0, remaining))
        response = requests.get(
            current_url,
            headers={"User-Agent": HTTP_USER_AGENT},
            allow_redirects=False,
            stream=True,
            timeout=(connect_timeout, read_timeout),
        )
        if response.status_code not in {301, 302, 303, 307, 308}:
            break
        location = response.headers.get("Location")
        response.close()
        if not location:
            raise requests.TooManyRedirects("redirect response had no Location header")
        if redirect_count >= MAX_REDIRECTS:
            raise requests.TooManyRedirects(f"more than {MAX_REDIRECTS} redirects")
        current_url = urljoin(current_url, location)

    if response is None:
        raise RuntimeError("download produced no response")

    with response:
        if time.monotonic() > deadline:
            raise requests.Timeout(f"download exceeded {timeout:.1f}s deadline")
        response.raise_for_status()
        content_length = response.headers.get("Content-Length")
        if content_length:
            try:
                if int(content_length) > max_bytes:
                    raise DownloadLimitError(
                        f"response declared {content_length} bytes; limit is {max_bytes}"
                    )
            except ValueError:
                pass

        chunks = []
        received = 0
        for chunk in response.iter_content(chunk_size=64 * 1024):
            if time.monotonic() > deadline:
                raise requests.Timeout(f"download exceeded {timeout:.1f}s deadline")
            if not chunk:
                continue
            received += len(chunk)
            if received > max_bytes:
                raise DownloadLimitError(
                    f"response exceeded {max_bytes} byte limit"
                )
            chunks.append(chunk)

        if time.monotonic() > deadline:
            raise requests.Timeout(f"download exceeded {timeout:.1f}s deadline")

    elapsed = time.monotonic() - started
    log.info(
        "network done phase=%s source=%s bytes=%d elapsed=%.2fs",
        phase, source, received, elapsed,
    )
    return b"".join(chunks)


def _fetch_feed(feed_url: str, source_name: str):
    payload = _bounded_download(
        feed_url,
        phase="feed_fetch",
        source=source_name,
        timeout=FEED_TIMEOUT,
        max_bytes=MAX_FEED_BYTES,
    )
    _set_phase("feed_parse", source=source_name, bytes=len(payload))
    return feedparser.parse(payload)


def _hash_title(title: str) -> str:
    norm = re.sub(r"\W+", " ", (title or "").lower()).strip()
    return hashlib.sha256(norm.encode("utf-8")).hexdigest()[:16]


def _matches_topic(text: str) -> bool:
    t = (text or "").lower()
    return any(kw in t for kw in sources.TOPIC_KEYWORDS)


def _clean_url(u: str) -> str:
    if not u:
        return u
    return u


def _parse_date(entry) -> str | None:
    for key in ("published", "updated", "created"):
        v = entry.get(key)
        if v:
            try:
                return dateparser.parse(v).astimezone(timezone.utc).isoformat()
            except Exception:
                continue
    return None


def _entry_snippet(entry) -> str:
    raw = entry.get("summary", "") or entry.get("description", "")
    text = re.sub(r"<[^>]+>", " ", raw)
    text = re.sub(r"\s+", " ", text).strip()
    return text[:500]


def _fetch_article_once(url: str, source: str) -> str:
    safe_url = _safe_url_for_log(url)
    scraper_started = time.monotonic()
    _set_phase(
        "home_scraper",
        source=source,
        url=safe_url,
        timeout_seconds=FETCH_TIMEOUT,
    )
    try:
        response = requests.post(
            f"{HOME_SCRAPER_URL}/v1/scrape",
            json={"url": url, "formats": ["markdown"]},
            timeout=(max(0.5, min(CONNECT_TIMEOUT, FETCH_TIMEOUT)), FETCH_TIMEOUT),
        )
        response.raise_for_status()
        data = response.json()
        markdown = data.get("data", {}).get("markdown", "") if data.get("success") else ""
        if markdown.strip():
            log.info(
                "home scraper done source=%s url=%s chars=%d elapsed=%.2fs",
                source, safe_url, len(markdown), time.monotonic() - scraper_started,
            )
            return markdown.strip()
    except OperationDeadlineExceeded:
        raise
    except Exception as e:
        log.info(
            "home scraper failed source=%s url=%s elapsed=%.2fs: %s; "
            "falling back to bounded download",
            source, safe_url, time.monotonic() - scraper_started, e,
        )

    try:
        downloaded = _bounded_download(
            url,
            phase="article_fetch",
            source=source,
            timeout=FETCH_TIMEOUT,
            max_bytes=MAX_ARTICLE_BYTES,
        )
        if not downloaded:
            return ""
        _set_phase("article_extract", source=source, url=safe_url, bytes=len(downloaded))
        text = trafilatura.extract(
            downloaded,
            url=url,
            include_comments=False,
            include_tables=False,
            favor_recall=True,
        )
        return (text or "").strip()
    except OperationDeadlineExceeded:
        raise
    except Exception as e:
        log.warning("fetch_article failed source=%s url=%s: %s", source, safe_url, e)
        return ""


def fetch_article(url: str, source: str = "article") -> str:
    """Fetch and extract an article within one absolute wall-clock budget."""
    safe_url = _safe_url_for_log(url)
    try:
        with _wall_clock_deadline(ARTICLE_TIMEOUT, f"article {safe_url}"):
            return _fetch_article_once(url, source)
    except OperationDeadlineExceeded as exc:
        log.warning("fetch_article deadline source=%s url=%s: %s", source, safe_url, exc)
        return ""


def ingest_feeds(limit: int | None = None, fetch_budget: ArticleFetchBudget | None = None,
                 attempt_limit: int | None = None) -> int:
    limit = MAX_NEW_PER_RUN if limit is None else max(0, limit)
    fetch_budget = fetch_budget or ArticleFetchBudget(MAX_ARTICLE_FETCHES_PER_RUN)
    stage_limit = fetch_budget.remaining if attempt_limit is None else max(0, attempt_limit)
    stage_attempts = 0
    blocked_article_hosts: set[str] = set()
    seen_title_hashes: set[str] = set()
    seen_normalized_titles: list[str] = []  # for intra-run fuzzy dedup
    inserted = 0
    for source_name, feed_url in sources.ALL_FEEDS:
        if (inserted >= limit or stage_attempts >= stage_limit
                or fetch_budget.remaining <= 0):
            break
        log.info("feed scan: %s", source_name)
        try:
            parsed = _fetch_feed(feed_url, source_name)
        except Exception as e:
            log.warning("feed parse failed %s: %s", source_name, e)
            continue
        if parsed.bozo and not parsed.entries:
            continue

        narrow = source_name in sources.TRUSTED_NARROW_FEEDS

        for entry in parsed.entries[:25]:
            if (inserted >= limit or stage_attempts >= stage_limit
                    or fetch_budget.remaining <= 0):
                break
            url = _clean_url(entry.get("link", ""))
            title = (entry.get("title") or "").strip()
            if not url or not title:
                continue
            pub = _parse_date(entry)
            if db.record_article_discovery_if_known(
                url, title, source_name, pub, channel="rss"
            ):
                continue
            th = _hash_title(title)
            if th in seen_title_hashes:
                continue
            seen_title_hashes.add(th)

            # Intra-run fuzzy dedup
            _skip_fuzzy = False
            _norm_t = re.sub(r"[^a-z0-9\s]", "", title.lower()).strip()
            for _prev in seen_normalized_titles:
                from difflib import SequenceMatcher as _SM
                if _SM(None, _norm_t, _prev).ratio() >= 0.70:
                    _skip_fuzzy = True
                    break
            if _skip_fuzzy:
                continue
            seen_normalized_titles.append(_norm_t)

            snippet = _entry_snippet(entry)
            search_blob = f"{title}\n{snippet}"
            if not narrow and not _matches_topic(search_blob):
                continue

            article_host = (urlsplit(url).hostname or "").lower()
            if article_host in blocked_article_hosts:
                continue
            if not fetch_budget.claim():
                break
            stage_attempts += 1
            body = fetch_article(url, source=f"rss:{source_name}")
            if len(body) < MIN_BODY_CHARS:
                if len(snippet) > MIN_BODY_CHARS:
                    body = snippet
                else:
                    continue

            issue = extraction_quality_issue(body)
            if issue:
                log.info("feed extraction rejected (%s): %s", issue, url)
                if issue == "google_consent" and article_host:
                    blocked_article_hosts.add(article_host)
                    log.info(
                        "article host suppressed for remainder of run after consent page: %s",
                        article_host,
                    )
                continue

            if not narrow and not _matches_topic(body[:4000]):
                continue

            slug = db.insert_pending(url, title, source_name, pub, snippet, body)
            if slug:
                inserted += 1
                log.info("queued [%s] %s", source_name, title[:90])
    log.info(
        "ingestion done: %d new pending; article_fetches=%d/%d run_remaining=%d",
        inserted, stage_attempts, stage_limit, fetch_budget.remaining,
    )
    return inserted


def ingest_gnews(limit: int | None = None, fetch_budget: ArticleFetchBudget | None = None,
                 attempt_limit: int | None = None) -> int:
    """Pull articles from GNews API and queue for analysis."""
    limit = MAX_NEW_PER_RUN if limit is None else max(0, limit)
    fetch_budget = fetch_budget or ArticleFetchBudget(MAX_ARTICLE_FETCHES_PER_RUN)
    stage_limit = fetch_budget.remaining if attempt_limit is None else max(0, attempt_limit)
    stage_attempts = 0
[redacted secret-like line]
        log.info("GNews: disabled or no API key, skipping")
        return 0
    inserted = 0
    for query in sources.GNEWS_QUERIES:
        if (inserted >= limit or stage_attempts >= stage_limit
                or fetch_budget.remaining <= 0):
            break
        log.info("gnews scan: %s", query)
        articles = sources.gnews_search(query, max_results=10)
        for a in articles:
            if (inserted >= limit or stage_attempts >= stage_limit
                    or fetch_budget.remaining <= 0):
                break
            url = a["url"]
            title = a["title"]
            if not url or not title:
                continue
            if db.record_article_discovery_if_known(
                url, title, a["source"] or "GNews", a["published"],
                channel="gnews",
            ):
                continue

            # GNews content is often truncated; fetch full article
            body = a["body"] or ""
            if len(body) < MIN_BODY_CHARS:
                if not fetch_budget.claim():
                    break
                stage_attempts += 1
                body = fetch_article(url, source=f"gnews:{query}")
            if len(body) < MIN_BODY_CHARS:
                if len(a["snippet"]) > MIN_BODY_CHARS:
                    body = a["snippet"]
                else:
                    continue

            issue = extraction_quality_issue(body)
            if issue:
                log.info("GNews extraction rejected (%s): %s", issue, url)
                continue

            slug = db.insert_pending(url, title, a["source"] or "GNews", a["published"], a["snippet"], body)
            if slug:
                inserted += 1
                log.info("queued [GNews/%s] %s", a["source"], title[:90])
        time.sleep(1)  # rate limit courtesy
    log.info(
        "gnews ingestion: %d new pending; article_fetches=%d/%d run_remaining=%d",
        inserted, stage_attempts, stage_limit, fetch_budget.remaining,
    )
    return inserted



def _clean_google_alerts_url(url: str) -> str:
    """Extract actual URL from Google Alerts redirect."""
    if "google.com/url" in url:
        from urllib.parse import urlparse, parse_qs
        parsed = urlparse(url)
        params = parse_qs(parsed.query)
        if "url" in params:
            return params["url"][0]
    return url


def ingest_google_alerts(limit: int | None = None,
                         fetch_budget: ArticleFetchBudget | None = None,
                         attempt_limit: int | None = None) -> int:
    """Pull articles from Google Alerts RSS (Atom) feeds and queue for analysis."""
    limit = MAX_NEW_PER_RUN if limit is None else max(0, limit)
    fetch_budget = fetch_budget or ArticleFetchBudget(MAX_ARTICLE_FETCHES_PER_RUN)
    stage_limit = fetch_budget.remaining if attempt_limit is None else max(0, attempt_limit)
    stage_attempts = 0
    blocked_article_hosts: set[str] = set()
    if not RSS_FEEDS_PATH.exists():
        log.info("Google Alerts: no rss_feeds.json found, skipping")
        return 0

    with open(RSS_FEEDS_PATH) as f:
        config = json.load(f)

    feeds = config.get("feeds", [])
    if not feeds:
        log.info("Google Alerts: no feeds configured")
        return 0

    max_per_feed = config.get("max_articles_per_feed", 20)
    seen_title_hashes: set[str] = set()
    inserted = 0

    for feed_cfg in feeds:
        if (inserted >= limit or stage_attempts >= stage_limit
                or fetch_budget.remaining <= 0):
            break
        feed_name = feed_cfg.get("name", "unnamed")
        feed_url = feed_cfg.get("url", "")
        if not feed_url:
            continue

        log.info("google alerts scan: %s", feed_name)
        try:
            parsed = _fetch_feed(feed_url, f"GoogleAlerts/{feed_name}")
        except Exception as e:
            log.warning("google alerts feed parse failed %s: %s", feed_name, e)
            continue
        if parsed.bozo and not parsed.entries:
            log.warning("google alerts feed bozo %s: %s", feed_name, getattr(parsed, "bozo_exception", ""))
            continue

        for entry in parsed.entries[:max_per_feed]:
            if (inserted >= limit or stage_attempts >= stage_limit
                    or fetch_budget.remaining <= 0):
                break
            url = _clean_google_alerts_url(entry.get("link", ""))
            title = (entry.get("title") or "").strip()
            if not url or not title:
                continue
            pub = _parse_date(entry)
            if db.record_article_discovery_if_known(
                url, title, f"GoogleAlerts/{feed_name}", pub,
                channel="google_alerts",
            ):
                continue
            th = _hash_title(title)
            if th in seen_title_hashes:
                continue
            seen_title_hashes.add(th)

            snippet = _entry_snippet(entry)

            article_host = (urlsplit(url).hostname or "").lower()
            if article_host in blocked_article_hosts:
                continue
            if not fetch_budget.claim():
                break
            stage_attempts += 1
            body = fetch_article(url, source=f"google_alerts:{feed_name}")
            if len(body) < MIN_BODY_CHARS:
                if len(snippet) > MIN_BODY_CHARS:
                    body = snippet
                else:
                    continue

            issue = extraction_quality_issue(body)
            if issue:
                log.info("Google Alerts extraction rejected (%s): %s", issue, url)
                if issue == "google_consent" and article_host:
                    blocked_article_hosts.add(article_host)
                continue

            slug = db.insert_pending(url, title, f"GoogleAlerts/{feed_name}", pub, snippet, body)
            if slug:
                inserted += 1
                log.info("queued [GoogleAlerts/%s] %s", feed_name, title[:90])

    log.info(
        "google alerts ingestion: %d new pending; article_fetches=%d/%d run_remaining=%d",
        inserted, stage_attempts, stage_limit, fetch_budget.remaining,
    )
    return inserted


def analyse_pending() -> int:
    pending = db.pending_for_analysis(limit=MAX_ANALYSE_PER_RUN)
    if not pending:
        log.info("no pending articles")
        return 0
    done = 0
    for row in pending:
        slug = row["slug"]
        try:
            _set_phase("oracle_prepare", source=slug)
            issue = extraction_quality_issue(row["body"] or row["snippet"] or "")
            if issue:
                db.quarantine_article(slug, issue)
                log.warning("quarantined before Oracle [%s]: %s", issue, slug)
                continue
            log.info("oracle -> [%s] %s", row["source"], row["title"][:90])
            _set_phase(
                "oracle",
                source=slug,
                article_source=row["source"],
                title=row["title"][:120],
            )
            result = oracle.consult(
                title=row["title"], url=row["url"],
                source=row["source"],
                article_text=row["body"] or row["snippet"] or "",
            )
            one_liner = oracle.extract_one_liner(result["verdict_md"])
            relevance = _score_relevance(
                row["title"], row.get("snippet", ""), one_liner, result["verdict_md"]
            )
            db.set_verdict(slug, result["verdict_md"], one_liner,
                          result["model"], result["price"], relevance=relevance)
            done += 1
            _crosslink_figures(row, result)
            time.sleep(2)
        except Exception as e:
            log.exception("oracle failed for slug=%s", slug)
            db.set_failed(slug, str(e))
    log.info("oracle pass done: %d analysed", done)
    return done



def _is_incidental_mention(article_title: str, figure_name: str, all_figures: list) -> bool:
    """Check if this figure is only incidentally mentioned in an article about someone else.
    Returns True if we should SKIP this entry (cross-figure misattribution)."""
    import re as _re
    title_lower = article_title.lower()
    figure_lower = figure_name.lower()
    figure_last = figure_name.split()[-1].lower()

    # Check if figure's own name is in the title — if so, article is about them
    if figure_lower in title_lower or (len(figure_last) >= 4 and figure_last in title_lower):
        return False  # Article title mentions this figure — keep it

    # Check if a DIFFERENT tracked figure's name is in the title
    for other in all_figures:
        other_name = other["name"].lower()
        other_last = other["name"].split()[-1].lower()
        if other_name == figure_lower:
            continue  # skip self
        if other_name in title_lower or (len(other_last) >= 4 and other_last in title_lower):
            # Title contains another figure's name, not ours — likely misattribution
            return True

    return False  # No other figure in title, keep it

def _crosslink_figures(article_row, oracle_result):
    """Cross-link articles to figures. Only attributes if full name is found."""
    import re as _re
    figures = _load_figures()
    if not figures:
        return
    text = (article_row.get("body") or article_row.get("snippet") or "")
    title = (article_row.get("title") or "")
    combined = (title + " " + text).lower()

    for fig in figures:
        name_lower = fig["name"].lower()
        last_name = fig["name"].split()[-1].lower()

        # Check for full name with word boundaries
        full_pattern = _re.compile(r'\b' + _re.escape(name_lower) + r'\b')
        full_matches = full_pattern.findall(combined)

        # Check last name only if 5+ chars
        last_matches = []
        if len(last_name) >= 5:
            last_pattern = _re.compile(r'\b' + _re.escape(last_name) + r'\b')
            last_matches = last_pattern.findall(combined)

        # Attribution rules:
        # - Full name found anywhere -> attribute
        # - Last name (5+ chars) found 2+ times -> attribute
        # - Otherwise -> skip
        if not full_matches and len(last_matches) < 2:
            continue

        quote_context = _extract_figure_context(text, fig["name"])
        if quote_context and len(quote_context) > 50:
            if db.record_cope_observation_if_known(
                fig["id"], quote_context,
                source_url=article_row["url"],
                source_title=article_row["title"],
                observed_at=article_row.get("published") or article_row.get("created_at"),
                channel="article_crosslink",
                article_slug=article_row["slug"],
            ):
                continue
            try:
                log.info("cope cross-link: %s in article %s",
                         fig["name"], article_row["slug"][:40])
                _set_phase(
                    "oracle_cope_crosslink",
                    source=article_row["slug"],
                    figure=fig["name"],
                )
                cope_result = oracle.score_cope(
                    fig["name"], fig.get("title", ""),
                    quote_context,
                    source_context="From article: " + article_row["title"],
                )
                # Skip N/A / off-topic entries (cope_type=N/A with score 0)
                if (cope_result.get("cope_type", "").strip().upper() == "N/A"
                        or (cope_result.get("cope_score", 0) == 0
                            and "N/A" in cope_result.get("cope_type", "").upper())):
                    log.info("cope cross-link skipped (off-topic/N/A): %s in %s",
                             fig["name"], article_row["slug"][:40])
                    continue
                # Cross-figure misattribution check
                if _is_incidental_mention(article_row["title"], fig["name"], figures):
                    log.info("cope cross-link skipped (cross-figure title): %s in %s",
                             fig["name"], article_row["slug"][:40])
                    continue
                # Quality gate: attribution strength, confidence, review flag
                ctype = cope_result.get("cope_type", "").lower().strip()
                cscore = cope_result.get("cope_score", 0)
                if cscore < 0 or "not_attributed" in ctype or ctype == "n/a":
                    log.info("cope cross-link skipped (not attributed/NA): %s in %s",
                             fig["name"], article_row["slug"][:40])
                    continue
                attr = cope_result.get("attribution_strength", "mentioned_only")
                if attr not in AUTO_PUBLISH_ATTRIBUTION:
                    log.info("cope cross-link skipped (attr=%s): %s in %s",
                             attr, fig["name"], article_row["slug"][:40])
                    continue
                conf = cope_result.get("confidence", 0.0)
                if conf < MIN_CONFIDENCE:
                    log.info("cope cross-link skipped (conf=%.2f): %s in %s",
                             conf, fig["name"], article_row["slug"][:40])
                    continue
                if cope_result.get("needs_review"):
                    log.info("cope cross-link skipped (needs_review): %s in %s",
                             fig["name"], article_row["slug"][:40])
                    continue
                db.add_cope_entry(
                    figure_id=fig["id"],
                    article_slug=article_row["slug"],
                    quote=_short_words(cope_result.get("cope_quote") or quote_context, 24),
                    source_url=article_row["url"],
                    source_title=article_row["title"],
                    cope_score=cope_result["cope_score"],
                    cope_type=cope_result.get("cope_type", "unknown"),
                    analysis_md=cope_result.get("analysis", ""),
                    model=cope_result.get("model", ""),
                    observed_at=article_row.get("published") or article_row.get("created_at"),
                    channel="article_crosslink",
                )
                time.sleep(1)
            except Exception as e:
                log.warning("cope cross-link failed for %s: %s", fig["name"], e)


def _extract_figure_context(text: str, name: str, window=800) -> str:
    """Extract text around mentions of a figure. Requires strong name match."""
    import re as _re
    lower = text.lower()
    name_lower = name.lower()
    last_name = name.split()[-1].lower()

    def _word_boundary_find(haystack, needle):
        """Find all positions of needle with word boundaries."""
        positions = []
        pattern = _re.compile(r'\b' + _re.escape(needle) + r'\b')
        for m in pattern.finditer(haystack):
            positions.append(m.start())
        return positions

    # Find full name matches (high confidence)
    full_positions = _word_boundary_find(lower, name_lower)

    # Find last name matches only if last name is 4+ chars (skip "Ng", "Li", etc.)
    last_positions = []
    if len(last_name) >= 4:
        last_positions = _word_boundary_find(lower, last_name)

    # Decide which positions to use
    if full_positions:
        # Full name found - use all positions (full + last)
        positions = sorted(set(full_positions + last_positions))
    elif len(last_positions) >= 2:
        # No full name but last name appears 2+ times with word boundaries
        positions = last_positions
    else:
        # Not enough evidence this article is about this figure
        return ""

    if not positions:
        return ""

    chunks = []
    for pos in positions[:3]:
        s = max(0, pos - window // 2)
        e = min(len(text), pos + window // 2)
        chunks.append(text[s:e])

    return "\n...\n".join(chunks)


def _load_figures() -> list[dict]:
    if not FIGURES_PATH.exists():
        log.warning("figures.yaml not found at %s", FIGURES_PATH)
        return []
    with open(FIGURES_PATH) as f:
        data = yaml.safe_load(f)
    return data.get("figures", [])


def sync_figures():
    """Make the figures table match figures.yaml.

    figures.yaml is the source of truth for who is tracked, but upsert alone
    is insert-only: a figure removed from the yaml kept its row and carried on
    appearing on the site while never being scanned again. That gap is how
    organisations (BCG) lingered as people and how Jeff Bezos sat unscanned
    with a single stale entry. Reconcile both directions — but deactivate
    rather than delete, because the scored evidence and its provenance are
    real analysis and the schema forbids dropping rows that carry provenance.
    """
    figures = _load_figures()
    for fig in figures:
        db.upsert_figure(
            fig["id"], fig["name"], fig.get("title"),
            fig.get("category"), fig.get("photo_url"),
            fig.get("cope_bias"),
        )
    wanted = {fig["id"] for fig in figures}
    with db.conn() as c:
        rows = c.execute(
            "SELECT id, name FROM figures WHERE COALESCE(active, 1) = 1"
        ).fetchall()
        orphans = [dict(r) for r in rows if r["id"] not in wanted]
        for orphan in orphans:
            c.execute(
                "UPDATE figures SET active = 0, inactive_reason = ?, "
                "updated_at = CURRENT_TIMESTAMP WHERE id = ?",
                ("absent from figures.yaml at sync", orphan["id"]),
            )
            log.warning(
                "figure %s (%s) is not in figures.yaml — deactivated, "
                "evidence retained", orphan["id"], orphan["name"],
            )
        # A figure listed in the yaml is tracked again, even if archived before.
        for fig_id in wanted:
            c.execute(
                "UPDATE figures SET active = 1, inactive_reason = NULL "
                "WHERE id = ? AND COALESCE(active, 1) = 0",
                (fig_id,),
            )
    log.info("synced %d figures to DB (%d deactivated as orphans)",
             len(figures), len(orphans))
    return figures


def scan_figure_news() -> int:
    figures = _load_figures()
    if not figures:
        return 0

    total_scored = 0
    for fig in figures:
        queries = fig.get("search_queries", [])
        if not queries:
            continue

        scored_this_figure = 0
        for query in queries:
            if scored_this_figure >= MAX_COPE_SCAN_PER_FIGURE:
                break

            feed_url = sources.google_news_url(query)
            try:
                parsed = _fetch_feed(feed_url, f"figure:{fig['name']}")
            except Exception as exc:
                log.warning("figure feed failed %s query=%s: %s", fig["name"], query, exc)
                continue

            for entry in parsed.entries[:5]:
                if scored_this_figure >= MAX_COPE_SCAN_PER_FIGURE:
                    break
                url = entry.get("link", "")
                title = (entry.get("title") or "").strip()
                if not url or not title:
                    continue

                observed_at = _parse_date(entry)
                if db.record_cope_observation_if_known(
                    fig["id"], "", source_url=url,
                    source_title=title, observed_at=observed_at,
                    channel="direct_google_news",
                ):
                    continue

                body = fetch_article(url, source=f"figure:{fig['name']}")
                issue = extraction_quality_issue(body)
                if issue:
                    log.info("cope scan extraction rejected (%s): %s", issue, url)
                    continue

                quote_context = _extract_figure_context(body, fig["name"])
                if not quote_context or len(quote_context) < 80:
                    continue

                if db.record_cope_observation_if_known(
                    fig["id"], quote_context, source_url=url,
                    source_title=title, observed_at=observed_at,
                    channel="direct_google_news",
                ):
                    continue

                try:
                    log.info("cope scan: %s -> %s", fig["name"], title[:60])
                    _set_phase(
                        "oracle_cope_scan",
                        source=fig["name"],
                        title=title[:120],
                    )
                    cope_result = oracle.score_cope(
                        fig["name"], fig.get("title", ""),
                        quote_context,
                        source_context=f"From: {title}",
                    )
                    # Skip N/A / off-topic entries
                    if (cope_result.get("cope_type", "").strip().upper() == "N/A"
                            or (cope_result.get("cope_score", 0) == 0
                                and "N/A" in cope_result.get("cope_type", "").upper())):
                        log.info("cope scan skipped (off-topic/N/A): %s in %s",
                                 fig["name"], title[:60])
                        continue
                    # Cross-figure misattribution check
                    if _is_incidental_mention(title, fig["name"], figures):
                        log.info("cope scan skipped (cross-figure title): %s in %s",
                                 fig["name"], title[:60])
                        continue
                    # Quality gate: attribution strength, confidence, review flag
                    ctype = cope_result.get("cope_type", "").lower().strip()
                    cscore = cope_result.get("cope_score", 0)
                    if cscore < 0 or "not_attributed" in ctype or ctype == "n/a":
                        log.info("cope scan skipped (not attributed/NA): %s in %s",
                                 fig["name"], title[:60])
                        continue
                    attr = cope_result.get("attribution_strength", "mentioned_only")
                    if attr not in AUTO_PUBLISH_ATTRIBUTION:
                        log.info("cope scan skipped (attr=%s): %s in %s",
                                 attr, fig["name"], title[:60])
                        continue
                    conf = cope_result.get("confidence", 0.0)
                    if conf < MIN_CONFIDENCE:
                        log.info("cope scan skipped (conf=%.2f): %s in %s",
                                 conf, fig["name"], title[:60])
                        continue
                    if cope_result.get("needs_review"):
                        log.info("cope scan skipped (needs_review): %s in %s",
                                 fig["name"], title[:60])
                        continue
                    added = db.add_cope_entry(
                        figure_id=fig["id"],
                        article_slug=None,
                        quote=_short_words(cope_result.get("cope_quote") or quote_context, 24),
                        source_url=url,
                        source_title=title,
                        cope_score=cope_result["cope_score"],
                        cope_type=cope_result.get("cope_type", "unknown"),
                        analysis_md=cope_result.get("analysis", ""),
                        model=cope_result.get("model", ""),
                        observed_at=observed_at,
                        channel="direct_google_news",
                    )
                    if added and added.get("inserted"):
                        scored_this_figure += 1
                        total_scored += 1
                    time.sleep(2)
                except Exception as e:
                    log.warning("cope score failed for %s: %s", fig["name"], e)

    log.info("cope scan done: %d new scores", total_scored)
    return total_scored


def main():
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(name)s | %(message)s",
        handlers=[
            logging.StreamHandler(),
            logging.FileHandler(
                str(Path(__file__).parent / "logs" / "pipeline.log"),
                encoding="utf-8",
            ),
        ],
    )
    db.init()

    mode = sys.argv[1] if len(sys.argv) > 1 else "all"
    started = datetime.now(timezone.utc).isoformat()
    _set_phase("startup", source=mode, started_at=started)
    log.info("=== copecheck v2 pipeline start mode=%s %s ===", mode, started)
    log.info(
        "limits: new_total=%d analyse=%d article_timeout=%.1fs "
        "fetch_timeout=%.1fs feed_timeout=%.1fs article_fetches=%d "
        "rss_fetches=%d gnews_fetches=%d article_bytes=%d feed_bytes=%d",
        MAX_NEW_PER_RUN,
        MAX_ANALYSE_PER_RUN,
        ARTICLE_TIMEOUT,
        FETCH_TIMEOUT,
        FEED_TIMEOUT,
        MAX_ARTICLE_FETCHES_PER_RUN,
        MAX_RSS_ARTICLE_FETCHES,
        MAX_GNEWS_ARTICLE_FETCHES,
        MAX_ARTICLE_BYTES,
        MAX_FEED_BYTES,
    )

    _set_phase("sync_figures", source=mode)
    sync_figures()

    if mode in ("all", "news"):
        fetch_budget = ArticleFetchBudget(MAX_ARTICLE_FETCHES_PER_RUN)
        n_new = ingest_feeds(
            MAX_NEW_PER_RUN,
            fetch_budget=fetch_budget,
            attempt_limit=min(MAX_RSS_ARTICLE_FETCHES, fetch_budget.remaining),
        )
        remaining = max(0, MAX_NEW_PER_RUN - n_new)
        n_gnews = ingest_gnews(
            remaining,
            fetch_budget=fetch_budget,
            attempt_limit=min(MAX_GNEWS_ARTICLE_FETCHES, fetch_budget.remaining),
        )
        remaining = max(0, remaining - n_gnews)
        n_alerts = ingest_google_alerts(
            remaining,
            fetch_budget=fetch_budget,
            attempt_limit=fetch_budget.remaining,
        )
        n_done = analyse_pending()
        log.info("news pipeline: rss=%d gnews=%d alerts=%d analysed=%d", n_new, n_gnews, n_alerts, n_done)

    if mode in ("all", "cope"):
        n_cope = scan_figure_news()
        log.info("cope pipeline: scored=%d", n_cope)

    snapshot = db.counts()
    log.info("counts: %s", snapshot)
    log.info("=== copecheck v2 pipeline done ===")
    _set_phase("complete", source=mode, counts=snapshot)


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