---
type: "Source File"
title: "\"\"\""
description: "\"\"\" CopeCheck UK -- Tiered Scoring Pipeline v1.0 Stages: A. Ingest -- Firecrawl article fetch, claim extraction B. First-pass scorer -- MiniMax C. Validation layer -- MiniMax checks internal consistency D. Escalation."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-08-24T12:57:08Z"
site: "uk"
source_path: "copecheck-uk/scoring_pipeline.py"
---

# """

Source path: `copecheck-uk/scoring_pipeline.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-08-24T12:57:08Z`

```py
"""
CopeCheck UK -- Tiered Scoring Pipeline v1.0

Stages:
  A. Ingest   -- Firecrawl article fetch, claim extraction
  B. First-pass scorer -- MiniMax
  C. Validation layer  -- MiniMax checks internal consistency
  D. Escalation layer  -- MiniMax for low-confidence / extreme scores
  E. Publish   -- Save to DB with rationale, confidence, source links

All prompts versioned as named constants.
"""

import json
import logging
import os
import re
import time
from datetime import datetime, timezone

import requests

from canonical_identity import canonical_url

log = logging.getLogger("scoring_pipeline")

# --- Config ---

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

[redacted secret-like line]
MINIMAX_URL = "https://api.minimax.io/v1/chat/completions"
MINIMAX_MODEL = os.environ.get("MINIMAX_MODEL", "MiniMax-M3")

# Sources considered sensational / tabloid
TABLOID_SOURCES = {
    "daily mail", "mail online", "the sun", "daily express",
    "daily star", "the mirror", "daily mirror", "gb news",
    "gbnews", "express.co.uk", "dailymail.co.uk",
}

# --- Prompt Constants (versioned) ---

PROMPT_VERSION = "1.0"

FIRST_PASS_SYSTEM_PROMPT = """You are the first-pass scoring engine for CopeCheck UK.

Your task is to score whether a public figure's statement avoids structural economic reality.

Return JSON only.

Scoring rule:
- 0 = directly engages with structural causes
- 100 = extreme denial, scapegoating, or fantasy framing
- High scores should be reserved for explicit blame-shifting, magical thinking, or narrative inversion

Important:
- Score only the claim attributed to the figure
- Do not score the journalist, headline tone, or publication bias
- If attribution is weak or ambiguous, set primary_mode to "unknown", reduce confidence, and set needs_review=true
- Do not score articles about personal gifts, donor declarations, party funding, expenses, property purchases, campaign finance, or fundraising unless the attributed claim makes a substantive structural economic claim; mark those as unknown/needs_review instead
- Prefer conservative scoring over theatrical scoring
- Scapegoating means blaming out-groups or convenient targets for structural failures
- Deflection means redirecting away from structural causes
- Gaslighting means reversing obvious causality or denying lived reality
- Fantasy economics means implying major outcomes without plausible mechanism
- Lucid means naming structural drivers directly

Output must match the provided schema exactly."""

FIRST_PASS_USER_TEMPLATE = """Figure: {person_name}
Role: {role}
Party/Org: {party}

Article title: {title}
Publisher: {publisher}
Date: {date}
URL: {url}

Relevant excerpt:
{clean_excerpt}

Quoted or attributed claim:
{attributed_claim}

Known structural frame for the site:
The UK economy has been hollowed out by rentier dynamics, low productive investment, housing constraints, weak wage growth, and policy avoidance of structural causes.

Now return the scoring JSON."""

FIRST_PASS_SCHEMA_EXAMPLE = """{
  "person": "Nigel Farage",
  "source_url": "https://example.com/article",
  "source_name": "BBC News",
  "claim_summary": "One-sentence summary of the attributed claim",
  "cope_score": 88,
  "band": "terminal_copium",
  "primary_mode": "scapegoating",
  "secondary_modes": ["deflection"],
  "scapegoat_target": "immigrants",
  "structural_issue_ignored": "housing scarcity and wage stagnation",
  "evidence_used": ["The article attributes X claim to the figure", "The article also states Y counterpoint"],
  "rationale_short": "Blames immigrants for structural shortages while ignoring housing and investment constraints.",
  "confidence": 0.84,
  "needs_review": false
}"""

VALIDATOR_SYSTEM_PROMPT = """You are validating a CopeCheck score.

Check whether:
1. The attributed claim is actually from the named figure
2. The rationale is supported by the excerpt
3. The scapegoat target, if present, is explicit or strongly implied
4. The score seems internally consistent with the rationale

Return JSON:
{"valid": true, "problems": [], "suggested_action": "publish"}

If invalid, return: {"valid": false, "problems": ["..."], "suggested_action": "retry" or "escalate"}"""

# Valid enum values
VALID_PRIMARY_MODES = {
    "lucid", "denial", "deflection", "scapegoating",
    "gaslighting", "fantasy_economics", "minimisation", "unknown",
}
PRIMARY_MODE_ALIASES = {
    "adaptationism": "minimisation",
    "evasion": "deflection",
    "fantasy_framing": "fantasy_economics",
    "incomplete_framing": "deflection",
    "individualism": "deflection",
    "issue_framing_limiting": "minimisation",
    "neutral": "unknown",
    "no_claim": "unknown",
    "not_applicable": "unknown",
    "other": "unknown",
    "policy_advocacy": "deflection",
    "policy_avoidance": "deflection",
    "structural_avoidance": "deflection",
    "structural_explanation": "lucid",
    "structural_vague": "minimisation",
    "technocratic_adaptation": "minimisation",
    "unclassifiable": "unknown",
}
VALID_BANDS = {
    "lucid": (0, 19),
    "moderate": (20, 59),
    "heavy_cope": (60, 79),
    "terminal_copium": (80, 100),
}
UNSCOREABLE_FINANCE_DIRECT_MARKERS = (
    "campaign finance",
    "crypto billionaire",
    "crypto donation",
    "donation",
    "donor",
    "electoral commission",
    "financial contributions",
    "fundraising",
    "harborne",
    "political donation",
    "political funding",
    "undeclared",
)
UNSCOREABLE_FINANCE_CONTEXT_MARKERS = (
    "gift",
    "helicopter",
    "house purchase",
    "i'm a celebrity",
    "personal finances",
    "personal protection",
)
UNSCOREABLE_FINANCE_MONEY_MARKERS = (
    "£", "$", "crypto", "finances", "funds", "million", "billionaire",
)
NON_PUBLIC_MODES = {"unknown", "n/a", "none", "other", "irrelevant", ""}
KNOWN_PUBLIC_FIGURE_NAMES = (
    "Angela Rayner",
    "Andy Burnham",
    "Bridget Phillipson",
    "Darren Jones",
    "Ed Davey",
    "Jeremy Corbyn",
    "Jonathan Reynolds",
    "Josh Simons",
    "Kemi Badenoch",
    "Keir Starmer",
    "Lucy Powell",
    "Nigel Farage",
    "Rachel Reeves",
    "Richard Tice",
    "Robert Jenrick",
    "Sadiq Khan",
    "Wes Streeting",
    "Yvette Cooper",
)

# Required fields in scoring output
REQUIRED_SCORE_FIELDS = {
    "person", "source_url", "source_name", "claim_summary",
    "cope_score", "band", "primary_mode", "secondary_modes",
    "scapegoat_target", "structural_issue_ignored", "evidence_used",
    "rationale_short", "confidence", "needs_review",
}


# --- AI Callers ---

def _call_minimax(system, user, timeout=120):
    """Call MiniMax API directly. Fast and cheap. Returns raw text."""
[redacted secret-like line]
[redacted secret-like line]
    url = MINIMAX_URL
    payload = {
        "model": MINIMAX_MODEL,
        "messages": [
            {"role": "system", "content": system},
            {"role": "user", "content": user},
        ],
[redacted secret-like line]
        "response_format": {"type": "json_object"},
    }
    resp = requests.post(
        url,
        headers={
[redacted secret-like line]
            "Content-Type": "application/json",
        },
        json=payload,
        timeout=timeout,
    )
    resp.raise_for_status()
    data = resp.json()
    choices = data.get("choices") or []
    if not choices:
        raise RuntimeError(f"MiniMax no choices: {json.dumps(data)[:400]}")
    content = choices[0].get("message", {}).get("content", "")
    if isinstance(content, dict):
        content = content.get("text") or json.dumps(content)
    # Strip <think> tags from MiniMax reasoning
    content = re.sub(r"<think>.*?</think>", "", str(content), flags=re.DOTALL).strip()
    return content


# --- Firecrawl Ingest ---

def fetch_article_firecrawl(url, timeout=45):
    """
    Fetch article via Home VPS Firecrawl-compatible scraper.
    Returns {"markdown": str, "title": str, "url": str} or raises.
    """
    endpoint = f"{FIRECRAWL_URL}/v1/scrape"
    payload = {"url": url, "formats": ["markdown"]}
    try:
        resp = requests.post(endpoint, json=payload, timeout=timeout)
        resp.raise_for_status()
        data = resp.json()
        if not data.get("success"):
            raise RuntimeError(f"Firecrawl failed: {data.get('error', 'unknown')}")
        scrape_data = data.get("data", {})
        markdown = scrape_data.get("markdown", "")
        metadata = scrape_data.get("metadata", {})
        title = metadata.get("title") or metadata.get("ogTitle") or ""
        return {
            "markdown": markdown,
            "title": title,
            "url": url,
            "source_name": metadata.get("sourceURL", "")
                or metadata.get("ogSiteName", ""),
        }
    except requests.exceptions.Timeout:
        raise RuntimeError(f"Firecrawl timeout for {url}")
    except requests.exceptions.ConnectionError:
        raise RuntimeError(f"Firecrawl unreachable at {FIRECRAWL_URL}")


def _strip_boilerplate(markdown):
    """Remove common boilerplate from article markdown."""
    lines = markdown.split("\n")
    cleaned = []
    skip_patterns = [
        r"^#{1,3}\s*(Share|Follow|Subscribe|Sign up|Cookie|Privacy|Terms)",
        r"^(Share this|Follow us|Subscribe to|Sign up for)",
        r"^\[.*\]\(javascript:",
        r"^!\[.*\]\(.*tracking",
        r"^(Advertisement|Sponsored|Promoted)",
    ]
    skip_re = re.compile("|".join(skip_patterns), re.IGNORECASE)
    for line in lines:
        if skip_re.match(line.strip()):
            continue
        cleaned.append(line)
    return "\n".join(cleaned).strip()


def _extract_claim(text, person_name):
    """
    Extract the key quoted or attributed claim from article text.
    Looks for direct quotes near the person's name.
    """
    name_lower = person_name.lower()
    last_name = person_name.split()[-1].lower()

    quote_pattern = re.compile(
        r'["\u201c]([^"\u201d]{20,500})["\u201d]',
        re.DOTALL,
    )
    quotes = quote_pattern.findall(text)

    best_quote = ""
    best_score = -1

    text_lower = text.lower()
    name_positions = [
        m.start() for m in re.finditer(re.escape(name_lower), text_lower)
    ]
    if not name_positions and len(last_name) >= 4:
        name_positions = [
            m.start()
            for m in re.finditer(r"\b" + re.escape(last_name) + r"\b", text_lower)
        ]

    for quote in quotes:
        quote_pos = text.find(quote)
        if quote_pos < 0:
            continue
        min_dist = float("inf")
        for np in name_positions:
            dist = abs(quote_pos - np)
            if dist < min_dist:
                min_dist = dist
        proximity_score = max(0, 2000 - min_dist)
        length_score = min(len(quote), 300)
        score = proximity_score + length_score
        if score > best_score:
            best_score = score
            best_quote = quote

    if best_quote:
        return best_quote

    if name_positions:
        pos = name_positions[0]
        start = max(0, pos - 100)
        end = min(len(text), pos + 600)
        return text[start:end].strip()

    return text[:800]


def _extract_excerpt(text, person_name, max_len=3000):
    """Extract relevant excerpt around the person's mentions."""
    name_lower = person_name.lower()
    text_lower = text.lower()

    positions = [
        m.start()
        for m in re.finditer(r"\b" + re.escape(name_lower) + r"\b", text_lower)
    ]
    if not positions:
        last_name = person_name.split()[-1].lower()
        if len(last_name) >= 4:
            positions = [
                m.start()
                for m in re.finditer(
                    r"\b" + re.escape(last_name) + r"\b", text_lower
                )
            ]

    if not positions:
        return text[:max_len]

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

    combined = "\n...\n".join(chunks)
    return combined[:max_len]


# --- JSON Validation ---

def _extract_json(raw):
    """Extract JSON from model output, handling markdown fences and think tags."""
    raw = raw.strip()
    # Strip <think>...</think> tags (MiniMax reasoning)
    raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL).strip()
    if raw.startswith("```"):
        first_nl = raw.index("\n") if "\n" in raw else 3
        raw = raw[first_nl + 1:]
        if raw.endswith("```"):
            raw = raw[:-3]
    raw = raw.strip()
    # Try direct parse first, then search for JSON object
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        match = re.search(r"\{.*\}", raw, re.DOTALL)
        if match:
            return json.loads(match.group())
        raise


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


