---
type: "Source File"
title: "\"\"\"Database layer for CopeCheck Policy.\"\"\""
description: "\"\"\"Database layer for CopeCheck Policy.\"\"\" import sqlite3 import os DB_PATH = os.path.join(os.path.dirname(__file__), \"policy_cope.db\") def _conn(): c = sqlite3.connect(DB_PATH) c.row_factory = sqlite3.Row."
resource: "https://policy.copecheck.com"
tags: ["copecheck", "policy", "source-file", "py"]
timestamp: "2026-08-24T09:39:54Z"
site: "policy"
source_path: "copecheck-policy/db.py"
---

# """Database layer for CopeCheck Policy."""

Source path: `copecheck-policy/db.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-24T09:39:54Z`

```py
"""Database layer for CopeCheck Policy."""
import sqlite3
import os

DB_PATH = os.path.join(os.path.dirname(__file__), "policy_cope.db")


def _conn():
    c = sqlite3.connect(DB_PATH)
    c.row_factory = sqlite3.Row
    c.execute("PRAGMA journal_mode=WAL")
    return c


def init_db():
    c = _conn()
    c.executescript("""
    CREATE TABLE IF NOT EXISTS policies (
        id          INTEGER PRIMARY KEY AUTOINCREMENT,
        slug        TEXT UNIQUE NOT NULL,
        name        TEXT NOT NULL,
        domain      TEXT NOT NULL,       -- e.g. 'Public & Social Investments'
        source      TEXT DEFAULT 'windfall',
        source_url  TEXT,
        summary     TEXT,                -- one-line description
        description TEXT,                -- full description from source
        challenge   TEXT,                -- the challenge section
        precedents  TEXT,                -- real-world precedents

        -- Scores (0-100, higher = more cope)
        overall_cope_score      REAL,
        unit_cost_score         REAL,
        interface_collapse_score REAL,
        propagation_score       REAL,
        coordination_score      REAL,

        verdict     TEXT,                -- Pure Cope / Heavy Cope / etc.
        analysis    TEXT,                -- full Sonnet analysis markdown

        -- Per-lens analysis text
        unit_cost_analysis      TEXT,
        interface_analysis      TEXT,
        propagation_analysis    TEXT,
        coordination_analysis   TEXT,

        survives    INTEGER DEFAULT 0,   -- 1 if promoted to front page
        model       TEXT,
        scored_at   TEXT,
        created_at  TEXT DEFAULT CURRENT_TIMESTAMP
    );

    CREATE TABLE IF NOT EXISTS think_tanks (
        id          INTEGER PRIMARY KEY AUTOINCREMENT,
        slug        TEXT UNIQUE NOT NULL,
        name        TEXT NOT NULL,
        url         TEXT,
        description TEXT,
        country     TEXT DEFAULT 'US',
        tier        INTEGER DEFAULT 2,   -- 1=major, 2=solid, 3=niche

        -- Aggregate scores
        overall_cope_score  REAL,
        paper_count         INTEGER DEFAULT 0,
        avg_cope_score      REAL,

        created_at  TEXT DEFAULT CURRENT_TIMESTAMP,
        updated_at  TEXT DEFAULT CURRENT_TIMESTAMP
    );

    CREATE TABLE IF NOT EXISTS think_tank_papers (
        id          INTEGER PRIMARY KEY AUTOINCREMENT,
        think_tank_id INTEGER NOT NULL,
        slug        TEXT UNIQUE NOT NULL,
        title       TEXT NOT NULL,
        url         TEXT,
        published   TEXT,
        summary     TEXT,
        body        TEXT,

        -- Scores
        overall_cope_score      REAL,
        unit_cost_score         REAL,
        interface_collapse_score REAL,
        propagation_score       REAL,
        coordination_score      REAL,

        verdict     TEXT,
        analysis    TEXT,
        model       TEXT,
        scored_at   TEXT,
        created_at  TEXT DEFAULT CURRENT_TIMESTAMP,

        FOREIGN KEY (think_tank_id) REFERENCES think_tanks(id)
    );

    CREATE TABLE IF NOT EXISTS oracle_questions (
        id          INTEGER PRIMARY KEY AUTOINCREMENT,
        question    TEXT NOT NULL,
        answer      TEXT,
        model       TEXT,
        created_at  TEXT DEFAULT CURRENT_TIMESTAMP
    );
    """)
    c.commit()
    c.close()


# --- Policy CRUD ---

def upsert_policy(slug, name, domain, summary, description="", challenge="",
                  precedents="", source="windfall", source_url=""):
    c = _conn()
    c.execute("""
        INSERT INTO policies (slug, name, domain, summary, description, challenge,
                              precedents, source, source_url)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(slug) DO UPDATE SET
            name=excluded.name, domain=excluded.domain, summary=excluded.summary,
            description=excluded.description, challenge=excluded.challenge,
            precedents=excluded.precedents, source=excluded.source,
            source_url=excluded.source_url
    """, (slug, name, domain, summary, description, challenge, precedents,
          source, source_url))
    c.commit()
    c.close()


def set_policy_scores(slug, scores: dict):
    c = _conn()
    c.execute("""
        UPDATE policies SET
            overall_cope_score = ?, unit_cost_score = ?,
            interface_collapse_score = ?, propagation_score = ?,
            coordination_score = ?, verdict = ?, analysis = ?,
            unit_cost_analysis = ?, interface_analysis = ?,
            propagation_analysis = ?, coordination_analysis = ?,
            survives = ?, model = ?, scored_at = CURRENT_TIMESTAMP
        WHERE slug = ?
    """, (
        scores.get("overall_cope_score"),
        scores.get("unit_cost_score"),
        scores.get("interface_collapse_score"),
        scores.get("propagation_score"),
        scores.get("coordination_score"),
        scores.get("verdict"),
        scores.get("analysis"),
        scores.get("unit_cost_analysis"),
        scores.get("interface_analysis"),
        scores.get("propagation_analysis"),
        scores.get("coordination_analysis"),
        1 if scores.get("overall_cope_score", 100) < 30 else 0,
        scores.get("model", ""),
        slug,
    ))
    c.commit()
    c.close()


def get_policy(slug):
    c = _conn()
    row = c.execute("SELECT * FROM policies WHERE slug = ?", (slug,)).fetchone()
    c.close()
    return row


def get_all_policies(order_by="overall_cope_score DESC"):
    c = _conn()
    rows = c.execute(f"SELECT * FROM policies ORDER BY {order_by}").fetchall()
    c.close()
    return rows


def get_policies_by_domain(domain):
    c = _conn()
    rows = c.execute(
        "SELECT * FROM policies WHERE domain = ? ORDER BY overall_cope_score DESC",
        (domain,)
    ).fetchall()
    c.close()
    return rows


def get_surviving_policies():
    c = _conn()
    rows = c.execute(
        "SELECT * FROM policies WHERE survives = 1 ORDER BY overall_cope_score ASC"
    ).fetchall()
    c.close()
    return rows


def get_content_freshness():
    """Dates and coverage needed to describe this reference dataset honestly."""
    c = _conn()
    row = c.execute("""
        SELECT
          (SELECT MAX(scored_at) FROM policies) AS policy_scored_at,
          (SELECT MAX(updated_at) FROM think_tanks) AS think_tanks_updated_at,
          (SELECT COUNT(*) FROM think_tank_papers) AS paper_count,
          (SELECT MAX(scored_at) FROM think_tank_papers) AS papers_scored_at
    """).fetchone()
    c.close()
    return dict(row) if row else {}


# --- Think Tank CRUD ---

def upsert_think_tank(slug, name, url="", description="", country="US", tier=2):
    c = _conn()
    c.execute("""
        INSERT INTO think_tanks (slug, name, url, description, country, tier)
        VALUES (?, ?, ?, ?, ?, ?)
        ON CONFLICT(slug) DO UPDATE SET
            name=excluded.name, url=excluded.url,
            description=excluded.description, country=excluded.country,
            tier=excluded.tier, updated_at=CURRENT_TIMESTAMP
    """, (slug, name, url, description, country, tier))
    c.commit()
    c.close()


def get_think_tank(slug):
    c = _conn()
    row = c.execute("SELECT * FROM think_tanks WHERE slug = ?", (slug,)).fetchone()
    c.close()
    return row


def get_all_think_tanks(order_by="overall_cope_score DESC NULLS LAST"):
    c = _conn()
    rows = c.execute(f"SELECT * FROM think_tanks ORDER BY {order_by}").fetchall()
    c.close()
    return rows


def get_think_tank_papers(think_tank_id):
    c = _conn()
    rows = c.execute(
        "SELECT * FROM think_tank_papers WHERE think_tank_id = ? ORDER BY overall_cope_score DESC",
        (think_tank_id,)
    ).fetchall()
    c.close()
    return rows


def update_think_tank_scores(think_tank_id):
    c = _conn()
    row = c.execute("""
        SELECT COUNT(*) as cnt, AVG(overall_cope_score) as avg_score
        FROM think_tank_papers
        WHERE think_tank_id = ? AND overall_cope_score IS NOT NULL
    """, (think_tank_id,)).fetchone()
    if row and row["cnt"] > 0:
        c.execute("""
            UPDATE think_tanks SET
                paper_count = ?, avg_cope_score = ?,
                overall_cope_score = ?, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        """, (row["cnt"], round(row["avg_score"], 1), round(row["avg_score"], 1),
              think_tank_id))
    c.commit()
    c.close()


# --- Oracle ---

def save_oracle_question(question, answer, model=""):
    c = _conn()
    c.execute("INSERT INTO oracle_questions (question, answer, model) VALUES (?, ?, ?)",
              (question, answer, model))
    c.commit()
    c.close()


def get_recent_questions(limit=20):
    c = _conn()
    rows = c.execute(
        "SELECT * FROM oracle_questions ORDER BY created_at DESC LIMIT ?",
        (limit,)
    ).fetchall()
    c.close()
    return rows


# Initialize on import
init_db()
```
