---
type: "Source File"
title: "\"\"\"SQLite storage for UK CopeCheck — figures, cope entries, oracle archive, stats, analyses, ask-oracle Q&A.\"\"\""
description: "\"\"\"SQLite storage for UK CopeCheck — figures, cope entries, oracle archive, stats, analyses, ask-oracle Q&A.\"\"\" import os import re import logging import sqlite3 import hashlib import json import math from contextlib."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-10-29T11:02:54Z"
site: "uk"
source_path: "copecheck-uk/db_uk.py"
---

# """SQLite storage for UK CopeCheck — figures, cope entries, oracle archive, stats, analyses, ask-oracle Q&A."""

Source path: `copecheck-uk/db_uk.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-10-29T11:02:54Z`

```py
"""SQLite storage for UK CopeCheck — figures, cope entries, oracle archive, stats, analyses, ask-oracle Q&A."""
import os
import re
import logging
import sqlite3
import hashlib
import json
import math
from contextlib import contextmanager
from datetime import datetime, timezone, timedelta
from pathlib import Path
from urllib.parse import urlsplit

from canonical_identity import (
    canonical_url,
    canonical_url_hash,
    exact_statement_match,
    new_event_fingerprint,
    normalise_text,
    provenance_key,
    same_event,
)

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

MONTH_ORDER_MAP = {"January":1,"February":2,"March":3,"April":4,"May":5,"June":6,
               "July":7,"August":8,"September":9,"October":10,"November":11,"December":12}
INVALID_PUBLIC_MODES = ("unknown", "n/a", "none", "other", "irrelevant", "")
EVENT_WINDOW_DAYS = 7.0

def normalise_source_url(url):
    """Compatibility wrapper around the shared, channel-neutral identity."""
    return canonical_url(url)

def _public_score_filter(alias=""):
    """SQL predicate for entries that should affect public figure scores.

    The pipeline can produce review records for articles that mention a figure
    without a scoreable claim. Those often arrive as cope_score=0 +
    primary_mode=unknown. They are useful in pipeline_results, but they should
    not be treated as lucid public cope entries or pulled into the leaderboard.
    """
    prefix = f"{alias}." if alias else ""
    return (
        f"lower(coalesce({prefix}cope_type, '')) "
        "NOT IN ('unknown', 'n/a', 'none', 'other', 'irrelevant', '')"
    )

def _parse_entry_time(value):
    try:
        ts = datetime.fromisoformat(str(value or "").replace("Z", "+00:00"))
        if ts.tzinfo is None:
            ts = ts.replace(tzinfo=timezone.utc)
        return ts
    except Exception:
        return datetime.now(timezone.utc) - timedelta(days=30)


def _entry_timestamp(entry):
    return entry.get("event_observed_at") or entry.get("created_at")


def _weighted_score(entries, half_life_days=45.0):
    now = datetime.now(timezone.utc)
    decay = math.log(2) / half_life_days
    total_w = 0.0
    total_s = 0.0
    for entry in entries:
        ts = _parse_entry_time(_entry_timestamp(entry))
        age_days = (now - ts).total_seconds() / 86400.0
        w = math.exp(-decay * age_days)
        total_w += w
        total_s += float(entry.get("cope_score") or 0) * w
    return round(total_s / total_w, 1) if total_w > 0 else 0.0

def _percentile(scores, p):
    if not scores:
        return 0.0
    ordered = sorted(float(s or 0) for s in scores)
    k = (len(ordered) - 1) * p
    lo = math.floor(k)
    hi = math.ceil(k)
    if lo == hi:
        return ordered[int(k)]
    return ordered[lo] * (hi - k) + ordered[hi] * (k - lo)

def _role_pressure(role):
    role_l = (role or "").lower()
    if "prime minister" in role_l and "former" not in role_l:
        return 12.0
    if any(marker in role_l for marker in (
        "chancellor of the exchequer",
        "leader of the opposition",
        "first minister",
[redacted secret-like line]
    )):
        return 6.0
    if "former prime minister" in role_l:
        return 5.0
    if any(marker in role_l for marker in (
        "leader",
        "mayor",
[redacted secret-like line]
        "shadow chancellor",
    )):
        return 4.0
    return 0.0

def _entry_age_days(entry, now):
    ts = _parse_entry_time(_entry_timestamp(entry))
    return max(0.0, (now - ts).total_seconds() / 86400.0)

def _institutional_floor(role, fig_type="", category=""):
    if (category or "").lower() == "structural_critic":
        return 0.0
    role_l = (role or "").lower()
    type_l = (fig_type or "").lower()
    is_political = type_l in {"politician", "political"} or any(marker in role_l for marker in (
        "prime minister",
        "chancellor",
[redacted secret-like line]
        "leader",
        "mayor",
        "minister",
        "mp",
    ))
    if not is_political:
        return 0.0
    if "prime minister" in role_l and "former" not in role_l:
        return 70.0
    if any(marker in role_l for marker in (
        "chancellor of the exchequer",
        "leader of the opposition",
        "first minister",
[redacted secret-like line]
    )):
        return 58.0
    if "former prime minister" in role_l:
        return 55.0
    if any(marker in role_l for marker in (
        "mayor",
[redacted secret-like line]
        "shadow chancellor",
        "leader",
        "minister",
    )):
        return 50.0
    return 42.0

def _public_cope_index(entries, role="", fig_type="", category=""):
    """Leaderboard score, not a plain average.

    A public figure should not be laundered back to "low cope" by one or two
    recent soft or lucid entries if there is a repeated record of high-severity
    claims. The index blends the recent average, the upper-quartile record, the
    strongest still-fresh claim, and a small role/frequency pressure term.
    """
    if not entries:
        return 0.0

    now = datetime.now(timezone.utc)
    scores = [float(entry.get("cope_score") or 0) for entry in entries]
    baseline = _weighted_score(entries, half_life_days=45.0)
    severe_threshold = max(60.0, _percentile(scores, 0.75))
    severe_entries = [
        entry for entry in entries
        if float(entry.get("cope_score") or 0) >= severe_threshold
    ]
    severe_avg = (
        _weighted_score(severe_entries, half_life_days=90.0)
        if severe_entries else baseline
    )

    half_life_days = 90.0
    decay = math.log(2) / half_life_days
    max_recent = max(
        float(entry.get("cope_score") or 0) * math.exp(-decay * _entry_age_days(entry, now))
        for entry in entries
    )
    high_recent = sum(
        1 for entry in entries
        if float(entry.get("cope_score") or 0) >= 60 and _entry_age_days(entry, now) <= 60
    )
    terminal_recent = sum(
        1 for entry in entries
        if float(entry.get("cope_score") or 0) >= 80 and _entry_age_days(entry, now) <= 60
    )
    lucid_recent = sum(
        1 for entry in entries
        if float(entry.get("cope_score") or 0) <= 19 and _entry_age_days(entry, now) <= 30
    )

    frequency_lift = min(10.0, high_recent * 1.0 + terminal_recent * 1.5)
    lucid_offset = min(6.0, lucid_recent * 0.8)
    score = (
        baseline * 0.47
        + severe_avg * 0.34
        + max_recent * 0.19
        + frequency_lift
        + _role_pressure(role)
        - lucid_offset
    )
    floor = _institutional_floor(role, fig_type, category)
    if floor:
        score = max(score, floor)
    return round(max(0.0, min(96.0, score)), 1)

def _format_latest_incident(entry):
    source = entry.get("source_title") or "source"
    score = int(round(float(entry.get("cope_score") or 0)))
    cope_type = entry.get("cope_type") or "scored"
    date = str(_entry_timestamp(entry) or "")[:10]
    date_part = f" on {date}" if date else ""
    return f"Latest: {source} — scored {score} ({cope_type}){date_part}"

def _public_entries(c, figure_id, limit=None, order="DESC"):
    limit_sql = " LIMIT ?" if limit is not None else ""
    params = (figure_id, limit) if limit is not None else (figure_id,)
    cur = c.execute(
        f"""SELECT * FROM cope_entries
            WHERE figure_id = ? AND {_public_score_filter()}
            ORDER BY COALESCE(event_observed_at, created_at) {order}, id {order}{limit_sql}""",
        params,
    )
    return [dict(r) for r in cur.fetchall()]

def _hydrate_public_figure(c, fig):
    entries = _public_entries(c, fig["id"])
    fig["total_quotes"] = len(entries)
    if entries:
        fig["cope_score"] = _public_cope_index(
            entries,
            fig.get("role", ""),
            fig.get("type", ""),
            fig.get("category", ""),
        )
        fig["latest_incident"] = _format_latest_incident(entries[0])
        fig["last_quote"] = entries[0].get("quote")
        fig["last_cope_type"] = entries[0].get("cope_type")
        fig["last_scored"] = entries[0].get("created_at")
    else:
        fig["cope_score"] = 0.0
        if not fig.get("latest_incident"):
            fig["latest_incident"] = "No scored sources yet — awaiting pipeline data."
    return fig

def _month_sort_key(month_str):
    parts = month_str.strip().split()
    if len(parts) == 2:
        m = MONTH_ORDER_MAP.get(parts[0], 0)
        try:
            return int(parts[1]) * 100 + m
        except ValueError:
            pass
    return 0


SCHEMA = """
CREATE TABLE IF NOT EXISTS figures (
    id          TEXT PRIMARY KEY,
    name        TEXT NOT NULL,
    role        TEXT,
    party       TEXT,
    type        TEXT,
    category    TEXT,
    cope_score  REAL DEFAULT 50.0,
    prev_score  REAL DEFAULT 50.0,
    latest_incident TEXT,
    scapegoat_of_choice TEXT,
    cope_streak_days INTEGER DEFAULT 0,
    photo_url   TEXT,
    watch_for   TEXT,
    why_monitor TEXT,
    total_quotes INTEGER DEFAULT 0,
    last_quote  TEXT,
    last_cope_type TEXT,
    last_scored TEXT,
    active      INTEGER DEFAULT 1,
    archived_reason 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),
    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) ON DELETE CASCADE,
    observation_key TEXT NOT NULL,
    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 analyses (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    input_text  TEXT,
    input_url   TEXT,
    extracted_title TEXT,
    cope_score  INTEGER,
    cope_type   TEXT,
    scapegoats  TEXT,
    structural_reality TEXT,
    what_data_says TEXT,
    verdict     TEXT,
    explanation TEXT,
    model       TEXT,
    slug        TEXT UNIQUE,
[redacted secret-like line]
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_analyses_created ON analyses(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_analyses_slug ON analyses(slug);

CREATE TABLE IF NOT EXISTS scapegoat_narratives (
    id          TEXT PRIMARY KEY,
    narrative   TEXT,
    scapegoat   TEXT,
    reality     TEXT,
    data_source TEXT,
    times_invoked INTEGER DEFAULT 0,
    trend       TEXT DEFAULT 'stable',
    updated_at  TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS oracle_archive (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    month       TEXT UNIQUE NOT NULL,
    data_json   TEXT NOT NULL,
    ai_summary  TEXT,
    ai_gap_analysis TEXT,
    ai_scapegoat_check TEXT,
    ai_model    TEXT,
    scored_at   TEXT,
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_oracle_month ON oracle_archive(month DESC);

CREATE TABLE IF NOT EXISTS stats_archive (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    month       TEXT UNIQUE NOT NULL,
    data_json   TEXT NOT NULL,
    ai_commentary TEXT,
    ai_model    TEXT,
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_stats_month ON stats_archive(month DESC);

CREATE TABLE IF NOT EXISTS oracle_questions (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    question    TEXT NOT NULL,
    answer      TEXT,
    data_context TEXT,
    model       TEXT,
[redacted secret-like line]
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_oracle_questions_created ON oracle_questions(created_at DESC);

CREATE TABLE IF NOT EXISTS bulletin_analyses (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    bulletin_type TEXT NOT NULL,
    bulletin_url TEXT NOT NULL,
    bulletin_title TEXT,
    bulletin_date TEXT,
    raw_text    TEXT,
    cope_score  INTEGER,
    ai_analysis TEXT,
    key_data_points TEXT,
    what_they_said TEXT,
    what_data_shows TEXT,
    emphasis_vs_downplay TEXT,
    language_choices TEXT,
    structural_issues_avoided TEXT,
    ai_model    TEXT,
    scored_at   TEXT,
    created_at  TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_bulletin_type ON bulletin_analyses(bulletin_type, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_bulletin_url ON bulletin_analyses(bulletin_url);
"""


@contextmanager
def conn():
    c = sqlite3.connect(DB_PATH, timeout=60)
    c.row_factory = sqlite3.Row
    c.execute("PRAGMA foreign_keys=ON")
    c.execute("PRAGMA journal_mode=WAL")
    try:
        yield c
        c.commit()
    finally:
        c.close()


def init():
    with conn() as c:
        c.executescript(SCHEMA)
        _ensure_column(c, "figures", "active", "INTEGER DEFAULT 1")
        _ensure_column(c, "figures", "archived_reason", "TEXT")
        _ensure_column(c, "cope_entries", "canonical_url", "TEXT")
        _ensure_column(c, "cope_entries", "canonical_url_hash", "TEXT")
        _ensure_column(c, "cope_entries", "event_fingerprint", "TEXT")
        _ensure_column(c, "cope_entries", "event_observed_at", "TEXT")
        _ensure_column(c, "cope_entries", "representative_quality", "INTEGER NOT NULL DEFAULT 0")
        _ensure_column(c, "youtube_videos", "processing_started_at", "TIMESTAMP")
        _ensure_column(c, "youtube_videos", "recovery_started_at", "TIMESTAMP")
        _ensure_column(c, "youtube_videos", "score_attempts", "INTEGER DEFAULT 0")
        # Worker lease. The external worker renews this every 60s while it holds
        # a job, so a dead or wedged worker stops looking "busy" within a couple
        # of minutes instead of occupying the serial queue for a full 25-minute
        # processing timeout. Purely additive: NULL means "this worker does not
        # send heartbeats", and every query below falls back to
        # processing_started_at in that case, so an older worker still works.
        _ensure_column(c, "youtube_videos", "lease_renewed_at", "TIMESTAMP")
        c.execute(
            "CREATE INDEX IF NOT EXISTS idx_cope_canonical "
            "ON cope_entries(figure_id, canonical_url_hash)"
        )
        # Existing databases must be backfilled/merged by
        # migrate_cope_events.py before the uniqueness invariant is enabled.
        missing = c.execute(
            "SELECT COUNT(*) FROM cope_entries WHERE event_fingerprint IS NULL"
        ).fetchone()[0]
        if not missing:
            c.execute(
                "CREATE UNIQUE INDEX IF NOT EXISTS uq_cope_figure_event "
                "ON cope_entries(figure_id, event_fingerprint)"
            )


def _ensure_column(c, table, column, ddl):
    existing = {row["name"] for row in c.execute(f"PRAGMA table_info({table})")}
    if column not in existing:
        c.execute(f"ALTER TABLE {table} ADD COLUMN {column} {ddl}")


def upsert_figure(fig_id, name, role, party, fig_type, category,
                  cope_score, latest_incident, scapegoat_of_choice,
                  cope_streak_days, photo_url="", watch_for="", why_monitor=""):
    with conn() as c:
        c.execute("""
            INSERT INTO figures (id, name, role, party, type, category,
                cope_score, latest_incident, scapegoat_of_choice,
                cope_streak_days, photo_url, watch_for, why_monitor)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(id) DO UPDATE SET
                name=excluded.name, role=excluded.role, party=excluded.party,
                type=excluded.type, category=excluded.category,
                latest_incident=CASE WHEN figures.latest_incident IS NOT NULL AND figures.latest_incident != 'Awaiting pipeline scoring from live news sources.' THEN figures.latest_incident ELSE excluded.latest_incident END,
                scapegoat_of_choice=excluded.scapegoat_of_choice,
                cope_streak_days=excluded.cope_streak_days,
                photo_url=COALESCE(NULLIF(excluded.photo_url, ''), photo_url),
                watch_for=excluded.watch_for,
                why_monitor=excluded.why_monitor,
                updated_at=CURRENT_TIMESTAMP
        """, (fig_id, name, role, party, fig_type, category,
              cope_score, latest_incident, scapegoat_of_choice,
              cope_streak_days, photo_url, watch_for, why_monitor))


def set_figure_active(figure_id, active=True, reason=""):
    with conn() as c:
        c.execute("""UPDATE figures
            SET active = ?, archived_reason = ?, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?""", (1 if active else 0, "" if active else reason, figure_id))


def get_figure(fig_id):
    with conn() as c:
        cur = c.execute("SELECT * FROM figures WHERE id = ?", (fig_id,))
        row = cur.fetchone()
        return _hydrate_public_figure(c, dict(row)) if row else None


def get_leaderboard(include_empty=False):
    """Return figures with live time-weighted cope scores.

    Recalculates each figure's score from cope_entries using the same
    exponential-decay formula as add_cope_entry(). Review/unknown zero entries
    are excluded because they usually mean "no scoreable claim was attributed",
    not "the figure made a perfectly lucid structural argument".
    """
    with conn() as c:
        cur = c.execute("SELECT * FROM figures WHERE COALESCE(active, 1) = 1 ORDER BY name ASC")
        figures = [dict(r) for r in cur.fetchall()]

        visible = []
        for fig in figures:
            _hydrate_public_figure(c, fig)
            if include_empty or int(fig.get("total_quotes") or 0) > 0:
                visible.append(fig)

        visible.sort(key=lambda f: (-f["cope_score"], f["name"]))
        return visible


def update_figure_score(figure_id, new_score, prev_score, quote, cope_type):
    with conn() as c:
        c.execute("""UPDATE figures SET cope_score = ?, prev_score = ?,
            total_quotes = (SELECT COUNT(*) FROM cope_entries WHERE figure_id = ? AND """ + _public_score_filter() + """),
            last_quote = ?, last_cope_type = ?,
            last_scored = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?""", (new_score, prev_score, figure_id, quote[:500], cope_type, figure_id))


def update_figure_photo(figure_id, photo_url):
    with conn() as c:
        c.execute("UPDATE figures SET photo_url = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
                  (photo_url, figure_id))


def _as_utc(value=None):
    now = 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 now
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=timezone.utc)
    return min(parsed.astimezone(timezone.utc), now)


def _representative_quality(source_url, source_title, quote):
    """Prefer direct, well-described observations without using score severity."""
    canonical = canonical_url(source_url)
    host = (urlsplit(canonical).hostname or "").lower() if canonical else ""
    quality = 80 if canonical else 0
    if host == "news.google.com":
        quality -= 60
    elif any(host == name or host.endswith("." + name) for name in (
        "aol.com", "aol.co.uk", "yahoo.com", "yahoo.co.uk",
    )):
        quality -= 20
    if str(source_title or "").strip():
        quality += 10
    quality += min(len(normalise_text(quote)), 500) // 25
    return max(0, quality)


def _insert_cope_provenance(c, entry_id, source_url, canonical, source_title,
                            quote, channel, observed_at, cope_score, cope_type,
                            analysis_md, model, quality,
                            legacy_cope_entry_id=None):
    actual_channel = str(channel or "unknown")
    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, source_url, canonical_url,
            source_title, quote, channel, observed_at, observed_cope_score,
            observed_cope_type, observed_analysis_md, observed_model,
            representative_quality, legacy_cope_entry_id)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
        (entry_id, observation, source_url, canonical, source_title, quote,
         actual_channel, observed_at, cope_score, cope_type, analysis_md, model,
         quality, legacy_cope_entry_id),
    )


def _recompute_figure_in_tx(c, figure_id):
    entries = _public_entries(c, figure_id, order="ASC")
    fig = c.execute(
        "SELECT cope_score, role, type, category FROM figures WHERE id=?",
        (figure_id,),
    ).fetchone()
    if not fig:
        return 0.0
    if not entries:
        c.execute(
            """UPDATE figures SET cope_score=0, prev_score=0, total_quotes=0,
                      latest_incident='No scored sources yet — awaiting pipeline data.',
                      last_quote=NULL, last_cope_type=NULL, last_scored=NULL,
                      updated_at=CURRENT_TIMESTAMP WHERE id=?""",
            (figure_id,),
        )
        return 0.0
    role, fig_type, category = fig["role"] or "", fig["type"] or "", fig["category"] or ""
    new_score = _public_cope_index(entries, role, fig_type, category)
    previous = (
        _public_cope_index(entries[:-1], role, fig_type, category)
        if len(entries) > 1 else 50.0
    )
    latest = entries[-1]
    last_scored = latest.get("event_observed_at") or latest.get("created_at")
    c.execute(
        """UPDATE figures SET cope_score=?, prev_score=?, total_quotes=?,
                  latest_incident=?, last_quote=?, last_cope_type=?,
                  last_scored=?, updated_at=CURRENT_TIMESTAMP WHERE id=?""",
        (new_score, previous, len(entries), _format_latest_incident(latest),
         (latest.get("quote") or "")[:500], latest.get("cope_type") or "",
         last_scored, figure_id),
    )
    return new_score


def add_cope_entry(figure_id, quote, source_url, source_title,
                   cope_score, cope_type, analysis_md, model,
                   observed_at=None, channel=None):
    """Insert one underlying event and retain repeat discoveries as provenance.

    Every UK ingestion path ultimately calls this function.  The immediate
    transaction and unique event key therefore make RSS, direct-news, Brave,
    and manual-submission races converge on one score-bearing row.
    """
    score_value = float(cope_score)
    if not 0 <= score_value <= 100:
        return {"inserted": False, "reason": "invalid_score"}
    raw_source_url = str(source_url or "").strip()
    canonical = canonical_url(raw_source_url)
    canonical_hash = canonical_url_hash(canonical)
    observed_dt = _as_utc(observed_at)
    observed_iso = observed_dt.isoformat()
    quality = _representative_quality(raw_source_url, source_title, quote)
    fingerprint = new_event_fingerprint(
        figure_id, source_title, quote, observed_iso
    )
    with conn() as c:
        c.execute("BEGIN IMMEDIATE")
        candidates = [dict(row) for row in c.execute(
            """SELECT * FROM cope_entries WHERE figure_id=?
               ORDER BY COALESCE(event_observed_at, created_at) DESC, id DESC""",
            (figure_id,),
        )]
        match = None
        for existing in candidates:
            existing_canonical = (
                existing.get("canonical_url")
                or canonical_url(existing.get("source_url"))
            )
            existing_at = _as_utc(
                existing.get("event_observed_at") or existing.get("created_at")
            )
            within_window = abs(
                (observed_dt - existing_at).total_seconds()
            ) <= EVENT_WINDOW_DAYS * 86400
            exact_url = bool(canonical and canonical == existing_canonical)
            timeless = exact_statement_match(
                "", quote or "", "", existing.get("quote") or "",
            )
            statement_match = same_event(
                canonical_a="",
                title_a="",
                quote_a=quote or "",
                canonical_b="",
                title_b="",
                quote_b=existing.get("quote") or "",
            )
            if timeless or (statement_match and (exact_url or within_window)):
                match = existing
                break
        if match:
            _insert_cope_provenance(
                c, match["id"], raw_source_url, canonical, source_title, quote,
                channel, observed_iso, score_value, cope_type, analysis_md,
                model, quality,
            )
            existing_quality = int(match.get("representative_quality") or 0)
            existing_canonical = (
                match.get("canonical_url")
                or canonical_url(match.get("source_url"))
            )
            existing_observed = _as_utc(
                match.get("event_observed_at") or match.get("created_at")
            )
            earliest = min(existing_observed, observed_dt).isoformat()
            observed_changed = earliest != existing_observed.isoformat()
            promote = (
                quality > existing_quality
                or (
                    quality == existing_quality and canonical
                    and (not existing_canonical or canonical < existing_canonical)
                )
            )
            if promote:
                c.execute(
                    """UPDATE cope_entries SET quote=?, source_url=?, source_title=?,
                              canonical_url=?, canonical_url_hash=?,
                              event_observed_at=?, representative_quality=?,
                              cope_score=?, cope_type=?, analysis_md=?, model=?
                        WHERE id=?""",
                    (quote, raw_source_url, source_title, canonical,
                     canonical_hash, earliest, quality, score_value, cope_type,
                     analysis_md, model, match["id"]),
                )
                _recompute_figure_in_tx(c, figure_id)
            elif observed_changed:
                c.execute(
                    "UPDATE cope_entries SET event_observed_at=? WHERE id=?",
                    (earliest, match["id"]),
                )
                _recompute_figure_in_tx(c, figure_id)
            return {
                "inserted": False,
                "entry_id": match["id"],
                "event_fingerprint": match.get("event_fingerprint"),
                "reason": "duplicate_event",
                "promoted": promote,
            }

        # ``new_event_fingerprint`` is a stable candidate key.  Resolve the
        # rare short-quote/same-headline collision without merging events that
        # failed the conservative statement matcher above.
        resolved_fingerprint = fingerprint
        collision_counter = 0
        while c.execute(
            "SELECT 1 FROM cope_entries WHERE figure_id=? AND event_fingerprint=?",
            (figure_id, resolved_fingerprint),
        ).fetchone():
            collision_counter += 1
            collision_basis = "\n".join((
                fingerprint, normalise_text(source_title), normalise_text(quote),
                canonical, str(collision_counter),
            ))
            resolved_fingerprint = hashlib.sha256(
                collision_basis.encode("utf-8")
            ).hexdigest()[:32]

        cursor = c.execute(
            """INSERT INTO cope_entries
               (figure_id, 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, quote, raw_source_url, source_title, canonical,
             canonical_hash, resolved_fingerprint, observed_iso, quality, score_value,
             cope_type, analysis_md, model),
        )
        entry_id = cursor.lastrowid
        _insert_cope_provenance(
            c, entry_id, raw_source_url, canonical, source_title, quote,
            channel, observed_iso, score_value, cope_type, analysis_md, model,
            quality,
        )
        _recompute_figure_in_tx(c, figure_id)
        return {
            "inserted": True,
            "entry_id": entry_id,
            "event_fingerprint": resolved_fingerprint,
        }


def figure_entries(figure_id, limit=50):
    with conn() as c:
        return _public_entries(c, figure_id, limit=limit)


def figure_score_history(figure_id):
    with conn() as c:
        cur = c.execute(
            f"""SELECT cope_score,
                       COALESCE(event_observed_at, created_at) AS scored_at
                  FROM cope_entries
                WHERE figure_id = ? AND {_public_score_filter()}
                ORDER BY COALESCE(event_observed_at, created_at) ASC, id ASC""",
            (figure_id,),
        )
        return [{"score": r["cope_score"], "date": r["scored_at"]} for r in cur.fetchall()]


def cope_entry_exists(figure_id, quote_prefix):
    with conn() as c:
        cur = c.execute("SELECT 1 FROM cope_entries WHERE figure_id = ? AND substr(quote, 1, 200) = ? LIMIT 1", (figure_id, quote_prefix[:200]))
        return cur.fetchone() is not None


def make_analysis_slug(text):
    base = re.sub(r"[^a-z0-9]+", "-", (text or "")[:60].lower()).strip("-")
    h = hashlib.sha256((text or "").encode()).hexdigest()[:8]
    return f"{base}-{h}" if base else f"analysis-{h}"


[redacted secret-like line]
    slug = make_analysis_slug(input_url or input_text)
    with conn() as c:
        try:
            c.execute("""INSERT INTO analyses (input_text, input_url, extracted_title,
                cope_score, cope_type, scapegoats, structural_reality,
[redacted secret-like line]
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
                (input_text[:2000], input_url, extracted_title,
                 result.get("cope_score", 0), result.get("cope_type", ""),
                 json.dumps(result.get("scapegoats_detected", [])),
                 result.get("structural_reality", ""),
                 result.get("what_data_says", ""),
                 result.get("verdict", ""),
                 result.get("explanation", ""),
[redacted secret-like line]
            return slug
        except sqlite3.IntegrityError:
            return slug


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


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


def upsert_narrative(narr_id, narrative, scapegoat, reality, data_source, times_invoked, trend):
    with conn() as c:
        c.execute("INSERT OR REPLACE INTO scapegoat_narratives (id, narrative, scapegoat, reality, data_source, times_invoked, trend) VALUES (?, ?, ?, ?, ?, ?, ?)",
                  (narr_id, narrative, scapegoat, reality, data_source, times_invoked, trend))


def get_narratives():
    with conn() as c:
        cur = c.execute("SELECT * FROM scapegoat_narratives ORDER BY times_invoked DESC")
        return [dict(r) for r in cur.fetchall()]


def save_oracle_month(month, data_json, ai_summary=None, ai_gap_analysis=None, ai_scapegoat_check=None, ai_model=None):
    with conn() as c:
        c.execute("""INSERT OR REPLACE INTO oracle_archive
            (month, data_json, ai_summary, ai_gap_analysis, ai_scapegoat_check, ai_model, scored_at)
            VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)""",
            (month, json.dumps(data_json) if isinstance(data_json, dict) else data_json,
             ai_summary, ai_gap_analysis, ai_scapegoat_check, ai_model))


def get_oracle_latest():
    with conn() as c:
        cur = c.execute("SELECT * FROM oracle_archive ORDER BY id DESC LIMIT 1")
        row = cur.fetchone()
        if row:
            d = dict(row)
            d["data"] = json.loads(d["data_json"])
            return d
        return None


def get_oracle_archive(limit=6):
    with conn() as c:
        cur = c.execute("SELECT * FROM oracle_archive")
        results = []
        for r in cur.fetchall():
            d = dict(r)
            d["data"] = json.loads(d["data_json"])
            results.append(d)
        results.sort(key=lambda x: _month_sort_key(x.get("month","")), reverse=True)
        return results[:limit]


def get_oracle_by_month(month):
    with conn() as c:
        cur = c.execute("SELECT * FROM oracle_archive WHERE month = ?", (month,))
        row = cur.fetchone()
        if row:
            d = dict(row)
            d["data"] = json.loads(d["data_json"])
            return d
        return None


def save_stats_month(month, data_json, ai_commentary=None, ai_model=None):
    with conn() as c:
        c.execute("INSERT OR REPLACE INTO stats_archive (month, data_json, ai_commentary, ai_model) VALUES (?, ?, ?, ?)",
                  (month, json.dumps(data_json) if isinstance(data_json, dict) else data_json, ai_commentary, ai_model))


def get_stats_archive(limit=60):
    with conn() as c:
        cur = c.execute("SELECT * FROM stats_archive")
        results = []
        for r in cur.fetchall():
            d = dict(r)
            d["data"] = json.loads(d["data_json"])
            results.append(d)
        results.sort(key=lambda x: _month_sort_key(x.get("month","")), reverse=True)
        return results[:limit]


def get_stats_latest():
    with conn() as c:
        cur = c.execute("SELECT * FROM stats_archive ORDER BY id DESC LIMIT 1")
        row = cur.fetchone()
        if row:
            d = dict(row)
            d["data"] = json.loads(d["data_json"])
            return d
        return None


def get_stats_by_month(month):
    with conn() as c:
        cur = c.execute("SELECT * FROM stats_archive WHERE month = ?", (month,))
        row = cur.fetchone()
        if row:
            d = dict(row)
            d["data"] = json.loads(d["data_json"])
            return d
        return None


[redacted secret-like line]
    with conn() as c:
[redacted secret-like line]
[redacted secret-like line]
        return c.execute("SELECT last_insert_rowid()").fetchone()[0]


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


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


def counts():
    with conn() as c:
        stats = {}
        stats["figures"] = c.execute("SELECT COUNT(*) FROM figures WHERE COALESCE(active, 1) = 1").fetchone()[0]
        stats["figures_total"] = c.execute("SELECT COUNT(*) FROM figures").fetchone()[0]
        stats["cope_entries"] = c.execute("SELECT COUNT(*) FROM cope_entries").fetchone()[0]
        stats["analyses"] = c.execute("SELECT COUNT(*) FROM analyses").fetchone()[0]
        stats["oracle_months"] = c.execute("SELECT COUNT(*) FROM oracle_archive").fetchone()[0]
        stats["stats_months"] = c.execute("SELECT COUNT(*) FROM stats_archive").fetchone()[0]
        try:
            stats["oracle_questions"] = c.execute("SELECT COUNT(*) FROM oracle_questions").fetchone()[0]
        except Exception:
            stats["oracle_questions"] = 0
        try:
            stats["bulletin_analyses"] = c.execute("SELECT COUNT(*) FROM bulletin_analyses").fetchone()[0]
        except Exception:
            stats["bulletin_analyses"] = 0
        return stats


def cope_entry_exists_by_url(url):
    target = canonical_url(url)
    with conn() as c:
        rows = c.execute(
            "SELECT source_url, canonical_url FROM cope_entries"
        ).fetchall()
        return any(
            target and target == (row["canonical_url"] or canonical_url(row["source_url"]))
            for row in rows
        )


def get_figures_with_recent_entries(limit=5):
    figures = get_leaderboard()[:limit]
    for fig in figures:
        fig["recent_entries"] = figure_entries(fig["id"], limit=3)
    return figures


# --- Bulletin analyses ---

def save_bulletin_analysis(bulletin_type, bulletin_url, bulletin_title, bulletin_date,
                           raw_text, cope_score, ai_analysis, key_data_points,
                           what_they_said, what_data_shows, emphasis_vs_downplay,
                           language_choices, structural_issues_avoided, ai_model):
    with conn() as c:
        existing = c.execute("SELECT id FROM bulletin_analyses WHERE bulletin_url = ?", (bulletin_url,)).fetchone()
        if existing:
            c.execute("""UPDATE bulletin_analyses SET
                bulletin_title=?, bulletin_date=?, raw_text=?, cope_score=?,
                ai_analysis=?, key_data_points=?, what_they_said=?, what_data_shows=?,
                emphasis_vs_downplay=?, language_choices=?, structural_issues_avoided=?,
                ai_model=?, scored_at=CURRENT_TIMESTAMP
                WHERE bulletin_url=?""",
                (bulletin_title, bulletin_date, raw_text, cope_score,
                 ai_analysis, key_data_points, what_they_said, what_data_shows,
                 emphasis_vs_downplay, language_choices, structural_issues_avoided,
                 ai_model, bulletin_url))
            return existing["id"]
        else:
            c.execute("""INSERT INTO bulletin_analyses
                (bulletin_type, bulletin_url, bulletin_title, bulletin_date,
                 raw_text, cope_score, ai_analysis, key_data_points,
                 what_they_said, what_data_shows, emphasis_vs_downplay,
                 language_choices, structural_issues_avoided, ai_model, scored_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)""",
                (bulletin_type, bulletin_url, bulletin_title, bulletin_date,
                 raw_text, cope_score, ai_analysis, key_data_points,
                 what_they_said, what_data_shows, emphasis_vs_downplay,
                 language_choices, structural_issues_avoided, ai_model))
            return c.execute("SELECT last_insert_rowid()").fetchone()[0]


def get_bulletin_analyses(bulletin_type=None, limit=20):
    with conn() as c:
        if bulletin_type:
            cur = c.execute("SELECT * FROM bulletin_analyses WHERE bulletin_type = ? ORDER BY created_at DESC LIMIT ?",
                            (bulletin_type, limit))
        else:
            cur = c.execute("SELECT * FROM bulletin_analyses ORDER BY created_at DESC LIMIT ?", (limit,))
        return [dict(r) for r in cur.fetchall()]


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


def get_latest_bulletin(bulletin_type):
    with conn() as c:
        cur = c.execute("SELECT * FROM bulletin_analyses WHERE bulletin_type = ? ORDER BY created_at DESC LIMIT 1",
                        (bulletin_type,))
        row = cur.fetchone()
        return dict(row) if row else None


def bulletin_url_exists(url):
    with conn() as c:
        cur = c.execute("SELECT 1 FROM bulletin_analyses WHERE bulletin_url = ? LIMIT 1", (url,))
        return cur.fetchone() is not None


# --- Pipeline Results (added by tiered scoring pipeline) ---

def save_pipeline_result_record(figure_id, source_url, source_name, score_data,
                                model, stage, prompt_version, raw_log_path=None,
                                reject_reason=None, published=True):
    """Save a full pipeline result record."""
    source_url = normalise_source_url(source_url)
    with conn() as c:
        c.execute("""INSERT INTO pipeline_results
            (figure_id, source_url, source_name, cope_score, band,
             primary_mode, secondary_modes, scapegoat_target,
             structural_issue_ignored, claim_summary, rationale_short,
             confidence, needs_review, model, stage, prompt_version,
             raw_log_path, reject_reason, published)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (figure_id, source_url, source_name,
             score_data.get("cope_score") if score_data else None,
             score_data.get("band") if score_data else None,
             score_data.get("primary_mode") if score_data else None,
             json.dumps(score_data.get("secondary_modes", [])) if score_data else None,
             score_data.get("scapegoat_target") if score_data else None,
             score_data.get("structural_issue_ignored") if score_data else None,
             score_data.get("claim_summary") if score_data else None,
             score_data.get("rationale_short") if score_data else None,
             score_data.get("confidence") if score_data else None,
             1 if (score_data and score_data.get("needs_review")) else 0,
             model, stage, prompt_version,
             raw_log_path, reject_reason, 1 if published else 0))
        return c.execute("SELECT last_insert_rowid()").fetchone()[0]


def get_needs_review(limit=50):
    """Get pipeline results that need admin review."""
    with conn() as c:
        cur = c.execute("""SELECT pr.*, f.name as figure_name, f.role as figure_role
            FROM pipeline_results pr
            LEFT JOIN figures f ON pr.figure_id = f.id
            WHERE pr.needs_review = 1 AND pr.review_status = 'pending'
            ORDER BY pr.created_at DESC LIMIT ?""", (limit,))
        return [dict(r) for r in cur.fetchall()]


def update_review_status(result_id, status):
    """Update the review status of a pipeline result."""
    with conn() as c:
        c.execute("UPDATE pipeline_results SET review_status = ? WHERE id = ?",
                  (status, result_id))


def get_pipeline_result(result_id):
    """Get a single pipeline result by ID."""
    with conn() as c:
        cur = c.execute("""SELECT pr.*, f.name as figure_name, f.role as figure_role
            FROM pipeline_results pr
            LEFT JOIN figures f ON pr.figure_id = f.id
            WHERE pr.id = ?""", (result_id,))
        row = cur.fetchone()
        return dict(row) if row else None


def pipeline_url_scored(source_url, figure_id):
    """Check if a URL has already been scored for a figure via pipeline."""
    target = canonical_url(source_url)
    with conn() as c:
        rows = c.execute(
            "SELECT source_url FROM pipeline_results WHERE figure_id=?",
            (figure_id,),
        ).fetchall()
        return any(
            target and target == canonical_url(row["source_url"])
            for row in rows
        )


def get_all_recent_entries(limit=50):
    """Get all recent cope entries across all figures, with figure name joined."""
    with conn() as c:
        cur = c.execute("""
            SELECT ce.*, f.name as figure_name, f.party as figure_party
            FROM cope_entries ce
            JOIN figures f ON ce.figure_id = f.id
            WHERE """ + _public_score_filter("ce") + """
            ORDER BY ce.created_at DESC
            LIMIT ?
        """, (limit,))
        return [dict(r) for r in cur.fetchall()]


# ── ASYNC_YOUTUBE_QUEUE_PATCH ─────────────────────────────────────────────────
# Added for async YouTube scoring pipeline (cc-node-01 worker)

def queue_youtube_video(video_id: str, url: str, submitted_by: str = "user") -> bool:
    """Insert a video as queued, or give an explicitly retried failure a new budget.
    Returns True if inserted/updated, False if already queued/processing/scored."""
    conn = sqlite3.connect(DB_PATH)
    try:
        conn.execute("BEGIN IMMEDIATE")
        existing = conn.execute(
            "SELECT status FROM youtube_videos WHERE video_id = ?", (video_id,)
        ).fetchone()
        if existing:
            if existing[0] != "failed":
                return False
            conn.execute(
                "UPDATE youtube_videos SET status='queued', queued_at=CURRENT_TIMESTAMP, "
                "processing_started_at=NULL, recovery_started_at=NULL, "
                "lease_renewed_at=NULL, score_attempts=0, "
                "error_msg=NULL, submitted_by=? WHERE video_id=? AND status='failed'",
                (submitted_by, video_id)
            )
        else:
            conn.execute(
                "INSERT INTO youtube_videos (video_id, url, status, queued_at, submitted_by) "
                "VALUES (?, ?, 'queued', CURRENT_TIMESTAMP, ?)",
                (video_id, url, submitted_by)
            )
        conn.commit()
        return True
    finally:
        conn.close()


def get_queued_videos(limit: int = 10) -> list:
    """Return queued videos oldest-first for the worker to process."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    try:
        rows = conn.execute(
            "SELECT video_id, url, queued_at, title, channel, transcript FROM youtube_videos "
            "WHERE status = 'queued' ORDER BY queued_at ASC LIMIT ?",
            (limit,)
        ).fetchall()
        return [dict(r) for r in rows]
    finally:
        conn.close()


def count_active_processing_youtube_videos(
    max_age_seconds: int = 1500, lease_ttl_seconds: int = None
) -> int:
    """How many videos the external worker is plausibly still working on.

    Used to tell a job merely waiting its turn in a serial queue (normal) from
    one that was genuinely abandoned (needs recovery). Getting this wrong in the
    permissive direction is expensive: a stale 'processing' row made the whole
    queue look busy, which suppressed queued recovery and let the queue stall
    silently for days while a wedged worker held a job it would never finish.

    A job counts as active only if its LEASE is fresh. The lease is renewed by
    the worker every 60s, so lease_ttl_seconds (default 180s, three missed
    beats) detects a dead worker in about two minutes rather than twenty-five.
    Rows with a NULL lease pre-date the heartbeat, or come from a worker that
    does not send one: those fall back to the old processing_started_at window
    so behaviour is never worse than before.
    """
    if lease_ttl_seconds is None:
        lease_ttl_seconds = 180
    cutoff = (datetime.now(timezone.utc) - timedelta(seconds=max_age_seconds)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    lease_cutoff = (
        datetime.now(timezone.utc) - timedelta(seconds=lease_ttl_seconds)
    ).strftime("%Y-%m-%d %H:%M:%S")
    conn = sqlite3.connect(DB_PATH)
    try:
        row = conn.execute(
            "SELECT COUNT(*) FROM youtube_videos "
            "WHERE status='processing' AND processing_started_at IS NOT NULL "
            "AND ("
            "  (lease_renewed_at IS NOT NULL AND "
            "   REPLACE(lease_renewed_at, 'T', ' ') > ?)"
            "  OR (lease_renewed_at IS NULL AND processing_started_at > ?)"
            ")",
            (lease_cutoff, cutoff),
        ).fetchone()
        return int(row[0]) if row else 0
    finally:
        conn.close()


def get_stale_queued_youtube_videos(max_age_seconds: int = 120) -> list:
    """Return jobs that no external worker claimed within the grace period."""
    cutoff = (datetime.now(timezone.utc) - timedelta(seconds=max_age_seconds)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    try:
        rows = conn.execute(
            "SELECT video_id, url, queued_at FROM youtube_videos "
            "WHERE status='queued' AND queued_at IS NOT NULL AND queued_at <= ? "
            "ORDER BY queued_at ASC",
            (cutoff,),
        ).fetchall()
        return [dict(row) for row in rows]
    finally:
        conn.close()


def claim_stale_queued_youtube_recovery(
    video_id: str, max_age_seconds: int = 120
) -> bool:
    """Atomically move an abandoned queued job into server-side recovery."""
    cutoff = (datetime.now(timezone.utc) - timedelta(seconds=max_age_seconds)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    conn = sqlite3.connect(DB_PATH)
    try:
        c = conn.execute(
            "UPDATE youtube_videos SET status='processing', "
            "processing_started_at=CURRENT_TIMESTAMP, "
            "recovery_started_at=CURRENT_TIMESTAMP "
            "WHERE video_id=? AND status='queued' "
            "AND queued_at IS NOT NULL AND queued_at <= ?",
            (video_id, cutoff),
        )
        conn.commit()
        return c.rowcount > 0
    finally:
        conn.close()


def claim_youtube_video(video_id: str) -> bool:
    """Atomically move a video from queued to processing. Returns True if claimed."""
    conn = sqlite3.connect(DB_PATH)
    try:
        c = conn.execute(
            "UPDATE youtube_videos SET status='processing', "
            "processing_started_at=CURRENT_TIMESTAMP, recovery_started_at=NULL, "
            "lease_renewed_at=CURRENT_TIMESTAMP "
            "WHERE video_id=? AND status='queued'",
            (video_id,)
        )
        conn.commit()
        return c.rowcount > 0
    finally:
        conn.close()


def renew_youtube_lease(video_id: str) -> bool:
    """Worker heartbeat: refresh the lease on a job it still holds.

    Only touches lease_renewed_at, and only for a row that is still
    'processing'. It cannot resurrect a terminal row, cannot change a score,
    and cannot alter provenance - so a late or duplicated heartbeat from a
    worker whose job was already recovered is a harmless no-op returning False.
    """
    conn = sqlite3.connect(DB_PATH)
    try:
        cur = conn.execute(
            "UPDATE youtube_videos SET lease_renewed_at=CURRENT_TIMESTAMP "
            "WHERE video_id=? AND status='processing'",
            (video_id,),
        )
        conn.commit()
        return (cur.rowcount or 0) > 0
    finally:
        conn.close()


def get_expired_lease_youtube_videos(lease_ttl_seconds: int = 180) -> list:
    """Processing jobs whose worker stopped renewing its lease.

    This is the fast path the 2026-10-03 incident needed and did not have: the
    worker process stayed alive but stopped making progress, so nothing crashed,
    nothing restarted, and the row sat 'processing' until the 25-minute timeout
    - with the whole serial queue suppressed behind it. A missed lease is
    positive evidence the holder is gone, so recovery can start in ~2 minutes.

    Only rows that have EVER had a lease are considered, so a worker that
    predates the heartbeat is never wrongly declared dead; those rows stay with
    the old processing-timeout path.
    """
    cutoff = (
        datetime.now(timezone.utc) - timedelta(seconds=lease_ttl_seconds)
    ).strftime("%Y-%m-%d %H:%M:%S")
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    try:
        rows = conn.execute(
            "SELECT video_id, url, title, channel, processing_started_at, "
            "lease_renewed_at FROM youtube_videos "
            "WHERE status='processing' AND lease_renewed_at IS NOT NULL "
            "AND REPLACE(lease_renewed_at, 'T', ' ') <= ? "
            "ORDER BY lease_renewed_at ASC",
            (cutoff,),
        ).fetchall()
        return [dict(row) for row in rows]
    finally:
        conn.close()


def claim_expired_lease_youtube_recovery(
    video_id: str, lease_ttl_seconds: int = 180
) -> bool:
    """Take ownership of a lease-expired job exactly once.

    Re-checks the lease age inside the UPDATE, so if the worker's heartbeat
    lands between the SELECT and here, the claim loses and returns False rather
    than racing a worker that is in fact alive.
    """
    cutoff = (
        datetime.now(timezone.utc) - timedelta(seconds=lease_ttl_seconds)
    ).strftime("%Y-%m-%d %H:%M:%S")
    conn = sqlite3.connect(DB_PATH)
    try:
        cur = conn.execute(
            "UPDATE youtube_videos SET recovery_started_at=CURRENT_TIMESTAMP "
            "WHERE video_id=? AND status='processing' "
            "AND recovery_started_at IS NULL "
            "AND lease_renewed_at IS NOT NULL "
            "AND REPLACE(lease_renewed_at, 'T', ' ') <= ?",
            (video_id, cutoff),
        )
        conn.commit()
        return (cur.rowcount or 0) > 0
    finally:
        conn.close()


def get_stale_processing_youtube_videos(max_age_seconds: int = 900) -> list:
    """Return processing jobs with no worker progress for the timeout window."""
    cutoff = (datetime.now(timezone.utc) - timedelta(seconds=max_age_seconds)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    try:
        rows = conn.execute(
            "SELECT video_id, url, title, channel, processing_started_at "
            "FROM youtube_videos WHERE status='processing' "
            "AND processing_started_at IS NOT NULL AND processing_started_at <= ?",
            (cutoff,),
        ).fetchall()
        return [dict(row) for row in rows]
    finally:
        conn.close()


def claim_stale_youtube_recovery(video_id: str, max_age_seconds: int = 900) -> bool:
    """Atomically reserve one stale processing job for server-side recovery."""
    cutoff = (datetime.now(timezone.utc) - timedelta(seconds=max_age_seconds)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    conn = sqlite3.connect(DB_PATH)
    try:
        c = conn.execute(
            "UPDATE youtube_videos SET recovery_started_at=CURRENT_TIMESTAMP "
            "WHERE video_id=? AND status='processing' "
            "AND processing_started_at IS NOT NULL AND processing_started_at <= ? "
            "AND (recovery_started_at IS NULL OR recovery_started_at <= ?)",
            (video_id, cutoff, cutoff),
        )
        conn.commit()
        return c.rowcount > 0
    finally:
        conn.close()


def complete_youtube_video(video_id: str, title: str, channel: str,
                           transcript_length: int, cope_score: float,
                           cope_summary: str, scapegoats: str,
                           cope_mechanisms: str, key_quotes: str = "",
                           video_summary: str = "", dt_verdict: str = "",
                           butchers_verdict: str = "") -> None:
    """Store final scored result and mark as scored."""
    conn = sqlite3.connect(DB_PATH)
    try:
        conn.execute(
            """UPDATE youtube_videos SET
               title=?, channel=?, transcript_length=?, cope_score=?,
               cope_summary=?, scapegoats=?, cope_mechanisms=?, key_quotes=?,
               video_summary=?, dt_verdict=?, butchers_verdict=?,
               status='scored', scored_at=CURRENT_TIMESTAMP, error_msg=NULL,
               processing_started_at=NULL, recovery_started_at=NULL
               WHERE video_id=? AND status <> 'scored'""",
            (title, channel, transcript_length, cope_score, cope_summary,
             scapegoats, cope_mechanisms, key_quotes,
             video_summary, dt_verdict, butchers_verdict, video_id)
        )
        conn.commit()
    finally:
        conn.close()


def add_youtube_extended_fields(video_id: str, video_summary: str = "",
                                dt_verdict: str = "", butchers_verdict: str = "",
                                scapegoats=None) -> None:
    """Additively store the three-layer oracle narrative fields.

    Deliberately does NOT touch cope_score, cope_summary, cope_mechanisms,
    key_quotes, transcript_length, title, channel, status or scored_at - those
    belong to the initial scoring pass. The extended (Codex) pass is
    non-deterministic, so it may add narrative but must never revise numbers.

    Each narrative field is written only when a non-empty value is supplied, so
    a partial extended result cannot blank an earlier good one. scapegoats is
    written only when supplied AND the initial pass left it empty.
    """
    sets, params = [], []
    for col, val in (("video_summary", video_summary),
                     ("dt_verdict", dt_verdict),
                     ("butchers_verdict", butchers_verdict)):
        if isinstance(val, str) and val.strip():
            sets.append(col + "=?")
            params.append(val)
    if isinstance(scapegoats, str) and scapegoats.strip():
        sets.append("scapegoats=CASE WHEN scapegoats IS NULL OR TRIM(scapegoats)='' "
                    "THEN ? ELSE scapegoats END")
        params.append(scapegoats)
    if not sets:
        return
    params.append(video_id)
    conn = sqlite3.connect(DB_PATH)
    try:
        conn.execute(
            "UPDATE youtube_videos SET " + ", ".join(sets) + " WHERE video_id=?",
            params
        )
        conn.commit()
    finally:
        conn.close()


def fail_youtube_video(video_id: str, error_msg: str) -> None:
    """Mark a video as failed."""
    conn = sqlite3.connect(DB_PATH)
    try:
        conn.execute(
            "UPDATE youtube_videos SET status='failed', error_msg=?, "
            "processing_started_at=NULL, recovery_started_at=NULL "
            "WHERE video_id=? AND status <> 'scored'",
            (error_msg[:1000], video_id)
        )
        conn.commit()
    finally:
        conn.close()


# ── YT_QUEUE_BACKSTOP_PATCH (added 2026-10-04) ───────────────────────────────
# Before this, three states had no owner at all:
#
#   1. status='processing' with processing_started_at IS NULL. Every watchdog
#      query filters on "processing_started_at IS NOT NULL", get_queued_videos
#      only returns status='queued', and queue_youtube_video refuses to re-queue
#      anything already 'processing'. Such a row is invisible to the recovery
#      path, invisible to the worker, and cannot even be resubmitted by the
#      user. It sits forever with nothing retrying it and nothing reporting it.
#
#   2. A 'processing' row whose recovery thread died silently (gunicorn worker
#      recycle, process restart, unhandled exit). The watchdog re-claims it
#      every timeout window but it never reaches a terminal state, so it loops
#      indefinitely without ever surfacing as a failure.
#
#   3. A burned recovery claim: claim_stale_youtube_recovery stamps
#      recovery_started_at, then _start_youtube_recovery declines because the
#      video is already in this process's in-flight set. The claim is spent but
#      no work was started, costing a full timeout window of dead time.
#
# The helpers below give each of those an owner and a clean terminal state.
# None of them touch cope_score, cope_summary, provenance or scored_at, and
# none of them delete rows.


def release_youtube_recovery_claim(video_id: str) -> None:
    """Hand back a recovery claim that was stamped but never acted on.

    Only clears recovery_started_at, and only while the row is still
    'processing', so it can never disturb a row that has since completed.
    """
    conn = sqlite3.connect(DB_PATH)
    try:
        conn.execute(
            "UPDATE youtube_videos SET recovery_started_at=NULL "
            "WHERE video_id=? AND status='processing'",
            (video_id,),
        )
        conn.commit()
    finally:
        conn.close()


def heal_youtube_null_processing_timestamps() -> int:
    """Make orphaned 'processing' rows visible to the watchdog again.

    A 'processing' row with no processing_started_at is unreachable by every
    other code path. Backfill the clock from the best evidence we have of when
    work began (queued_at, else now) so the normal timeout and backstop logic
    can take ownership. Additive: sets only the missing timestamp.
    """
    conn = sqlite3.connect(DB_PATH)
    try:
        cur = conn.execute(
            "UPDATE youtube_videos "
            "SET processing_started_at=COALESCE(queued_at, CURRENT_TIMESTAMP) "
            "WHERE status='processing' AND processing_started_at IS NULL"
        )
        conn.commit()
        return cur.rowcount or 0
    finally:
        conn.close()


def get_ownerless_youtube_jobs(ceiling_seconds: int) -> list:
    """Non-terminal jobs older than the hard ceiling, by any available clock.

    Deliberately tolerant of NULL timestamps: COALESCE walks
    processing_started_at -> queued_at -> scored_at so a row cannot hide from
    the backstop by having a missing clock, which is exactly how rows went
    permanently stuck before.
    """
    cutoff = (datetime.now(timezone.utc) - timedelta(seconds=ceiling_seconds)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    try:
        rows = conn.execute(
            "SELECT video_id, url, title, channel, status, queued_at, "
            "processing_started_at, recovery_started_at, "
            "COALESCE(processing_started_at, queued_at, scored_at) AS since "
            "FROM youtube_videos "
            "WHERE status IN ('queued', 'processing') "
            "AND COALESCE(REPLACE(processing_started_at, 'T', ' '), "
            "             REPLACE(queued_at, 'T', ' '), "
            "             REPLACE(scored_at, 'T', ' '), '1970-01-01') <= ? "
            "ORDER BY since ASC",
            (cutoff,),
        ).fetchall()
        return [dict(row) for row in rows]
    finally:
        conn.close()


def abandon_youtube_job(video_id: str, error_msg: str, ceiling_seconds: int) -> bool:
    """Terminalise a job that blew the hard ceiling. Returns True if it moved.

    Resolves to 'failed', which queue_youtube_video already treats as
    re-queueable, so the video becomes both visible and retryable instead of
    silently parked. Re-checks the age and the non-terminal status inside the
    UPDATE so it can never terminalise a row that finished in the meantime.
    """
    cutoff = (datetime.now(timezone.utc) - timedelta(seconds=ceiling_seconds)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    conn = sqlite3.connect(DB_PATH)
    try:
        cur = conn.execute(
            "UPDATE youtube_videos SET status='failed', error_msg=?, "
            "processing_started_at=NULL, recovery_started_at=NULL "
            "WHERE video_id=? AND status IN ('queued', 'processing') "
            "AND COALESCE(REPLACE(processing_started_at, 'T', ' '), "
            "             REPLACE(queued_at, 'T', ' '), "
            "             REPLACE(scored_at, 'T', ' '), '1970-01-01') <= ?",
            (error_msg[:1000], video_id, cutoff),
        )
        conn.commit()
        return (cur.rowcount or 0) > 0
    finally:
        conn.close()


def youtube_queue_health(stuck_seconds: int, ceiling_seconds: int) -> dict:
    """Read-only snapshot of queue health for monitoring.

    Returns counts by status plus the specific pathologies worth alerting on.
    Pure SELECT: safe to call from a read-only connection or a monitor.
    """
    stuck_cutoff = (
        datetime.now(timezone.utc) - timedelta(seconds=stuck_seconds)
    ).strftime("%Y-%m-%d %H:%M:%S")
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    try:
        by_status = {
            row[0]: row[1]
            for row in conn.execute(
                "SELECT status, COUNT(*) FROM youtube_videos GROUP BY status"
            )
        }
        stuck = [
            dict(row)
            for row in conn.execute(
                "SELECT video_id, status, queued_at, processing_started_at, "
                "recovery_started_at FROM youtube_videos "
                "WHERE status IN ('queued', 'processing') "
                "AND COALESCE(REPLACE(processing_started_at, 'T', ' '), "
                "             REPLACE(queued_at, 'T', ' '), "
                "             REPLACE(scored_at, 'T', ' '), '1970-01-01') <= ?",
                (stuck_cutoff,),
            )
        ]
        no_clock = conn.execute(
            "SELECT COUNT(*) FROM youtube_videos "
            "WHERE status='processing' AND processing_started_at IS NULL"
        ).fetchone()[0]
        return {
            "by_status": by_status,
            "stuck": stuck,
            "processing_without_clock": int(no_clock),
            "stuck_seconds": stuck_seconds,
            "ceiling_seconds": ceiling_seconds,
        }
    finally:
        conn.close()


def get_youtube_video(video_id: str):
    """Return a single video record by video_id, or None."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    try:
        row = conn.execute(
            "SELECT * FROM youtube_videos WHERE video_id=?", (video_id,)
        ).fetchone()
        return dict(row) if row else None
    finally:
        conn.close()


def get_all_youtube_videos(limit: int = 100) -> list:
    """Return all videos (all statuses), newest activity first."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    try:
        rows = conn.execute(
            """SELECT * FROM youtube_videos
               ORDER BY COALESCE(scored_at, queued_at, CURRENT_TIMESTAMP) DESC
               LIMIT ?""",
            (limit,)
        ).fetchall()
        return [dict(r) for r in rows]
    finally:
        conn.close()


# ── RETRY_CLASSIFICATION_PATCH (added 2026-10-24) ────────────────────────────
# Before this, app.py decided retryable-vs-terminal with a literal substring
# test (`if "transcript" in worker_error.lower()`). Any error that did not
# happen to contain the word "transcript" skipped classification AND recovery
# and went straight to fail_youtube_video() - terminal, no retry. That is how
# Rqt9kWoTJbc dead-ended on a malformed scoring JSON response, which is a
# transient fault that should have been retried.
#
# The helpers below give the retry path three things it did not have:
#   1. a persisted, bounded attempt counter (youtube_videos.score_attempts),
#   2. a re-queue that is distinct from a failure, so a retryable error
#      actually gets another pass instead of only being labelled retryable,
#   3. an attempt audit row per decision, restoring youtube_score_attempts.
#
# None of these touch cope_score, cope_summary, scored_at or provenance, and
# none of them delete rows.

# A retryable error gets this many total scoring passes before it is declared
# terminal. Bounded on purpose: without a cap, a persistently malformed scoring
# response would re-queue itself forever and the worker would spin on one video.
YOUTUBE_MAX_SCORE_ATTEMPTS = 3


def ensure_youtube_retry_schema() -> None:
    """Idempotently add the retry bookkeeping this module relies on."""
    conn = sqlite3.connect(DB_PATH, timeout=60)
    try:
        cols = {r[1] for r in conn.execute("PRAGMA table_info(youtube_videos)")}
        if "score_attempts" not in cols:
            conn.execute(
                "ALTER TABLE youtube_videos ADD COLUMN score_attempts INTEGER DEFAULT 0"
            )
        conn.execute("""CREATE TABLE IF NOT EXISTS youtube_score_attempts (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            video_id    TEXT,
            title       TEXT,
            attempt_num INTEGER DEFAULT 1,
            status      TEXT,
            error_msg   TEXT,
            scored_at   TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_yt_attempts_video "
            "ON youtube_score_attempts(video_id, scored_at)"
        )
        conn.commit()
    except Exception:
        pass
    finally:
        conn.close()


def get_youtube_score_attempts(video_id: str) -> int:
    """How many scoring passes this video has already consumed."""
    conn = sqlite3.connect(DB_PATH, timeout=60)
    try:
        row = conn.execute(
            "SELECT COALESCE(score_attempts, 0) FROM youtube_videos WHERE video_id = ?",
            (video_id,),
        ).fetchone()
        return int(row[0]) if row else 0
    except Exception:
        return 0
    finally:
        conn.close()


def log_youtube_score_attempt(video_id: str, title: str, attempt_num: int,
                              status: str, error_msg: str = None) -> None:
    """Append one row to the attempt audit trail.

    The trail recorded nothing between 2026-09-12 and 2026-10-24 because its
    only writer was youtube_scorer._log_attempt, inside the in-process
    score_video() path. Once scoring moved to the cc-node-01 worker, the live
    path became worker -> POST /api/internal/score-complete, which never logged
    anything. This is the writer for that path.
    """
    try:
        ensure_youtube_retry_schema()
        conn = sqlite3.connect(DB_PATH, timeout=60)
        try:
            conn.execute(
                "INSERT INTO youtube_score_attempts "
                "(video_id, title, attempt_num, status, error_msg) "
                "VALUES (?, ?, ?, ?, ?)",
                (video_id or "", (title or "")[:300], int(attempt_num or 1),
                 str(status or "")[:60], (error_msg or "")[:1000]),
            )
            conn.commit()
        finally:
            conn.close()
    except Exception as exc:
        logging.warning("log_youtube_score_attempt failed for %s: %s", video_id, exc)


def bump_youtube_score_attempts(video_id: str) -> int:
    """Increment and return this video's persisted attempt count."""
    conn = sqlite3.connect(DB_PATH, timeout=60)
    try:
        conn.execute(
            "UPDATE youtube_videos SET score_attempts = COALESCE(score_attempts, 0) + 1 "
            "WHERE video_id = ?",
            (video_id,),
        )
        conn.commit()
        row = conn.execute(
            "SELECT COALESCE(score_attempts, 0) FROM youtube_videos WHERE video_id = ?",
            (video_id,),
        ).fetchone()
        return int(row[0]) if row else 0
    except Exception as exc:
        logging.warning("bump_youtube_score_attempts failed for %s: %s", video_id, exc)
        return 0
    finally:
        conn.close()


def resolve_youtube_worker_failure(video_id: str, error_msg: str, stage: str,
                                   retryable: bool, reason: str = "") -> dict:
    """Consume one worker failure and transition its row under the shared cap.

    The transaction makes repeated callbacks harmless once the first callback
    has queued or failed the row. It also protects a result that already scored.
    An explicit user retry starts a new budget in queue_youtube_video instead.
    """
    conn = sqlite3.connect(DB_PATH, timeout=60)
    try:
        conn.execute("BEGIN IMMEDIATE")
        row = conn.execute(
            "SELECT status, COALESCE(score_attempts, 0) FROM youtube_videos "
            "WHERE video_id=?", (video_id,),
        ).fetchone()
        if not row or row[0] != "processing":
            return {"status": "noop"}

        attempts = int(row[1]) + 1
        exhausted = bool(retryable and attempts >= YOUTUBE_MAX_SCORE_ATTEMPTS)
        if not retryable:
            status = "failed"
            message = "NOT RETRYABLE (%s) - %s" % (reason, error_msg)
        elif exhausted:
            status = "failed"
            message = "RETRY BUDGET EXHAUSTED after %d/%d attempts (%s) - %s" % (
                attempts, YOUTUBE_MAX_SCORE_ATTEMPTS, stage, error_msg,
            )
        else:
            status = "queued"
            message = "RETRY PENDING - " + str(error_msg)

        conn.execute(
            "UPDATE youtube_videos SET status=?, score_attempts=?, error_msg=?, "
            "queued_at=CASE WHEN ?='queued' THEN CURRENT_TIMESTAMP ELSE queued_at END, "
            "processing_started_at=NULL, recovery_started_at=NULL, lease_renewed_at=NULL "
            "WHERE video_id=? AND status='processing'",
            (status, attempts, message[:1000], status, video_id),
        )
        conn.commit()
        return {
            "status": "requeued" if status == "queued" else "failed",
            "attempts": attempts, "retryable": retryable, "exhausted": exhausted,
        }
    finally:
        conn.close()


def retry_youtube_video(video_id: str, error_msg: str) -> bool:
    """Put a retryable failure back on the queue instead of killing it.

    Returns True if the video was re-queued. The cc-node-01 worker polls for
    status='queued', so re-queueing is what actually causes another attempt -
    and it works even while the VPS cannot reach the worker, because the worker
    initiates the connection.

    Never resurrects a row that has already scored, and never clears the error
    text: error_msg stays readable so an in-flight retry is still diagnosable.
    """
    conn = sqlite3.connect(DB_PATH, timeout=60)
    try:
        updated = conn.execute(
            "UPDATE youtube_videos SET status='queued', queued_at=CURRENT_TIMESTAMP, "
            "processing_started_at=NULL, recovery_started_at=NULL, "
            "lease_renewed_at=NULL, error_msg=? "
            "WHERE video_id=? AND status <> 'scored'",
            (("RETRY PENDING - " + str(error_msg))[:1000], video_id),
        )
        conn.commit()
        return updated.rowcount > 0
    except Exception as exc:
        logging.warning("retry_youtube_video failed for %s: %s", video_id, exc)
        return False
    finally:
        conn.close()
```