def _validate_score_schema(score):
    """Validate score dict against required schema. Returns list of problems."""
    problems = []

    missing = REQUIRED_SCORE_FIELDS - set(score.keys())
    if missing:
        problems.append(f"Missing fields: {', '.join(sorted(missing))}")

    if "cope_score" in score:
        cs = score["cope_score"]
        if not isinstance(cs, (int, float)) or cs < 0 or cs > 100:
            problems.append(f"cope_score must be 0-100, got {cs}")

    if "confidence" in score:
        c = score["confidence"]
        if not isinstance(c, (int, float)) or c < 0 or c > 1:
            problems.append(f"confidence must be 0-1, got {c}")

    if "primary_mode" in score:
        pm = score["primary_mode"]
        if pm not in VALID_PRIMARY_MODES:
            problems.append(f"primary_mode '{pm}' not in {VALID_PRIMARY_MODES}")

    if "band" in score:
        band = score["band"]
        if band not in VALID_BANDS:
            problems.append(f"band '{band}' not in {set(VALID_BANDS.keys())}")
        elif "cope_score" in score:
            lo, hi = VALID_BANDS[band]
            cs = int(score["cope_score"])
            if cs < lo or cs > hi:
                problems.append(f"band '{band}' expects score {lo}-{hi}, got {cs}")

    if "secondary_modes" in score:
        if not isinstance(score["secondary_modes"], list):
            problems.append("secondary_modes must be a list")

    if "evidence_used" in score:
        if not isinstance(score["evidence_used"], list):
            problems.append("evidence_used must be a list")

    if "needs_review" in score:
        if not isinstance(score["needs_review"], bool):
            problems.append("needs_review must be boolean")

    if "rationale_short" in score and "evidence_used" in score:
        rat = (score.get("rationale_short") or "").lower()
        if len(rat) < 20:
            problems.append("rationale_short too short")

    return problems


