---
type: "Source File"
title: "\"\"\"CopeCheck Policy — Scoring policy proposals against the Discontinuity Thesis.\"\"\""
description: "\"\"\"CopeCheck Policy — Scoring policy proposals against the Discontinuity Thesis.\"\"\" import os import re from flask import Flask, render_template, request, jsonify, abort, Response import db app = Flask(__name__)."
resource: "https://policy.copecheck.com"
tags: ["copecheck", "policy", "source-file", "py"]
timestamp: "2026-09-26T08:28:11Z"
site: "policy"
source_path: "copecheck-policy/app.py"
---

# """CopeCheck Policy — Scoring policy proposals against the Discontinuity Thesis."""

Source path: `copecheck-policy/app.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-26T08:28:11Z`

```py
"""CopeCheck Policy — Scoring policy proposals against the Discontinuity Thesis."""
import os
import re
from flask import Flask, render_template, request, jsonify, abort, Response
import db

app = Flask(__name__)


[redacted secret-like line]

DOMAINS = [
    "Public & Social Investments",
    "Labor Market Adaptation",
    "Active Labour Market Policy",
    "Wealth Capture",
    "Regulation & Market Design",
    "Global Coordination",
]

DOMAIN_SLUGS = {
    "public-social-investments": "Public & Social Investments",
    "labor-market-adaptation": "Labor Market Adaptation",
    "active-labour-market-policy": "Active Labour Market Policy",
    "wealth-capture": "Wealth Capture",
    "regulation-market-design": "Regulation & Market Design",
    "global-coordination": "Global Coordination",
}


# --- Template Filters ---

@app.template_filter('copecolor')
def copecolor(score):
    try:
        s = float(score or 0)
    except (ValueError, TypeError):
        return 'cope-moderate'
    if s >= 80: return 'cope-terminal'
    if s >= 60: return 'cope-heavy'
    if s >= 40: return 'cope-moderate'
    if s >= 20: return 'cope-partial'
    return 'cope-lucid'


@app.template_filter('copelabel')
def copelabel(score):
    try:
        s = float(score or 0)
    except (ValueError, TypeError):
        return 'Partial Cope'
    if s >= 80: return 'Pure Cope'
    if s >= 60: return 'Heavy Cope'
    if s >= 40: return 'Partial Cope'
    if s >= 20: return 'Somewhat Lucid'
    return 'Actually Addresses Reality'


@app.template_filter('domainslug')
def domainslug(domain):
    return re.sub(r'[^a-z0-9]+', '-', domain.lower().strip()).strip('-')


@app.context_processor
def inject_content_freshness():
    try:
        freshness = db.get_content_freshness()
    except Exception:
        freshness = {}
    return {"content_freshness": freshness}


# --- Routes ---

# ── CDN & Cache Headers ──────────────────────────────────────
@app.after_request
def add_cache_headers(response):
    """Set cache headers for Cloudflare CDN."""
    path = request.path
    if path.startswith('/static/'):
        # Static assets: cache aggressively at CDN and browser
        response.headers['Cache-Control'] = 'public, max-age=604800, stale-while-revalidate=86400'
    elif path.startswith('/api/'):
        # API responses: never cache
        response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
    elif path.endswith('.xml'):
        # Sitemaps/feeds: cache 1 hour
        response.headers['Cache-Control'] = 'public, max-age=3600'
    else:
        # HTML pages: short cache, but allow CDN to serve stale during spikes
        response.headers['Cache-Control'] = 'public, max-age=300, stale-while-revalidate=3600, stale-if-error=86400'
    # Vary by encoding so CDN caches gzip and plain separately
    response.headers.setdefault('Vary', 'Accept-Encoding')
    return response

@app.route('/')
def index():
    policies = db.get_all_policies("overall_cope_score DESC NULLS LAST")
    survivors = db.get_surviving_policies()
    stats = {
        "total": len(policies),
        "scored": len([p for p in policies if p["overall_cope_score"] is not None]),
        "pure_cope": len([p for p in policies if (p["overall_cope_score"] or 0) >= 80]),
        "survivors": len(survivors),
    }
    return render_template('index.html', policies=policies, survivors=survivors,
                           stats=stats, domains=DOMAINS)


@app.route('/policy/<slug>')
def policy_detail(slug):
    policy = db.get_policy(slug)
    if not policy:
        abort(404)
    return render_template('policy.html', policy=policy)


@app.route('/domain/<slug>')
def domain_detail(slug):
    domain_name = DOMAIN_SLUGS.get(slug)
    if not domain_name:
        abort(404)
    policies = db.get_policies_by_domain(domain_name)
    return render_template('domain.html', domain=domain_name, policies=policies)


@app.route('/think-tanks')
def think_tanks():
    tanks = db.get_all_think_tanks()
    return render_template('think_tanks.html', tanks=tanks)


@app.route('/think-tank/<slug>')
def think_tank_detail(slug):
    tank = db.get_think_tank(slug)
    if not tank:
        abort(404)
    papers = db.get_think_tank_papers(tank["id"])
    # Get linked canonical policies
    c = db._conn()
    rows = c.execute("""
        SELECT p.slug, p.name, p.domain, p.summary, p.overall_cope_score, p.verdict,
               ttp.source_url
        FROM think_tank_policies ttp
        JOIN policies p ON p.slug = ttp.policy_slug
        WHERE ttp.think_tank_slug = ?
        ORDER BY p.overall_cope_score DESC
    """, (slug,)).fetchall()
    c.close()
    linked_policies = [dict(r) for r in rows]
    return render_template('think_tank.html', tank=tank, papers=papers, linked_policies=linked_policies)


@app.route('/the-standard')
def the_standard():
    return render_template('standard.html')


@app.route('/about')
def about():
    return render_template('about.html')


@app.route('/oracle', methods=['GET', 'POST'])
def oracle():
    answer = None
    question = None
    if request.method == 'POST':
        question = request.form.get('question', '').strip()
        if question:
            # TODO: implement oracle
            answer = "Oracle scoring coming soon."
            db.save_oracle_question(question, answer)
    recent = db.get_recent_questions(10)
    return render_template('oracle.html', question=question, answer=answer, recent=recent)


# --- SEO Routes ---

@app.route('/sitemap.xml')
def sitemap():
    policies = db.get_all_policies()
    tanks = db.get_all_think_tanks()
    xml = ['<?xml version="1.0" encoding="UTF-8"?>']
    xml.append('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')
    xml.append(f'<url><loc>https://policy.copecheck.com/</loc><priority>1.0</priority></url>')
    xml.append(f'<url><loc>https://policy.copecheck.com/the-standard</loc><priority>0.9</priority></url>')
    xml.append(f'<url><loc>https://policy.copecheck.com/think-tanks</loc><priority>0.8</priority></url>')
    xml.append(f'<url><loc>https://policy.copecheck.com/about</loc><priority>0.5</priority></url>')
    for d_slug in DOMAIN_SLUGS:
        xml.append(f'<url><loc>https://policy.copecheck.com/domain/{d_slug}</loc><priority>0.7</priority></url>')
    for p in policies:
        xml.append(f'<url><loc>https://policy.copecheck.com/policy/{p["slug"]}</loc><priority>0.6</priority></url>')
    for t in tanks:
        xml.append(f'<url><loc>https://policy.copecheck.com/think-tank/{t["slug"]}</loc><priority>0.6</priority></url>')
    xml.append('</urlset>')
    return Response('\n'.join(xml), mimetype='application/xml')


@app.route('/robots.txt')
def robots():
    txt = """User-agent: *
Allow: /

User-agent: GPTBot
Allow: /

User-agent: Claude-Web
Allow: /

User-agent: Applebot-Extended
Allow: /

User-agent: Google-Extended
Allow: /

Sitemap: https://policy.copecheck.com/sitemap.xml
"""
    return Response(txt, mimetype='text/plain')


@app.route('/llms.txt')
def llms_txt():
    policies = db.get_all_policies()
    lines = [
        "# CopeCheck Policy",
        "> Scoring policy proposals against the Discontinuity Thesis v3.3",
        "",
        "## About",
        "CopeCheck Policy scores AI economic policy proposals from think tanks and policy atlases",
        "against the Discontinuity Thesis v3.3 (Interface Collapse) framework.",
        "Each policy is tested on four dimensions: unit-cost survivability, interface collapse",
        "resistance, propagation blindness, and coordination feasibility.",
        "",
        f"## Policies Scored: {len(policies)}",
        "",
    ]
    for p in policies:
        score = f" — Cope: {p['overall_cope_score']:.0f}" if p['overall_cope_score'] else ""
        lines.append(f"- [{p['name']}](https://policy.copecheck.com/policy/{p['slug']}){score}")
    lines.append("")
    lines.append("## Links")
    lines.append("- [Full Policy List](https://policy.copecheck.com/)")
    lines.append("- [The Standard](https://policy.copecheck.com/the-standard)")
    lines.append("- [Think Tanks](https://policy.copecheck.com/think-tanks)")
    return Response('\n'.join(lines), mimetype='text/plain')


@app.route('/llms-full.txt')
def llms_full():
    policies = db.get_all_policies()
    lines = [
        "# CopeCheck Policy — Full Data Export",
        "",
        "Each policy scored against the Discontinuity Thesis v3.3 (Interface Collapse).",
        "Scoring: unit_cost (30%) + interface_collapse (25%) + propagation (25%) + coordination (20%)",
        "",
    ]
    for p in policies:
        lines.append(f"## {p['name']}")
        lines.append(f"Domain: {p['domain']}")
        lines.append(f"Summary: {p['summary'] or ''}")
        if p['overall_cope_score'] is not None:
            lines.append(f"Overall Cope Score: {p['overall_cope_score']:.0f}/100 ({p['verdict']})")
            lines.append(f"Unit Cost: {p['unit_cost_score']:.0f} | Interface: {p['interface_collapse_score']:.0f} | Propagation: {p['propagation_score']:.0f} | Coordination: {p['coordination_score']:.0f}")
            if p['analysis']:
                lines.append(f"Analysis: {p['analysis']}")
        lines.append("")
    return Response('\n'.join(lines), mimetype='text/plain')




# --- Newsletter subscribe (Resend) ---
@app.route('/api/subscribe', methods=['POST'])
def api_newsletter_subscribe():
    """Subscribe email to Resend Cope Report audience."""
    import requests as _req, os as _os
    data = request.get_json(silent=True) or {}
    email = data.get('email', '').strip()
    if not email or '@' not in email:
        return jsonify({'success': False, 'message': 'Please enter a valid email address.'}), 400
[redacted secret-like line]
[redacted secret-like line]
        return jsonify({'success': False, 'message': 'Server configuration error.'}), 500
    try:
        r = _req.post(
            'https://api.resend.com/audiences/e0c71613-ce4e-4e25-a920-515dfe0a90ff/contacts',
[redacted secret-like line]
            json={'email': email, 'unsubscribed': False},
            timeout=8
        )
        if r.status_code in (200, 201):
            return jsonify({'success': True, 'message': "You're subscribed!"})
        if r.status_code == 422:
            return jsonify({'success': True, 'message': "Already subscribed — you're good!"})
        return jsonify({'success': False, 'message': 'Something went wrong. Please try again.'}), 500
    except Exception:
        return jsonify({'success': False, 'message': 'Connection error. Please try again.'}), 500



# --- Feedback endpoint ---
@app.route('/api/feedback', methods=['POST'])
def api_feedback():
[redacted secret-like line]
    import json as _json, os as _os, threading
    from datetime import datetime as _dt
    data = request.get_json(silent=True) or {}
    text = data.get('text', '').strip()
    if not text or len(text) > 5000:
        return jsonify({'error': 'Invalid feedback'}), 400
    entry = {
        'text': text,
        'email': data.get('email', '').strip()[:200],
        'page': data.get('page', '')[:500],
        'site': 'policy.copecheck.com',
        'ts': _dt.utcnow().isoformat(),
        'ip': request.remote_addr,
    }
    # Save locally
    fb_dir = _os.path.join(_os.path.dirname(__file__), 'feedback')
    _os.makedirs(fb_dir, exist_ok=True)
    fb_file = _os.path.join(fb_dir, 'feedback.jsonl')
    with open(fb_file, 'a') as f:
        f.write(_json.dumps(entry) + "\n")
[redacted secret-like line]
    def _notify():
        try:
            import requests as _req
[redacted secret-like line]
        except Exception:
            pass
    threading.Thread(target=_notify, daemon=True).start()
    return jsonify({'success': True})

@app.route('/ai-disclosure')
def ai_disclosure():
    return render_template('ai_disclosure.html')

if __name__ == '__main__':
    app.run(debug=True, port=8102)


# ── Trailing-slash canonicalisation (added 2026-09-26, infra audit) ──
# Flask 404s on "/foo/" when the route is declared as "/foo". This installs a
# before_request hook that 301s the slashed form to the canonical slash-less
# one, but only when the slashed form is not itself a real route. Revert by
# deleting these three lines and slash_canonical.py.
from slash_canonical import install_slash_canonicaliser  # noqa: E402
install_slash_canonicaliser(app)  # noqa: E402
```
