---
type: "Source File"
title: "\"\"\"SQLite storage for CopeCheck v2 — articles, figures, cope scores, comments, submissions.\"\"\""
description: "\"\"\"SQLite storage for CopeCheck v2 — articles, figures, cope scores, comments, submissions.\"\"\" import os import re import sqlite3 import hashlib import math import time from contextlib import contextmanager from."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-26T20:49:41Z"
site: "main"
source_path: "copecheck/db.py"
---

# """SQLite storage for CopeCheck v2 — articles, figures, cope scores, comments, submissions."""

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

```py
"""SQLite storage for CopeCheck v2 — articles, figures, cope scores, comments, submissions."""
import os
import re
import sqlite3
import hashlib
import math
import time
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path

from canonical_identity import (
    canonical_url,
    canonical_url_hash,
    exact_statement_match,
    new_event_fingerprint,
    provenance_key,
    same_event,
)
from content_quality import extraction_quality_issue
import publish_gate

DB_PATH = os.environ.get(
    "COPECHECK_DB",
    str(Path(__file__).parent / "data" / "copecheck.db"),
)
Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)

SCHEMA = """
CREATE TABLE IF NOT EXISTS articles (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    slug        TEXT UNIQUE NOT NULL,
    url         TEXT NOT NULL,
    url_hash    TEXT UNIQUE NOT NULL,
    canonical_url TEXT UNIQUE NOT NULL,
    canonical_url_hash TEXT NOT NULL,
    title_hash  TEXT,
    title       TEXT NOT NULL,
    source      TEXT NOT NULL,
    published   TEXT,
    snippet     TEXT,
    body        TEXT,
    verdict_md  TEXT,
    one_liner   TEXT,
    model       TEXT,
    price       REAL,
    status      TEXT DEFAULT 'pending',
    error       TEXT,
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP,
    analysed_at TEXT,
    relevance   REAL DEFAULT NULL,
    index_status TEXT DEFAULT 'noindex',
    index_reason TEXT DEFAULT 'scanner content awaits quality gate',
    index_checked_at TEXT,
    indexed_source TEXT DEFAULT 'rss'
);
CREATE INDEX IF NOT EXISTS idx_articles_created ON articles(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_articles_analysed ON articles(analysed_at DESC);
CREATE INDEX IF NOT EXISTS idx_articles_status ON articles(status);
CREATE INDEX IF NOT EXISTS idx_articles_title_hash ON articles(title_hash);

CREATE TABLE IF NOT EXISTS article_provenance (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    article_slug TEXT NOT NULL REFERENCES articles(slug),
    observation_key TEXT NOT NULL,
    raw_url TEXT NOT NULL,
    canonical_url TEXT NOT NULL,
    source_title TEXT,
    source TEXT,
    channel TEXT,
    observed_at TEXT,
    legacy_article_id INTEGER,
    legacy_slug TEXT,
    legacy_url_hash TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(article_slug, observation_key)
);
CREATE INDEX IF NOT EXISTS idx_article_provenance_slug
    ON article_provenance(article_slug, created_at);

CREATE TABLE IF NOT EXISTS article_aliases (
    alias_slug TEXT PRIMARY KEY,
    article_slug TEXT NOT NULL REFERENCES articles(slug),
    reason TEXT NOT NULL DEFAULT 'canonical_url_merge',
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS figures (
    id          TEXT PRIMARY KEY,
    name        TEXT NOT NULL,
    title       TEXT,
    category    TEXT,
    photo_url   TEXT,
    cope_bias   TEXT,
    cope_score  REAL DEFAULT 50.0,
    prev_score  REAL DEFAULT 50.0,
    total_quotes INTEGER DEFAULT 0,
    last_quote  TEXT,
    last_cope_type TEXT,
    last_scored TEXT,
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP,
    updated_at  TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS cope_entries (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    figure_id   TEXT NOT NULL REFERENCES figures(id),
    article_slug TEXT REFERENCES articles(slug),
    quote       TEXT NOT NULL,
    source_url  TEXT,
    source_title TEXT,
    canonical_url TEXT,
    canonical_url_hash TEXT,
    event_fingerprint TEXT NOT NULL,
    event_observed_at TEXT,
    representative_quality INTEGER NOT NULL DEFAULT 0,
    cope_score  REAL NOT NULL,
    cope_type   TEXT,
    analysis_md TEXT,
    model       TEXT,
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_cope_figure ON cope_entries(figure_id, created_at DESC);

CREATE TABLE IF NOT EXISTS cope_entry_provenance (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    cope_entry_id INTEGER NOT NULL REFERENCES cope_entries(id),
    observation_key TEXT NOT NULL,
    article_slug TEXT,
    source_url TEXT,
    canonical_url TEXT,
    source_title TEXT,
    quote TEXT,
    channel TEXT,
    observed_at TEXT,
    observed_cope_score REAL,
    observed_cope_type TEXT,
    observed_analysis_md TEXT,
    observed_model TEXT,
    representative_quality INTEGER,
    legacy_cope_entry_id INTEGER,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(cope_entry_id, observation_key)
);
CREATE INDEX IF NOT EXISTS idx_cope_provenance_entry
    ON cope_entry_provenance(cope_entry_id, created_at);


CREATE TABLE IF NOT EXISTS url_submissions (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    figure_id   TEXT NOT NULL REFERENCES figures(id),
    url         TEXT NOT NULL,
    canonical_url TEXT,
    canonical_url_hash TEXT,
    url_type    TEXT DEFAULT 'unknown',
    extracted_text TEXT,
    status      TEXT DEFAULT 'pending',
    error_msg   TEXT,
    submitted_by TEXT DEFAULT 'anonymous',
[redacted secret-like line]
    referrer    TEXT DEFAULT '',
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP,
    processed_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_urlsub_status ON url_submissions(status, created_at);
CREATE TABLE IF NOT EXISTS comments (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    article_slug TEXT NOT NULL,
    author_name TEXT DEFAULT 'Anonymous',
    body        TEXT NOT NULL,
[redacted secret-like line]
    referrer    TEXT DEFAULT '',
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_comments_slug ON comments(article_slug, created_at ASC);

CREATE TABLE IF NOT EXISTS submissions (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    title       TEXT,
    source      TEXT,
    url         TEXT,
    text_preview TEXT,
    body        TEXT,
    verdict_md  TEXT,
    one_liner   TEXT,
    model       TEXT,
    price       REAL,
[redacted secret-like line]
    status      TEXT DEFAULT 'pending',
    error       TEXT,
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP,
    index_status TEXT DEFAULT 'trial_index',
    index_reason TEXT DEFAULT 'manual submission indexed by default',
    index_checked_at TEXT,
    indexed_source TEXT DEFAULT 'manual'
);
CREATE INDEX IF NOT EXISTS idx_submissions_created ON submissions(created_at DESC);

CREATE TABLE IF NOT EXISTS suggestions (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    name        TEXT NOT NULL,
    reason      TEXT,
    example     TEXT,
[redacted secret-like line]
    status      TEXT DEFAULT 'pending',
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE VIRTUAL TABLE IF NOT EXISTS articles_fts USING fts5(
    slug UNINDEXED, title, source, snippet, one_liner, verdict_md
);

"""


@contextmanager
def conn():
    c = sqlite3.connect(DB_PATH, timeout=30)
    c.row_factory = sqlite3.Row
    # Provenance/alias rows are part of the public audit trail.  Enforce their
    # declared references so an old maintenance script cannot silently orphan
    # them by deleting a canonical article or event directly.
    c.execute("PRAGMA foreign_keys=ON")
    c.execute("PRAGMA journal_mode=WAL")
    publish_gate.ensure_schema(c)
    try:
        yield c
        c.commit()
    finally:
        c.close()


def _table_exists(c, table: str) -> bool:
    cur = c.execute(
        "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",
        (table,),
    )
    return cur.fetchone() is not None


def _columns(c, table: str) -> set[str]:
    if not _table_exists(c, table):
        return set()
    return {row["name"] for row in c.execute(f"PRAGMA table_info({table})")}


def _ensure_columns(c, table: str, columns: list[tuple[str, str]]) -> None:
    existing = _columns(c, table)
    for name, definition in columns:
        if name not in existing:
            c.execute(f"ALTER TABLE {table} ADD COLUMN {name} {definition}")
            existing.add(name)


def _ensure_index_policy_columns(c) -> None:
    _ensure_columns(c, "articles", [
        ("relevance", "REAL DEFAULT NULL"),
        ("index_status", "TEXT DEFAULT 'noindex'"),
        ("index_reason", "TEXT DEFAULT 'scanner content awaits quality gate'"),
        ("index_checked_at", "TEXT"),
        ("indexed_source", "TEXT DEFAULT 'rss'"),
    ])
    _ensure_columns(c, "submissions", [
        ("index_status", "TEXT DEFAULT 'trial_index'"),
        ("index_reason", "TEXT DEFAULT 'manual submission indexed by default'"),
        ("index_checked_at", "TEXT"),
        ("indexed_source", "TEXT DEFAULT 'manual'"),
    ])
    if _table_exists(c, "instant_scores"):
        _ensure_columns(c, "instant_scores", [
            ("index_status", "TEXT DEFAULT 'trial_index'"),
            ("index_reason", "TEXT DEFAULT 'manual instant score indexed by default'"),
            ("index_checked_at", "TEXT"),
            ("indexed_source", "TEXT DEFAULT 'instant'"),
        ])

    c.execute("CREATE INDEX IF NOT EXISTS idx_articles_index_status ON articles(index_status, analysed_at DESC)")
    c.execute("CREATE INDEX IF NOT EXISTS idx_submissions_index_status ON submissions(index_status, created_at DESC)")
    if _table_exists(c, "instant_scores"):
        c.execute("CREATE INDEX IF NOT EXISTS idx_instant_index_status ON instant_scores(index_status, created_at DESC)")

    c.execute(
        """UPDATE articles
           SET index_status = COALESCE(index_status, 'noindex'),
               index_reason = COALESCE(index_reason, 'scanner content awaits quality gate'),
               indexed_source = COALESCE(indexed_source,
                   CASE
                     WHEN source LIKE 'GoogleAlerts/%' THEN 'rss'
                     WHEN source LIKE 'GNews%' THEN 'scanner'
                     ELSE 'rss'
                   END)
           WHERE status = 'analysed'"""
    )
    c.execute(
        """UPDATE submissions
           SET index_status = COALESCE(index_status, 'trial_index'),
               index_reason = COALESCE(index_reason, 'manual submission indexed by default'),
               indexed_source = COALESCE(indexed_source, 'manual')
           WHERE status = 'analysed'"""
    )
    if _table_exists(c, "instant_scores"):
        c.execute(
            """UPDATE instant_scores
               SET index_status = COALESCE(index_status, 'trial_index'),
                   index_reason = COALESCE(index_reason, 'manual instant score indexed by default'),
                   indexed_source = COALESCE(indexed_source, 'instant')"""
        )


def _ensure_identity_columns(c) -> None:
    """Make code forwards-compatible; the backfill owns legacy uniqueness."""
    _ensure_columns(c, "articles", [
        ("canonical_url", "TEXT"),
        ("canonical_url_hash", "TEXT"),
    ])
    _ensure_columns(c, "cope_entries", [
        ("canonical_url", "TEXT"),
        ("canonical_url_hash", "TEXT"),
        ("event_fingerprint", "TEXT"),
        ("event_observed_at", "TEXT"),
        ("representative_quality", "INTEGER DEFAULT 0"),
    ])
    _ensure_columns(c, "url_submissions", [
        ("canonical_url", "TEXT"),
        ("canonical_url_hash", "TEXT"),
    ])
    _ensure_columns(c, "article_provenance", [
        ("legacy_article_id", "INTEGER"),
        ("legacy_slug", "TEXT"),
        ("legacy_url_hash", "TEXT"),
    ])
    _ensure_columns(c, "cope_entry_provenance", [
        ("observed_cope_score", "REAL"),
        ("observed_cope_type", "TEXT"),
        ("observed_analysis_md", "TEXT"),
        ("observed_model", "TEXT"),
        ("representative_quality", "INTEGER"),
        ("legacy_cope_entry_id", "INTEGER"),
    ])
    c.execute(
        "CREATE INDEX IF NOT EXISTS idx_articles_canonical_hash "
        "ON articles(canonical_url_hash)"
    )
    c.execute(
        "CREATE INDEX IF NOT EXISTS idx_cope_canonical "
        "ON cope_entries(figure_id, canonical_url_hash)"
    )
    c.execute(
        "CREATE INDEX IF NOT EXISTS idx_urlsub_canonical "
        "ON url_submissions(figure_id, canonical_url_hash, created_at)"
    )

    # A brand-new database can be constrained immediately.  A legacy database
    # with null identities must first be processed by migrate_canonical_dedupe.
    legacy_articles = c.execute(
        "SELECT COUNT(*) FROM articles WHERE canonical_url IS NULL"
    ).fetchone()[0]
    legacy_entries = c.execute(
        "SELECT COUNT(*) FROM cope_entries WHERE event_fingerprint IS NULL"
    ).fetchone()[0]
    if not legacy_articles:
        c.execute(
            "CREATE UNIQUE INDEX IF NOT EXISTS uq_articles_canonical_url "
            "ON articles(canonical_url)"
        )
    if not legacy_entries:
        c.execute(
            "CREATE UNIQUE INDEX IF NOT EXISTS uq_cope_figure_event "
            "ON cope_entries(figure_id, event_fingerprint)"
        )

    _ensure_identity_guards(c)


def _ensure_identity_guards(c) -> None:
    """Enforce legacy-ALTER identity invariants at the database boundary.

    SQLite cannot add a NOT NULL constraint with ``ALTER TABLE``.  These
    triggers make the migrated schema reject raw/forgotten writers that omit
    the identities used by the unique indexes.  The provenance delete guards
    also stop old maintenance scripts from silently orphaning audit rows when
    they connect without ``PRAGMA foreign_keys=ON``.
    """
    c.executescript(
        """
        CREATE TRIGGER IF NOT EXISTS trg_articles_require_canonical_insert
        BEFORE INSERT ON articles
        WHEN NEW.canonical_url IS NULL OR trim(NEW.canonical_url) = ''
        BEGIN
          SELECT RAISE(ABORT, 'articles.canonical_url is required');
        END;

        CREATE TRIGGER IF NOT EXISTS trg_articles_require_canonical_update
        BEFORE UPDATE OF canonical_url ON articles
        WHEN NEW.canonical_url IS NULL OR trim(NEW.canonical_url) = ''
        BEGIN
          SELECT RAISE(ABORT, 'articles.canonical_url is required');
        END;

        CREATE TRIGGER IF NOT EXISTS trg_cope_require_event_insert
        BEFORE INSERT ON cope_entries
        WHEN NEW.event_fingerprint IS NULL OR trim(NEW.event_fingerprint) = ''
        BEGIN
          SELECT RAISE(ABORT, 'cope_entries.event_fingerprint is required');
        END;

        CREATE TRIGGER IF NOT EXISTS trg_cope_require_event_update
        BEFORE UPDATE OF event_fingerprint ON cope_entries
        WHEN NEW.event_fingerprint IS NULL OR trim(NEW.event_fingerprint) = ''
        BEGIN
          SELECT RAISE(ABORT, 'cope_entries.event_fingerprint is required');
        END;

        CREATE TRIGGER IF NOT EXISTS trg_articles_preserve_provenance_delete
        BEFORE DELETE ON articles
        WHEN EXISTS (
          SELECT 1 FROM article_provenance
           WHERE article_slug = OLD.slug
        )
        BEGIN
          SELECT RAISE(ABORT, 'move article provenance before deleting article');
        END;

        CREATE TRIGGER IF NOT EXISTS trg_cope_preserve_provenance_delete
        BEFORE DELETE ON cope_entries
        WHEN EXISTS (
          SELECT 1 FROM cope_entry_provenance
           WHERE cope_entry_id = OLD.id
        )
        BEGIN
          SELECT RAISE(ABORT, 'move cope provenance before deleting event');
        END;
        """
    )





def init():
    with conn() as c:
        c.executescript(SCHEMA)
        _ensure_index_policy_columns(c)
        _ensure_identity_columns(c)


INDEXABLE_STATUSES = {"index", "trial_index"}
AGGREGATOR_HINTS = {
    "yahoo", "moneycontrol", "msn", "aol", "marketscreener", "marketwatch",
    "benzinga", "investing.com", "business insider india", "times of india",
    "india today", "techie tonic", "futureiot", "webpronews", "newsbreak",
    "livemint", "the economic times", "economictimes", "finance.yahoo",
}


def _status_source(source: str | None) -> str:
    s = (source or "").strip()
    if s.startswith("GoogleAlerts/"):
        return "rss"
    if s.startswith("GNews"):
        return "scanner"
    return "rss"


def _as_float(value, default=None):
    try:
        if value is None or value == "":
            return default
        return float(value)
    except (TypeError, ValueError):
        return default


def _is_aggregator(source: str | None, url: str | None = None) -> bool:
    text = " ".join([source or "", url or ""]).lower()
    return any(hint in text for hint in AGGREGATOR_HINTS)


def representative_quality(c, article_slug, source_title, source_url) -> int:
    """Deterministic source rank used to select one scored observation.

    Original/non-aggregator publication is the strongest signal, followed by
    a quality-gated analysed article and extraction completeness.  It contains
    no arrival-time component, so discovery order cannot change the winner.
    """
    original_bonus = not _is_aggregator(source_title, source_url)
    quality = 4_000_000 if original_bonus else 0
    article = None
    if article_slug:
        article = c.execute(
            "SELECT status, body, verdict_md, source, url FROM articles WHERE slug=?",
            (article_slug,),
        ).fetchone()
    if article:
        body = article["body"] or ""
        if extraction_quality_issue(body) is None:
            quality += 2_000_000
        if article["status"] == "analysed":
            quality += 500_000
        if article["verdict_md"]:
            quality += 250_000
        quality += min(len(body), 100_000)
        # The stored publisher name can reveal syndication even when a title
        # does not.  Remove the original-source bonus in that case.
        if original_bonus and _is_aggregator(article["source"], article["url"]):
            quality -= 4_000_000
    return quality


def default_article_index_policy(title=None, source=None, url=None, relevance=None,
                                 linked=False, clicks=0, impressions=0,
                                 age_days=None):
    """Return (status, reason, indexed_source) for scanner/RSS article pages."""
    source_kind = "curated" if linked else _status_source(source)
    rel = _as_float(relevance, 0.0) or 0.0
    clicks = _as_float(clicks, 0.0) or 0.0
    impressions = _as_float(impressions, 0.0) or 0.0

    if linked:
        return "index", "linked to public figure cope evidence", "curated"
    if clicks > 0:
        return "index", "Search Console clicks present", source_kind
    if impressions > 0:
        return "index", "Search Console impressions present; keep indexed for review", source_kind
    if _is_aggregator(source, url):
        return "noindex", "aggregator or syndicated source; keep crawlable only", source_kind
    if rel >= 75:
        return "index", f"high relevance score {rel:.0f}", source_kind
    if rel >= 65 and (age_days is None or age_days < 14):
        return "trial_index", f"new high-signal scanner article, relevance {rel:.0f}", source_kind
    if rel >= 65:
        return "review", f"high-signal article has no Search Console signal after review window, relevance {rel:.0f}", source_kind
    return "noindex", f"scanner/RSS article below index floor, relevance {rel:.0f}", source_kind


def is_indexable(row) -> bool:
    return (row or {}).get("index_status") in INDEXABLE_STATUSES



def url_hash(url: str) -> str:
    """Legacy-width hash of the shared, channel-neutral canonical URL."""
    return canonical_url_hash(url)[:20]


def normalize_title(title: str) -> str:
    """Normalize a title for hashing: lowercase, strip punctuation, collapse whitespace."""
    t = (title or "").lower()
    t = re.sub(r"[^a-z0-9\s]", "", t)
    t = re.sub(r"\s+", " ", t).strip()
    return t


def title_hash(title: str) -> str:
    """Hash of normalized title for exact-title dedup."""
    norm = normalize_title(title)
    return hashlib.sha256(norm.encode("utf-8")).hexdigest()[:16]


def title_exists(title: str) -> bool:
    """Check if an article with the same normalized title already exists."""
    th = title_hash(title)
    with conn() as c:
        cur = c.execute("SELECT 1 FROM articles WHERE title_hash = ? LIMIT 1", (th,))
        return cur.fetchone() is not None


def fuzzy_title_exists(title: str, days_window: int = 3) -> bool:
    """Check if a similar article title was ingested in the last N days.
    Uses SequenceMatcher with 0.70 threshold + shared entity check."""
    from difflib import SequenceMatcher
    norm_new = normalize_title(title)
    if len(norm_new) < 10:
        return False
    with conn() as c:
        cur = c.execute(
            """SELECT title FROM articles
               WHERE created_at >= datetime('now', ? || ' days')
               ORDER BY created_at DESC LIMIT 200""",
            (f"-{days_window}",),
        )
        for row in cur.fetchall():
            norm_existing = normalize_title(row[0])
            sim = SequenceMatcher(None, norm_new, norm_existing).ratio()
            if sim >= 0.70:
                return True
            # Also check: if >0.55 similarity AND they share numbers, likely same story
            if sim >= 0.55:
                nums_new = set(re.findall(r"\b\d+\b", norm_new))
                nums_old = set(re.findall(r"\b\d+\b", norm_existing))
                if nums_new and nums_new & nums_old:
                    return True
    return False


def make_slug(title: str, url: str) -> str:
    base = re.sub(r"[^a-z0-9]+", "-", (title or "").lower()).strip("-")[:60]
    if not base:
        base = "article"
    return f"{base}-{url_hash(url)[:8]}"


def exists(url: str) -> bool:
    ch = canonical_url_hash(url)
    with conn() as c:
        cur = c.execute(
            """SELECT 1 FROM articles
               WHERE canonical_url_hash = ? OR canonical_url = ? OR url = ?
               LIMIT 1""",
            (ch, canonical_url(url), url),
        )
        return cur.fetchone() is not None


def by_url_hash(url: str):
    """Look up article by URL hash."""
    ch = canonical_url_hash(url)
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM articles
               WHERE canonical_url_hash = ? OR canonical_url = ? OR url = ?
               LIMIT 1""",
            (ch, canonical_url(url), url),
        )
        row = cur.fetchone()
        return dict(row) if row else None


def _strip_html(text):
    """Remove HTML tags from text (e.g. <b>AI</b> -> AI)."""
    if not text:
        return text
    return re.sub(r'<[^>]+>', '', text)


def _article_provenance(c, article_slug, raw_url, source_title, source,
                        published=None, channel=None):
    canonical = canonical_url(raw_url)
    actual_channel = channel or _status_source(source)
    observation = provenance_key(
        canonical, f"{raw_url}\n{source}\nchannel:{actual_channel}", ""
    )
    c.execute(
        """INSERT OR IGNORE INTO article_provenance
           (article_slug, observation_key, raw_url, canonical_url,
            source_title, source, channel, observed_at)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
        (article_slug, observation, raw_url, canonical, source_title, source,
         actual_channel, published),
    )


def record_article_discovery_if_known(url, title, source, published=None,
                                      channel=None):
    """Attach a feed/channel observation to an existing canonical article."""
    canonical = canonical_url(url)
    if not canonical:
        return None
    with conn() as c:
        c.execute("BEGIN IMMEDIATE")
        row = c.execute(
            "SELECT slug FROM articles WHERE canonical_url=? LIMIT 1",
            (canonical,),
        ).fetchone()
        if not row:
            return None
        _article_provenance(
            c, row["slug"], url, _strip_html(title), source,
            published, channel,
        )
        return row["slug"]


def insert_pending(url, title, source, published, snippet, body, channel=None):
    """Insert one canonical publisher resource and record every discovery.

    The lock and canonical unique key make check-and-insert safe across the
    RSS, Google News, Brave and direct-submission workers.
    """
    title = _strip_html(title)
    canonical = canonical_url(url)
    if not canonical:
        return None
    canonical_hash = canonical_url_hash(canonical)
    slug = make_slug(title, canonical)
    th = title_hash(title)
    with conn() as c:
        c.execute("BEGIN IMMEDIATE")
        existing = c.execute(
            "SELECT slug FROM articles WHERE canonical_url = ? LIMIT 1",
            (canonical,),
        ).fetchone()
        if existing:
            _article_provenance(
                c, existing["slug"], url, title, source, published, channel
            )
            return None
        try:
            cur = c.execute(
                """INSERT INTO articles
                (slug, url, url_hash, canonical_url, canonical_url_hash,
                 title, title_hash, source, published, snippet, body, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')""",
                (slug, url, canonical_hash[:20], canonical, canonical_hash,
                 title, th, source, published, snippet, body),
            )
            _article_provenance(c, slug, url, title, source, published, channel)
            return slug
        except sqlite3.IntegrityError:
            existing = c.execute(
                "SELECT slug FROM articles WHERE canonical_url = ? LIMIT 1",
                (canonical,),
            ).fetchone()
            if existing:
                _article_provenance(
                    c, existing["slug"], url, title, source, published, channel
                )
            return None


def set_verdict(slug, verdict_md, one_liner, model, price, relevance=None):
    with conn() as c:
        existing = c.execute(
            "SELECT title, source, url, index_status, indexed_source FROM articles WHERE slug = ?",
            (slug,),
        ).fetchone()
        status, reason, indexed_source = default_article_index_policy(
            title=existing["title"] if existing else "",
            source=existing["source"] if existing else "",
            url=existing["url"] if existing else "",
            relevance=relevance,
        )
        if existing and existing["index_status"] == "index" and existing["indexed_source"] == "curated":
            status = existing["index_status"]
            indexed_source = existing["indexed_source"]
            reason = "preserved curated index status"

        # ---- shared daily publish cap -------------------------------------
        # Only promotions to an indexable status consume a slot. Capped-out
        # candidates stay fully analysed but noindex, and are queued so the
        # drainer can publish them on a later day, highest relevance first.
        if status in publish_gate.INDEXABLE_STATUSES:
            priority = _as_float(relevance, 0.0) or 0.0
            if indexed_source == "curated":
                priority += 1000.0
            if not publish_gate.claim_slot(
                c, slug, channel=indexed_source or "scanner",
                index_status=status, priority=priority,
            ):
                publish_gate.enqueue(
                    c, slug, desired_status=status, desired_reason=reason,
                    desired_source=indexed_source,
                    channel=indexed_source or "scanner", priority=priority,
                )
                status = "noindex"
                reason = "awaiting daily publish slot (queued)"
        # [redacted]
        cur = c.execute(
            """UPDATE articles
               SET verdict_md = ?, one_liner = ?, model = ?, price = ?,
                   relevance = ?,
                   status = 'analysed', analysed_at = CURRENT_TIMESTAMP,
                   error = NULL,
                   index_status = ?,
                   index_reason = ?,
                   index_checked_at = CURRENT_TIMESTAMP,
                   indexed_source = ?
               WHERE slug = ?""",
            (verdict_md, one_liner, model, price, relevance,
             status, reason, indexed_source, slug),
        )


def set_failed(slug, error):
    with conn() as c:
        cur = c.execute(
            "UPDATE articles SET status = 'failed', error = ? WHERE slug = ?",
            (error[:1000], slug),
        )


def quarantine_article(slug, reason):
    """Fail closed on deterministic consent, block, error, or short pages."""
    with conn() as c:
        c.execute(
            """UPDATE articles
                  SET status='quarantined', error=?, index_status='noindex',
                      index_reason=?, index_checked_at=CURRENT_TIMESTAMP
                WHERE slug=?""",
            (f"extraction_quality:{reason}",
             f"quarantined non-article extraction: {reason}", slug),
        )


def pending_for_analysis(limit=25):
    with conn() as c:
        cur = c.execute(
            "SELECT * FROM articles WHERE status = 'pending' ORDER BY id ASC LIMIT ?",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


def recent_analysed(limit=60, min_relevance=None):
    with conn() as c:
        if min_relevance is not None:
            cur = c.execute(
                """SELECT * FROM articles
                   WHERE status = 'analysed' AND verdict_md IS NOT NULL
                     AND (relevance IS NULL OR relevance >= ?)
                   ORDER BY analysed_at DESC LIMIT ?""",
                (min_relevance, limit),
            )
        else:
            cur = c.execute(
                """SELECT * FROM articles
                   WHERE status = 'analysed' AND verdict_md IS NOT NULL
                   ORDER BY analysed_at DESC LIMIT ?""",
                (limit,),
            )
        return [dict(r) for r in cur.fetchall()]


def sitemap_articles(limit=500):
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM articles
               WHERE status = 'analysed'
                 AND verdict_md IS NOT NULL
                 AND index_status IN ('index', 'trial_index')
               ORDER BY
                 CASE index_status WHEN 'index' THEN 0 ELSE 1 END,
                 analysed_at DESC
               LIMIT ?""",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


def sitemap_submissions(limit=200):
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM submissions
               WHERE status = 'analysed'
                 AND verdict_md IS NOT NULL
                 AND index_status IN ('index', 'trial_index')
               ORDER BY created_at DESC
               LIMIT ?""",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


def index_policy_counts():
    with conn() as c:
        counts_by_status = {}
        for table in ("articles", "submissions", "instant_scores"):
            if not _table_exists(c, table) or "index_status" not in _columns(c, table):
                continue
            cur = c.execute(
                f"""SELECT COALESCE(index_status, 'unset') AS status, COUNT(*) AS n
                    FROM {table}
                    GROUP BY COALESCE(index_status, 'unset')"""
            )
            for row in cur.fetchall():
                counts_by_status[row["status"]] = counts_by_status.get(row["status"], 0) + row["n"]
        return counts_by_status


def noindex_articles(limit=20):
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM articles
               WHERE status = 'analysed'
                 AND verdict_md IS NOT NULL
                 AND COALESCE(index_status, 'noindex') NOT IN ('index', 'trial_index')
               ORDER BY analysed_at DESC
               LIMIT ?""",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


def by_slug(slug):
    with conn() as c:
        cur = c.execute("SELECT * FROM articles WHERE slug = ?", (slug,))
        row = cur.fetchone()
        if row:
            result = dict(row)
            result["canonical_slug"] = result["slug"]
            return result
        row = c.execute(
            """SELECT a.* FROM article_aliases aa
               JOIN articles a ON a.slug=aa.article_slug
               WHERE aa.alias_slug=?""",
            (slug,),
        ).fetchone()
        if not row:
            return None
        result = dict(row)
        result["canonical_slug"] = result["slug"]
        result["requested_alias"] = slug
        return result


def counts():
    with conn() as c:
        cur = c.execute("SELECT status, COUNT(*) AS n FROM articles GROUP BY status")
        return {r["status"]: r["n"] for r in cur.fetchall()}



# ── Figures are people, not organisations ─────────────────────────────────
# Organisations kept drifting into the Cope Index (Chatham Financial,
# Microsoft Research, BCG). Their reports are real evidence, but they are
# not individuals and must not be listed as tracked figures.
[redacted secret-like line]
    "inc", "inc.", "llc", "ltd", "ltd.", "plc", "gmbh", "corp", "corp.",
    "corporation", "company", "co", "co.", "group", "holdings", "partners",
    "associates", "consulting", "consultancy", "advisors", "advisory",
    "institute", "institution", "foundation", "university", "college",
    "school", "laboratory", "laboratories", "labs", "lab", "research",
    "centre", "center", "council", "committee", "commission", "bureau",
    "agency", "association", "federation", "society", "union", "trust",
    "bank", "capital", "ventures", "fund", "systems", "technologies",
    "solutions", "industries", "international", "global", "worldwide",
    "ministry", "department", "office", "authority", "organisation",
    "organization", "press", "media", "news", "journal", "review",
    "financial", "securities", "management", "insurance", "analytics",
    "sciences", "health", "energy", "motors", "networks", "software",
}


def looks_like_organisation(name):
    """Heuristic: True when a candidate figure name is an organisation.

    Deliberately conservative — it blocks obvious organisations and lets
    ambiguous names through to human review rather than silently rejecting
    a real person.
    """
    raw = (name or "").strip()
    if not raw:
        return True
    lowered = raw.lower()
    cleaned = lowered.replace("(", " ").replace(")", " ").replace(",", " ")
[redacted secret-like line]
[redacted secret-like line]
        return True
[redacted secret-like line]
        return True
    # All-caps acronyms with no lowercase letters (BCG, IMF, OECD, NBER)
    letters = [ch for ch in raw if ch.isalpha()]
    if letters and all(ch.isupper() for ch in letters) and len(raw.split()) <= 2:
        return True
    return False


def upsert_figure(fig_id, name, title, category, photo_url, cope_bias):
    with conn() as c:
        cur = c.execute(
            """INSERT INTO figures (id, name, title, category, photo_url, cope_bias)
               VALUES (?, ?, ?, ?, ?, ?)
               ON CONFLICT(id) DO UPDATE SET
                   name=excluded.name, title=excluded.title,
                   category=excluded.category, photo_url=excluded.photo_url,
                   cope_bias=excluded.cope_bias, updated_at=CURRENT_TIMESTAMP""",
            (fig_id, name, title, category, photo_url, cope_bias),
        )


def get_figure(fig_id, include_inactive=False):
    """Fetch one figure. Archived non-person entries are hidden by default."""
    with conn() as c:
        cur = c.execute("SELECT * FROM figures WHERE id = ?", (fig_id,))
        row = cur.fetchone()
        if not row:
            return None
        rec = dict(row)
        if not include_inactive and not int(rec.get("active", 1) or 0):
            return None
        return rec


def get_leaderboard(include_inactive=False):
    """Tracked figures for public listings.

    Figures are individuals. Entries archived as non-persons (organisations,
    reports, institutions) are held at active=0: their scored evidence and
    provenance stay in the database, but they are not listed as people.
    """
    where = "" if include_inactive else "WHERE COALESCE(active, 1) = 1"
    with conn() as c:
        cur = c.execute(
            f"""SELECT * FROM figures {where} ORDER BY cope_score DESC, name ASC"""
        )
        return [dict(r) for r in cur.fetchall()]


HALF_LIFE_DAYS = 14.0
EVENT_WINDOW_DAYS = 7.0


def _as_utc(value, fallback=None):
    fallback = fallback or datetime.now(timezone.utc)
    if isinstance(value, datetime):
        parsed = value
    else:
        try:
            parsed = datetime.fromisoformat(str(value or "").replace("Z", "+00:00"))
        except (TypeError, ValueError):
            return fallback
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=timezone.utc)
    parsed = parsed.astimezone(timezone.utc)
    # Discovery metadata must not let a future timestamp dominate the score.
    return min(parsed, datetime.now(timezone.utc))


def weighted_cope_score(entries, as_of=None):
    """Return the documented 14-day half-life aggregate over unique events."""
    if not entries:
        return 50.0
    at = _as_utc(as_of)
    pool = list(entries)
    weighted = total_weight = 0.0
    decay = math.log(2.0) / HALF_LIFE_DAYS
    for entry in pool:
        observed = entry["event_observed_at"] if "event_observed_at" in entry.keys() else None
        created = entry["created_at"] if "created_at" in entry.keys() else None
        stamp = _as_utc(observed or created, at)
        age_days = max(0.0, (at - stamp).total_seconds() / 86400.0)
        weight = math.exp(-decay * age_days)
        weighted += float(entry["cope_score"]) * weight
        total_weight += weight
    return round(weighted / total_weight, 1) if total_weight else 50.0


def _score_history_rows(entries):
    history = []
    ordered = sorted(
        entries,
        key=lambda row: (
            str(row["event_observed_at"] or row["created_at"] or ""), row["id"]
        ),
    )
    for index, entry in enumerate(ordered):
        at = entry["event_observed_at"] or entry["created_at"]
        history.append({
            "score": weighted_cope_score(ordered[:index + 1], as_of=at),
            "date": at,
            "event_score": float(entry["cope_score"]),
        })
    return history


def recompute_figure(c, figure_id):
    entries = c.execute(
        """SELECT * FROM cope_entries WHERE figure_id = ?
           ORDER BY COALESCE(event_observed_at, created_at), id""",
        (figure_id,),
    ).fetchall()
    if not entries:
        c.execute(
            """UPDATE figures SET cope_score=50.0, prev_score=50.0,
                      total_quotes=0, last_quote=NULL, last_cope_type=NULL,
                      last_scored=NULL, updated_at=CURRENT_TIMESTAMP
                WHERE id=?""",
            (figure_id,),
        )
        return 50.0
    history = _score_history_rows(entries)
    current = weighted_cope_score(entries)
    previous = history[-2]["score"] if len(history) > 1 else 50.0
    last = entries[-1]
    c.execute(
        """UPDATE figures SET cope_score=?, prev_score=?, total_quotes=?,
                  last_quote=?, last_cope_type=?, last_scored=?,
                  updated_at=CURRENT_TIMESTAMP WHERE id=?""",
        (current, previous, len(entries), (last["quote"] or "")[:500],
         last["cope_type"], last["event_observed_at"] or last["created_at"],
         figure_id),
    )
    return current


def _cope_provenance(c, entry_id, article_slug, source_url, canonical,
                     source_title, quote, channel, observed_at,
                     observed_score=None, observed_type=None,
                     observed_analysis=None, observed_model=None,
                     quality=None):
    actual_channel = channel or "unknown"
    existing = c.execute(
        """SELECT 1 FROM cope_entry_provenance
            WHERE cope_entry_id=? AND COALESCE(canonical_url,'')=?
              AND COALESCE(source_title,'')=? AND COALESCE(quote,'')=?
              AND COALESCE(channel,'')=?
            LIMIT 1""",
        (entry_id, canonical or "", source_title or "", quote or "",
         actual_channel),
    ).fetchone()
    if existing:
        return
    observation = provenance_key(
        canonical, f"{source_title or ''}\nchannel:{actual_channel}",
        quote or "",
    )
    c.execute(
        """INSERT OR IGNORE INTO cope_entry_provenance
           (cope_entry_id, observation_key, article_slug, source_url,
            canonical_url, source_title, quote, channel, observed_at,
            observed_cope_score, observed_cope_type, observed_analysis_md,
            observed_model, representative_quality)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
        (entry_id, observation, article_slug, source_url, canonical,
         source_title, quote, actual_channel, observed_at, observed_score,
         observed_type, observed_analysis, observed_model, quality),
    )


def _gated_curated_promote(c, article_slug):
    """Promote a figure-linked article to index, subject to the daily cap.

    Figure-linked cope evidence is the site's highest-value content, so it
    gets a large priority boost and wins the queue against scanner articles.
    Cope entry rows are always written regardless: only the *indexing* of the
    linked article page is rate limited.
    """
    if not article_slug:
        return False
    if publish_gate.claim_slot(
        c, article_slug, channel="curated", index_status="index",
        priority=1000.0,
    ):
        c.execute(
            """UPDATE articles SET index_status='index',
                      index_reason='linked to public figure cope evidence',
                      index_checked_at=CURRENT_TIMESTAMP,
                      indexed_source='curated' WHERE slug=?""",
            (article_slug,),
        )
        return True
    publish_gate.enqueue(
        c, article_slug, desired_status="index",
        desired_reason="linked to public figure cope evidence",
        desired_source="curated", channel="curated", priority=1000.0,
    )
    return False


def add_cope_entry(figure_id, article_slug, quote, source_url, source_title,
                   cope_score, cope_type, analysis_md, model,
                   observed_at=None, channel=None):
    """Insert one unique underlying event and retain every source observation."""
    type_key = (cope_type or "").strip().lower()
    quote_key = (quote or "").strip().lower()
    invalid_type = (
        type_key == "not_attributed" or type_key.startswith("n/a")
        or quote_key.startswith(("n/a", "[no relevant]", "[leave blank]"))
    )
    if not 0 <= float(cope_score) <= 100 or invalid_type:
        return {"inserted": False, "reason": "invalid"}
    canonical = canonical_url(source_url)
    canonical_hash = canonical_url_hash(canonical)
    observed_dt = _as_utc(observed_at)
    observed_iso = observed_dt.isoformat()
    candidate_fingerprint = new_event_fingerprint(
        figure_id, source_title, quote, observed_iso
    )
    with conn() as c:
        c.execute("BEGIN IMMEDIATE")
        proposed_quality = representative_quality(
            c, article_slug, source_title, source_url
        )
        candidates = c.execute(
            """SELECT * FROM cope_entries WHERE figure_id = ?
               ORDER BY COALESCE(event_observed_at, created_at) DESC, id DESC""",
            (figure_id,),
        ).fetchall()
        match = None
        for existing in candidates:
            existing_canonical = existing["canonical_url"] or canonical_url(existing["source_url"])
            exact_url = bool(canonical and canonical == existing_canonical)
            existing_at = _as_utc(existing["event_observed_at"] or existing["created_at"])
            within_window = abs((observed_dt - existing_at).total_seconds()) <= EVENT_WINDOW_DAYS * 86400
            timeless = exact_statement_match(
                source_title or "", quote or "",
                existing["source_title"] or "", existing["quote"] or "",
            )
            if exact_url or timeless or (within_window and same_event(
                canonical_a=canonical,
                title_a=source_title or "",
                quote_a=quote or "",
                canonical_b=existing_canonical,
                title_b=existing["source_title"] or "",
                quote_b=existing["quote"] or "",
            )):
                match = existing
                break
        if match:
            _cope_provenance(
                c, match["id"], article_slug, source_url, canonical,
                source_title, quote, channel, observed_iso, cope_score,
                cope_type, analysis_md, model, proposed_quality,
            )
            existing_quality = int(match["representative_quality"] or 0)
            if not existing_quality:
                existing_quality = representative_quality(
                    c, match["article_slug"], match["source_title"],
                    match["source_url"],
                )
            existing_canonical = match["canonical_url"] or canonical_url(match["source_url"])
            promote = (
                proposed_quality > existing_quality
                or (
                    proposed_quality == existing_quality and canonical
                    and (not existing_canonical or canonical < existing_canonical)
                )
            )
            if promote:
                earliest = min(
                    _as_utc(match["event_observed_at"] or match["created_at"]),
                    observed_dt,
                ).isoformat()
                c.execute(
                    """UPDATE cope_entries SET article_slug=?, quote=?,
                              source_url=?, source_title=?, canonical_url=?,
                              canonical_url_hash=?, event_observed_at=?,
                              representative_quality=?, cope_score=?, cope_type=?,
                              analysis_md=?, model=? WHERE id=?""",
                    (article_slug, quote, source_url, source_title, canonical,
                     canonical_hash, earliest, proposed_quality, cope_score,
                     cope_type, analysis_md, model, match["id"]),
                )
                recompute_figure(c, figure_id)
            if article_slug:
                _gated_curated_promote(c, article_slug)
            return {
                "inserted": False, "entry_id": match["id"],
                "event_fingerprint": match["event_fingerprint"],
                "reason": "duplicate_event",
                "promoted": promote,
            }

        cur = c.execute(
            """INSERT INTO cope_entries
               (figure_id, article_slug, quote, source_url, source_title,
                canonical_url, canonical_url_hash, event_fingerprint,
                event_observed_at, representative_quality, cope_score,
                cope_type, analysis_md, model)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (figure_id, article_slug, quote, source_url, source_title,
             canonical, canonical_hash, candidate_fingerprint, observed_iso,
             proposed_quality, cope_score, cope_type, analysis_md, model),
        )
        entry_id = cur.lastrowid
        _cope_provenance(
            c, entry_id, article_slug, source_url, canonical, source_title,
            quote, channel, observed_iso, cope_score, cope_type, analysis_md,
            model, proposed_quality,
        )
        if article_slug:
            _gated_curated_promote(c, article_slug)
        recompute_figure(c, figure_id)
        return {
            "inserted": True, "entry_id": entry_id,
            "event_fingerprint": candidate_fingerprint,
        }




[redacted secret-like line]
    """Queue a URL for extraction and scoring."""
    canonical = canonical_url(url)
    canonical_hash = canonical_url_hash(canonical)
    with conn() as c:
        c.execute("BEGIN IMMEDIATE")
        # Dedupe: don't resubmit same URL for same figure within 7 days
        cur = c.execute(
            """SELECT 1 FROM url_submissions
               WHERE figure_id = ? AND canonical_url_hash = ?
               AND created_at > datetime('now', '-7 days')""",
            (figure_id, canonical_hash),
        )
        if cur.fetchone():
            return None  # already submitted recently
        # Also check if this URL is already in cope_entries
        cur = c.execute(
            """SELECT 1 FROM cope_entries
               WHERE figure_id = ? AND canonical_url_hash = ?""",
            (figure_id, canonical_hash),
        )
        if cur.fetchone():
            return None  # already scored
        cur = c.execute(
            """INSERT INTO url_submissions
               (figure_id, url, canonical_url, canonical_url_hash,
[redacted secret-like line]
               VALUES (?, ?, ?, ?, ?, ?)""",
[redacted secret-like line]
        )
        return cur.lastrowid


def get_pending_submissions(limit=20):
    """Get pending URL submissions for processing."""
    with conn() as c:
        cur = c.execute(
            """SELECT us.*, f.name as figure_name, f.title as figure_title
               FROM url_submissions us
               JOIN figures f ON us.figure_id = f.id
               WHERE us.status = 'pending'
               ORDER BY us.created_at ASC LIMIT ?""",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


def update_submission(sub_id, status, extracted_text=None, url_type=None, error_msg=None):
    """Update a URL submission after processing."""
    with conn() as c:
        cur = c.execute(
            """UPDATE url_submissions SET
                   status = ?,
                   extracted_text = COALESCE(?, extracted_text),
                   url_type = COALESCE(?, url_type),
                   error_msg = ?,
                   processed_at = CURRENT_TIMESTAMP
               WHERE id = ?""",
            (status, extracted_text, url_type, error_msg, sub_id),
        )


def get_submissions_for_figure(figure_id, limit=10):
    """Get recent submissions for a figure."""
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM url_submissions
               WHERE figure_id = ?
               ORDER BY created_at DESC LIMIT ?""",
            (figure_id, limit),
        )
        return [dict(r) for r in cur.fetchall()]


def figure_entries(figure_id, limit=50):
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM cope_entries
               WHERE figure_id = ? AND cope_score >= 0
                 AND cope_type != 'not_attributed' AND cope_type != 'N/A'
               ORDER BY created_at DESC LIMIT ?""",
            (figure_id, limit),
        )
        entries = [dict(r) for r in cur.fetchall()]
        for entry in entries:
            provenance = c.execute(
                """SELECT source_url, canonical_url, source_title, channel,
                          observed_at, observed_cope_score,
                          observed_cope_type, observed_model,
                          representative_quality
                     FROM cope_entry_provenance
                    WHERE cope_entry_id=? ORDER BY observed_at, id""",
                (entry["id"],),
            ).fetchall()
            entry["provenance"] = [dict(row) for row in provenance]
            primary_canonical = entry.get("canonical_url") or canonical_url(entry.get("source_url"))
            entry["alternate_sources"] = [
                item for item in entry["provenance"]
                if (item.get("canonical_url") or canonical_url(item.get("source_url")))
                != primary_canonical
            ]
            entry["additional_sources"] = len(entry["alternate_sources"])
        return entries


def figure_score_history(figure_id):
    """Get aggregate-score history after each unique event."""
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM cope_entries
               WHERE figure_id = ?
               ORDER BY COALESCE(event_observed_at, created_at), id""",
            (figure_id,),
        )
        return _score_history_rows(cur.fetchall())


def cope_entry_exists(figure_id, quote_text, source_url=None,
                      source_title=None, observed_at=None):
    """Read-only fast check; add_cope_entry repeats it under a write lock."""
    canonical = canonical_url(source_url)
    observed = _as_utc(observed_at)
    has_statement = bool((quote_text or "").strip())
    with conn() as c:
        rows = c.execute(
            "SELECT * FROM cope_entries WHERE figure_id=?",
            (figure_id,),
        ).fetchall()
        for row in rows:
            existing_canonical = row["canonical_url"] or canonical_url(row["source_url"])
            if canonical and canonical == existing_canonical:
                return True
            existing_at = _as_utc(row["event_observed_at"] or row["created_at"])
            timeless = has_statement and exact_statement_match(
                source_title or "", quote_text or "",
                row["source_title"] or "", row["quote"] or "",
            )
            if timeless:
                return True
            if abs((observed - existing_at).total_seconds()) > EVENT_WINDOW_DAYS * 86400:
                continue
            if has_statement and same_event(
                canonical_a=canonical,
                title_a=source_title or "",
                quote_a=quote_text or "",
                canonical_b=existing_canonical,
                title_b=row["source_title"] or "",
                quote_b=row["quote"] or "",
            ):
                return True
        return False


def record_cope_observation_if_known(
    figure_id, quote_text, source_url=None, source_title=None,
    observed_at=None, channel=None, article_slug=None,
):
    """Attach provenance to a known event without invoking the scorer.

    Matching is repeated under BEGIN IMMEDIATE so concurrent scanners cannot
    both decide the observation is new.  A pre-extraction call with no quote
    may only use exact canonical URL identity; fuzzy/title event matching is
    deliberately deferred until content has passed the extraction gate.
    """
    canonical = canonical_url(source_url)
    observed = _as_utc(observed_at)
    has_statement = bool((quote_text or "").strip())
    with conn() as c:
        c.execute("BEGIN IMMEDIATE")
        proposed_quality = representative_quality(
            c, article_slug, source_title, source_url
        )
        rows = c.execute(
            "SELECT * FROM cope_entries WHERE figure_id=?",
            (figure_id,),
        ).fetchall()
        for row in rows:
            existing_canonical = row["canonical_url"] or canonical_url(row["source_url"])
            exact_url = bool(canonical and canonical == existing_canonical)
            timeless = has_statement and exact_statement_match(
                source_title or "", quote_text or "",
                row["source_title"] or "", row["quote"] or "",
            )
            existing_at = _as_utc(row["event_observed_at"] or row["created_at"])
            within_window = abs((observed - existing_at).total_seconds()) <= EVENT_WINDOW_DAYS * 86400
            fuzzy = has_statement and within_window and same_event(
                canonical_a=canonical,
                title_a=source_title or "",
                quote_a=quote_text or "",
                canonical_b=existing_canonical,
                title_b=row["source_title"] or "",
                quote_b=row["quote"] or "",
            )
            if exact_url or timeless or fuzzy:
                existing_quality = int(row["representative_quality"] or 0)
                if not existing_quality:
                    existing_quality = representative_quality(
                        c, row["article_slug"], row["source_title"],
                        row["source_url"],
                    )
                promote = (
                    proposed_quality > existing_quality
                    or (
                        proposed_quality == existing_quality and canonical
                        and (not existing_canonical or canonical < existing_canonical)
                    )
                )
                # A better representative needs a score; let the caller reach
                # the Oracle, then add_cope_entry will promote it atomically.
                if promote:
                    return None
                _cope_provenance(
                    c, row["id"], article_slug, source_url, canonical,
                    source_title, quote_text, channel, observed.isoformat(),
                )
                if article_slug:
                    _gated_curated_promote(c, article_slug)
                return row["id"]
        return None


[redacted secret-like line]
    with conn() as c:
        cur = c.execute(
[redacted secret-like line]
               VALUES (?, ?, ?, ?)""",
            (article_slug, (author_name or "Anonymous").strip()[:50],
[redacted secret-like line]
        )


def get_comments(article_slug):
    with conn() as c:
        cur = c.execute(
            """SELECT id, author_name, body, created_at FROM comments
               WHERE article_slug = ? ORDER BY created_at ASC""",
            (article_slug,),
        )
        return [dict(r) for r in cur.fetchall()]


def comment_count(article_slug):
    with conn() as c:
        cur = c.execute(
            "SELECT COUNT(*) AS n FROM comments WHERE article_slug = ?",
            (article_slug,),
        )
        return cur.fetchone()["n"]


[redacted secret-like line]
    with conn() as c:
        cur = c.execute(
            """SELECT COUNT(*) AS n FROM comments
[redacted secret-like line]
[redacted secret-like line]
        )
        return cur.fetchone()["n"]


# ─── SUBMISSIONS ──────────────────────────────────────────

[redacted secret-like line]
    with conn() as c:
        cur = c.execute(
            """INSERT INTO submissions
[redacted secret-like line]
                index_status, index_reason, index_checked_at, indexed_source)
               VALUES (?, ?, ?, ?, ?, ?, 'trial_index',
                       'manual submission indexed by default',
                       CURRENT_TIMESTAMP, 'manual')""",
[redacted secret-like line]
        )
        return c.execute("SELECT last_insert_rowid()").fetchone()[0]


def set_submission_verdict(sub_id, verdict_md, one_liner, model, price):
    with conn() as c:
        cur = c.execute(
            """UPDATE submissions
               SET verdict_md = ?, one_liner = ?, model = ?, price = ?,
                   status = 'analysed'
               WHERE id = ?""",
            (verdict_md, one_liner, model, price, sub_id),
        )


def set_submission_failed(sub_id, error):
    with conn() as c:
        cur = c.execute(
            "UPDATE submissions SET status = 'failed', error = ? WHERE id = ?",
            (error[:1000], sub_id),
        )


def get_submission(sub_id):
    with conn() as c:
        cur = c.execute(
            "SELECT * FROM submissions WHERE id = ? AND status = 'analysed'",
            (sub_id,),
        )
        row = cur.fetchone()
        return dict(row) if row else None


# ─── SUGGESTIONS ──────────────────────────────────────────

[redacted secret-like line]
    with conn() as c:
        cur = c.execute(
[redacted secret-like line]
               VALUES (?, ?, ?, ?)""",
[redacted secret-like line]
        )
        return True


[redacted secret-like line]
    with conn() as c:
        cur = c.execute(
            """SELECT COUNT(*) AS n FROM suggestions
[redacted secret-like line]
[redacted secret-like line]
        )
        return cur.fetchone()["n"]


# ─── COPE OF THE WEEK ────────────────────────────────────

def cope_of_the_week():
    """Return the top cope entry from the past week, cached in cotw_archive."""
    from datetime import datetime, timedelta
    import re as _re
    today = datetime.utcnow().date()
    monday = today - timedelta(days=today.weekday())
    week_key = monday.strftime("%Y-%m-%d")

    with conn() as c:
        row = c.execute(
            "SELECT * FROM cotw_archive WHERE week_start = ?", (week_key,)
        ).fetchone()
        if row:
            d = dict(row)
            if not d.get('figure_name'):
                t = d.get('title', '')
                if ' \u2014 ' in t:
                    d['figure_name'] = t.split(' \u2014 ')[0]
            if not d.get('cope_score'):
                t = d.get('title', '')
                m = _re.search(r'(\d+)/100', t)
                if m:
                    d['cope_score'] = float(m.group(1))
            if not d.get('cope_type'):
                d['cope_type'] = d.get('source', 'Maximum Cope')
            return d

        week_ago = (today - timedelta(days=7)).strftime("%Y-%m-%d")
        entry = c.execute(
            "SELECT ce.*, f.name as figure_name "
            "FROM cope_entries ce "
            "JOIN figures f ON ce.figure_id = f.id "
            "WHERE ce.created_at >= ? "
            "AND ce.cope_score BETWEEN 0 AND 100 "
            "ORDER BY ce.cope_score DESC LIMIT 1",
            (week_ago,)
        ).fetchone()

        if not entry:
            return None

        entry = dict(entry)
        slug = "cope-%s-%s" % (entry['figure_id'], week_key)
        fig = entry['figure_name']
        score = entry['cope_score']
        ctype = entry.get('cope_type', '')
        title = "%s \u2014 %d/100 Cope Score" % (fig, int(score))

        cur = c.execute(
            "INSERT OR REPLACE INTO cotw_archive "
            "(week_start, slug, title, source, one_liner, url, published, analysed_at, figure_name, cope_score, cope_type, analysis_md) "
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (week_key, slug, title, ctype, entry.get('quote', ''),
             entry.get('source_url', ''), entry.get('created_at', ''),
             entry.get('created_at', ''), fig, score, ctype, entry.get('analysis_md', ''))
        )

        cached = c.execute(
            "SELECT * FROM cotw_archive WHERE week_start = ?", (week_key,)
        ).fetchone()
        if cached:
            d = dict(cached)
            if not d.get('figure_name'):
                d['figure_name'] = fig
            if not d.get('cope_score'):
                d['cope_score'] = score
            if not d.get('cope_type'):
                d['cope_type'] = ctype or 'Maximum Cope'
            return d
        return None

def cotw_archive_list(limit=52):
    """Return past Cope of the Week winners, newest first."""
    with conn() as c:
        cur = c.execute(
            """SELECT ca.*, a.snippet, a.verdict_md
               FROM cotw_archive ca
               LEFT JOIN articles a ON a.slug = ca.slug
               ORDER BY ca.week_start DESC LIMIT ?""",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


# ─── SEARCH ───────────────────────────────────────────────

def rebuild_fts():
    """Rebuild the FTS5 index from articles table."""
    with conn() as c:
        cur = c.execute("DELETE FROM articles_fts")
        cur = c.execute("""
            INSERT INTO articles_fts(slug, title, source, snippet, one_liner, verdict_md)
            SELECT slug, title, source, COALESCE(snippet,''), COALESCE(one_liner,''), COALESCE(verdict_md,'')
            FROM articles WHERE status = 'analysed'
        """)


def search_articles(query, limit=30):
    """Full-text search across articles."""
    if not query or len(query.strip()) < 2:
        return []
    safe_q = re.sub(r'[^\w\s]', ' ', query).strip()
    terms = safe_q.split()
    if not terms:
        return []
    fts_query = ' OR '.join(f'"{t}"*' for t in terms[:5])
    with conn() as c:
        try:
            cur = c.execute("""
                SELECT a.* FROM articles a
                JOIN articles_fts f ON a.slug = f.slug
                WHERE articles_fts MATCH ?
                ORDER BY rank
                LIMIT ?
            """, (fts_query, limit))
            return [dict(r) for r in cur.fetchall()]
        except Exception:
            like_q = f"%{safe_q}%"
            cur = c.execute("""
                SELECT * FROM articles
                WHERE status = 'analysed' AND (
                    title LIKE ? OR one_liner LIKE ? OR source LIKE ? OR verdict_md LIKE ?
                )
                ORDER BY analysed_at DESC LIMIT ?
            """, (like_q, like_q, like_q, like_q, limit))
            return [dict(r) for r in cur.fetchall()]


# ─── INSTANT SCORES ──────────────────────────────────────

INSTANT_SCHEMA = """
CREATE TABLE IF NOT EXISTS instant_scores (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    name        TEXT NOT NULL,
    slug        TEXT UNIQUE NOT NULL,
    research_text TEXT,
    quotes_json TEXT,
    cope_score  REAL,
    cope_types  TEXT,
    oracle_verdict TEXT,
[redacted secret-like line]
    perplexity_model TEXT,
    scoring_model TEXT,
    total_price REAL DEFAULT 0,
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP,
    index_status TEXT DEFAULT 'trial_index',
    index_reason TEXT DEFAULT 'manual instant score indexed by default',
    index_checked_at TEXT,
    indexed_source TEXT DEFAULT 'instant'
);
CREATE INDEX IF NOT EXISTS idx_instant_slug ON instant_scores(slug);
CREATE INDEX IF NOT EXISTS idx_instant_name ON instant_scores(name COLLATE NOCASE);
CREATE INDEX IF NOT EXISTS idx_instant_created ON instant_scores(created_at DESC);
"""


def init_instant():
    with conn() as c:
        c.executescript(INSTANT_SCHEMA)
        _ensure_index_policy_columns(c)


def get_instant_by_slug(slug):
    with conn() as c:
        cur = c.execute("SELECT * FROM instant_scores WHERE slug = ?", (slug,))
        row = cur.fetchone()
        return dict(row) if row else None


def get_cached_instant(name, max_age_hours=24):
    """Return cached instant score if fresh enough."""
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM instant_scores
               WHERE name = ? COLLATE NOCASE
                 AND created_at > datetime('now', ?)
               ORDER BY created_at DESC LIMIT 1""",
            (name.strip(), f"-{max_age_hours} hours"),
        )
        row = cur.fetchone()
        return dict(row) if row else None


def save_instant_score(name, slug, research_text, quotes_json, cope_score,
[redacted secret-like line]
                       scoring_model, total_price):
    with conn() as c:
        try:
            cur = c.execute(
                """INSERT INTO instant_scores
                   (name, slug, research_text, quotes_json, cope_score, cope_types,
[redacted secret-like line]
                    index_status, index_reason, index_checked_at, indexed_source)
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                           'trial_index', 'manual instant score indexed by default',
                           CURRENT_TIMESTAMP, 'instant')""",
                (name, slug, research_text, quotes_json, cope_score, cope_types,
[redacted secret-like line]
            )
            return c.execute("SELECT last_insert_rowid()").fetchone()[0]
        except sqlite3.IntegrityError:
            return None


[redacted secret-like line]
    with conn() as c:
        cur = c.execute(
            """SELECT COUNT(*) AS n FROM instant_scores
[redacted secret-like line]
[redacted secret-like line]
        )
        return cur.fetchone()["n"]


def recent_instant_scores(limit=20):
    with conn() as c:
        cur = c.execute(
            "SELECT * FROM instant_scores ORDER BY created_at DESC LIMIT ?",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


def sitemap_instant_scores(limit=100):
    with conn() as c:
        cur = c.execute(
            """SELECT * FROM instant_scores
               WHERE index_status IN ('index', 'trial_index')
               ORDER BY created_at DESC LIMIT ?""",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


# ─── FEEDBACK ─────────────────────────────────────────────

FEEDBACK_SCHEMA = """
CREATE TABLE IF NOT EXISTS feedback (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    name        TEXT,
    email       TEXT,
    message     TEXT NOT NULL,
[redacted secret-like line]
    referrer    TEXT DEFAULT '',
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_feedback_created ON feedback(created_at DESC);
"""


def init_feedback():
    with conn() as c:
        c.executescript(FEEDBACK_SCHEMA)


[redacted secret-like line]
    with conn() as c:
        cur = c.execute(
[redacted secret-like line]
               VALUES (?, ?, ?, ?, ?)""",
[redacted secret-like line]
        )
        return True


[redacted secret-like line]
    with conn() as c:
        cur = c.execute(
            """SELECT COUNT(*) AS n FROM feedback
[redacted secret-like line]
[redacted secret-like line]
        )
        return cur.fetchone()["n"]


def get_all_feedback(limit=200):
    with conn() as c:
        cur = c.execute(
            "SELECT * FROM feedback ORDER BY created_at DESC LIMIT ?",
            (limit,),
        )
        return [dict(r) for r in cur.fetchall()]


# ─── ADMIN HELPERS ────────────────────────────────────────

def get_all_suggestions(status=None):
    with conn() as c:
        if status:
            cur = c.execute(
                "SELECT * FROM suggestions WHERE status = ? ORDER BY created_at DESC",
                (status,),
            )
        else:
            cur = c.execute("SELECT * FROM suggestions ORDER BY created_at DESC")
        return [dict(r) for r in cur.fetchall()]


def get_suggestion(sid):
    with conn() as c:
        cur = c.execute("SELECT * FROM suggestions WHERE id = ?", (sid,))
        row = cur.fetchone()
        return dict(row) if row else None


def update_suggestion_status(sid, status):
    with conn() as c:
        cur = c.execute("UPDATE suggestions SET status = ? WHERE id = ?", (status, sid))


def get_admin_stats():
    with conn() as c:
        stats = {}
        stats["total_articles"] = c.execute("SELECT COUNT(*) FROM articles").fetchone()[0]
        stats["total_verdicts"] = c.execute("SELECT COUNT(*) FROM articles WHERE status = 'analysed'").fetchone()[0]
        stats["total_comments"] = c.execute("SELECT COUNT(*) FROM comments").fetchone()[0]
        stats["total_submissions"] = c.execute("SELECT COUNT(*) FROM submissions").fetchone()[0]
        stats["total_figures"] = c.execute("SELECT COUNT(*) FROM figures").fetchone()[0]
        stats["total_cope_entries"] = c.execute("SELECT COUNT(*) FROM cope_entries").fetchone()[0]
        stats["suggestions_pending"] = c.execute("SELECT COUNT(*) FROM suggestions WHERE status = 'pending'").fetchone()[0]
        stats["suggestions_approved"] = c.execute("SELECT COUNT(*) FROM suggestions WHERE status = 'approved'").fetchone()[0]
        stats["suggestions_dismissed"] = c.execute("SELECT COUNT(*) FROM suggestions WHERE status = 'dismissed'").fetchone()[0]
        try:
            stats["total_feedback"] = c.execute("SELECT COUNT(*) FROM feedback").fetchone()[0]
        except Exception:
            stats["total_feedback"] = 0
        return stats
```