def _normalise_score_modes(score):
    """Map model-invented mode labels back into the public enum."""
    if not isinstance(score, dict):
        return score

    def clean_mode(value):
        mode = str(value or "").strip().lower().replace("-", "_").replace(" ", "_")
        if mode in VALID_PRIMARY_MODES:
            return mode
        return PRIMARY_MODE_ALIASES.get(mode, "unknown")

    primary = clean_mode(score.get("primary_mode"))
    score["primary_mode"] = primary

    secondary = score.get("secondary_modes", [])
    if not isinstance(secondary, list):
        secondary = []
    normalised_secondary = []
    for mode in secondary:
        cleaned = clean_mode(mode)
        if cleaned in VALID_PRIMARY_MODES and cleaned != primary and cleaned not in normalised_secondary:
            normalised_secondary.append(cleaned)
    score["secondary_modes"] = normalised_secondary

    if primary == "unknown":
        score["needs_review"] = True
    return score


def _correct_band(score):
    """Auto-correct the band field based on cope_score."""
    score = _normalise_score_modes(score)
    cs = score.get("cope_score", 50)
    if isinstance(cs, (int, float)):
        cs = int(cs)
        for band_name, (lo, hi) in VALID_BANDS.items():
            if lo <= cs <= hi:
                score["band"] = band_name
                break
    return score


