---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Backfill canonical identities, merge duplicate resources/events, recompute scores. Dry-run is the default. ``--apply`` takes BEGIN IMMEDIATE before planning, creates a full SQLite backup from."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-08-24T12:54:28Z"
site: "main"
source_path: "copecheck/migrate_canonical_dedupe.py"
---

# !/usr/bin/env python3

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

```py
#!/usr/bin/env python3
"""Backfill canonical identities, merge duplicate resources/events, recompute scores.

Dry-run is the default.  ``--apply`` takes BEGIN IMMEDIATE before planning,
creates a full SQLite backup from a second read connection, and commits all
schema/data/score changes as one transaction.
"""
from __future__ import annotations

import argparse
import json
import math
import sqlite3
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path

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


EVENT_WINDOW_DAYS = 7.0
HALF_LIFE_DAYS = 14.0
AGGREGATOR_HINTS = {
    "yahoo", "msn", "aol", "benzinga", "marketscreener", "newsbreak",
    "times of india", "timesofindia", "india today", "livemint",
    "economictimes", "the economic times", "business insider india",
    "moneycontrol", "investing.com", "webpronews",
}


def _columns(conn, table):
    return {row[1] for row in conn.execute(f"PRAGMA table_info({table})")}


def _ensure_column(conn, table, name, definition):
    if name not in _columns(conn, table):
        conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {definition}")


def ensure_schema(conn):
    _ensure_column(conn, "articles", "canonical_url", "TEXT")
    _ensure_column(conn, "articles", "canonical_url_hash", "TEXT")
    _ensure_column(conn, "cope_entries", "canonical_url", "TEXT")
    _ensure_column(conn, "cope_entries", "canonical_url_hash", "TEXT")
    _ensure_column(conn, "cope_entries", "event_fingerprint", "TEXT")
    _ensure_column(conn, "cope_entries", "event_observed_at", "TEXT")
    _ensure_column(conn, "cope_entries", "representative_quality", "INTEGER DEFAULT 0")
    _ensure_column(conn, "url_submissions", "canonical_url", "TEXT")
    _ensure_column(conn, "url_submissions", "canonical_url_hash", "TEXT")
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS article_provenance (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            article_slug TEXT NOT NULL REFERENCES articles(slug),
            observation_key TEXT NOT NULL,
            raw_url TEXT NOT NULL,
            canonical_url TEXT NOT NULL,
            source_title TEXT,
            source TEXT,
            channel TEXT,
            observed_at TEXT,
            legacy_article_id INTEGER,
            legacy_slug TEXT,
            legacy_url_hash TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(article_slug, observation_key)
        );
        CREATE INDEX IF NOT EXISTS idx_article_provenance_slug
            ON article_provenance(article_slug, created_at);
        CREATE TABLE IF NOT EXISTS article_aliases (
            alias_slug TEXT PRIMARY KEY,
            article_slug TEXT NOT NULL REFERENCES articles(slug),
            reason TEXT NOT NULL DEFAULT 'canonical_url_merge',
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        );
        CREATE TABLE IF NOT EXISTS cope_entry_provenance (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            cope_entry_id INTEGER NOT NULL REFERENCES cope_entries(id),
            observation_key TEXT NOT NULL,
            article_slug TEXT,
            source_url TEXT,
            canonical_url TEXT,
            source_title TEXT,
            quote TEXT,
            channel TEXT,
            observed_at TEXT,
            observed_cope_score REAL,
            observed_cope_type TEXT,
            observed_analysis_md TEXT,
            observed_model TEXT,
            representative_quality INTEGER,
            legacy_cope_entry_id INTEGER,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(cope_entry_id, observation_key)
        );
        CREATE INDEX IF NOT EXISTS idx_cope_provenance_entry
            ON cope_entry_provenance(cope_entry_id, created_at);
        CREATE TABLE IF NOT EXISTS cope_entries_quarantine (
            legacy_cope_entry_id INTEGER PRIMARY KEY,
            figure_id TEXT,
            article_slug TEXT,
            quote TEXT,
            source_url TEXT,
            source_title TEXT,
            cope_score REAL,
            cope_type TEXT,
            analysis_md TEXT,
            model TEXT,
            created_at TEXT,
            reason TEXT NOT NULL,
            quarantined_at TEXT DEFAULT CURRENT_TIMESTAMP
        );
        """
    )
    _ensure_column(conn, "article_provenance", "legacy_article_id", "INTEGER")
    _ensure_column(conn, "article_provenance", "legacy_slug", "TEXT")
    _ensure_column(conn, "article_provenance", "legacy_url_hash", "TEXT")
    for name, definition in (
        ("observed_cope_score", "REAL"),
        ("observed_cope_type", "TEXT"),
        ("observed_analysis_md", "TEXT"),
        ("observed_model", "TEXT"),
        ("representative_quality", "INTEGER"),
        ("legacy_cope_entry_id", "INTEGER"),
    ):
        _ensure_column(conn, "cope_entry_provenance", name, definition)


def ensure_identity_guards(conn):
    """Backfill NOT NULL-equivalent guards legacy ALTER cannot express."""
    conn.executescript(
        """
        CREATE TRIGGER IF NOT EXISTS trg_articles_require_canonical_insert
        BEFORE INSERT ON articles
        WHEN NEW.canonical_url IS NULL OR trim(NEW.canonical_url) = ''
        BEGIN
          SELECT RAISE(ABORT, 'articles.canonical_url is required');
        END;

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

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

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

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

        CREATE TRIGGER IF NOT EXISTS trg_cope_preserve_provenance_delete
        BEFORE DELETE ON cope_entries
        WHEN EXISTS (
          SELECT 1 FROM cope_entry_provenance
           WHERE cope_entry_id = OLD.id
        )
        BEGIN
          SELECT RAISE(ABORT, 'move cope provenance before deleting event');
        END;
        """
    )
def _utc(value, fallback=None):
    fallback = fallback or datetime.now(timezone.utc)
    try:
        parsed = datetime.fromisoformat(str(value or "").replace("Z", "+00:00"))
    except (TypeError, ValueError):
        return fallback
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=timezone.utc)
    return min(parsed.astimezone(timezone.utc), datetime.now(timezone.utc))


def _article_channel(row):
    source = str(row["source"] or "")
    legacy_hash = str(row["url_hash"] or "")
    if legacy_hash.startswith("codex-"):
        return "codex"
    if source.startswith("GoogleAlerts/"):
        return "google_alerts"
    if source.startswith("GNews"):
        return "gnews"
    return "rss"


def _article_rank(row):
    issue = extraction_quality_issue(row["body"] or "")
    return (
        int(issue is None),
        int(row["status"] == "analysed"),
        int(bool(row["verdict_md"])),
        len(row["body"] or ""),
        -int(row["id"]),
    )


def _invalid_cope_observation(row):
    type_key = str(row.get("cope_type") or "").strip().lower()
    quote_key = str(row.get("quote") or "").strip().lower()
    try:
        score = float(row.get("cope_score"))
    except (TypeError, ValueError):
        return True
    return (
        not 0 <= score <= 100
        or type_key == "not_attributed"
        or type_key.startswith("n/a")
        or quote_key.startswith(("n/a", "[no relevant]", "[leave blank]"))
    )


def _is_aggregator(source_title, source_url, article_source=None):
    text = " ".join((source_title or "", source_url or "", article_source or "")).lower()
    return any(hint in text for hint in AGGREGATOR_HINTS)


def observation_quality(conn, row):
    """Rank original, valid and complete evidence without arrival-time bias."""
    article = None
    if row.get("article_slug"):
        article = conn.execute(
            "SELECT status, body, verdict_md, source, url FROM articles WHERE slug=?",
            (row["article_slug"],),
        ).fetchone()
    article_source = article["source"] if article else None
    original = not _is_aggregator(
        row.get("source_title"), row.get("source_url"), article_source
    )
    quality = 4_000_000 if original else 0
    if article:
        body = article["body"] or ""
        if extraction_quality_issue(body) is None:
            quality += 2_000_000
        if article["status"] == "analysed":
            quality += 500_000
        if article["verdict_md"]:
            quality += 250_000
        quality += min(len(body), 100_000)
    return quality


def article_groups(conn):
    rows = list(conn.execute("SELECT * FROM articles ORDER BY id"))
    groups = defaultdict(list)
    for row in rows:
        groups[canonical_url(row["url"])].append(row)
    return rows, groups


def _event_observed(row, article_published):
    # Once the migration has established a canonical event time, preserve it.
    # Falling back to the representative article's publication date on a
    # subsequent pass can move a merged event forward in time and change its
    # decayed weight despite there being no new observation.
    value = (row.get("event_observed_at")
             or article_published.get(row.get("article_slug"))
             or row.get("created_at"))
    return _utc(value).isoformat()


def event_clusters(conn):
    article_published = {
        row["slug"]: row["published"]
        for row in conn.execute("SELECT slug, published FROM articles")
        if row["published"]
    }
    by_figure = defaultdict(list)
    for row in conn.execute("SELECT * FROM cope_entries ORDER BY created_at, id"):
        item = dict(row)
        if _invalid_cope_observation(item):
            continue
        item["_canonical"] = canonical_url(row["source_url"])
        item["_observed"] = _event_observed(item, article_published)
        by_figure[row["figure_id"]].append(item)

    clusters = []
    for figure_id, rows in by_figure.items():
        rows.sort(key=lambda row: (row["_observed"], row["id"]))
        parents = list(range(len(rows)))

        def find(index):
            while parents[index] != index:
                parents[index] = parents[parents[index]]
                index = parents[index]
            return index

        def union(left, right):
            left_root, right_root = find(left), find(right)
            if left_root != right_root:
                parents[right_root] = left_root

        for left_index, left in enumerate(rows):
            left_at = _utc(left["_observed"])
            for right_index in range(left_index + 1, len(rows)):
                right = rows[right_index]
                exact_url = bool(
                    left["_canonical"]
                    and left["_canonical"] == right["_canonical"]
                )
                timeless = exact_statement_match(
                    left["source_title"] or "", left["quote"] or "",
                    right["source_title"] or "", right["quote"] or "",
                )
                within_window = abs(
                    (left_at - _utc(right["_observed"])).total_seconds()
                ) <= EVENT_WINDOW_DAYS * 86400
                fuzzy = within_window and same_event(
                    canonical_a=left["_canonical"],
                    title_a=left["source_title"] or "",
                    quote_a=left["quote"] or "",
                    canonical_b=right["_canonical"],
                    title_b=right["source_title"] or "",
                    quote_b=right["quote"] or "",
                )
                if exact_url or timeless or fuzzy:
                    union(left_index, right_index)

        components = defaultdict(list)
        for index, row in enumerate(rows):
            components[find(index)].append(row)
        clusters.extend(components.values())
    return clusters


def plan(conn):
    articles, a_groups = article_groups(conn)
    clusters = event_clusters(conn)
    all_cope_rows = [dict(row) for row in conn.execute("SELECT * FROM cope_entries")]
    invalid_cope_rows = [row for row in all_cope_rows if _invalid_cope_observation(row)]
    duplicate_article_groups = [group for group in a_groups.values() if len(group) > 1]
    duplicate_event_groups = [group for group in clusters if len(group) > 1]
    orphan_article_refs = conn.execute(
        """SELECT COUNT(*)
             FROM cope_entries ce
             LEFT JOIN articles a ON a.slug=ce.article_slug
            WHERE ce.article_slug IS NOT NULL AND a.slug IS NULL"""
    ).fetchone()[0]
    return {
        "articles_before": len(articles),
        "canonical_articles": len(a_groups),
        "article_duplicate_groups": len(duplicate_article_groups),
        "articles_to_merge": sum(len(group) - 1 for group in duplicate_article_groups),
        "cope_entries_before": len(all_cope_rows),
        "invalid_cope_entries_to_quarantine": len(invalid_cope_rows),
        "valid_cope_observations": len(all_cope_rows) - len(invalid_cope_rows),
        "canonical_events": len(clusters),
        "event_duplicate_groups": len(duplicate_event_groups),
        "cope_entries_to_merge": sum(len(group) - 1 for group in duplicate_event_groups),
        "orphan_article_refs_to_repair": orphan_article_refs,
        "affected_figures": sorted({
            group[0]["figure_id"] for group in duplicate_event_groups
        }),
    }


def backup_database(db_path, backup_dir=None):
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    directory = backup_dir or db_path.parent
    directory.mkdir(parents=True, exist_ok=True)
    target_path = directory / f"{db_path.name}.bak-canonical-dedupe-{stamp}"
    with sqlite3.connect(db_path) as source, sqlite3.connect(target_path) as target:
        source.backup(target)
    return target_path


def _insert_article_provenance(conn, winner_slug, row, canonical):
    channel = _article_channel(row)
    key = provenance_key(
        canonical, f"legacy-article-{row['id']}\n{row['url']}\n{row['source']}", ""
    )
    conn.execute(
        """INSERT OR IGNORE INTO article_provenance
           (article_slug, observation_key, raw_url, canonical_url,
            source_title, source, channel, observed_at, created_at,
            legacy_article_id, legacy_slug, legacy_url_hash)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
        (winner_slug, key, row["url"], canonical, row["title"], row["source"],
         channel, row["published"], row["created_at"], row["id"],
         row["slug"], row["url_hash"]),
    )


def apply_article_merge(conn):
    _rows, groups = article_groups(conn)
    merged = 0
    for canonical, group in groups.items():
        winner = max(group, key=_article_rank)
        winner_slug = winner["slug"]
        for row in group:
            _insert_article_provenance(conn, winner_slug, row, canonical)
        for loser in group:
            if loser["id"] == winner["id"]:
                continue
            loser_slug = loser["slug"]
            conn.execute(
                """INSERT OR REPLACE INTO article_aliases
                   (alias_slug, article_slug, reason) VALUES (?, ?, ?)""",
                (loser_slug, winner_slug, "canonical_url_merge"),
            )
            conn.execute(
                "UPDATE cope_entries SET article_slug=? WHERE article_slug=?",
                (winner_slug, loser_slug),
            )
            conn.execute(
                "UPDATE comments SET article_slug=? WHERE article_slug=?",
                (winner_slug, loser_slug),
            )
            conn.execute("DELETE FROM articles WHERE id=?", (loser["id"],))
            merged += 1
        chash = canonical_url_hash(canonical)
        conn.execute(
            """UPDATE articles SET canonical_url=?, canonical_url_hash=?, url_hash=?
               WHERE id=?""",
            (canonical, chash, chash[:20], winner["id"]),
        )
    return merged


def _cope_channel(row):
    if row.get("article_slug"):
        return "article_crosslink"
    if "news.google." in str(row.get("source_url") or ""):
        return "direct_google_news"
    return "legacy"


def quarantine_invalid_entries(conn):
    rows = [dict(row) for row in conn.execute("SELECT * FROM cope_entries")]
    invalid = [row for row in rows if _invalid_cope_observation(row)]
    for row in invalid:
        conn.execute(
            """INSERT OR REPLACE INTO cope_entries_quarantine
               (legacy_cope_entry_id, figure_id, article_slug, quote,
                source_url, source_title, cope_score, cope_type, analysis_md,
                model, created_at, reason)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (row["id"], row["figure_id"], row.get("article_slug"),
             row.get("quote"), row.get("source_url"), row.get("source_title"),
             row.get("cope_score"), row.get("cope_type"), row.get("analysis_md"),
             row.get("model"), row.get("created_at"),
             "legacy_unattributed_or_na_sentinel"),
        )
        conn.execute("DELETE FROM cope_entries WHERE id=?", (row["id"],))
    return len(invalid)


def _insert_cope_provenance(conn, entry_id, row, quality):
    channel = _cope_channel(row)
    key = provenance_key(
        row["_canonical"],
        f"legacy-cope-{row['id']}\n{row.get('source_title') or ''}",
        row.get("quote") or "",
    )
    conn.execute(
        """INSERT OR IGNORE INTO cope_entry_provenance
           (cope_entry_id, observation_key, article_slug, source_url,
            canonical_url, source_title, quote, channel, observed_at, created_at,
            observed_cope_score, observed_cope_type, observed_analysis_md,
            observed_model, representative_quality, legacy_cope_entry_id)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
        (entry_id, key, row.get("article_slug"), row.get("source_url"),
         row["_canonical"], row.get("source_title"), row.get("quote"),
         channel, row["_observed"], row.get("created_at"),
         row.get("cope_score"), row.get("cope_type"), row.get("analysis_md"),
         row.get("model"), quality, row["id"]),
    )


def apply_event_merge(conn, quality_by_id):
    clusters = event_clusters(conn)
    merged = 0
    for cluster in clusters:
        cluster.sort(key=lambda row: (
            -quality_by_id.get(row["id"], 0),
            row["_canonical"], row.get("source_title") or "",
            row.get("quote") or "", row.get("model") or "", row["id"],
        ))
        winner = cluster[0]
        event_id = winner["id"]
        event_observed = min(row["_observed"] for row in cluster)
        fingerprint = new_event_fingerprint(
            winner["figure_id"], winner.get("source_title"),
            winner.get("quote"), event_observed,
        )
        for row in cluster:
            _insert_cope_provenance(
                conn, event_id, row, quality_by_id.get(row["id"], 0)
            )
        for loser in (row for row in cluster if row["id"] != event_id):
            # Supports an interrupted/older staged run without losing its ledger.
            old_provenance = list(conn.execute(
                "SELECT * FROM cope_entry_provenance WHERE cope_entry_id=?",
                (loser["id"],),
            ))
            for provenance in old_provenance:
                conn.execute(
                    """INSERT OR IGNORE INTO cope_entry_provenance
                       (cope_entry_id, observation_key, article_slug, source_url,
                        canonical_url, source_title, quote, channel, observed_at,
                        created_at, observed_cope_score, observed_cope_type,
                        observed_analysis_md, observed_model,
                        representative_quality, legacy_cope_entry_id)
                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
                    (event_id, provenance["observation_key"], provenance["article_slug"],
                     provenance["source_url"], provenance["canonical_url"],
                     provenance["source_title"], provenance["quote"],
                     provenance["channel"], provenance["observed_at"],
                     provenance["created_at"], provenance["observed_cope_score"],
                     provenance["observed_cope_type"],
                     provenance["observed_analysis_md"], provenance["observed_model"],
                     provenance["representative_quality"],
                     provenance["legacy_cope_entry_id"]),
                )
            conn.execute(
                "DELETE FROM cope_entry_provenance WHERE cope_entry_id=?",
                (loser["id"],),
            )
            conn.execute("DELETE FROM cope_entries WHERE id=?", (loser["id"],))
            merged += 1
        conn.execute(
            """UPDATE cope_entries
                  SET canonical_url=?, canonical_url_hash=?,
                      event_fingerprint=?, event_observed_at=?
                      , representative_quality=?
                WHERE id=?""",
            (winner["_canonical"], canonical_url_hash(winner["_canonical"]),
             fingerprint, event_observed, quality_by_id.get(event_id, 0), event_id),
        )
    return merged


def detach_orphan_article_refs(conn):
    """Resolve aliases, then detach truly missing article rows from events.

    Historical databases contain a small number of manually seeded cope rows
    whose ``article_slug`` never existed.  Their original slug already lives
    in the scored-observation provenance inserted by ``apply_event_merge``;
    leaving it on the canonical row would violate the declared foreign key
    once runtime enforcement is enabled.
    """
    conn.execute(
        """UPDATE cope_entries
              SET article_slug=(
                    SELECT aa.article_slug FROM article_aliases aa
                     WHERE aa.alias_slug=cope_entries.article_slug
                  )
            WHERE article_slug IS NOT NULL
              AND NOT EXISTS (
                    SELECT 1 FROM articles a WHERE a.slug=cope_entries.article_slug
                  )
              AND EXISTS (
                    SELECT 1 FROM article_aliases aa
                     WHERE aa.alias_slug=cope_entries.article_slug
                  )"""
    )
    cursor = conn.execute(
        """UPDATE cope_entries SET article_slug=NULL
            WHERE article_slug IS NOT NULL
              AND NOT EXISTS (
                    SELECT 1 FROM articles a WHERE a.slug=cope_entries.article_slug
                  )"""
    )
    return cursor.rowcount


def _weighted(rows, at=None):
    if not rows:
        return 50.0
    at = _utc(at)
    pool = rows
    decay = math.log(2.0) / HALF_LIFE_DAYS
    numerator = denominator = 0.0
    for row in pool:
        stamp = _utc(row["event_observed_at"] or row["created_at"])
        age = max(0.0, (at - stamp).total_seconds() / 86400.0)
        weight = math.exp(-decay * age)
        numerator += float(row["cope_score"]) * weight
        denominator += weight
    return round(numerator / denominator, 1) if denominator else 50.0


def recompute_scores(conn):
    changes = []
    for figure in conn.execute("SELECT id, cope_score FROM figures ORDER BY id"):
        rows = [dict(row) for row in conn.execute(
            """SELECT * FROM cope_entries WHERE figure_id=?
               ORDER BY COALESCE(event_observed_at, created_at), id""",
            (figure["id"],),
        )]
        old = float(figure["cope_score"] or 50.0)
        if rows:
            current = _weighted(rows)
            previous = _weighted(rows[:-1], rows[-2]["event_observed_at"] or rows[-2]["created_at"]) if len(rows) > 1 else 50.0
            last = rows[-1]
            conn.execute(
                """UPDATE figures SET cope_score=?, prev_score=?, total_quotes=?,
                          last_quote=?, last_cope_type=?, last_scored=?,
                          updated_at=CURRENT_TIMESTAMP WHERE id=?""",
                (current, previous, len(rows), (last["quote"] or "")[:500],
                 last["cope_type"], last["event_observed_at"] or last["created_at"],
                 figure["id"]),
            )
        else:
            current = 50.0
            conn.execute(
                """UPDATE figures SET cope_score=50, prev_score=50,
                          total_quotes=0, last_quote=NULL, last_cope_type=NULL,
                          last_scored=NULL, updated_at=CURRENT_TIMESTAMP
                   WHERE id=?""",
                (figure["id"],),
            )
        if current != old:
            changes.append({"figure_id": figure["id"], "before": old, "after": current})
    return changes


def apply_migration(conn):
    ensure_schema(conn)
    quality_by_id = {
        row["id"]: observation_quality(conn, dict(row))
        for row in conn.execute("SELECT * FROM cope_entries")
    }
    quarantined = quarantine_invalid_entries(conn)
    articles_merged = apply_article_merge(conn)
    entries_merged = apply_event_merge(conn, quality_by_id)
    orphan_refs_detached = detach_orphan_article_refs(conn)
    for row in conn.execute("SELECT id, url FROM url_submissions"):
        canonical = canonical_url(row["url"])
        conn.execute(
            """UPDATE url_submissions SET canonical_url=?, canonical_url_hash=?
               WHERE id=?""",
            (canonical, canonical_url_hash(canonical), row["id"]),
        )
    conn.execute(
        "CREATE UNIQUE INDEX IF NOT EXISTS uq_articles_canonical_url "
        "ON articles(canonical_url)"
    )
    conn.execute(
        "CREATE UNIQUE INDEX IF NOT EXISTS uq_cope_figure_event "
        "ON cope_entries(figure_id, event_fingerprint)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_articles_canonical_hash "
        "ON articles(canonical_url_hash)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_cope_canonical "
        "ON cope_entries(figure_id, canonical_url_hash)"
    )
    ensure_identity_guards(conn)
    score_changes = recompute_scores(conn)
    conn.execute("DELETE FROM articles_fts")
    conn.execute(
        """INSERT INTO articles_fts
           (slug, title, source, snippet, one_liner, verdict_md)
           SELECT slug, title, source, COALESCE(snippet,''),
                  COALESCE(one_liner,''), COALESCE(verdict_md,'')
             FROM articles WHERE status='analysed'"""
    )
    return (
        articles_merged, entries_merged, quarantined,
        orphan_refs_detached, score_changes,
    )


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--db", type=Path, required=True)
    parser.add_argument("--apply", action="store_true")
    parser.add_argument("--backup-dir", type=Path)
    args = parser.parse_args()
    if not args.db.is_file():
        parser.error(f"database not found: {args.db}")

    if args.apply:
        connection = sqlite3.connect(args.db)
    else:
        connection = sqlite3.connect(args.db.resolve().as_uri() + "?mode=ro", uri=True)
    connection.row_factory = sqlite3.Row
    summary = {"mode": "apply" if args.apply else "dry-run", "database": str(args.db)}
    try:
        if args.apply:
            connection.execute("BEGIN IMMEDIATE")
            summary["backup"] = str(backup_database(args.db, args.backup_dir))
            ensure_schema(connection)
        summary.update(plan(connection))
        if args.apply:
            (a_merged, e_merged, quarantined,
             orphan_refs_detached, score_changes) = apply_migration(connection)
            summary["articles_merged"] = a_merged
            summary["cope_entries_merged"] = e_merged
            summary["cope_entries_quarantined"] = quarantined
            summary["orphan_article_refs_detached"] = orphan_refs_detached
            summary["score_changes"] = score_changes
            summary["article_provenance_rows"] = connection.execute(
                "SELECT COUNT(*) FROM article_provenance"
            ).fetchone()[0]
            summary["cope_provenance_rows"] = connection.execute(
                "SELECT COUNT(*) FROM cope_entry_provenance"
            ).fetchone()[0]
            summary["cope_quarantine_rows"] = connection.execute(
                "SELECT COUNT(*) FROM cope_entries_quarantine"
            ).fetchone()[0]
            summary["article_alias_rows"] = connection.execute(
                "SELECT COUNT(*) FROM article_aliases"
            ).fetchone()[0]
            summary["articles_after"] = connection.execute(
                "SELECT COUNT(*) FROM articles"
            ).fetchone()[0]
            summary["cope_entries_after"] = connection.execute(
                "SELECT COUNT(*) FROM cope_entries"
            ).fetchone()[0]
            summary["integrity_check"] = connection.execute(
                "PRAGMA integrity_check"
            ).fetchone()[0]
            if summary["integrity_check"] != "ok":
                raise RuntimeError(f"integrity check failed: {summary['integrity_check']}")
            foreign_key_violations = list(connection.execute(
                "PRAGMA foreign_key_check"
            ))
            summary["foreign_key_violations"] = len(foreign_key_violations)
            if foreign_key_violations:
                raise RuntimeError(
                    f"foreign key check failed: {len(foreign_key_violations)} violations"
                )
            connection.commit()
    except Exception:
        if args.apply:
            connection.rollback()
        raise
    finally:
        connection.close()
    print(json.dumps(summary, indent=2, sort_keys=True))
    return 0


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