---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Apply Tier 1 + Tier 2 index changes to CopeCheck — fully reversible. Every change is recorded in `prune_batches` with the article's exact prior index_status / index_reason / indexed_source, so."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-25T21:05:24Z"
site: "main"
source_path: "copecheck/prune_apply.py"
---

# !/usr/bin/env python3

Source path: `copecheck/prune_apply.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-25T21:05:24Z`

```py
#!/usr/bin/env python3
"""Apply Tier 1 + Tier 2 index changes to CopeCheck — fully reversible.

Every change is recorded in `prune_batches` with the article's exact prior
index_status / index_reason / indexed_source, so `prune_rollback.py <batch>`
restores it byte-for-byte.

CRITERIA PRINCIPLE
------------------
Prune triggers are STRUCTURAL ONLY — properties of the document itself:
  * body too short to rank            (T2a, <500 chars)
  * duplicate headline                (T1c)
  * source URL confirmed dead         (T1d, 404/410 on both HEAD and GET)

Traffic and Search Console data are NOT used as prune triggers, and are NOT
used to spare a structurally-weak article either. A 300-character body cannot
rank whatever last quarter's impressions said, so the structural signal stands
on its own and stale data cannot distort it in either direction.

The ONE carve-out is editorial, not statistical: articles carrying public-figure
cope evidence (`indexed_source='curated'` or an attached `cope_entries` row) are
never demoted. That is the site's core asset.

Criteria that rest SOLELY on traffic (e.g. "zero human pageviews") are reported
but NOT applied, because the only data available for them is a four-month-old
Search Console snapshot.

Nothing is deleted. No provenance row is touched. Only articles.index_status,
index_reason and index_checked_at change — none of which feed figure scoring.

Usage:
  prune_apply.py --dry-run
  prune_apply.py --apply
"""
import argparse
import json
import os
import sys
from datetime import datetime, timezone

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import db  # noqa: E402

DEAD_JSON = os.path.join(HERE, "data", "deadlink_audit.json")
GSC_JSON = os.path.join(HERE, "data", "search-console-page-stats.json")
ANALYTICS = os.path.join(HERE, "data", "analytics.db")

SCHEMA = """
CREATE TABLE IF NOT EXISTS prune_batches (
    id                 INTEGER PRIMARY KEY AUTOINCREMENT,
    batch              TEXT NOT NULL,
    tier               TEXT NOT NULL,
    slug               TEXT NOT NULL,
    article_id         INTEGER,
    old_index_status   TEXT,
    old_index_reason   TEXT,
    old_indexed_source TEXT,
    new_index_status   TEXT,
    new_index_reason   TEXT,
    applied_at         TEXT DEFAULT CURRENT_TIMESTAMP,
    rolled_back_at     TEXT
);
CREATE INDEX IF NOT EXISTS idx_prune_batch ON prune_batches(batch);
CREATE INDEX IF NOT EXISTS idx_prune_slug  ON prune_batches(slug);
"""

IDX = "index_status IN ('index','trial_index')"


def editorial_protected(c):
    """The single carve-out: articles carrying public-figure cope evidence.

    Editorial, not statistical — no traffic or impression data involved.
    """
    keep = set()
    for r in c.execute("SELECT slug FROM articles WHERE indexed_source='curated'"):
        keep.add(r["slug"])
    for r in c.execute("SELECT DISTINCT article_slug FROM cope_entries "
                       "WHERE article_slug IS NOT NULL"):
        keep.add(r["article_slug"])
    keep.discard(None)
    return keep


def build_changes(c):
    keep = editorial_protected(c)
    print(f"editorial carve-out (cope evidence, never demoted): {len(keep)}")

    changes, seen = [], set()

    def add(tier, rows, reason_fn):
        skipped = 0
        for r in rows:
            s = r["slug"]
            if s in keep:
                skipped += 1
                continue
            if s in seen:
                continue
            seen.add(s)
            changes.append((tier, s, reason_fn(r)))
        return skipped

    # --- T1c: exact duplicate normalised headline, keep the earliest --------
    dup = c.execute(f"""
        SELECT slug FROM articles WHERE {IDX} AND slug IN (
          SELECT slug FROM (
            SELECT slug, ROW_NUMBER() OVER (
              PARTITION BY title_hash ORDER BY created_at ASC) rn
              FROM articles WHERE title_hash IS NOT NULL) WHERE rn > 1)
    """).fetchall()
    sk = add("T1c-duplicate-title", dup,
             lambda r: "duplicate headline; earlier entry is canonical")
    print(f"  T1c duplicate headline    : {len(dup):>4} matched, "
          f"{sk} editorially protected")

    # --- T1d: source URL confirmed dead (404/410 on HEAD *and* GET) --------
    try:
        audit = json.load(open(DEAD_JSON))
        dead = [d["slug"] for d in audit["dead"]]
        print(f"      (dead-link audit: {audit['checked']} URLs checked, "
              f"{len(dead)} confirmed dead)")
    except Exception as e:
        dead = []
        print(f"  ! dead-link audit unavailable ({e}); T1d SKIPPED")
    if dead:
        qs = ",".join("?" * len(dead))
        rows = c.execute(
            f"SELECT slug FROM articles WHERE {IDX} AND slug IN ({qs})",
            dead).fetchall()
        sk = add("T1d-dead-source-link", rows,
                 lambda r: "source URL returns 404/410; evidence unreachable")
        print(f"  T1d dead source link      : {len(rows):>4} matched, "
              f"{sk} editorially protected")

    # --- T2a: body too short to rank ---------------------------------------
    thin = c.execute(f"""
        SELECT slug, LENGTH(COALESCE(body,'')) n FROM articles
         WHERE {IDX} AND LENGTH(COALESCE(body,'')) < 500
    """).fetchall()
    sk = add("T2a-thin-body", thin,
             lambda r: f"body too short to rank ({r['n']} chars, floor 500)")
    print(f"  T2a thin body (<500 chars): {len(thin):>4} matched, "
          f"{sk} editorially protected")

    return changes


def report_traffic_only(c, changes):
    """Size the traffic-dependent set WITHOUT acting on it."""
    acted = {s for _, s, _ in changes}
    protected = editorial_protected(c)
    if not os.path.exists(ANALYTICS):
        print("\n  (analytics.db missing; cannot size traffic-only set)")
        return
    c.execute(f"ATTACH DATABASE 'file:{ANALYTICS}?mode=ro' AS anx")
    viewed = {r["slug"] for r in c.execute("""
        SELECT replace(substr(path,4),'/','') slug FROM anx.pageviews
         WHERE path LIKE '/v/%' AND user_agent LIKE 'Mozilla/%'
           AND user_agent NOT LIKE '%bot%' AND user_agent NOT LIKE '%Bot%'
           AND user_agent NOT LIKE '%crawl%'
         GROUP BY 1""")}
    c.execute("DETACH DATABASE anx")
    rows = [r["slug"] for r in
            c.execute(f"SELECT slug FROM articles WHERE {IDX}")]
    only = [s for s in rows
            if s not in viewed and s not in acted and s not in protected]
    print("\n" + "-" * 66)
    print("CARVED OUT — NOT APPLIED (traffic-only criterion)")
    print("-" * 66)
    print(f"  Indexable, structurally sound, but zero genuine human")
    print(f"  pageviews ever recorded:  {len(only)} articles")
    print("  Not actioned: the only corroborating search data is the")
    print("  25 May Search Console snapshot, now four months stale.")
    return only


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--apply", action="store_true")
    ap.add_argument("--dry-run", action="store_true")
    a = ap.parse_args()
    if not (a.apply or a.dry_run):
        ap.error("choose --apply or --dry-run")

    batch = datetime.now(timezone.utc).strftime("prune-%Y%m%dT%H%M%SZ")

    with db.conn() as c:
        c.executescript(SCHEMA)
        before = c.execute(
            f"SELECT COUNT(*) FROM articles WHERE {IDX}").fetchone()[0]
        print(f"indexable before: {before}\n")

        changes = build_changes(c)
        print(f"\nTOTAL to demote to noindex : {len(changes)}")
        print(f"indexable after            : {before - len(changes)}")

        report_traffic_only(c, changes)

        if a.dry_run:
            print("\n--- DRY RUN, nothing written ---")
            by = {}
            for t, s, r in changes:
                by.setdefault(t, []).append(s)
            for t, ss in sorted(by.items()):
                print(f"\n{t}: {len(ss)}")
                for s in ss[:3]:
                    print("   ·", s)
            return 0

        c.execute("BEGIN IMMEDIATE")
        for tier, slug, reason in changes:
            row = c.execute(
                "SELECT id, index_status, index_reason, indexed_source "
                "FROM articles WHERE slug=?", (slug,)).fetchone()
            if not row or row["index_status"] not in ("index", "trial_index"):
                continue
            c.execute(
                """INSERT INTO prune_batches
                     (batch, tier, slug, article_id, old_index_status,
                      old_index_reason, old_indexed_source,
                      new_index_status, new_index_reason)
                   VALUES (?,?,?,?,?,?,?,?,?)""",
                (batch, tier, slug, row["id"], row["index_status"],
                 row["index_reason"], row["indexed_source"], "noindex", reason))
            c.execute(
                """UPDATE articles
                      SET index_status='noindex', index_reason=?,
                          index_checked_at=CURRENT_TIMESTAMP
                    WHERE slug=?""", (reason, slug))

        after = c.execute(
            f"SELECT COUNT(*) FROM articles WHERE {IDX}").fetchone()[0]
        n = c.execute("SELECT COUNT(*) FROM prune_batches WHERE batch=?",
                      (batch,)).fetchone()[0]
        print(f"\nAPPLIED batch {batch}")
        print(f"  rows recorded for rollback : {n}")
        print(f"  indexable {before} -> {after}")
        print(f"\nrollback:  venv/bin/python3 prune_rollback.py {batch}")
    return 0


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