# --- Pipeline Stages ---

def _run_first_pass(article, person):
    """Stage B: First-pass scoring with MiniMax."""
    user_prompt = FIRST_PASS_USER_TEMPLATE.format(
        person_name=person["name"],
        role=person.get("role", ""),
        party=person.get("party", ""),
        title=article.get("title", ""),
        publisher=article.get("source_name", ""),
        date=article.get("date", ""),
        url=article.get("url", ""),
        clean_excerpt=article.get("excerpt", "")[:3000],
        attributed_claim=article.get("claim", "")[:1000],
    )

    system = (
        FIRST_PASS_SYSTEM_PROMPT
        + "\n\nRequired output schema:\n"
        + FIRST_PASS_SCHEMA_EXAMPLE
    )

    raw = _call_minimax(system, user_prompt)
    log.debug("First-pass (MiniMax) raw output: %s", raw[:500])
    score = _extract_json(raw)
    score = _correct_band(score)
    return score, raw


def _run_validator(score, article, person):
    """Stage C: Validation with cheap model."""
    user_prompt = json.dumps(
        {
            "score": score,
            "person_name": person["name"],
            "article_title": article.get("title", ""),
            "excerpt": article.get("excerpt", "")[:2000],
            "attributed_claim": article.get("claim", "")[:500],
        },
        indent=2,
    )

    raw = _call_minimax(VALIDATOR_SYSTEM_PROMPT, user_prompt, timeout=60)
    log.debug("Validator (MiniMax) raw output: %s", raw[:500])
    result = _extract_json(raw)
    return result, raw


def _run_escalation(article, person):
    """Stage D: Escalation to MiniMax (big model)."""
    user_prompt = FIRST_PASS_USER_TEMPLATE.format(
        person_name=person["name"],
        role=person.get("role", ""),
        party=person.get("party", ""),
        title=article.get("title", ""),
        publisher=article.get("source_name", ""),
        date=article.get("date", ""),
        url=article.get("url", ""),
        clean_excerpt=article.get("excerpt", "")[:4000],
        attributed_claim=article.get("claim", "")[:1500],
    )

    system = (
        FIRST_PASS_SYSTEM_PROMPT
        + "\n\nRequired output schema:\n"
        + FIRST_PASS_SCHEMA_EXAMPLE
    )

    # Primary: MiniMax (fast, reliable)
    try:
        raw = _call_minimax(system, user_prompt)
        log.debug("Escalation (MiniMax) raw output: %s", raw[:500])
        score = _extract_json(raw)
        score = _correct_band(score)
        return score, raw
    except Exception as e:
        log.warning("Escalation MiniMax failed: %s -- escalation unavailable (Straico retired)", e)
        raise


def _is_tabloid(source_name):
    """Check if source is in the tabloid/sensational bucket."""
    return (source_name or "").lower().strip() in TABLOID_SOURCES


def _has_heavy_quotation(text):
    """Check if text has heavy quotation/irony/reported speech markers."""
    quote_marks = len(re.findall(r'["\u201c\u201d]', text))
    words = len(text.split())
    if words == 0:
        return False
    return (quote_marks / words) > 0.02


# --- Main Pipeline ---

def score_article(
    url,
    person,
    date="",
    source_name="",
    pre_fetched_text=None,
    pre_fetched_title=None,
):
    """
    Full tiered scoring pipeline for a single article + person.

    Args:
        url: Article URL
        person: {"name": str, "role": str, "party": str, "id": str}
        date: Article date string
        source_name: Publisher name
        pre_fetched_text: If already fetched, skip Firecrawl
        pre_fetched_title: Pre-fetched title

    Returns:
        {
            "score": dict (the full scoring output),
            "model": str,
            "stage": str (which stage produced the final score),
            "raw_outputs": list of raw model outputs,
            "validation": dict or None,
            "published": bool,
            "reject_reason": str or None,
        }
    """
    result = {
        "score": None,
        "model": None,
        "stage": None,
        "raw_outputs": [],
        "validation": None,
        "published": False,
        "reject_reason": None,
    }

    # --- Stage A: Ingest ---
    log.info("Pipeline: ingesting %s for %s", url[:80], person["name"])

    if pre_fetched_text:
        markdown = pre_fetched_text
        title = pre_fetched_title or ""
    else:
        try:
            fetched = fetch_article_firecrawl(url)
            markdown = fetched["markdown"]
            title = fetched.get("title", "")
            if not source_name:
                source_name = fetched.get("source_name", "")
        except Exception as e:
            log.warning("Firecrawl failed for %s: %s -- rejecting", url, e)
            result["reject_reason"] = f"source_fetch_failed: {e}"
            return result

    clean_text = _strip_boilerplate(markdown)

    if not clean_text or len(clean_text) < 200:
        result["reject_reason"] = "excerpt_too_short"
        return result

    claim = _extract_claim(clean_text, person["name"])
    excerpt = _extract_excerpt(clean_text, person["name"])

    if not claim or len(claim) < 30:
        result["reject_reason"] = "no_attributed_claim_found"
        return result

    article = {
        "url": url,
        "title": title,
        "source_name": source_name,
        "date": date,
        "excerpt": excerpt,
        "claim": claim,
        "full_text": clean_text,
    }
    # Keep identity metadata outside model-controlled JSON.  The event key
    # must use the resource actually fetched, not a URL/headline the scorer
    # may omit, rewrite, or hallucinate in its response.
    result["source_url"] = url
    result["source_title"] = title
    result["source_name"] = source_name
    result["observed_at"] = date or None

    # --- Stage B: First-pass scorer ---
    log.info("Pipeline: first-pass scoring for %s", person["name"])
    first_pass_score = None
    try:
        first_pass_score, raw_fp = _run_first_pass(article, person)
        result["raw_outputs"].append({"stage": "first_pass", "raw": raw_fp})
    except json.JSONDecodeError:
        log.warning("First-pass JSON failed, retrying once...")
        try:
            first_pass_score, raw_fp = _run_first_pass(article, person)
            result["raw_outputs"].append(
                {"stage": "first_pass_retry", "raw": raw_fp}
            )
        except Exception as e2:
            log.warning("First-pass retry failed: %s -- escalating", e2)
    except Exception as e:
        log.warning("First-pass failed: %s -- escalating", e)

    # If first pass still failed, escalate to big model
    if first_pass_score is None:
        log.info("Pipeline: escalating (first pass failed entirely)")
        try:
            esc_score, raw_esc = _run_escalation(article, person)
            result["raw_outputs"].append(
                {"stage": "escalation_from_failure", "raw": raw_esc}
            )
            result["score"] = esc_score
            result["model"] = f"minimax/{MINIMAX_MODEL}"
            result["stage"] = "escalation"
            result["published"] = True
            return result
        except Exception as e:
            result["reject_reason"] = f"all_models_failed: {e}"
            return result

    # --- Stage C: Schema validation ---
    schema_problems = _validate_score_schema(first_pass_score)
    if schema_problems:
        log.warning("Schema problems in first pass: %s -- escalating", schema_problems)
        try:
            esc_score, raw_esc = _run_escalation(article, person)
            result["raw_outputs"].append(
                {"stage": "escalation_from_schema", "raw": raw_esc}
            )
            esc_problems = _validate_score_schema(esc_score)
            if not esc_problems:
                result["score"] = esc_score
                result["model"] = f"minimax/{MINIMAX_MODEL}"
                result["stage"] = "escalation"
                result["published"] = True
                return result
            else:
                result["reject_reason"] = (
                    f"schema_invalid_after_escalation: {esc_problems}"
                )
                result["score"] = esc_score
                return result
        except Exception as e:
            result["reject_reason"] = f"escalation_failed: {e}"
            return result

    # --- Routing logic: decide if we need validation / escalation ---
    cope_score = first_pass_score.get("cope_score", 50)
    confidence = first_pass_score.get("confidence", 0.5)
    primary_mode = first_pass_score.get("primary_mode", "unknown")

    needs_escalation = False
    escalation_reason = ""

    if confidence < 0.72:
        needs_escalation = True
        escalation_reason = f"low_confidence ({confidence})"

    if primary_mode == "unknown":
        needs_escalation = True
        escalation_reason = "primary_mode_unknown"

    needs_validation = False
    if cope_score <= 15 or cope_score >= 85:
        needs_validation = True
    if _is_tabloid(source_name):
        needs_validation = True
    if _has_heavy_quotation(article.get("excerpt", "")):
        needs_validation = True

    # --- Stage C (cont): Semantic validation if needed ---
    if needs_validation and not needs_escalation:
        log.info("Pipeline: running validator (score=%s, source=%s)",
                 cope_score, source_name)
        try:
            validation, raw_val = _run_validator(
                first_pass_score, article, person
            )
            result["raw_outputs"].append(
                {"stage": "validation", "raw": raw_val}
            )
            result["validation"] = validation

            if not validation.get("valid", True):
                suggested = validation.get("suggested_action", "escalate")
                if suggested == "escalate":
                    needs_escalation = True
                    escalation_reason = (
                        f"validator_failed: {validation.get('problems', [])}"
                    )
                elif suggested == "retry":
                    log.info("Pipeline: validator said retry, retrying first pass")
                    try:
                        first_pass_score, raw_fp2 = _run_first_pass(
                            article, person
                        )
                        result["raw_outputs"].append(
                            {"stage": "first_pass_after_retry", "raw": raw_fp2}
                        )
                        first_pass_score = _correct_band(first_pass_score)
                        sp = _validate_score_schema(first_pass_score)
                        if sp:
                            needs_escalation = True
                            escalation_reason = f"retry_still_invalid: {sp}"
                    except Exception:
                        needs_escalation = True
                        escalation_reason = "retry_failed"
        except Exception as e:
            log.warning("Validator failed: %s -- continuing without", e)

    # --- Stage D: Escalation if needed ---
    if needs_escalation:
        log.info("Pipeline: escalating to Sonnet (reason: %s)", escalation_reason)
        try:
            esc_score, raw_esc = _run_escalation(article, person)
            result["raw_outputs"].append(
                {"stage": "escalation", "raw": raw_esc}
            )
            esc_problems = _validate_score_schema(esc_score)
            if not esc_problems:
                result["score"] = esc_score
                result["model"] = f"minimax/{MINIMAX_MODEL}"
                result["stage"] = f"escalation ({escalation_reason})"
                result["published"] = True
                return result
            else:
                log.warning("Escalation schema issues: %s", esc_problems)
                esc_score["needs_review"] = True
                result["score"] = esc_score
                result["model"] = f"minimax/{MINIMAX_MODEL}"
                result["stage"] = "escalation_with_issues"
                result["published"] = True
                return result
        except Exception as e:
            log.warning(
                "Escalation failed: %s -- publishing first pass with review flag", e)
            first_pass_score["needs_review"] = True
            result["score"] = first_pass_score
            result["model"] = f"minimax/{MINIMAX_MODEL}"
            result["stage"] = "first_pass_escalation_failed"
            result["published"] = True
            return result

    # --- Stage E: Publish ---
    result["score"] = first_pass_score
    result["model"] = f"minimax/{MINIMAX_MODEL}"
    result["stage"] = "first_pass"
    result["published"] = True

    log.info(
        "Pipeline: published score=%s band=%s mode=%s conf=%s for %s",
        first_pass_score.get("cope_score"),
        first_pass_score.get("band"),
        first_pass_score.get("primary_mode"),
        first_pass_score.get("confidence"),
        person["name"],
    )

    return result


# --- DB Integration ---

def _looks_unattributed_or_unscoreable(score):
    claim = (score.get("claim_summary") or "").strip().lower()
    rationale = (score.get("rationale_short") or "").strip().lower()
    combined = f"{claim} {rationale}"
    no_claim_markers = (
        "no claim",
        "no claim attributed",
        "no claim was attributed",
        "no attributed claim",
        "no economic claim",
        "no economic or structural claim",
        "no structural claim",
        "no specific claim",
        "no specific substantive claim",
        "no statement",
        "no statement attributed",
        "not attributed",
        "attributed to another",
        "attributed to the chancellor, not",
        "attributed to the figure listed",
        "attribution is flawed",
        "attribution is mismatched",
        "attribution mismatch",
        "attribution to starmer is weak",
        "cannot be scored",
        "claim is not made by",
        "provided text",
        "mentions the figure",
        "not made by",
        "not the requested figure",
        "not to the public figure",
        "quoted statement comes from",
        "statement comes from",
        "procedural",
    )
    return any(marker in combined for marker in no_claim_markers)


def _looks_personal_or_party_finance(score):
    combined = " ".join(
        str(score.get(key) or "")
        for key in (
            "source_url",
            "source_name",
            "claim_summary",
            "rationale_short",
            "structural_issue_ignored",
            "scapegoat_target",
        )
    ).lower()
    if any(marker in combined for marker in UNSCOREABLE_FINANCE_DIRECT_MARKERS):
        return True
    has_finance_context = any(marker in combined for marker in UNSCOREABLE_FINANCE_CONTEXT_MARKERS)
    has_money_context = any(marker in combined for marker in UNSCOREABLE_FINANCE_MONEY_MARKERS)
    return has_finance_context and has_money_context


def _normalised_name_bits(name):
    name = re.sub(r"[^a-z\s]", " ", str(name or "").lower())
    bits = [bit for bit in name.split() if bit not in {"sir", "dame", "lord", "lady", "the"}]
    return bits


def [redacted](score, target_name=""):
    target_bits = _normalised_name_bits(target_name)
    if not target_bits:
        return False
    target_full = " ".join(target_bits)
    target_last = target_bits[-1]
    claim = str(score.get("claim_summary") or "").lower()
    rationale = str(score.get("rationale_short") or "").lower()
    claim_targeted = target_full in claim or re.search(r"\b" + re.escape(target_last) + r"\b", claim)
    explicit_mismatch = (
        "not made by" in rationale
        or "attributed to" in rationale and f"not {target_last}" in rationale
        or "quoted statement comes from" in rationale
        or "statement comes from" in rationale
        or "attribution to" in rationale and "weak" in rationale
        or "attribution is flawed" in rationale
        or "attribution mismatch" in rationale
    )
    if explicit_mismatch:
        return True
    for name in KNOWN_PUBLIC_FIGURE_NAMES:
        other_bits = _normalised_name_bits(name)
        if not other_bits or other_bits[-1] == target_last:
            continue
        other_full = " ".join(other_bits)
        if other_full in claim and not claim_targeted:
            return True
    return False


def _is_public_score(score, target_name=""):
    """Return True only for scoreable public claims.

    The pipeline may produce review records for articles that merely mention a
    figure. Those should remain in pipeline_results, but they must not become
    public cope_entries because score=0 + unknown mode looks like a lucid score.
    """
    if not score:
        return False
    mode = (score.get("primary_mode") or "").strip().lower()
    band = (score.get("band") or "").strip().lower()
    try:
        cope_score = float(score.get("cope_score"))
    except (TypeError, ValueError):
        return False
    if score.get("needs_review"):
        return False
    if mode in NON_PUBLIC_MODES:
        return False
    if cope_score <= 0 and mode in NON_PUBLIC_MODES:
        return False
    if cope_score <= 0 and band == "lucid" and _looks_unattributed_or_unscoreable(score):
        return False
    if _looks_unattributed_or_unscoreable(score):
        return False
    if [redacted](score, target_name):
        return False
    if _looks_personal_or_party_finance(score):
        return False
    return 0 <= cope_score <= 100


def save_pipeline_result(result, figure_id, db_module):
    """
    Save a pipeline result to the database.
    Uses existing db_uk functions + pipeline_results table.
    Returns 1 on success, -1 on failure.
    """
    if not result.get("published") or not result.get("score"):
        log.warning("Not saving unpublished result for %s", figure_id)
        return -1

    score = result["score"]
    raw_source_url = result.get("source_url") or score.get("source_url", "")
    source_url = _normalise_source_url(raw_source_url)
    source_name = result.get("source_name") or score.get("source_name", "")
    source_title = (
        result.get("source_title") or score.get("source_title")
        or source_name
    )
    score["source_url"] = source_url
    score["source_name"] = source_name

    # Build analysis markdown with commentary marking
    analysis_parts = [
        f"**Claim:** {score.get('claim_summary', 'N/A')}",
        f"**Mode:** {score.get('primary_mode', 'unknown')}",
        f"**Band:** {score.get('band', 'unknown')}",
        f"**Confidence:** {score.get('confidence', 'N/A')}",
        f"**Rationale:** {score.get('rationale_short', 'N/A')}",
    ]
    if score.get("scapegoat_target"):
        analysis_parts.append(
            f"**Scapegoat target:** {score['scapegoat_target']}"
        )
    if score.get("structural_issue_ignored"):
        analysis_parts.append(
            f"**Structural issue ignored:** {score['structural_issue_ignored']}"
        )
    analysis_parts.append(
        f"\n*This is AI-generated commentary, not fact. "
        f"Scored by {result.get('model', 'unknown')} "
        f"via {result.get('stage', 'unknown')} stage. "
        f"Prompt version: {PROMPT_VERSION}*"
    )

    analysis_md = "\n\n".join(analysis_parts)
    cope_type = score.get("primary_mode", "unknown")
    figure = None
    try:
        figure = db_module.get_figure(figure_id)
    except Exception:
        figure = None
    target_name = (figure or {}).get("name") or score.get("person") or figure_id
    public_score = _is_public_score(score, target_name=target_name)
    reject_reason = None if public_score else "not_public_scoreable_claim"

    # Save the detailed record first. Review/unscoreable items stay here only.
    try:
        db_module.save_pipeline_result_record(
            figure_id=figure_id,
            source_url=source_url,
            source_name=source_name,
            score_data=score,
            model=result.get("model", "unknown"),
            stage=result.get("stage", "unknown"),
            prompt_version=PROMPT_VERSION,
            reject_reason=reject_reason,
            published=public_score,
        )
    except Exception as e:
        log.warning("Failed to save pipeline_result record: %s", e)

    if not public_score:
        log.info(
            "Saved pipeline result for review only: %s score=%s mode=%s needs_review=%s",
            figure_id,
            score.get("cope_score"),
            cope_type,
            score.get("needs_review", False),
        )
        return 0

    # Save to cope_entries (public table) only for scoreable claims.
    event_result = db_module.add_cope_entry(
        figure_id=figure_id,
        quote=score.get("claim_summary", "")[:500],
        source_url=raw_source_url,
        source_title=source_title,
        cope_score=score.get("cope_score", 50),
        cope_type=cope_type,
        analysis_md=analysis_md,
        model=result.get("model", "unknown"),
        observed_at=result.get("observed_at"),
        channel=source_name or result.get("stage", "unknown"),
    )

    log.info(
        "Saved pipeline result: %s score=%s needs_review=%s event=%s",
        figure_id,
        score.get("cope_score"),
        score.get("needs_review", False),
        event_result.get("reason", "new_event") if isinstance(event_result, dict) else "legacy",
    )

    if isinstance(event_result, dict) and not event_result.get("inserted"):
        return 0
    return 1


def save_raw_log(result, figure_id, log_dir=None):
    """Save raw model outputs for debugging."""
    if not log_dir:
        log_dir = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), "logs", "pipeline_raw"
        )
    os.makedirs(log_dir, exist_ok=True)

    ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
    filename = f"{ts}_{figure_id}.json"
    filepath = os.path.join(log_dir, filename)

    log_data = {
        "timestamp": ts,
        "figure_id": figure_id,
        "stage": result.get("stage"),
        "model": result.get("model"),
        "published": result.get("published"),
        "reject_reason": result.get("reject_reason"),
        "score": result.get("score"),
        "validation": result.get("validation"),
        "raw_outputs": result.get("raw_outputs", []),
        "prompt_version": PROMPT_VERSION,
    }

    try:
        with open(filepath, "w") as f:
            json.dump(log_data, f, indent=2, default=str)
        log.debug("Raw log saved: %s", filepath)
    except Exception as e:
        log.warning("Failed to save raw log: %s", e)
```
