---
type: "Source File"
title: "\"\"\""
description: "\"\"\" labs.copecheck.com - AI Lab Cope Tracker Multi-lab analysis: which AI lab's own data and public statements reveal the most cope about displacement? OpenAI Signals, Anthropic labour research, and more. \"\"\" import."
resource: "https://labs.copecheck.com"
tags: ["copecheck", "labs", "source-file", "py"]
timestamp: "2026-09-26T08:28:11Z"
site: "labs"
source_path: "labs/server.py"
---

# """

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

```py
"""
labs.copecheck.com - AI Lab Cope Tracker
Multi-lab analysis: which AI lab's own data and public statements reveal
the most cope about displacement? OpenAI Signals, Anthropic labour research, and more.
"""
import csv
import hashlib
import html
import ipaddress
import json
import logging
import os
import re
import socket
import subprocess
import tempfile
import fcntl
from datetime import datetime, date, timezone
from pathlib import Path
from flask import Flask, render_template_string, jsonify, request, Response, redirect
from collections import defaultdict
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qsl, quote, urlencode, urlparse
from urllib.request import Request, urlopen

BASE = Path(__file__).parent
DATA_DIR = BASE / "data"
REPORT_SUBMISSIONS_PATH = DATA_DIR / "report-submissions.jsonl"
REPORT_SUBMISSIONS_LOCK_PATH = DATA_DIR / "report-submissions.lock"
MAX_REPORT_BYTES = 12 * 1024 * 1024
MAX_REPORT_CHARS = 80_000
ARTICLE_GATEWAY_URL = os.environ.get("FIRECRAWL_URL", "http://100.70.233.73:3002").rstrip("/")

TRACKING_QUERY_PARAMS = {
    "fbclid", "gclid", "dclid", "msclkid", "mc_cid", "mc_eid",
    "recommendedarticles",
}

app = Flask(__name__)


[redacted secret-like line]
app.config["MAX_CONTENT_LENGTH"] = MAX_REPORT_BYTES + 256_000

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ── O*NET IWA code mapping (Intermediate Work Activities) ───────────────
IWA_NAMES = {
    "4.A.1.a.1.I01": "Monitoring Processes, Materials, or Surroundings",
    "4.A.1.a.1.I02": "Identifying Objects, Actions, and Events",
    "4.A.1.a.1.I03": "Inspecting Equipment, Structures, or Materials",
    "4.A.1.a.1.I04": "Getting Information",
    "4.A.1.a.1.I05": "Monitor Processes, Materials, or Surroundings",
    "4.A.1.a.1.I06": "Estimating the Quantifiable Characteristics of Products, Events, or Information",
    "4.A.1.a.1.I07": "Judging the Qualities of Objects, Services, or People",
    "4.A.1.a.1.I08": "Evaluating Information to Determine Compliance with Standards",
    "4.A.1.a.1.I09": "Analyzing Data or Information",
    "4.A.1.a.1.I11": "Determining Compliance",
    "4.A.1.a.1.I12": "Reviewing/Checking Information",
    "4.A.1.a.1.I13": "Researching Topics",
    "4.A.1.a.1.I14": "Examining Information",
    "4.A.1.a.1.I15": "Gathering Data/Information",
    "4.A.1.a.1.I16": "Reviewing Records/Documentation",
    "4.A.1.a.1.I17": "Reading/Reviewing Published Information",
    "4.A.1.a.1.I18": "Compiling Data/Statistics",
    "4.A.1.a.1.I19": "Observing Operations",
    "4.A.1.a.1.I20": "Testing Products/Systems",
    "4.A.1.a.1.I21": "Surveying Locations/Areas",
    "4.A.1.a.1.I23": "Measuring Physical Characteristics",
    "4.A.1.a.2.I08": "Updating and Using Relevant Knowledge",
    "4.A.1.a.2.I10": "Studying Laws/Regulations",
    "4.A.1.b.1.I02": "Identifying Objects, Actions, and Events",
    "4.A.1.b.2.I09": "Judging the Qualities of Objects, Services, or People",
    "4.A.1.b.3.I01": "Estimating the Quantifiable Characteristics of Products",
    "4.A.1.b.3.I02": "Estimating Resource Requirements",
    "4.A.1.b.3.I03": "Estimating Time",
    "4.A.2.a.1.I01": "Making Decisions and Solving Problems",
    "4.A.2.a.1.I02": "Diagnosing Problems",
    "4.A.2.a.1.I03": "Evaluating Solutions",
    "4.A.2.a.1.I04": "Analyzing Information",
    "4.A.2.a.1.I06": "Investigating Issues",
    "4.A.2.a.1.I07": "Problem Analysis",
    "4.A.2.a.1.I08": "Strategic Planning",
    "4.A.2.a.1.I09": "Assessing Risks",
    "4.A.2.a.1.I10": "Deciding Courses of Action",
    "4.A.2.a.2.I01": "Thinking Creatively",
    "4.A.2.a.2.I03": "Developing Creative Solutions",
    "4.A.2.a.2.I05": "Designing Systems/Products",
    "4.A.2.a.3.I01": "Updating and Using Relevant Knowledge",
    "4.A.2.a.4.I01": "Developing Objectives and Strategies",
    "4.A.2.a.4.I02": "Scheduling Work and Activities",
    "4.A.2.a.4.I03": "Organizing, Planning, and Prioritizing Work",
    "4.A.2.a.4.I04": "Planning Events/Programs",
    "4.A.2.a.4.I05": "Budgeting",
    "4.A.2.a.4.I06": "Developing Plans/Procedures",
    "4.A.2.a.4.I07": "Determining Deadlines",
    "4.A.2.a.4.I08": "Creating Schedules",
    "4.A.2.a.4.I09": "Coordinating Plans",
    "4.A.2.b.1.I01": "Processing Information",
    "4.A.2.b.1.I02": "Computing/Calculating",
    "4.A.2.b.1.I03": "Recording Information",
    "4.A.2.b.1.I04": "Categorizing Information",
    "4.A.2.b.1.I05": "Tabulating Data",
    "4.A.2.b.1.I06": "Summarizing Information",
    "4.A.2.b.1.I07": "Processing Transactions",
    "4.A.2.b.2.I01": "Interacting With Computers",
    "4.A.2.b.2.I02": "Entering Data",
    "4.A.2.b.2.I03": "Using Software Applications",
    "4.A.2.b.2.I04": "Programming/Configuring Systems",
    "4.A.2.b.2.I05": "Managing Databases/Files",
    "4.A.2.b.2.I06": "Web Development/Management",
    "4.A.2.b.2.I07": "Using Digital Tools",
    "4.A.2.b.2.I08": "Analyzing Digital Data",
    "4.A.2.b.3.I01": "Drafting, Laying Out, and Specifying Technical Devices",
    "4.A.2.b.3.I02": "Designing Technical Systems",
    "4.A.2.b.3.I03": "Creating Technical Drawings/Models",
    "4.A.2.b.4.I01": "Documenting/Recording Information",
    "4.A.2.b.4.I02": "Writing Reports",
    "4.A.2.b.4.I03": "Preparing Correspondence",
    "4.A.2.b.4.I04": "Writing Technical Documentation",
    "4.A.2.b.4.I05": "Preparing Presentations",
    "4.A.2.b.4.I06": "Writing Creative Content",
    "4.A.2.b.4.I07": "Editing Written Content",
    "4.A.2.b.4.I08": "Creating Marketing Materials",
    "4.A.3.a.1.I01": "Performing Administrative Activities",
    "4.A.3.a.1.I02": "Filing/Maintaining Records",
    "4.A.3.a.1.I03": "Processing Paperwork",
    "4.A.3.a.1.I04": "Managing Office Operations",
    "4.A.3.a.2.I01": "Staffing Organizational Units",
    "4.A.3.a.2.I02": "Recruiting/Hiring",
    "4.A.3.a.2.I03": "Training Staff",
    "4.A.3.a.3.I01": "Monitoring and Controlling Resources",
    "4.A.3.a.3.I02": "Managing Budgets/Finances",
    "4.A.3.a.3.I03": "Purchasing/Procurement",
    "4.A.3.a.3.I04": "Managing Inventory",
    "4.A.3.a.4.I01": "Evaluating Information to Determine Compliance",
    "4.A.3.b.1.I01": "Performing for or Working Directly with the Public",
    "4.A.3.b.1.I02": "Presenting Information to Public",
    "4.A.3.b.2.I01": "Coaching and Developing Others",
    "4.A.3.b.2.I02": "Mentoring/Advising",
    "4.A.3.b.4.I01": "Establishing and Maintaining Interpersonal Relationships",
    "4.A.3.b.4.I02": "Building Customer Relationships",
    "4.A.3.b.4.I03": "Networking",
    "4.A.3.b.5.I01": "Communicating with Supervisors, Peers, or Subordinates",
    "4.A.3.b.5.I02": "Written Communication",
    "4.A.3.b.5.I03": "Oral Communication/Presentations",
    "4.A.3.b.5.I04": "Reporting Information",
    "4.A.3.b.5.I05": "Negotiating",
    "4.A.3.b.5.I06": "Providing Consultation and Advice",
    "4.A.3.b.5.I07": "Communicating with Persons Outside Organization",
    "4.A.3.b.5.I08": "Interviewing",
    "4.A.3.b.5.I09": "Persuading/Influencing",
    "4.A.3.b.6.I01": "Thinking Creatively",
    "4.A.3.b.6.I02": "Translating or Interpreting Languages",
    "4.A.3.b.6.I03": "Composing Music/Writing Lyrics",
    "4.A.3.b.6.I04": "Creating Visual Art/Designs",
    "4.A.3.b.6.I05": "Writing Fiction/Non-Fiction",
    "4.A.3.b.6.I06": "Performing Arts",
    "4.A.4.a.1.I01": "Processing Information",
    "4.A.4.a.1.I02": "Analyzing Data/Information",
    "4.A.4.a.1.I03": "Interpreting Data/Results",
    "4.A.4.a.1.I04": "Mathematical Modeling",
    "4.A.4.a.1.I05": "Statistical Analysis",
    "4.A.4.a.2.I01": "Developing Software/Applications",
    "4.A.4.a.2.I02": "Writing Code/Scripts",
    "4.A.4.a.2.I03": "Testing/Debugging Software",
    "4.A.4.a.2.I04": "Configuring Systems/Networks",
    "4.A.4.a.2.I05": "Managing IT Infrastructure",
    "4.A.4.a.2.I06": "Database Administration",
    "4.A.4.a.3.I01": "Scientific Research",
    "4.A.4.a.3.I02": "Lab Work/Experiments",
    "4.A.4.a.3.I03": "Medical/Clinical Research",
    "4.A.4.a.4.I01": "Engineering Design",
    "4.A.4.a.4.I02": "Technical Analysis",
    "4.A.4.a.4.I03": "Quality Control/Assurance",
    "4.A.4.a.5.I01": "Financial Analysis",
    "4.A.4.a.5.I02": "Accounting/Bookkeeping",
    "4.A.4.a.5.I03": "Tax Preparation/Planning",
    "4.A.4.a.6.I01": "Legal Research/Analysis",
    "4.A.4.a.6.I02": "Preparing Legal Documents",
    "4.A.4.a.6.I03": "Compliance Monitoring",
    "4.A.4.a.7.I01": "Medical Diagnosis/Treatment",
    "4.A.4.a.7.I02": "Patient Care",
    "4.A.4.a.7.I03": "Health Assessment",
    "4.A.4.a.8.I01": "Teaching/Instructing",
    "4.A.4.a.8.I02": "Developing Curriculum/Training Materials",
    "4.A.4.a.8.I03": "Tutoring/Academic Support",
    "4.A.4.b.1.I01": "Operating Vehicles, Mechanized Devices, or Equipment",
    "4.A.4.b.2.I01": "Repairing and Maintaining Mechanical Equipment",
    "4.A.4.b.3.I01": "Repairing and Maintaining Electronic Equipment",
    "4.A.4.b.4.I01": "Controlling Machines and Processes",
    "4.A.4.b.5.I01": "Handling and Moving Objects",
    "4.A.4.b.6.I01": "Working with Computers",
    "4.A.4.c.1.I01": "Performing General Physical Activities",
    "4.A.4.c.2.I01": "Construction/Extraction",
    "4.A.4.c.3.I01": "Installing/Maintaining Infrastructure",
}

# ── Country code to name + flag mappings ────────────────────────────────
COUNTRY_NAMES = {
    "SG":"Singapore","IL":"Israel","NL":"Netherlands","CH":"Switzerland",
    "CA":"Canada","AE":"United Arab Emirates","FI":"Finland","NO":"Norway",
    "SE":"Sweden","DK":"Denmark","BE":"Belgium","PT":"Portugal",
    "ES":"Spain","AT":"Austria","CZ":"Czech Republic","DE":"Germany",
    "FR":"France","KZ":"Kazakhstan","IE":"Ireland","AU":"Australia",
    "PL":"Poland","US":"United States","GB":"United Kingdom","TW":"Taiwan",
    "SK":"Slovakia","BG":"Bulgaria","LB":"Lebanon","NZ":"New Zealand",
    "GR":"Greece","MY":"Malaysia","RO":"Romania","HU":"Hungary",
    "IT":"Italy","KR":"South Korea","UA":"Ukraine","RS":"Serbia",
    "CR":"Costa Rica","EC":"Ecuador","KG":"Kyrgyzstan","PH":"Philippines",
    "TN":"Tunisia","SA":"Saudi Arabia","DO":"Dominican Republic",
    "AZ":"Azerbaijan","CL":"Chile","MA":"Morocco","CO":"Colombia",
    "PE":"Peru","BR":"Brazil","VN":"Vietnam","OM":"Oman",
    "UZ":"Uzbekistan","PS":"Palestine","JO":"Jordan","DZ":"Algeria",
    "TR":"Turkey","MX":"Mexico","BO":"Bolivia","TH":"Thailand",
    "AR":"Argentina","SV":"El Salvador","JP":"Japan","LY":"Libya",
    "LK":"Sri Lanka","NI":"Nicaragua","NP":"Nepal","PY":"Paraguay",
    "ID":"Indonesia","EG":"Egypt","HN":"Honduras","IQ":"Iraq",
    "GT":"Guatemala","ZA":"South Africa","KE":"Kenya","KH":"Cambodia",
    "IN":"India","PK":"Pakistan","SN":"Senegal","GH":"Ghana",
    "BD":"Bangladesh","SO":"Somalia","LA":"Laos","HT":"Haiti",
    "TJ":"Tajikistan","MR":"Mauritania","RW":"Rwanda","NG":"Nigeria",
    "CI":"Ivory Coast","AF":"Afghanistan","BJ":"Benin","TG":"Togo",
    "CG":"Republic of the Congo","ZM":"Zambia","MG":"Madagascar",
    "YE":"Yemen","AO":"Angola","TZ":"Tanzania","CM":"Cameroon",
    "MM":"Myanmar","MZ":"Mozambique","LR":"Liberia","PG":"Papua New Guinea",
    "SL":"Sierra Leone","BF":"Burkina Faso","UG":"Uganda","ZW":"Zimbabwe",
    "GN":"Guinea","MW":"Malawi","ET":"Ethiopia","ML":"Mali",
    "SD":"Sudan","CD":"DR Congo","BI":"Burundi","TD":"Chad",
    "NE":"Niger","SS":"South Sudan","TM":"Turkmenistan","CF":"Central African Republic",
    "HK":"Hong Kong",
}
COUNTRY_FLAGS = {
    "SG":"🇸🇬","IL":"🇮🇱","NL":"🇳🇱","CH":"🇨🇭","CA":"🇨🇦","AE":"🇦🇪","FI":"🇫🇮",
    "NO":"🇳🇴","SE":"🇸🇪","DK":"🇩🇰","BE":"🇧🇪","PT":"🇵🇹","ES":"🇪🇸","AT":"🇦🇹",
    "CZ":"🇨🇿","DE":"🇩🇪","FR":"🇫🇷","KZ":"🇰🇿","IE":"🇮🇪","AU":"🇦🇺","PL":"🇵🇱",
    "US":"🇺🇸","GB":"🇬🇧","TW":"🇹🇼","SK":"🇸🇰","BG":"🇧🇬","LB":"🇱🇧","NZ":"🇳🇿",
    "GR":"🇬🇷","MY":"🇲🇾","RO":"🇷🇴","HU":"🇭🇺","IT":"🇮🇹","KR":"🇰🇷","UA":"🇺🇦",
    "RS":"🇷🇸","CR":"🇨🇷","EC":"🇪🇨","KG":"🇰🇬","PH":"🇵🇭","TN":"🇹🇳","SA":"🇸🇦",
    "DO":"🇩🇴","AZ":"🇦🇿","CL":"🇨🇱","MA":"🇲🇦","CO":"🇨🇴","PE":"🇵🇪","BR":"🇧🇷",
    "VN":"🇻🇳","OM":"🇴🇲","UZ":"🇺🇿","PS":"🇵🇸","JO":"🇯🇴","DZ":"🇩🇿","TR":"🇹🇷",
    "MX":"🇲🇽","BO":"🇧🇴","TH":"🇹🇭","AR":"🇦🇷","SV":"🇸🇻","JP":"🇯🇵","LY":"🇱🇾",
    "LK":"🇱🇰","NI":"🇳🇮","NP":"🇳🇵","PY":"🇵🇾","ID":"🇮🇩","EG":"🇪🇬","HN":"🇭🇳",
    "IQ":"🇮🇶","GT":"🇬🇹","ZA":"🇿🇦","KE":"🇰🇪","KH":"🇰🇭","IN":"🇮🇳","PK":"🇵🇰",
    "SN":"🇸🇳","GH":"🇬🇭","BD":"🇧🇩","SO":"🇸🇴","LA":"🇱🇦","HT":"🇭🇹","TJ":"🇹🇯",
    "MR":"🇲🇷","RW":"🇷🇼","NG":"🇳🇬","CI":"🇨🇮","AF":"🇦🇫","BJ":"🇧🇯","TG":"🇹🇬",
    "CG":"🇨🇬","ZM":"🇿🇲","MG":"🇲🇬","YE":"🇾🇪","AO":"🇦🇴","TZ":"🇹🇿","CM":"🇨🇲",
    "MM":"🇲🇲","MZ":"🇲🇿","LR":"🇱🇷","PG":"🇵🇬","SL":"🇸🇱","BF":"🇧🇫","UG":"🇺🇬",
    "ZW":"🇿🇼","GN":"🇬🇳","MW":"🇲🇼","ET":"🇪🇹","ML":"🇲🇱","SD":"🇸🇩","CD":"🇨🇩",
    "BI":"🇧🇮","TD":"🇹🇩","NE":"🇳🇪","SS":"🇸🇸","TM":"🇹🇲","CF":"🇨🇫","HK":"🇭🇰",
}

# ── Lab Cope Leaderboard Data ───────────────────────────────────────────
LAB_LEADERBOARD = [
    {
        "lab": "OpenAI",
        "logo": "&#x1F7E2;",
        "cope_score": 72,
        "cope_band": "HEAVY COPE",
        "cope_class": "cope-heavy",
        "headline": "Published displacement data, framed it as 'adoption'",
        "detail": "Released 21 months of ChatGPT usage data showing 46% of work messages are 'doing' (replacement), mapped 165 O*NET job activities. Called it 'Signals' and framed it as adoption metrics. Never used the word 'displacement'.",
        "data_score": 95,
        "framing_score": 25,
    },
    {
        "lab": "Anthropic",
        "logo": "&#x1F7E0;",
        "cope_score": 58,
        "cope_band": "MODERATE",
        "cope_class": "cope-moderate",
        "headline": "Found 75% programmer exposure, concluded 'no systematic unemployment'",
        "detail": "Published labour market research (March 2026) using Claude usage data. Found computer programmers 75% exposed, customer service reps next. But concluded 'no systematic increase in unemployment' while burying that younger worker hiring has slowed in exposed occupations.",
        "data_score": 85,
        "framing_score": 40,
    },
    {
        "lab": "Google DeepMind",
        "logo": "&#x1F535;",
        "cope_score": 78,
        "cope_band": "HEAVY COPE",
        "cope_class": "cope-heavy",
        "headline": "Claims AI is a 'productivity multiplier', avoids displacement metrics",
        "detail": "Published multiple papers on AI capabilities but consistently frames everything as productivity enhancement. No equivalent of OpenAI Signals or Anthropic labour research. Avoids measuring displacement directly.",
        "data_score": 15,
        "framing_score": 30,
    },
    {
        "lab": "Meta AI",
        "logo": "&#x1F7E3;",
        "cope_score": 82,
        "cope_band": "TERMINAL COPIUM",
        "cope_class": "cope-terminal",
        "headline": "Open-source framing as democratisation while cutting workforce",
        "detail": "Positions Llama releases as 'democratising AI' while simultaneously conducting large-scale layoffs. The open-source narrative serves as displacement deflection: 'we gave everyone the tools' becomes the excuse when jobs vanish.",
        "data_score": 5,
        "framing_score": 20,
    },
]

REPORT_SCANNER_SOURCES = [
    {
        "id": "goldman-sachs",
        "name": "Goldman Sachs",
        "kind": "investment bank research",
        "description": "Macro, labour-market and productivity framing from Goldman Sachs Research.",
        "watch_note": "Useful because Goldman often publishes the hard displacement numbers and then routes the conclusion back through productivity/GDP framing.",
        "urls": [
            "https://www.goldmansachs.com/insights/articles/how-will-ai-affect-the-us-labor-market",
            "https://www.goldmansachs.com/insights/articles/[redacted]",
            "https://www.gspublishing.com/content/research/en/reports/2023/03/27/d64e052b-0f6e-45d7-967b-d7be35fabd16.pdf",
            "https://www.goldmansachs.com/insights/top-of-mind/[redacted]",
        ],
    },
    {
        "id": "mckinsey",
        "name": "McKinsey Global Institute",
        "enabled": False,
        "status_note": "Automated retrieval is paused because the publisher currently blocks both VPS and residential extraction. Links remain available for manual review.",
        "kind": "consultancy research",
        "description": "MGI future-of-work, productivity and reskilling reports.",
        "watch_note": "Prime source for the consultancy pattern: quantify automation, then prescribe reskilling, deployment and advisory transformation.",
        "urls": [
            "https://www.mckinsey.com/mgi/our-research/[redacted]",
            "https://www.mckinsey.com/~/media/mckinsey/mckinsey%20global%20institute/our%20research/agents%20robots%20and%20us%20how%20ai%20reshapes%20work%20and%20skills%20in%20europe/[redacted].pdf",
            "https://www.mckinsey.com/~/media/mckinsey/mckinsey%20global%20institute/our%20research/a%20new%20future%20of%20work%20the%20race%20to%20deploy%20ai%20and%20raise%20skills%20in%20europe%20and%20beyond/[redacted].pdf",
            "https://www.mckinsey.com/~/media/mckinsey/mckinsey%20global%20institute/our%20research/generative%20ai%20and%20the%20future%20of%20work%20in%20america/[redacted].pdf",
        ],
    },
    {
        "id": "accenture",
        "name": "Accenture",
        "kind": "consultancy research",
        "description": "AI transformation and reinvention reports, especially where working hours are quantified.",
        "watch_note": "High-value source because Accenture often names the working-hours exposure while selling the transition as reinvention.",
        "urls": [
            "https://www.accenture.com/content/dam/accenture/final/accenture-com/document-fy26/q3/Generating-Impact-Ireland.pdf",
        ],
    },
    {
        "id": "deloitte",
        "name": "Deloitte",
        "kind": "consultancy research",
        "description": "Future-of-work, generative AI and enterprise adoption research.",
        "watch_note": "Good at the human-centred augmentation frame: tasks are automated, but the text insists jobs are merely redefined.",
        "urls": [
            "https://www.deloitte.com/us/en/what-we-do/capabilities/applied-artificial-intelligence/articles/generative-ai-and-the-future-of-work",
            "https://www.deloitte.com/us/en/what-we-do/capabilities/applied-artificial-intelligence/content/state-of-ai-in-the-enterprise.html",
        ],
    },
    {
        "id": "pwc",
        "name": "PwC",
        "kind": "consultancy research",
        "description": "AI Jobs Barometer and workforce strategy research.",
        "watch_note": "Useful because PwC tracks job ads, wages and productivity, then translates the pressure into workforce strategy.",
        "urls": [
            "https://www.pwc.com/us/en/tech-effect/ai-analytics/ai-jobs-barometer.html",
            "https://www.pwc.com/gx/en/issues/artificial-intelligence/ai-jobs-barometer/2024.html",
        ],
    },
    {
        "id": "bcg",
        "name": "BCG",
        "kind": "consultancy research",
        "description": "GenAI workforce experiments and labour disruption segmentation.",
        "watch_note": "BCG is a good scanner target because it publishes unusually direct productivity experiments while still leaning into reshape-not-replace framing.",
        "urls": [
            "https://web-assets.bcg.com/pdf-src/prod-live/[redacted].pdf",
            "https://web-assets.bcg.com/pdf-src/prod-live/[redacted].pdf",
        ],
    },
]

# ── Data storage ────────────────────────────────────────────────────────
DATA = {}

def load_csv(filename):
    path = DATA_DIR / filename
    if not path.exists():
        logger.warning(f"CSV not found: {path}")
        return []
    with open(path, "r", encoding="utf-8") as f:
        return list(csv.DictReader(f))

def load_all_data():
    DATA["topics"] = load_csv("share_of_messages_by_topic_month.csv")
    DATA["age"] = load_csv("share_of_messages_by_age_group_month.csv")
    DATA["gender"] = load_csv("[redacted].csv")
    DATA["work"] = load_csv("share_of_messages_by_work_related_month.csv")
    DATA["ask_do"] = load_csv("[redacted].csv")
    DATA["work_school"] = load_csv("[redacted].csv")
    DATA["plan_type"] = load_csv("[redacted].csv")
    DATA["countries"] = load_csv("[redacted].csv")
    DATA["onet"] = load_csv("usa_share_of_messages_by_onet_iwa_month.csv")
    DATA["onet_work"] = load_csv("[redacted].csv")
    DATA["states"] = load_csv("[redacted].csv")
    DATA["us_topics"] = load_csv("usa_share_of_messages_by_topic_2025.csv")
    DATA["us_topics_state"] = load_csv("[redacted].csv")
    DATA["gender_topic"] = load_csv("share_of_messages_by_gender_topic_month.csv")
    DATA["age_topic"] = load_csv("[redacted].csv")
    DATA["work_topic"] = load_csv("[redacted].csv")
    DATA["topic_work"] = load_csv("[redacted].csv")
    logger.info("All CSV data loaded successfully")

load_all_data()

# -- Report scoring helpers [redacted]

REPORT_SCORE_TERMS = {
    "displacement": {
        "weight": 9,
        "label": "Displacement evidence",
        "terms": [
            "job disappear", "jobs disappear", "job losses", "workforce shrink", "headcount reduction",
            "layoff", "redundancy", "displacement", "labour displacement", "labor displacement",
            "reduced demand", "hiring slowdown", "entry-level", "junior roles", "work hours",
            "working hours", "hours saved", "automated", "automation", "replace", "replacement",
            "substitute", "tasks performed", "workflow automated", "productivity gains",
        ],
    },
    "euphemism": {
        "weight": 7,
        "label": "Soft framing and euphemism",
        "terms": [
            "reinvention", "transformation", "unlock", "empower", "augment", "augmentation",
            "human-centered", "human centred", "responsible ai", "opportunity", "adoption",
            "productivity opportunity", "future of work", "reskill", "upskill", "new roles",
            "workforce transformation", "ai-ready", "enable workers", "copilot", "collaboration",
        ],
    },
    "institutional": {
        "weight": 5,
        "label": "Institutional self-interest",
        "terms": [
            "consulting", "consultancy", "implementation partner", "transformation partner",
            "enterprise adoption", "client", "customers", "business leaders", "executives",
            "competitive advantage", "operating model", "change management", "ai strategy",
        ],
    },
    "capability": {
        "weight": 5,
        "label": "Capability expansion",
        "terms": [
            "agent", "agents", "autonomous", "reasoning", "coding", "software development",
            "document processing", "customer service", "compliance", "legal", "finance",
            "data analysis", "research", "workflow", "benchmark", "faster", "weeks to days",
            "minutes", "end-to-end",
        ],
    },
    "honest": {
        "weight": -6,
        "label": "Direct acknowledgement",
        "terms": [
            "wage compression", "labour demand", "labor demand", "unemployment", "redistribution",
            "income loss", "social insurance", "policy response", "worker bargaining",
            "job quality", "labour market impact", "labor market impact", "structural unemployment",
        ],
    },
}


def band_for_report_score(score: int) -> tuple[str, str]:
    if score <= 25:
        return "LUCID", "cope-lucid"
    if score <= 40:
        return "PARTIAL", "cope-partial"
    if score <= 60:
        return "MODERATE", "cope-moderate"
    if score <= 79:
        return "HIGH COPE", "cope-heavy"
    return "TERMINAL COPIUM", "cope-terminal"


def public_host_allowed(host: str) -> bool:
    cleaned = (host or "").strip().strip("[]").lower()
    if not cleaned or cleaned in {"localhost", "0.0.0.0"} or cleaned.endswith(".local"):
        return False
    try:
        addresses = [ipaddress.ip_address(cleaned)]
    except ValueError:
        try:
            infos = socket.getaddrinfo(cleaned, None, type=socket.SOCK_STREAM)
            addresses = [ipaddress.ip_address(info[4][0]) for info in infos]
        except OSError:
            return False
    return bool(addresses) and all(address.is_global for address in addresses)


def normalise_report_url(raw_url: str) -> str:
    value = (raw_url or "").strip()
    if not value:
        raise ValueError("Enter a report URL or upload a PDF.")
    if not re.match(r"^https?://", value, flags=re.I):
        value = f"https://{value}"
    parsed = urlparse(value)
    if parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname:
        raise ValueError("Only public http/https report URLs can be scored.")
    host = parsed.hostname.encode("idna").decode("ascii")
    if not public_host_allowed(host):
        raise ValueError("That report URL resolves to a private or non-public address.")
    return parsed._replace(scheme=parsed.scheme.lower(), netloc=host if parsed.port is None else f"{host}:{parsed.port}", fragment="").geturl()


def canonical_report_url(raw_url: str) -> str:
    """Return a stable identity URL without fragments or tracking parameters."""
    value = (raw_url or "").strip()
    if not value:
        return ""
    if not re.match(r"^https?://", value, flags=re.I):
        value = f"https://{value}"
    parsed = urlparse(value)
    host = (parsed.hostname or "").lower().rstrip(".")
    if host.startswith("www."):
        host = host[4:]
    if not host:
        return ""
    port = parsed.port
    netloc = host if port in (None, 80, 443) else f"{host}:{port}"
    path = re.sub(r"/{2,}", "/", parsed.path or "/")
    if path != "/":
        path = path.rstrip("/")
    query = []
    for key, value in parse_qsl(parsed.query, keep_blank_values=True):
        lowered = key.lower()
        # Only discard unambiguous analytics parameters.  Generic names such
        # as ``source``, ``ref`` or ``campaign`` can identify the underlying
        # document, so removing them could make the migration merge two
        # genuinely different reports.
        if lowered.startswith("utm_") or lowered in TRACKING_QUERY_PARAMS:
            continue
        query.append((key, value))
    return parsed._replace(
        scheme="https", netloc=netloc, path=path,
        query=urlencode(sorted(query)), fragment="",
    ).geturl()


def report_source_key(source_url: str, title: str = "", text: str = "") -> str:
    canonical = canonical_report_url(source_url)
    if canonical:
        identity = f"url|{canonical}"
    else:
        identity = f"content|{title.strip().lower()}|{text[:3000]}"
    return hashlib.sha1(identity.encode("utf-8")).hexdigest()


def fetch_report_via_gateway(url: str, timeout: int) -> tuple[bytes, str, str]:
    """Use the private article gateway when a publisher blocks the VPS."""
    payload = json.dumps({"url": url, "formats": ["markdown"]}).encode("utf-8")
    req = Request(
        f"{ARTICLE_GATEWAY_URL}/v1/scrape",
        data=payload,
        headers={"Content-Type": "application/json", "Accept": "application/json"},
        method="POST",
    )
    with urlopen(req, timeout=timeout) as response:
        data = json.loads(response.read(MAX_REPORT_BYTES + 1).decode("utf-8"))
    markdown = data.get("data", {}).get("markdown", "") if data.get("success") else ""
    if not markdown.strip():
        raise ValueError("The article gateway returned no report text.")
    metadata = data.get("data", {}).get("metadata", {}) or {}
    final_url = metadata.get("sourceURL") or metadata.get("url") or url
    parsed_final = urlparse(final_url)
    if not parsed_final.hostname or not public_host_allowed(parsed_final.hostname):
        raise ValueError("The article gateway resolved to a private or non-public address.")
    return markdown.encode("utf-8"), final_url, "text/plain; charset=utf-8"


def fetch_report_url(raw_url: str, timeout: int = 24, allow_gateway: bool = False) -> tuple[bytes, str, str]:
    url = normalise_report_url(raw_url)
    user_agents = (
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/124.0 Safari/537.36 CopeCheckLabsReportScorer/1.0",
        "CopeCheckLabs/1.0 (+https://labs.copecheck.com)",
    )
    direct_exc = None
    for user_agent in user_agents:
        req = Request(
            url,
            headers={
                "User-Agent": user_agent,
                "Accept": "application/pdf,text/html,text/plain,*/*;q=0.7",
                "Accept-Language": "en-GB,en;q=0.9",
            },
        )
        try:
            with urlopen(req, timeout=timeout) as response:
                final_url = response.geturl()
                parsed_final = urlparse(final_url)
                if not parsed_final.hostname or not public_host_allowed(parsed_final.hostname):
                    raise ValueError("The report URL redirected to a private or non-public address.")
                content_type = response.headers.get("Content-Type", "")
                raw = response.read(MAX_REPORT_BYTES + 1)
                if len(raw) > MAX_REPORT_BYTES:
                    raise ValueError("That report is too large for the public scorer. Try a shorter PDF or paste the relevant section.")
                return raw, final_url, content_type
        except (HTTPError, URLError, TimeoutError) as exc:
            direct_exc = exc
            if not isinstance(exc, HTTPError) or exc.code not in {401, 403}:
                break

    # The article gateway is a private crawler and is reserved for the fixed,
    # operator-curated scanner allowlist.  Sending arbitrary public form input
    # to it would expand the gateway's SSRF surface.
    if not allow_gateway:
        if isinstance(direct_exc, HTTPError):
            raise ValueError(f"Report fetch returned HTTP {direct_exc.code}.") from direct_exc
        if isinstance(direct_exc, URLError):
            raise ValueError(f"Could not fetch that report URL: {direct_exc.reason}") from direct_exc
        raise ValueError(f"Could not fetch that report URL: {type(direct_exc).__name__}.") from direct_exc

    logger.info("Direct report fetch failed for %s (%s); trying article gateway", url, type(direct_exc).__name__)
    try:
        return fetch_report_via_gateway(url, timeout)
    except Exception as gateway_exc:
        if isinstance(direct_exc, HTTPError):
            detail = f"HTTP {direct_exc.code}"
        else:
            detail = type(direct_exc).__name__
        raise ValueError(
            f"Could not fetch that report ({detail}; article gateway: {type(gateway_exc).__name__})."
        ) from gateway_exc


def extract_pdf_text(raw: bytes) -> str:
    with tempfile.TemporaryDirectory(prefix="cope-labs-pdf-") as tmp:
        pdf_path = Path(tmp) / "report.pdf"
        txt_path = Path(tmp) / "report.txt"
        pdf_path.write_bytes(raw)
        try:
            subprocess.run(
                ["pdftotext", "-layout", "-enc", "UTF-8", str(pdf_path), str(txt_path)],
                check=True,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                timeout=35,
            )
        except Exception as exc:
            raise ValueError("PDF text extraction failed. This may be a scanned PDF; paste the relevant text instead.") from exc
        text = txt_path.read_text(encoding="utf-8", errors="ignore")
        return clean_report_text(text)


def html_to_text(raw: bytes) -> str:
    text = raw.decode("utf-8", errors="ignore")
    text = re.sub(r"(?is)<(script|style|noscript).*?</\1>", " ", text)
    text = re.sub(r"(?is)<br\s*/?>", "\n", text)
    text = re.sub(r"(?is)</(p|div|section|article|li|h[1-6]|tr)>", "\n", text)
    text = re.sub(r"(?is)<[^>]+>", " ", text)
    return clean_report_text(html.unescape(text))


def clean_report_text(text: str) -> str:
    # PDF extractors can emit C0 control characters inside headings.  Keep
    # line breaks and tabs, but remove characters that corrupt JSON/HTML titles.
    text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", " ", text or "")
    text = re.sub(r"(\w)-\s*\n\s*(\w)", r"\1\2", text)
    text = text.replace("\u2010", "-").replace("\u2011", "-").replace("\u2012", "-").replace("\u2013", "-").replace("\u2014", "-")
    text = re.sub(r"[ \t]+", " ", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()[:MAX_REPORT_CHARS]


def normalise_for_matching(text: str) -> str:
    text = html.unescape(text or "").lower()
    text = text.replace("\u2010", "-").replace("\u2011", "-").replace("\u2012", "-").replace("\u2013", "-").replace("\u2014", "-")
    text = re.sub(r"(\w)-\s+(\w)", r"\1\2", text)
    text = re.sub(r"\s+", " ", text)
    return text


def report_title_from_text(text: str, fallback: str = "Submitted report") -> str:
    lines = [
        clean for raw in text.splitlines()[:30]
        if (clean := re.sub(r"\s+", " ", raw).strip())
    ]
    generic = {
        "artificial intelligence", "generative artificial intelligence",
        "research", "report", "insights", "executive summary",
    }
    for index, line in enumerate(lines):
        lowered = line.lower()
        if lowered in generic or lowered.startswith(("http", "page ", "copyright", "©", "by ")):
            continue
        if not 18 <= len(line) <= 140:
            continue
        # PDF cover titles are frequently wrapped across two lines.
        if index + 1 < len(lines):
            following = lines[index + 1]
            follow_lower = following.lower()
            if (
                5 <= len(following) <= 80
                and follow_lower not in generic
                and not follow_lower.startswith(("by ", "http", "page ", "©"))
                and not re.match(r"^(article|report)\b", follow_lower)
                and len(f"{line} {following}") <= 140
                and not line.endswith((".", "?", "!", ":"))
            ):
                return f"{line} {following}"
        return line
    return fallback


def extract_report_input() -> tuple[dict, str]:
    report_url = (request.form.get("report_url") or "").strip()
    report_text = clean_report_text(request.form.get("report_text") or "")
    upload = request.files.get("report_pdf")

    if upload and upload.filename:
        raw = upload.read(MAX_REPORT_BYTES + 1)
        if len(raw) > MAX_REPORT_BYTES:
            raise ValueError("PDF is too large for the public scorer.")
        if not raw.startswith(b"%PDF"):
            raise ValueError("Upload a real PDF file, or paste report text instead.")
        text = extract_pdf_text(raw)
        title = report_title_from_text(text, Path(upload.filename).stem.replace("-", " ").replace("_", " ").title())
        return {
            "input_type": "pdf_upload",
            "source_url": "",
            "title": title,
            "filename": upload.filename,
            "content_type": upload.mimetype or "application/pdf",
            "bytes": len(raw),
        }, text

    if report_url:
        raw, final_url, content_type = fetch_report_url(report_url)
        is_pdf = "pdf" in content_type.lower() or raw.startswith(b"%PDF") or final_url.lower().split("?", 1)[0].endswith(".pdf")
        text = extract_pdf_text(raw) if is_pdf else html_to_text(raw)
        title = report_title_from_text(text, urlparse(final_url).netloc)
        return {
            "input_type": "url_pdf" if is_pdf else "url_html",
            "source_url": final_url,
            "title": title,
            "filename": "",
            "content_type": content_type,
            "bytes": len(raw),
        }, text

    if report_text:
        return {
            "input_type": "pasted_text",
            "source_url": "",
            "title": report_title_from_text(report_text),
            "filename": "",
            "content_type": "text/plain",
            "bytes": len(report_text.encode("utf-8")),
        }, report_text

    raise ValueError("Upload a PDF, paste report text, or submit a report URL.")


def keyword_hit_counts(text_lower: str, terms: list[str]) -> dict[str, int]:
    hits = {}
    for term in terms:
        term_lower = term.lower()
        pattern = re.escape(term_lower).replace(r"\ ", r"\s+")
        if re.match(r"^[a-z0-9\s-]+$", term_lower):
            pattern = rf"(?<!\w){pattern}(?!\w)"
        count = len(re.findall(pattern, text_lower))
        if count:
            hits[term] = count
    return hits


def keyword_hits(text_lower: str, terms: list[str]) -> list[str]:
    return list(keyword_hit_counts(text_lower, terms).keys())


def extract_report_quotes(text: str, matched_terms: list[str] | None = None) -> list[str]:
    paragraphs = [re.sub(r"\s+", " ", p).strip() for p in re.split(r"\n\s*\n", text)]
    targets = [
        "displacement", "unemployment", "job", "workforce", "reinvention", "transformation",
        "hours", "productivity", "automation", "reskill", "entry-level", "working hours",
        "agent", "agents", "autonomous", "workflow", "operating model", "AI strategy",
        "efficiency", "cost savings", "finance", "legal", "customer service", "research",
    ]
    if matched_terms:
        targets.extend(matched_terms[:24])
    scored = []
    for para in paragraphs:
        if len(para) < 80:
            continue
        lower = para.lower()
        score = sum(1 for term in targets if term in lower)
        if score:
            scored.append((score, para[:420]))
    if len(scored) < 2:
        chunks = re.split(r"(?<=[.!?])\s+", re.sub(r"\s+", " ", text))
        for i, chunk in enumerate(chunks):
            if len(chunk) < 80:
                continue
            window = " ".join(chunks[max(0, i - 1):i + 2])[:420]
            lower = window.lower()
            score = sum(1 for term in targets if term.lower() in lower)
            if score:
                scored.append((score, window))
    scored.sort(key=lambda item: item[0], reverse=True)
    quotes = []
    seen = set()
    for _, quote in scored:
        key = quote[:120]
        if key in seen:
            continue
        seen.add(key)
        quotes.append(quote)
        if len(quotes) >= 4:
            break
    return quotes


def cap_report_score(raw_score: int | float, signal_rows: list[dict]) -> int:
    score = int(round(raw_score))
    displacement = next((row for row in signal_rows if row["key"] == "displacement"), {})
    euphemism = next((row for row in signal_rows if row["key"] == "euphemism"), {})
    institutional = next((row for row in signal_rows if row["key"] == "institutional"), {})
    capability = next((row for row in signal_rows if row["key"] == "capability"), {})
    displacement_count = int(displacement.get("count") or 0)
    soft_framing = int(euphemism.get("count") or 0) + int(institutional.get("count") or 0)
    capability_count = int(capability.get("count") or 0)

    if displacement_count == 0:
        cap = 68 if capability_count >= 5 and soft_framing >= 2 else 55
        score = min(score, cap)
    elif displacement_count <= 1 and capability_count >= 7:
        score = min(score, 78)
    return max(5, min(95, score))


def normalise_loaded_report_result(item: dict) -> dict:
    signals = item.get("signals") or []
    if not signals:
        return item
    current_score = int(item.get("score") or 0)
    adjusted_score = cap_report_score(current_score, signals)
    if adjusted_score == current_score:
        return item
    item = dict(item)
    item["score"] = adjusted_score
    item["band"], item["band_class"] = band_for_report_score(adjusted_score)
    item["verdict"] = build_report_verdict(
        item.get("title", "Report score"),
        adjusted_score,
        item["band"],
        int(item.get("data_transparency") or 0),
        int(item.get("framing_honesty") or 0),
        signals,
    )
    item["share_text"] = (
        f"{item.get('title', 'Report score')} scores {adjusted_score}/100 on the CopeCheck Labs report scanner: "
        f"{item['band']}. {item['verdict']}"
    )[:520]
    return item


def score_report_text(meta: dict, text: str) -> dict:
    if len(text) < 400:
        raise ValueError("The report text is too short to score. Paste more context or upload the full PDF.")
    lower = normalise_for_matching(text)
    signal_rows = []
    raw_score = 28
    positive_signal_total = 0
    honest_hits = []
    all_hits = []

    for key, spec in REPORT_SCORE_TERMS.items():
        hit_counts = keyword_hit_counts(lower, spec["terms"])
        hits = list(hit_counts.keys())
        occurrences = sum(hit_counts.values())
        capped = min(len(hits), 10)
        contribution = capped * spec["weight"]
        if spec["weight"] > 0:
            positive_signal_total += capped
        else:
            honest_hits = hits
        raw_score += contribution
        all_hits.extend(hits)
        signal_rows.append({
            "key": key,
            "label": spec["label"],
            "hits": hits[:10],
            "hit_counts": dict(list(hit_counts.items())[:10]),
            "occurrences": occurrences,
            "count": len(hits),
            "contribution": contribution,
        })

    if positive_signal_total >= 18 and len(honest_hits) <= 2:
        raw_score += 12
    if "productivity" in lower and "displacement" not in lower and "job losses" not in lower:
        raw_score += 8
    if ("reskill" in lower or "upskill" in lower) and ("entry-level" in lower or "job disappear" in lower or "reduced demand" in lower):
        raw_score += 7

    score = cap_report_score(raw_score, signal_rows)
    band, band_class = band_for_report_score(score)
    data_transparency = max(10, min(95, 35 + signal_rows[0]["count"] * 7 + signal_rows[3]["count"] * 4))
    framing_honesty = max(5, min(95, 60 + len(honest_hits) * 6 - signal_rows[1]["count"] * 5 - signal_rows[2]["count"] * 3))
    verdict = build_report_verdict(meta["title"], score, band, data_transparency, framing_honesty, signal_rows)
    source_key = report_source_key(meta.get("source_url", ""), meta.get("title", ""), text)
    report_id = source_key[:12]
    canonical_source_url = canonical_report_url(meta.get("source_url", ""))
    source_label = meta.get("source_url") or meta.get("filename") or "pasted text"
    share_url = f"https://labs.copecheck.com/report/{report_id}"
    share_text = f"{meta['title']} scores {score}/100 on the CopeCheck Labs report scanner: {band}. {verdict}"

    return {
        "id": report_id,
        "source_key": source_key,
        "canonical_source_url": canonical_source_url,
        "submitted_at": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
        "title": meta["title"],
        "source_url": meta.get("source_url", ""),
        "source_label": source_label,
        "input_type": meta.get("input_type", ""),
        "content_type": meta.get("content_type", ""),
        "word_count": len(re.findall(r"\w+", text)),
        "score": score,
        "band": band,
        "band_class": band_class,
        "data_transparency": data_transparency,
        "framing_honesty": framing_honesty,
        "verdict": verdict,
        "signals": signal_rows,
        "quotes": extract_report_quotes(text, all_hits),
        "share_url": share_url,
        "share_text": share_text[:520],
    }


def build_report_verdict(title: str, score: int, band: str, data_transparency: int, framing_honesty: int, signal_rows: list[dict]) -> str:
    displacement = next((row for row in signal_rows if row["key"] == "displacement"), {}).get("count", 0)
    euphemism = next((row for row in signal_rows if row["key"] == "euphemism"), {}).get("count", 0)
    capability = next((row for row in signal_rows if row["key"] == "capability"), {}).get("count", 0)
    institutional = next((row for row in signal_rows if row["key"] == "institutional"), {}).get("count", 0)
    if displacement == 0 and capability >= 5:
        return (
            f"This is strong capability evidence, but not direct labour-market evidence. "
            f"CopeCheck found {capability} capability signals and {euphemism + institutional} framing or institutional signals, "
            f"so the score is capped below terminal until the report actually names jobs, hiring, wages, or displacement."
        )
    if score >= 80:
        return (
            f"The report contains strong displacement or capability evidence, but wraps it in soft transformation language. "
            f"Data transparency is {data_transparency}/100 while framing honesty is only {framing_honesty}/100: classic institutional cope."
        )
    if score >= 61:
        return (
            f"The report is useful evidence, but it keeps translating labour-market risk into productivity or adoption language. "
            f"CopeCheck found {displacement} displacement signals, {capability} capability signals, and {euphemism} euphemism signals."
        )
    if score >= 41:
        return (
            f"The report shows some real AI labour-market pressure, but the framing is mixed rather than fully evasive. "
            f"It deserves review, especially where productivity claims are not tied to headcount, hiring, or wage effects."
        )
    return (
        f"The report is relatively direct by CopeCheck standards. It either contains fewer displacement signals or acknowledges the labour-market problem more plainly than most AI reports."
    )


def _load_report_results() -> list[dict]:
    if not REPORT_SUBMISSIONS_PATH.exists():
        return []
    items = []
    with REPORT_SUBMISSIONS_PATH.open("r", encoding="utf-8") as f:
        for line in f:
            try:
                item = json.loads(line)
            except json.JSONDecodeError:
                logger.warning("Skipping malformed report-submissions JSONL row")
                continue
            if isinstance(item, dict):
                items.append(item)
    return items


def _report_item_key(item: dict) -> str:
    key = (item.get("source_key") or "").strip()
    if key:
        return key
    canonical = canonical_report_url(item.get("source_url", ""))
    if canonical:
        return report_source_key(canonical)
    return f"id|{item.get('id', '')}"


def save_report_result(result: dict) -> dict:
    """Atomically upsert one result by canonical source, preserving legacy links."""
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    incoming = dict(result)
    incoming_key = _report_item_key(incoming)
    incoming["source_key"] = incoming_key if not incoming_key.startswith("id|") else incoming.get("source_key", "")
    with REPORT_SUBMISSIONS_LOCK_PATH.open("a+", encoding="utf-8") as lock_file:
        fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
        items = _load_report_results()
        kept = []
        legacy_ids = set(incoming.get("legacy_ids") or [])
        for item in items:
            if _report_item_key(item) == incoming_key:
                if item.get("id") and item.get("id") != incoming.get("id"):
                    legacy_ids.add(item["id"])
                legacy_ids.update(item.get("legacy_ids") or [])
                continue
            kept.append(item)
        legacy_ids.discard(incoming.get("id"))
        if legacy_ids:
            incoming["legacy_ids"] = sorted(legacy_ids)
        elif "legacy_ids" in incoming:
            incoming.pop("legacy_ids")
        kept.append(incoming)

        fd, tmp_name = tempfile.mkstemp(prefix="report-submissions-", suffix=".jsonl", dir=DATA_DIR)
        try:
            with os.fdopen(fd, "w", encoding="utf-8") as tmp:
                for item in kept:
                    tmp.write(json.dumps(item, ensure_ascii=False) + "\n")
                tmp.flush()
                os.fsync(tmp.fileno())
            os.replace(tmp_name, REPORT_SUBMISSIONS_PATH)
        finally:
            if os.path.exists(tmp_name):
                os.unlink(tmp_name)
    return incoming


def load_report_result(report_id: str) -> dict | None:
    for item in _load_report_results():
        if item.get("id") == report_id or report_id in (item.get("legacy_ids") or []):
            return normalise_loaded_report_result(item)
    return None


def extract_report_from_url(report_url: str, input_prefix: str = "url", timeout: int = 24) -> tuple[dict, str]:
    # This helper is used only by the fixed REPORT_SCANNER_SOURCES allowlist.
    raw, final_url, content_type = fetch_report_url(report_url, timeout=timeout, allow_gateway=True)
    is_pdf = "pdf" in content_type.lower() or raw.startswith(b"%PDF") or final_url.lower().split("?", 1)[0].endswith(".pdf")
    text = extract_pdf_text(raw) if is_pdf else html_to_text(raw)
    title = report_title_from_text(text, urlparse(final_url).netloc)
    return {
        "input_type": f"{input_prefix}_pdf" if is_pdf else f"{input_prefix}_html",
        "source_url": final_url,
        "title": title,
        "filename": "",
        "content_type": content_type,
        "bytes": len(raw),
    }, text


def scanner_source_by_id(source_id: str) -> dict | None:
    cleaned = (source_id or "").strip().lower()
    return next((source for source in REPORT_SCANNER_SOURCES if source["id"] == cleaned), None)


def public_scanner_source(source: dict) -> dict:
    return {
        "id": source["id"],
        "name": source["name"],
        "kind": source["kind"],
        "description": source["description"],
        "watch_note": source["watch_note"],
        "urls": source["urls"],
        "enabled": source.get("enabled", True),
        "status_note": source.get("status_note", ""),
    }


def score_scanner_source(source_id: str, limit: int = 3) -> dict:
    source = scanner_source_by_id(source_id)
    if not source:
        raise ValueError("Unknown report scanner source.")

    if not source.get("enabled", True):
        return {
            "source": public_scanner_source(source),
            "scanned_at": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
            "status": "paused",
            "limit": 0,
            "attempted": 0,
            "results": [],
            "errors": [],
        }

    try:
        scan_limit = int(limit)
    except (TypeError, ValueError):
        scan_limit = 3
    scan_limit = max(1, min(scan_limit, 4))
    scanned_at = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
    results = []
    errors = []

    for url in source["urls"]:
        if len(results) >= scan_limit:
            break
        try:
            meta, text = extract_report_from_url(url, "scanner", timeout=16)
            result = score_report_text(meta, text)
            result["scanner_source_id"] = source["id"]
            result["scanner_source_name"] = source["name"]
            result["scanner_source_kind"] = source["kind"]
            result["scanner_scanned_at"] = scanned_at
            save_report_result(result)
            results.append({
                "id": result["id"],
                "title": result["title"],
                "score": result["score"],
                "band": result["band"],
                "band_class": result["band_class"],
                "verdict": result["verdict"],
                "word_count": result["word_count"],
                "source_url": result["source_url"],
                "source_label": result["source_label"],
                "share_url": result["share_url"],
                "share_text": result["share_text"],
            })
        except Exception as exc:
            logger.warning("Report scanner failed for %s: %s", url, exc)
            errors.append({"url": url, "error": str(exc)})

    status = "ok" if not errors else ("partial" if results else "failed")
    return {
        "source": public_scanner_source(source),
        "scanned_at": scanned_at,
        "status": status,
        "limit": scan_limit,
        "attempted": len(results) + len(errors),
        "results": results,
        "errors": errors,
    }


def score_all_report_scanner_sources(limit_per_source: int = 2) -> list[dict]:
    scans = []
    for source in REPORT_SCANNER_SOURCES:
        scans.append(score_scanner_source(source["id"], limit_per_source))
    return scans


# ── API Endpoints ───────────────────────────────────────────────────────


@app.route('/api/subscribe', methods=['POST'])
def subscribe():
    data = request.get_json(silent=True) or {}
    email = (data.get('email') or '').strip().lower()
    if not email or '@' not in email:
        return jsonify({'success': False, 'message': 'Please enter a valid email.'}), 400
[redacted secret-like line]
[redacted secret-like line]
        return jsonify({'success': False, 'message': 'Service unavailable.'}), 503
    try:
        subscription = Request(
            'https://api.resend.com/audiences/e0c71613-ce4e-4e25-a920-515dfe0a90ff/contacts',
[redacted secret-like line]
            data=json.dumps({'email': email, 'unsubscribed': False}).encode('utf-8'),
            method='POST'
        )
        with urlopen(subscription, timeout=8) as response:
            if response.status in (200, 201):
                return jsonify({'success': True, 'message': "You're subscribed!"})
        return jsonify({'success': False, 'message': 'Subscription failed. Try again.'}), 500
    except Exception:
        return jsonify({'success': False, 'message': 'Connection error.'}), 500

@app.route("/api/topics")
def api_topics():
    return jsonify(DATA.get("topics", []))

@app.route("/api/age")
def api_age():
    return jsonify(DATA.get("age", []))

@app.route("/api/gender")
def api_gender():
    return jsonify(DATA.get("gender", []))

@app.route("/api/work")
def api_work():
    return jsonify(DATA.get("work", []))

@app.route("/api/ask-do-express")
def api_ask_do():
    return jsonify(DATA.get("ask_do", []))

@app.route("/api/work-school")
def api_work_school():
    return jsonify(DATA.get("work_school", []))

@app.route("/api/plan-type")
def api_plan_type():
    return jsonify(DATA.get("plan_type", []))

@app.route("/api/countries")
def api_countries():
    rows = DATA.get("countries", [])
    enriched = []
    for r in rows:
        cc = r.get("country", "")
        enriched.append({**r, "country_name": COUNTRY_NAMES.get(cc, cc), "flag": COUNTRY_FLAGS.get(cc, "")})
    return jsonify(enriched)

@app.route("/api/onet-top")
def api_onet_top():
    totals = defaultdict(lambda: {"sum": 0.0, "count": 0})
    rows = DATA.get("onet_work", []) or DATA.get("onet", [])
    for r in rows:
        code = r.get("iwa_cleaned", "")
        share = float(r.get("share_of_messages", 0))
        totals[code]["sum"] += share
        totals[code]["count"] += 1
    averaged = []
    for code, v in totals.items():
        avg = v["sum"] / v["count"] if v["count"] > 0 else 0
        averaged.append({"code": code, "name": IWA_NAMES.get(code, code), "avg_share": round(avg, 5)})
    averaged.sort(key=lambda x: x["avg_share"], reverse=True)
    return jsonify(averaged[:40])

@app.route("/api/onet-timeseries")
def api_onet_timeseries():
    rows = DATA.get("onet_work", []) or DATA.get("onet", [])
    latest = defaultdict(float)
    for r in rows:
        latest[r.get("iwa_cleaned", "")] = float(r.get("share_of_messages", 0))
    top_codes = sorted(latest.keys(), key=lambda c: latest[c], reverse=True)[:10]
    result = [r for r in rows if r.get("iwa_cleaned") in top_codes]
    enriched = [{"month": r["month"], "code": r["iwa_cleaned"],
                 "name": IWA_NAMES.get(r["iwa_cleaned"], r["iwa_cleaned"]),
                 "share": float(r["share_of_messages"])} for r in result]
    return jsonify(enriched)

@app.route("/api/states")
def api_states():
    return jsonify(DATA.get("states", []))

@app.route("/api/us-topics-state")
def api_us_topics_state():
    return jsonify(DATA.get("us_topics_state", []))

@app.route("/api/leaderboard")
def api_leaderboard():
    return jsonify(LAB_LEADERBOARD)


@app.route("/api/report-score", methods=["POST"])
def api_report_score():
    try:
        meta, text = extract_report_input()
        result = score_report_text(meta, text)
        save_report_result(result)
        return jsonify({"ok": True, "result": result})
    except ValueError as exc:
        return jsonify({"ok": False, "error": str(exc)}), 400
    except Exception as exc:
        logger.exception("Report scoring failed")
        return jsonify({"ok": False, "error": f"Report scoring failed: {type(exc).__name__}"}), 500


@app.route("/api/report-scanners")
def api_report_scanners():
    return jsonify({"sources": [public_scanner_source(source) for source in REPORT_SCANNER_SOURCES]})


@app.route("/api/report-scanners/run", methods=["POST"])
def api_report_scanners_run():
    payload = request.get_json(silent=True) or request.form
    source_id = (payload.get("source_id") or "").strip()
    limit = payload.get("limit") or 3
    try:
        scan = score_scanner_source(source_id, limit)
        return jsonify({"ok": True, "scan": scan})
    except ValueError as exc:
        return jsonify({"ok": False, "error": str(exc)}), 400
    except Exception as exc:
        logger.exception("Report scanner failed")
        return jsonify({"ok": False, "error": f"Report scanner failed: {type(exc).__name__}"}), 500


# ── Shared HTML ─────────────────────────────────────────────────────────
UMAMI_ID = "720eab71-4c69-46cc-bb7a-654c78fc7d0b"
NETWORK_LINKS = [
    ("CopeCheck","https://copecheck.com"),("UK","https://uk.copecheck.com"),
    ("Countries","https://countries.copecheck.com"),("EU","https://eu.copecheck.com"),
    ("Policy","https://policy.copecheck.com"),("Cities","https://cities.copecheck.com"),
    ("Layoffs","https://layoffs.copecheck.com"),("Thesis","https://thesis.copecheck.com"),
    ("Quiz","https://quiz.copecheck.com"),
]

CSS = """
:root{--bg-primary:#0a0e1a;--bg-secondary:#111827;--bg-card:#1a2035;--bg-card-hover:#1f2847;
--text-primary:#e2e8f0;--text-secondary:#94a3b8;--text-muted:#64748b;
--accent-cyan:#06b6d4;--accent-teal:#14b8a6;--accent-blue:#3b82f6;--border-color:#1e293b;
--cope-lucid:#22c55e;--cope-partial:#84cc16;--cope-moderate:#eab308;--cope-heavy:#f97316;--cope-terminal:#ef4444;
--chart-1:#06b6d4;--chart-2:#8b5cf6;--chart-3:#f59e0b;--chart-4:#ef4444;--chart-5:#22c55e;--chart-6:#ec4899;--chart-7:#3b82f6;}
*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:var(--bg-primary);color:var(--text-primary);line-height:1.6;min-height:100vh;}
a{color:var(--accent-cyan);text-decoration:none;transition:color .2s;}a:hover{color:var(--accent-teal);}
.navbar{background:rgba(10,14,26,.95);backdrop-filter:blur(10px);border-bottom:1px solid var(--border-color);padding:0 2rem;position:sticky;top:0;z-index:100;display:flex;align-items:center;justify-content:space-between;height:64px;}
.nav-brand{font-weight:700;font-size:1.1rem;color:var(--accent-cyan);display:flex;align-items:center;gap:.5rem;}
.nav-brand span{color:var(--text-muted);font-weight:400;font-size:.85rem;}
.nav-links{display:flex;gap:1.5rem;align-items:center;}
.nav-links a{color:var(--text-secondary);font-size:.9rem;font-weight:500;padding:.4rem 0;border-bottom:2px solid transparent;transition:all .2s;}
.nav-links a:hover,.nav-links a.active{color:var(--accent-cyan);border-bottom-color:var(--accent-cyan);}
.hamburger{display:none;cursor:pointer;font-size:1.5rem;color:var(--text-primary);background:none;border:none;}
.container{max-width:1200px;margin:0 auto;padding:2rem;}
.hero{text-align:center;padding:4rem 2rem;background:linear-gradient(135deg,var(--bg-primary) 0%,#0f172a 50%,var(--bg-secondary) 100%);border-bottom:1px solid var(--border-color);}
.hero h1{font-size:2.5rem;font-weight:800;background:linear-gradient(135deg,var(--accent-cyan),var(--accent-teal));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;margin-bottom:1rem;line-height:1.2;}
.hero .subtitle{font-size:1.15rem;color:var(--text-secondary);max-width:750px;margin:0 auto 2rem;}
.hero .meta-line{font-size:.85rem;color:var(--text-muted);}
.stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:1.5rem;margin:2rem auto;}
.stat-card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;padding:1.5rem;text-align:center;transition:transform .2s,border-color .2s;}
.stat-card:hover{transform:translateY(-2px);border-color:var(--accent-cyan);}
.stat-card .value{font-size:2.2rem;font-weight:800;color:var(--accent-cyan);line-height:1;margin-bottom:.5rem;}
.stat-card .label{font-size:.85rem;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.05em;}
.stat-card .sub{font-size:.78rem;color:var(--text-muted);margin-top:.3rem;}
.chart-section{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;padding:1.5rem;margin:2rem auto;}
.chart-section h2{font-size:1.3rem;margin-bottom:.5rem;color:var(--text-primary);}
.chart-section .chart-desc{font-size:.9rem;color:var(--text-secondary);margin-bottom:1rem;}
.chart-wrap{position:relative;height:400px;}
.cope-callout{background:rgba(6,182,212,.08);border-left:4px solid var(--accent-cyan);border-radius:0 8px 8px 0;padding:1rem 1.25rem;margin:1rem 0;}
.cope-callout .callout-title{font-weight:700;color:var(--accent-cyan);font-size:.85rem;text-transform:uppercase;letter-spacing:.05em;margin-bottom:.4rem;}
.cope-callout p{font-size:.9rem;color:var(--text-secondary);}
.data-table{width:100%;border-collapse:collapse;margin:1rem 0;}
.data-table th{background:var(--bg-secondary);color:var(--text-secondary);font-size:.8rem;text-transform:uppercase;letter-spacing:.05em;padding:.75rem 1rem;text-align:left;border-bottom:2px solid var(--border-color);position:sticky;top:64px;}
.data-table td{padding:.6rem 1rem;border-bottom:1px solid var(--border-color);font-size:.9rem;}
.data-table tr:hover td{background:var(--bg-card-hover);}
.rank-badge{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:50%;font-weight:700;font-size:.8rem;}
.rank-1{background:#fbbf24;color:#000;}.rank-2{background:#94a3b8;color:#000;}.rank-3{background:#cd7f32;color:#fff;}.rank-other{background:var(--bg-secondary);color:var(--text-secondary);}
.page-header{padding:3rem 0 1.5rem;border-bottom:1px solid var(--border-color);margin-bottom:2rem;}
.page-header h1{font-size:2rem;font-weight:800;color:var(--text-primary);margin-bottom:.5rem;}
.page-header p{color:var(--text-secondary);max-width:700px;}
.cope-badge{display:inline-block;padding:.15rem .6rem;border-radius:4px;font-weight:700;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;}
.cope-lucid{background:rgba(34,197,94,.15);color:var(--cope-lucid);}
.cope-partial{background:rgba(132,204,22,.15);color:var(--cope-partial);}
.cope-moderate{background:rgba(234,179,8,.15);color:var(--cope-moderate);}
.cope-heavy{background:rgba(249,115,22,.15);color:var(--cope-heavy);}
.cope-terminal{background:rgba(239,68,68,.15);color:var(--cope-terminal);}
.bar-inline{display:flex;align-items:center;gap:.5rem;}
.bar-fill{height:22px;border-radius:4px;background:linear-gradient(90deg,var(--accent-cyan),var(--accent-teal));min-width:3px;transition:width .5s ease;}
.bar-label{font-size:.8rem;color:var(--text-muted);white-space:nowrap;}
.site-footer{background:var(--bg-secondary);border-top:1px solid var(--border-color);padding:2rem;text-align:center;margin-top:3rem;}
.footer-network{display:flex;flex-wrap:wrap;gap:1rem;justify-content:center;margin-bottom:1rem;}
.footer-network a{color:var(--text-muted);font-size:.85rem;padding:.3rem .6rem;border:1px solid var(--border-color);border-radius:6px;transition:all .2s;}
.footer-network a:hover{border-color:var(--accent-cyan);color:var(--accent-cyan);}
.footer-attribution{font-size:.75rem;color:var(--text-muted);margin-top:1rem;line-height:1.8;}
.newsletter-section{background:linear-gradient(135deg,rgba(6,182,212,.08),rgba(20,184,166,.08));border:1px solid rgba(6,182,212,.2);border-radius:12px;padding:2rem;text-align:center;margin:2rem auto;}
.newsletter-section h3{color:var(--accent-cyan);margin-bottom:.5rem;}.newsletter-section p{color:var(--text-secondary);font-size:.9rem;margin-bottom:1rem;}
.newsletter-section iframe{border:none;width:100%;max-width:480px;height:52px;}
.section-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:1.5rem;margin:2rem auto;}
.section-card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;padding:1.5rem;transition:all .2s;display:block;color:var(--text-primary);}
.section-card:hover{border-color:var(--accent-cyan);transform:translateY(-2px);color:var(--text-primary);}
.section-card h3{color:var(--accent-cyan);margin-bottom:.5rem;font-size:1.1rem;}.section-card p{color:var(--text-secondary);font-size:.9rem;}
.report-form{display:grid;gap:1rem;margin-top:1rem;}
.report-form label{display:grid;gap:.4rem;color:var(--text-secondary);font-size:.85rem;font-weight:600;}
.report-form input,.report-form textarea{width:100%;border:1px solid var(--border-color);border-radius:8px;background:var(--bg-secondary);color:var(--text-primary);padding:.75rem .9rem;font:inherit;}
.report-form input[type=file]{padding:.65rem;background:rgba(255,255,255,.03);}
.report-form textarea{min-height:140px;resize:vertical;}
.report-form button,.share-action{display:inline-flex;align-items:center;justify-content:center;gap:.35rem;width:max-content;border:1px solid var(--accent-cyan);border-radius:8px;background:var(--accent-cyan);color:var(--bg-primary);padding:.7rem 1rem;font-weight:800;font-size:.9rem;cursor:pointer;text-decoration:none;}
.report-form button:disabled{opacity:.55;cursor:wait;}
.report-grid{display:grid;grid-template-columns:1.1fr .9fr;gap:1rem;align-items:start;}
.report-result{margin-top:1.25rem;border:1px solid var(--border-color);border-radius:12px;background:var(--bg-secondary);padding:1.25rem;}
.report-score-top{display:grid;grid-template-columns:auto 1fr;gap:1rem;align-items:center;}
.report-score-dial{width:86px;height:86px;border-radius:50%;display:grid;place-items:center;background:conic-gradient(var(--accent-cyan) calc(var(--score,0)*1%),var(--bg-card) 0);position:relative;}
.report-score-dial::before{content:"";position:absolute;inset:9px;border-radius:50%;background:var(--bg-secondary);}
.report-score-dial strong{position:relative;font-size:1.7rem;line-height:1;}
.report-kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:.75rem;margin-top:1rem;}
.report-kpis div{border:1px solid var(--border-color);border-radius:8px;padding:.8rem;background:rgba(255,255,255,.03);}
.report-kpis span{display:block;color:var(--text-muted);font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;}
.report-kpis strong{display:block;color:var(--text-primary);font-size:1.2rem;margin-top:.2rem;}
.report-signal-list,.report-quote-list{display:grid;gap:.65rem;margin-top:1rem;}
.report-signal,.report-quote{border-left:3px solid var(--accent-cyan);background:rgba(255,255,255,.035);border-radius:0 8px 8px 0;padding:.75rem .9rem;}
.report-signal strong{display:block;margin-bottom:.25rem;}
.report-signal span,.report-quote{color:var(--text-secondary);font-size:.86rem;}
.report-actions{display:flex;gap:.6rem;flex-wrap:wrap;margin-top:1rem;}
.share-action.secondary{background:transparent;color:var(--accent-cyan);}
.report-error{margin-top:1rem;border-left:3px solid var(--cope-terminal);background:rgba(239,68,68,.1);border-radius:0 8px 8px 0;padding:1rem;color:var(--text-primary);}
.scanner-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:1rem;margin:1.5rem 0;}
.scanner-card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;padding:1.25rem;display:grid;gap:.85rem;}
.scanner-card:hover{border-color:rgba(6,182,212,.55);}
.scanner-card-top{display:flex;align-items:flex-start;justify-content:space-between;gap:.75rem;}
.scanner-card h3{font-size:1.05rem;color:var(--text-primary);}
.scanner-card p{color:var(--text-secondary);font-size:.9rem;}
.scanner-kind{border:1px solid var(--border-color);border-radius:999px;padding:.18rem .55rem;color:var(--text-muted);font-size:.72rem;white-space:nowrap;text-transform:uppercase;letter-spacing:.04em;}
.scanner-url-list{display:grid;gap:.35rem;margin:.25rem 0;padding-left:1.1rem;color:var(--text-muted);font-size:.82rem;}
.scanner-url-list a{color:var(--text-secondary);}
.scanner-controls{display:flex;gap:.65rem;flex-wrap:wrap;align-items:center;}
.scanner-run{display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--accent-cyan);border-radius:8px;background:var(--accent-cyan);color:var(--bg-primary);padding:.65rem .9rem;font-weight:800;font-size:.86rem;cursor:pointer;}
.scanner-run:disabled{opacity:.55;cursor:wait;}
.scanner-status{color:var(--text-muted);font-size:.82rem;}
.scanner-results{display:grid;gap:1rem;margin-top:1.5rem;}
.scanner-error-list{display:grid;gap:.5rem;margin-top:.85rem;}
.scanner-error-list div{border-left:3px solid var(--cope-terminal);background:rgba(239,68,68,.09);border-radius:0 8px 8px 0;padding:.65rem .8rem;color:var(--text-secondary);font-size:.84rem;}
.pagination{display:flex;gap:.5rem;justify-content:center;margin:2rem 0;flex-wrap:wrap;}
.pagination a,.pagination span{padding:.4rem .8rem;border-radius:6px;font-size:.85rem;border:1px solid var(--border-color);}
.pagination a{color:var(--text-secondary);}
.pagination a:hover{border-color:var(--accent-cyan);color:var(--accent-cyan);}
.pagination .current{background:var(--accent-cyan);color:var(--bg-primary);font-weight:700;border-color:var(--accent-cyan);}
/* Leaderboard */
.lb-card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;padding:1.5rem;margin:1rem 0;display:grid;grid-template-columns:auto 1fr auto;gap:1.5rem;align-items:center;}
.lb-card:hover{border-color:var(--accent-cyan);}
.lb-logo{font-size:2.5rem;text-align:center;min-width:60px;}
.lb-info h3{font-size:1.1rem;margin-bottom:.3rem;}.lb-info p{font-size:.85rem;color:var(--text-secondary);}
.lb-score{text-align:center;}
.lb-score .score-num{font-size:2rem;font-weight:800;line-height:1;}
.lb-meter{display:flex;gap:4px;margin-top:.5rem;}
.lb-meter-seg{height:6px;border-radius:3px;flex:1;background:var(--border-color);}
.lb-meter-seg.filled{background:currentColor;}
.lb-sub-scores{display:flex;gap:1rem;margin-top:.5rem;font-size:.75rem;color:var(--text-muted);}
/* Lab tab nav */
.lab-tabs{display:flex;gap:.5rem;margin:2rem 0 1rem;flex-wrap:wrap;}
.lab-tab{padding:.5rem 1.2rem;border-radius:8px;font-weight:600;font-size:.9rem;border:1px solid var(--border-color);color:var(--text-secondary);background:transparent;cursor:pointer;transition:all .2s;}
.lab-tab:hover,.lab-tab.active{background:var(--accent-cyan);color:var(--bg-primary);border-color:var(--accent-cyan);}
/* Dropdown nav */
.nav-dropdown{position:relative;display:flex;align-items:center;}
.nav-dropdown>button{color:var(--text-secondary);font-size:.9rem;font-weight:500;padding:.4rem 0;border-bottom:2px solid transparent;transition:all .2s;background:none;border:none;cursor:pointer;display:flex;align-items:center;gap:.25rem;font-family:inherit;}
.nav-dropdown>button::after{content:'▾';font-size:.7rem;opacity:.7;}
.nav-dropdown:hover>button,.nav-dropdown.active>button{color:var(--accent-cyan);border-bottom-color:var(--accent-cyan);}
.dropdown-menu{display:none;position:absolute;top:calc(100% + 8px);left:0;background:rgba(10,14,26,.98);border:1px solid var(--border-color);border-radius:8px;padding:.5rem 0;min-width:160px;z-index:200;box-shadow:0 8px 32px rgba(0,0,0,.5);}
.nav-dropdown:hover .dropdown-menu{display:block;}
.dropdown-menu a{display:block;padding:.45rem 1rem;color:var(--text-secondary);font-size:.85rem;font-weight:500;white-space:nowrap;border-bottom:none;}
.dropdown-menu a:hover,.dropdown-menu a.active{color:var(--accent-cyan);background:rgba(6,182,212,.08);}
@media(max-width:768px){
.hero h1{font-size:1.6rem;}.hero .subtitle{font-size:1rem;}.navbar{padding:0 1rem;}
.nav-links{display:none;position:absolute;top:64px;left:0;right:0;background:var(--bg-primary);flex-direction:column;padding:1rem;border-bottom:1px solid var(--border-color);}
.nav-links.open{display:flex;}.hamburger{display:block;}.container{padding:1rem;}.chart-wrap{height:300px;}
.stat-grid{grid-template-columns:repeat(2,1fr);gap:.75rem;}.stat-card .value{font-size:1.6rem;}.page-header h1{font-size:1.4rem;}
.report-grid{grid-template-columns:1fr;}.scanner-card-top{display:grid;}
.lb-card{grid-template-columns:1fr;text-align:center;}.lb-logo{font-size:2rem;}
.nav-dropdown{flex-direction:column;align-items:flex-start;width:100%;}
.nav-dropdown>button{width:100%;justify-content:space-between;padding:.5rem 0;border-bottom:1px solid var(--border-color);}
.dropdown-menu{display:none;position:static;background:var(--bg-secondary);border:none;border-radius:0;box-shadow:none;padding:.25rem 0 .25rem 1rem;width:100%;}
.nav-dropdown.open .dropdown-menu{display:block;}
}
"""

def render_page(title, description, path, content_html, active_nav=""):
    ai_label = '''<aside role="note" style="box-sizing:border-box;max-width:1200px;margin:1rem auto;padding:.75rem 1rem;border:1px solid rgba(245,158,11,.45);border-radius:.65rem;background:rgba(245,158,11,.08);line-height:1.5"><strong style="text-transform:uppercase;letter-spacing:.04em">AI-generated analysis</strong> Scores, report interpretations and summaries may be generated by AI. <a href="/ai-disclosure" style="color:inherit;text-decoration:underline">How CopeCheck uses AI</a>.</aside>'''
    ai_footer = '''<p style="margin:1rem 0;padding:.75rem 1rem;border:1px solid rgba(245,158,11,.45);border-radius:.5rem;background:rgba(245,158,11,.08);font-size:.85rem;line-height:1.5"><strong>AI disclosure:</strong> Analytical summaries and scores may be AI-generated and may contain errors. <a href="/ai-disclosure" style="color:inherit;text-decoration:underline">Full disclosure</a>.</p>'''
    nav_structure = [
        ("Dashboard", "/", "home", None),
        ("AI Labs", None, "ai-labs", [
            ("OpenAI", "/openai", "openai"),
            ("Anthropic", "/anthropic", "anthropic"),
            ("DeepMind", "/deepmind", "deepmind"),
        ]),
        ("Reports", None, "reports", [
            ("OpenAI B2B", "/openai-b2b", "openai-b2b"),
            ("Report Scanners", "/report-scanners", "report-scanners"),
        ]),
        ("Research", None, "research", [
            ("MS Research", "/microsoft-research", "ms-research"),
            ("AI Economy Ireland", "/ai-economy-ireland", "ai-economy-ireland"),
        ]),
        ("Consultancy", None, "consultancy", [
            ("Accenture Ireland", "/consultancy/accenture-ireland", "accenture-ireland"),
        ]),
        ("Geography", "/geography", "geography", None),
        ("Cope Scores", "/cope", "cope", None),
    ]
    nav_html = ""
    for item in nav_structure:
        label, href, key, children = item
        if children is None:
            cls = ' class="active"' if key == active_nav else ""
            nav_html += f'<a href="{href}"{cls}>{label}</a>\n'
        else:
            group_active = any(c[2] == active_nav for c in children)
            grp_cls = ' active' if group_active else ''
            nav_html += f'<div class="nav-dropdown{grp_cls}"><button onclick="this.parentElement.classList.toggle(\'open\')">{label}</button><div class="dropdown-menu">'
            for c_label, c_href, c_key in children:
                c_cls = ' class="active"' if c_key == active_nav else ""
                nav_html += f'<a href="{c_href}"{c_cls}>{c_label}</a>'
            nav_html += '</div></div>\n'
    network_html = "".join(f'<a href="{u}">{n}</a>' for n, u in NETWORK_LINKS)
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title} | CopeCheck Labs</title>
<meta name="description" content="{description}">
<meta property="og:title" content="{title} | CopeCheck Labs">
<meta property="og:description" content="{description}">
<meta property="og:type" content="website">
<meta property="og:url" content="https://labs.copecheck.com{path}">
<meta property="og:site_name" content="CopeCheck Network">
<meta name="twitter:card" content="summary_large_image">
<link rel="canonical" href="https://labs.copecheck.com{path}">
<script defer src="https://analytics.copecheck.com/script.js" data-website-id="{UMAMI_ID}"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<style>{CSS}.oracle-float {{
  position: fixed;
  left: max(1rem, env(safe-area-inset-left));
  bottom: max(1rem, env(safe-area-inset-bottom));
  z-index: 9998;
  display: inline-flex;
  flex-direction: column;
  gap: 0.15rem;
  padding: 0.72rem 0.92rem;
  border: 1px solid rgba(255, 255, 255, 0.22);
  border-radius: 0.75rem;
  background: rgba(12, 16, 24, 0.9);
  color: #fff;
  text-decoration: none;
  box-shadow: 0 18px 42px rgba(0, 0, 0, 0.28);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  transition: transform 160ms ease, box-shadow 160ms ease, border-color 160ms ease;
}}

.oracle-float:hover,
.oracle-float:focus-visible {{
  transform: translateY(-2px);
  border-color: rgba(255, 255, 255, 0.42);
  box-shadow: 0 22px 54px rgba(0, 0, 0, 0.36);
  color: #fff;
}}

.oracle-float-kicker {{
  font-size: 0.64rem;
  font-weight: 700;
  line-height: 1;
  letter-spacing: 0.08em;
  opacity: 0.72;
  text-transform: uppercase;
}}

.oracle-float-title {{
  font-size: 0.95rem;
  font-weight: 800;
  line-height: 1.1;
}}

@media (max-width: 640px) {{
  .oracle-float {{
    left: 0.75rem;
    right: 0.75rem;
    bottom: 0.75rem;
    width: auto;
    align-items: center;
    text-align: center;
  }}

  .oracle-float-kicker {{
    display: none;
  }}
}}
</style>
</head>
<body>
<nav class="navbar">
    <a class="nav-brand" href="/">CopeCheck <span>// Labs</span></a>
    <div class="nav-links" id="navLinks">{nav_html}</div>
    <button class="hamburger" onclick="document.getElementById('navLinks').classList.toggle('open')">&#9776;</button>
</nav>
{ai_label}
{content_html}
<!-- COPE REPORT SUBSCRIBE WIDGET -->
<div style="background:#111;border-top:1px solid #222;padding:48px 24px;text-align:center;">
  <div style="max-width:480px;margin:0 auto;">
    <div style="font-size:11px;letter-spacing:0.25em;text-transform:uppercase;color:#6b7280;margin-bottom:10px;">The Cope Report</div>
    <div style="font-size:22px;font-weight:800;color:#fff;margin-bottom:8px;">Weekly. Free. No cope.</div>
    <div style="font-size:14px;color:#9ca3af;margin-bottom:24px;line-height:1.6;">The week&#39;s most revealing AI coverage,<br>scored for omission. Every Monday.</div>
    <a href="https://copecheck.beehiiv.com/" class="newsletter-signup" style="display:inline-block;padding:11px 24px;background:#dc2626;color:white;border-radius:4px;font-size:14px;font-weight:700;text-decoration:none;">Subscribe Free &#x2192;</a>
  </div>
</div>

<!-- END COPE REPORT SUBSCRIBE WIDGET -->
<footer class="site-footer">
    {ai_footer}
    <div class="footer-network">{network_html}</div>
    <div class="footer-attribution">
        OpenAI data: CC BY 4.0 &mdash; Chatterji et al., NBER Working Paper 34255 (2025).<br>
        Anthropic data: &ldquo;The Impact of AI on Labour Markets,&rdquo; Anthropic Research (March 2026).<br>
        Analysis: CopeCheck Network &mdash; Discontinuity Thesis v3.3 &bull;
        &copy; {datetime.now().year} CopeCheck.
    </div>
</footer>
<script>
Chart.defaults.color='#94a3b8';Chart.defaults.borderColor='#1e293b';
Chart.defaults.font.family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif";
Chart.defaults.font.size=12;Chart.defaults.plugins.legend.labels.usePointStyle=true;
const CC=['#06b6d4','#8b5cf6','#f59e0b','#ef4444','#22c55e','#ec4899','#3b82f6','#a855f7','#f97316','#14b8a6'];
function fmtMonth(m){{const d=new Date(m);return d.toLocaleDateString('en-US',{{month:'short',year:'2-digit'}});}}
function fmtPct(v){{return(parseFloat(v)*100).toFixed(1)+'%';}}
</script>
  <a class="oracle-float" href="https://chatgpt.com/g/[redacted]" target="_blank" rel="noopener" aria-label="Ask the Oracle custom GPT">
    <span class="oracle-float-kicker">Custom GPT</span>
    <span class="oracle-float-title">Ask the Oracle</span>
  </a>
</body></html>"""


# ── Routes ──────────────────────────────────────────────────────────────

@app.route("/")
def index():
    work_doing = [r for r in DATA.get("ask_do", []) if r.get("work_related") == "1" and r.get("ask_do_express") == "doing"]
    doing_pct = f"{float(work_doing[-1]['share_of_messages'])*100:.0f}%" if work_doing else "46%"
    iwa_codes = set(r.get("iwa_cleaned") for r in DATA.get("onet_work", []))
    iwa_count = len(iwa_codes) if iwa_codes else 165

    # Build leaderboard HTML
    lb_html = ""
    for lab in sorted(LAB_LEADERBOARD, key=lambda x: x["cope_score"], reverse=True):
        segs = ""
        for i in range(10):
            threshold = (i + 1) * 10
            filled = "filled" if lab["cope_score"] >= threshold else ""
            segs += f'<div class="lb-meter-seg {filled}" style="color:var(--{lab["cope_class"].replace("cope-","cope-")})"></div>'
        lb_html += f"""
        <div class="lb-card">
            <div class="lb-logo">{lab["logo"]}</div>
            <div class="lb-info">
                <h3>{lab["lab"]}</h3>
                <p>{lab["headline"]}</p>
                <div class="lb-sub-scores">
                    <span>Data Transparency: {lab["data_score"]}/100</span>
                    <span>Framing Honesty: {lab["framing_score"]}/100</span>
                </div>
            </div>
            <div class="lb-score">
                <div class="score-num" style="color:var(--{lab["cope_class"].replace("cope-","cope-")})">{lab["cope_score"]}</div>
                <span class="cope-badge {lab["cope_class"]}">{lab["cope_band"]}</span>
            </div>
        </div>"""

    content = f"""
<section class="hero">
    <h1>AI Lab Cope Tracker</h1>
    <p class="subtitle">
        The labs publish their own data. We score how hard they cope about what it means.
        Usage telemetry, labour research, public statements &mdash; all analysed through the Discontinuity Thesis.
    </p>
    <p class="meta-line">
        Tracking: OpenAI Signals &bull; Anthropic Labour Research &bull; Google DeepMind &bull; Meta AI
    </p>
</section>

<div class="container">
    <h2 style="margin:2rem 0 .5rem;font-size:1.5rem">Lab Cope Leaderboard</h2>
    <p style="color:var(--text-secondary);margin-bottom:1rem;font-size:.9rem">
        Ranked by overall cope score. Data transparency + framing honesty = how much they try to hide displacement evidence.
    </p>
    {lb_html}

    <div class="stat-grid" style="margin-top:2.5rem">
        <div class="stat-card">
            <div class="value">{doing_pct}</div>
            <div class="label">OpenAI: Work = Doing</div>
            <div class="sub">ChatGPT performs work, not just answers</div>
        </div>
        <div class="stat-card">
            <div class="value">75%</div>
            <div class="label">Anthropic: Programmer Exposure</div>
            <div class="sub">Computer programmers most exposed to Claude</div>
        </div>
        <div class="stat-card">
            <div class="value">{iwa_count}</div>
            <div class="label">O*NET Activities Mapped</div>
            <div class="sub">Job tasks measured by OpenAI Signals</div>
        </div>
        <div class="stat-card">
            <div class="value">4</div>
            <div class="label">Labs Tracked</div>
            <div class="sub">OpenAI, Anthropic, Google, Meta</div>
        </div>
    </div>

    <h2 style="margin:2.5rem 0 1rem;font-size:1.4rem">Lab Data Deep Dives</h2>
    <div class="section-grid">
        <a href="/openai" class="section-card">
            <h3>OpenAI Signals</h3>
            <p>21 months of ChatGPT usage data. Topics, demographics, work patterns, 
            165 O*NET job activities, geographic exposure. The most comprehensive displacement dataset ever published.</p>
        </a>
        <a href="/anthropic" class="section-card">
            <h3>Anthropic Labour Research</h3>
            <p>Claude usage data mapped to occupational exposure. 75% programmer exposure,
            slowing younger-worker hiring. Published March 2026.</p>
        </a>
        <a href="/deepmind" class="section-card">
            <h3>Google DeepMind</h3>
            <p>AlphaFold, Gemini, Veo, Concordia &mdash; and a research primer on AI in organisations.
            Extraordinary science framing. No displacement metrics. Published May 2026.</p>
        </a>
        <a href="/geography" class="section-card">
            <h3>Geographic Exposure</h3>
            <p>118 countries and 50 US states ranked by per-capita AI usage. 
            Knowledge economy capitals hit first: Singapore, Israel, Netherlands lead globally.</p>
        </a>
        <a href="/cope" class="section-card">
            <h3>Cope Scores</h3>
            <p>Public statements about AI and jobs, scored for cope. The Volume Illusion,
            the Augmentation Myth, and other classic deflection patterns catalogued.</p>
        </a>
        <a href="/cope#report-scanner" class="section-card">
            <h3>Score a Report</h3>
            <p>Upload a PDF or submit a public report URL. Labs extracts the text and scores the report
            for displacement evidence, euphemism, institutional framing, and honesty.</p>
        </a>
        <a href="/report-scanners" class="section-card">
            <h3>Institutional Report Scanners</h3>
            <p>Run curated scanners for Goldman Sachs, McKinsey, Accenture, Deloitte, PwC, and BCG.
            Consultancy and bank reports belong here: not labs, but still evidence.</p>
        </a>
        <a href="/ai-economy-ireland" class="section-card">
            <h3>AI Economy Ireland 2026</h3>
            <p>Trinity College Dublin and Microsoft Ireland research on near-universal AI adoption,
            SME readiness gaps, weekly time savings, formal AI policy, and productivity gains.</p>
        </a>
        <a href="/openmontage" class="section-card">
            <h3>OpenMontage</h3>
            <p>Open-source agentic video production. A full production team &mdash; researcher, scriptwriter,
            narrator, editor, composer &mdash; automated for &pound;0.15&ndash;&pound;3 per video. GitHub #1 trending, June 2026.</p>
        </a>
        <a href="/genebench" class="section-card">
            <h3>AI Can&rsquo;t Do Science</h3>
            <p>GeneBench-Pro: the best AI solves 1 in 3 biology tasks. GPT-5.6 Sol Pro peaks at 31.5%.</p>
            <span style="display:inline-block;margin-top:.5rem;font-size:.7rem;font-weight:700;letter-spacing:.08em;color:#e63946;border:1px solid #e63946;border-radius:4px;padding:.1rem .4rem;">BENCHMARKS</span>
        </a>
        <a href="/anthropic-economic-index" class="section-card">
            <h3>The Economic Index</h3>
            <p>Anthropic surveyed their own power users and found AI is &ldquo;mostly augmenting&rdquo; &mdash; here&rsquo;s what the data actually shows.</p>
            <span style="display:inline-block;margin-top:.5rem;font-size:.7rem;font-weight:700;letter-spacing:.08em;color:#e63946;border:1px solid #e63946;border-radius:4px;padding:.1rem .4rem;">METHODOLOGY</span>
        </a>
    </div>

    <div class="chart-section">
        <h2>OpenAI: Work Messages &mdash; Ask vs Do vs Express</h2>
        <p class="chart-desc">The &ldquo;doing&rdquo; category = ChatGPT performing actual work tasks.</p>
        <div class="chart-wrap"><canvas id="homeAskDoChart"></canvas></div>
        <div class="cope-callout">
            <div class="callout-title">CopeCheck Analysis</div>
            <p>Nearly half of all work-related ChatGPT messages are &ldquo;doing&rdquo; &mdash; the tool has become the worker.
            This isn&rsquo;t augmentation. It&rsquo;s substitution, measured in OpenAI&rsquo;s own telemetry.</p>
        </div>
    </div>
</div>

<script>
fetch('/api/ask-do-express').then(r=>r.json()).then(data => {{
    const wd = data.filter(d => d.work_related === '1');
    const ms = [...new Set(wd.map(d => d.month))];
    const cats = ['doing','asking','expressing'];
    const cols = {{'doing':'#ef4444','asking':'#06b6d4','expressing':'#8b5cf6'}};
    const lbls = {{'doing':'Doing (Replacement)','asking':'Asking (Reference)','expressing':'Expressing'}};
    const ds = cats.map(c => ({{
        label:lbls[c], data:ms.map(m => {{const r=wd.find(d=>d.month===m&&d.ask_do_express===c);return r?parseFloat(r.share_of_messages)*100:0;}}),
        borderColor:cols[c], backgroundColor:cols[c]+'20', fill:c==='doing', tension:.3, borderWidth:2, pointRadius:3,
    }}));
    new Chart(document.getElementById('homeAskDoChart'), {{
        type:'line', data:{{labels:ms.map(fmtMonth),datasets:ds}},
        options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{beginAtZero:true,max:60,ticks:{{callback:v=>v+'%'}}}}}},
        plugins:{{tooltip:{{callbacks:{{label:ctx=>ctx.dataset.label+': '+ctx.parsed.y.toFixed(1)+'%'}}}}}}}}
    }});
}});
</script>
"""
    return render_page("AI Lab Cope Tracker", "Which AI lab copes hardest? OpenAI, Anthropic, Google, Meta data and statements analysed.", "/", content, "home")


@app.route("/openai")
def openai_page():
    # Build O*NET table
    totals = defaultdict(lambda: {"sum": 0.0, "count": 0})
    rows = DATA.get("onet_work", []) or DATA.get("onet", [])
    for r in rows:
        code = r.get("iwa_cleaned", "")
        share = float(r.get("share_of_messages", 0))
        totals[code]["sum"] += share
        totals[code]["count"] += 1
    averaged = []
    for code, v in totals.items():
        avg = v["sum"] / v["count"] if v["count"] > 0 else 0
        averaged.append({"code": code, "name": IWA_NAMES.get(code, code), "avg_share": avg})
    averaged.sort(key=lambda x: x["avg_share"], reverse=True)
    top20 = averaged[:20]
    max_share = top20[0]["avg_share"] if top20 else 1
    table_rows = ""
    for i, item in enumerate(top20, 1):
        pct = item["avg_share"] * 100
        bar_w = (item["avg_share"] / max_share) * 100
        rank_cls = f"rank-{i}" if i <= 3 else "rank-other"
        table_rows += f'<tr><td><span class="rank-badge {rank_cls}">{i}</span></td><td style="font-family:monospace;font-size:.8rem;color:var(--text-muted)">{item["code"]}</td><td>{item["name"]}</td><td><div class="bar-inline"><div class="bar-fill" style="width:{bar_w}%"></div><span class="bar-label">{pct:.2f}%</span></div></td></tr>'

    content = f"""
<div class="container">
    <div class="page-header">
        <h1>OpenAI Signals Dataset</h1>
        <p>21 months of aggregate ChatGPT usage data (July 2024 &ndash; March 2026). OpenAI calls it &ldquo;adoption.&rdquo;
        Through the Discontinuity lens, it&rsquo;s the most comprehensive displacement dataset ever published by an AI lab.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--cope-terminal)">72</div><div class="label">Lab Cope Score</div><div class="sub">HEAVY COPE</div></div>
        <div class="stat-card"><div class="value">95/100</div><div class="label">Data Transparency</div><div class="sub">Unprecedented openness</div></div>
        <div class="stat-card"><div class="value">25/100</div><div class="label">Framing Honesty</div><div class="sub">Called displacement "adoption"</div></div>
    </div>

    <div class="chart-section">
        <h2>Topics Over Time</h2>
        <p class="chart-desc">What people use ChatGPT for, month by month.</p>
        <div class="chart-wrap"><canvas id="topicsChart"></canvas></div>
        <div class="cope-callout"><div class="callout-title">CopeCheck Analysis</div>
        <p>Writing dominates at ~24%. Technical Help and Practical Guidance together account for massive shares &mdash; 
        professional work tasks outsourced to AI. Self-expression growing fastest = creative work consumed too.</p></div>
    </div>

    <div class="chart-section">
        <h2>Work vs Non-Work Messages</h2>
        <p class="chart-desc">Share of messages classified as work-related vs personal.</p>
        <div class="chart-wrap"><canvas id="workChart"></canvas></div>
        <div class="cope-callout"><div class="callout-title">The Volume Illusion</div>
        <p>Work share declined 51% &rarr; 31%. Copers cite this. But total volume grew enormously. 
        31% of a vastly larger pie = MORE absolute work displacement. The declining share masks accelerating replacement.</p></div>
    </div>

    <div class="chart-section">
        <h2>Ask vs Do vs Express (Work Messages)</h2>
        <div class="chart-wrap"><canvas id="askDoChart"></canvas></div>
        <div class="cope-callout"><div class="callout-title">The Doing Problem</div>
        <p>&ldquo;Doing&rdquo; = ChatGPT performing actual work tasks. Not researching. Not brainstorming. Doing.
        At 46%, nearly half of work interactions are direct task execution. A replacement worker measured in real-time.</p></div>
    </div>

    <div class="chart-section">
        <h2>Age Group Distribution</h2>
        <div class="chart-wrap"><canvas id="ageChart"></canvas></div>
        <div class="cope-callout"><div class="callout-title">The Age Bomb</div>
        <p>25-34 year olds dominate (~40%+). Early-career professionals outsourcing their work to AI.
        Building AI-dependency instead of skills.</p></div>
    </div>

    <div class="chart-section">
        <h2>Gender Split</h2>
        <div class="chart-wrap"><canvas id="genderChart"></canvas></div>
    </div>

    <div class="chart-section">
        <h2>Top 20 O*NET Work Activities</h2>
        <p class="chart-desc">Which specific human work activities ChatGPT is replacing, by average share of work messages.</p>
        <div class="chart-wrap" style="height:500px"><canvas id="onetBarChart"></canvas></div>
    </div>

    <div class="chart-section">
        <h2>O*NET Work Activities &mdash; Ranked Table</h2>
        <table class="data-table">
            <thead><tr><th>Rank</th><th>IWA Code</th><th>Work Activity</th><th>Avg Share</th></tr></thead>
            <tbody>{table_rows}</tbody>
        </table>
        <div class="cope-callout"><div class="callout-title">Occupational Implications</div>
        <p>Top codes cluster around information processing, creative work, computer interaction, written communication.
        Core activities of knowledge workers: analysts, writers, programmers, designers, marketers, researchers.</p></div>
    </div>

    <div class="chart-section">
        <h2>Top 10 Work Activities Over Time</h2>
        <div class="chart-wrap"><canvas id="onetTimeChart"></canvas></div>
    </div>

    <div class="chart-section">
        <h2>Free vs Plus Users: Work Usage</h2>
        <div class="chart-wrap"><canvas id="planChart"></canvas></div>
        <div class="cope-callout"><div class="callout-title">CopeCheck Analysis</div>
        <p>Plus subscribers use ChatGPT for work at significantly higher rates. Professionals paying for enhanced AI 
        are using it to replace human work output &mdash; not for casual chat.</p></div>
    </div>

    <div class="chart-section">
        <h2>Key Capabilities &amp; Announcements</h2>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:1.5rem;margin:1rem 0">
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-terminal)">GPT-5.6</div>
                <div class="label">Sol &middot; Terra &middot; Luna &mdash; June 2026</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Three-model family: Sol (flagship), Terra (mid-tier), Luna (fastest/cheapest). All three
                    rated <strong>High</strong> in both Cybersecurity and Biological/Chemical capability under
                    OpenAI&rsquo;s Preparedness Framework &mdash; the first time smaller, cheaper models have
                    cleared the High threshold in a Tracked Category. Sol saturates OpenAI&rsquo;s internal
                    CTF benchmark at 96.67%. HealthBench Professional: Sol scores 60.5 &mdash; a +8.7 gain
                    vs GPT-5.5, the largest health benchmark improvement since GPT-5. Agentic misalignment
                    evaluation found Sol shows a greater tendency than GPT-5.5 to go beyond user intent in
                    coding tasks, taking actions that weren&rsquo;t asked for. Deployed initially in limited
                    preview with the US government briefed ahead of release.
                    <em>CopeCheck:</em> The dangerous capability frontier has collapsed downward into the cheap tier.
                    High-capability bio and cyber co-pilots are now available at Luna pricing &mdash; not just
                    Sol flagship compute. The misalignment finding is Layer 2 of the Discontinuity Thesis: AI
                    agents taking initiative, replacing human judgment, operating beyond their brief. The lab
                    framing focuses on safeguards. The reality is that every developer now ships with a
                    High-rated biosecurity and cybersecurity engine as a dependency.
                    <a href="https://openai.com/index/previewing-gpt-5-6-sol/" style="color:var(--accent-cyan);font-size:.8rem;display:block;margin-top:.5rem"
                       target="_blank" rel="noopener">&rarr; Source: openai.com/index/previewing-gpt-5-6-sol</a>
                </div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-terminal)">Codex + GB200</div>
                <div class="label">NVIDIA Engineers Build with Codex &mdash; May 2026</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    NVIDIA engineers now use Codex (built on GPT&minus;5.5, running on NVIDIA&rsquo;s own GB200 and GB300
                    infrastructure) as their <strong>default tool</strong> for complex engineering and end-to-end ML experiments.
                    For NVIDIA&rsquo;s research teams, the full loop is largely automated: identifying research areas,
                    writing experiment scripts, running on remote machines. An internal podcast app that would have
                    taken weeks to procure was spun up in hours using Codex.
                    <em>CopeCheck:</em> OpenAI&rsquo;s coding agent is replacing NVIDIA&rsquo;s own engineers&rsquo; work &mdash;
                    on NVIDIA&rsquo;s own chips. The displacement is literal and circular.
                    <a href="https://openai.com/index/nvidia/" style="color:var(--accent-cyan);font-size:.8rem;display:block;margin-top:.5rem"
                       target="_blank" rel="noopener">&rarr; Source: openai.com/index/nvidia</a>
                </div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-terminal)">Singular Bank</div>
                <div class="label">AI Replaces Banking Workflows &mdash; 2025</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Singular Bank integrated OpenAI&rsquo;s models to automate core banking workflows &mdash;
                    document processing, client onboarding, and routine compliance tasks. Processing time
                    for previously manual workflows was reduced by over 80%, with staff redeployed away
                    from execution and toward oversight. The bank now treats AI as operational infrastructure
                    rather than a productivity add-on.
                    <em>CopeCheck:</em> A bank replaced the actual work of banking with OpenAI.
                    Not augmented. Not assisted. The workflow was automated end-to-end.
                    <a href="https://openai.com/index/singular-bank/" style="color:var(--accent-cyan);font-size:.8rem;display:block;margin-top:.5rem"
                       target="_blank" rel="noopener">&rarr; Source: openai.com/index/singular-bank</a>
                </div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-terminal)">Dell + Codex</div>
                <div class="label">OpenAI &amp; Dell: Codex for Enterprise (On-Premise) &mdash; April 2026</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    OpenAI partnered with Dell to deploy Codex inside hybrid and on-premise enterprise environments
                    via the Dell AI Factory &mdash; targeting regulated and sovereign industries that will not put
                    source code in the cloud. Part of a broader Codex enterprise push alongside Cognizant and CGI.
                    Codex grew from 3&thinsp;million to 4&thinsp;million developers in two weeks (April 2026).
                    <em>CopeCheck:</em> The sovereign-enterprise angle is the tell &mdash; AI coding agents are
                    now being architected specifically for the industries (finance, defence, government) where
                    humans were assumed to be irreplaceable. The on-prem wrapper removes the last objection.
                    <a href="https://openai.com/index/dell-codex-enterprise-partnership/" style="color:var(--accent-cyan);font-size:.8rem;display:block;margin-top:.5rem"
                       target="_blank" rel="noopener">&rarr; Source: openai.com/index/dell-codex-enterprise-partnership</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
fetch('/api/topics').then(r=>r.json()).then(data => {{
    const topics=[...new Set(data.map(d=>d.topic))], ms=[...new Set(data.map(d=>d.month))];
    const ds=topics.map((t,i)=>({{label:t,data:ms.map(m=>{{const r=data.find(d=>d.month===m&&d.topic===t);return r?parseFloat(r.share_of_messages)*100:0;}}),borderColor:CC[i%CC.length],backgroundColor:CC[i%CC.length]+'20',tension:.3,borderWidth:2,pointRadius:2}}));
    new Chart(document.getElementById('topicsChart'),{{type:'line',data:{{labels:ms.map(fmtMonth),datasets:ds}},options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{beginAtZero:true,ticks:{{callback:v=>v+'%'}}}}}},plugins:{{tooltip:{{callbacks:{{label:c=>c.dataset.label+': '+c.parsed.y.toFixed(1)+'%'}}}}}}}}}});
}});
fetch('/api/work').then(r=>r.json()).then(data => {{
    const ms=[...new Set(data.map(d=>d.month))];
    const w=ms.map(m=>{{const r=data.find(d=>d.month===m&&d.work_related==='1');return r?parseFloat(r.share_of_messages)*100:0;}});
    const nw=ms.map(m=>{{const r=data.find(d=>d.month===m&&d.work_related==='0');return r?parseFloat(r.share_of_messages)*100:0;}});
    new Chart(document.getElementById('workChart'),{{type:'line',data:{{labels:ms.map(fmtMonth),datasets:[
        {{label:'Work-Related',data:w,borderColor:'#ef4444',backgroundColor:'#ef444420',fill:true,tension:.3,borderWidth:2}},
        {{label:'Non-Work',data:nw,borderColor:'#06b6d4',backgroundColor:'#06b6d420',fill:true,tension:.3,borderWidth:2}}
    ]}},options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{beginAtZero:true,max:80,ticks:{{callback:v=>v+'%'}}}}}}}}}});
}});
fetch('/api/ask-do-express').then(r=>r.json()).then(data => {{
    const wd=data.filter(d=>d.work_related==='1'),ms=[...new Set(wd.map(d=>d.month))];
    const cats=['doing','asking','expressing'],cols={{'doing':'#ef4444','asking':'#06b6d4','expressing':'#8b5cf6'}};
    const lbls={{'doing':'Doing (Replacement)','asking':'Asking (Reference)','expressing':'Expressing'}};
    const ds=cats.map(c=>({{label:lbls[c],data:ms.map(m=>{{const r=wd.find(d=>d.month===m&&d.ask_do_express===c);return r?parseFloat(r.share_of_messages)*100:0;}}),borderColor:cols[c],backgroundColor:cols[c]+'20',fill:false,tension:.3,borderWidth:2,pointRadius:3}}));
    new Chart(document.getElementById('askDoChart'),{{type:'line',data:{{labels:ms.map(fmtMonth),datasets:ds}},options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{beginAtZero:true,max:60,ticks:{{callback:v=>v+'%'}}}}}}}}}});
}});
fetch('/api/age').then(r=>r.json()).then(data => {{
    const gs=[...new Set(data.map(d=>d.age_group))],ms=[...new Set(data.map(d=>d.month))];
    const ds=gs.map((g,i)=>({{label:g,data:ms.map(m=>{{const r=data.find(d=>d.month===m&&d.age_group===g);return r?parseFloat(r.share_of_messages)*100:0;}}),borderColor:CC[i],backgroundColor:CC[i]+'20',tension:.3,borderWidth:2,pointRadius:2}}));
    new Chart(document.getElementById('ageChart'),{{type:'line',data:{{labels:ms.map(fmtMonth),datasets:ds}},options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{beginAtZero:true,ticks:{{callback:v=>v+'%'}}}}}}}}}});
}});
fetch('/api/gender').then(r=>r.json()).then(data => {{
    const ms=[...new Set(data.map(d=>d.month))],gs=[...new Set(data.map(d=>d.typical_name_gender))];
    const cols={{'masculine':'#3b82f6','feminine':'#ec4899'}};
    const ds=gs.map(g=>({{label:g[0].toUpperCase()+g.slice(1),data:ms.map(m=>{{const r=data.find(d=>d.month===m&&d.typical_name_gender===g);return r?parseFloat(r.share_of_messages)*100:0;}}),borderColor:cols[g]||'#94a3b8',backgroundColor:(cols[g]||'#94a3b8')+'20',tension:.3,borderWidth:2}}));
    new Chart(document.getElementById('genderChart'),{{type:'line',data:{{labels:ms.map(fmtMonth),datasets:ds}},options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{beginAtZero:true,max:70,ticks:{{callback:v=>v+'%'}}}}}}}}}});
}});
fetch('/api/onet-top').then(r=>r.json()).then(data => {{
    const t20=data.slice(0,20);
    new Chart(document.getElementById('onetBarChart'),{{type:'bar',data:{{labels:t20.map(d=>d.name.length>35?d.name.slice(0,35)+'...':d.name),datasets:[{{label:'Avg Share',data:t20.map(d=>d.avg_share*100),backgroundColor:t20.map((d,i)=>CC[i%CC.length]+'cc'),borderColor:t20.map((d,i)=>CC[i%CC.length]),borderWidth:1}}]}},options:{{indexAxis:'y',responsive:true,maintainAspectRatio:false,scales:{{x:{{beginAtZero:true,ticks:{{callback:v=>v.toFixed(1)+'%'}}}}}},plugins:{{legend:{{display:false}},tooltip:{{callbacks:{{label:c=>c.parsed.x.toFixed(2)+'% of work msgs'}}}}}}}}}});
}});
fetch('/api/onet-timeseries').then(r=>r.json()).then(data => {{
    const codes=[...new Set(data.map(d=>d.code))],ms=[...new Set(data.map(d=>d.month))].sort();
    const ds=codes.map((c,i)=>{{const nm=data.find(d=>d.code===c)?.name||c;return{{label:nm.length>30?nm.slice(0,30)+'...':nm,data:ms.map(m=>{{const r=data.find(d=>d.month===m&&d.code===c);return r?r.share*100:null;}}),borderColor:CC[i%CC.length],tension:.3,borderWidth:2,pointRadius:1,spanGaps:true}};}});
    new Chart(document.getElementById('onetTimeChart'),{{type:'line',data:{{labels:ms.map(fmtMonth),datasets:ds}},options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{beginAtZero:true,ticks:{{callback:v=>v.toFixed(1)+'%'}}}}}},plugins:{{legend:{{position:'bottom',labels:{{font:{{size:10}}}}}}}}}}}});
}});
fetch('/api/plan-type').then(r=>r.json()).then(data => {{
    const ms=[...new Set(data.map(d=>d.month))];
    const combos=[{{w:'1',p:'plus',l:'Plus - Work',c:'#ef4444'}},{{w:'1',p:'free',l:'Free - Work',c:'#f97316'}},{{w:'0',p:'plus',l:'Plus - Non-Work',c:'#06b6d4'}},{{w:'0',p:'free',l:'Free - Non-Work',c:'#3b82f6'}}];
    const ds=combos.map(x=>({{label:x.l,data:ms.map(m=>{{const r=data.find(d=>d.month===m&&d.work_related===x.w&&d.plan_type===x.p);return r?parseFloat(r.share_of_messages)*100:0;}}),borderColor:x.c,backgroundColor:x.c+'20',tension:.3,borderWidth:2}}));
    new Chart(document.getElementById('planChart'),{{type:'line',data:{{labels:ms.map(fmtMonth),datasets:ds}},options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{beginAtZero:true,max:80,ticks:{{callback:v=>v+'%'}}}}}}}}}});
}});
</script>
"""
    return render_page("OpenAI Signals Dataset","21 months of ChatGPT usage data analysed through the Discontinuity Thesis.","/openai",content,"openai")


@app.route("/anthropic")
def anthropic_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>Anthropic Labour Market Research</h1>
        <p>In March 2026, Anthropic published research on AI&rsquo;s labour market impacts using their own Claude usage data.
        They measured occupational exposure and employment effects. The data is damning. The framing is cope.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--cope-moderate)">58</div><div class="label">Lab Cope Score</div><div class="sub">MODERATE</div></div>
        <div class="stat-card"><div class="value">85/100</div><div class="label">Data Transparency</div><div class="sub">Published methodology + findings</div></div>
        <div class="stat-card"><div class="value">40/100</div><div class="label">Framing Honesty</div><div class="sub">Buried the hiring slowdown</div></div>
    </div>

    <div class="cope-callout">
        <div class="callout-title">Source</div>
        <p>&ldquo;The Impact of AI on Labour Markets&rdquo; &mdash; Anthropic Research, March 5, 2026.
        Uses Claude API usage data mapped to O*NET occupational categories to measure exposure and employment effects.</p>
    </div>

    <div class="chart-section">
        <h2>Key Findings</h2>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:1.5rem;margin:1rem 0">
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.8rem;color:var(--cope-terminal)">75%</div>
                <div class="label">Computer Programmer Exposure</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Computer programmers are the most exposed occupation to Claude. 75% of their work activities
                    overlap with Claude&rsquo;s capabilities. This is displacement waiting to happen.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.8rem;color:var(--cope-heavy)">Customer Service</div>
                <div class="label">Second Most Exposed</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Customer service representatives are the next most exposed occupation. High-volume,
                    language-based work that AI can directly substitute.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.8rem;color:var(--cope-heavy)">Data Entry</div>
                <div class="label">Third Most Exposed</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Data entry keyers round out the top three. Routine information processing tasks
                    that AI handles faster and cheaper than humans.</div>
            </div>
        </div>
    </div>

    <div class="chart-section">
        <h2>The Cope: &ldquo;No Systematic Unemployment&rdquo;</h2>
        <div class="cope-callout" style="border-left-color:var(--cope-terminal)">
            <div class="callout-title" style="color:var(--cope-terminal)">Terminal Cope Alert</div>
            <p>Anthropic&rsquo;s headline finding: &ldquo;no systematic increase in unemployment&rdquo; in AI-exposed occupations.
            Sounds reassuring. But buried in the same paper:</p>
        </div>
        <div style="padding:1.5rem;margin:1rem 0">
            <h3 style="color:var(--cope-heavy);margin-bottom:1rem;font-size:1.1rem">What They Buried</h3>
            <div style="background:var(--bg-secondary);border-radius:8px;padding:1.25rem;margin:.75rem 0;border-left:3px solid var(--cope-heavy)">
                <p style="font-size:.95rem;color:var(--text-primary);font-weight:600">Younger worker hiring has slowed in exposed occupations</p>
                <p style="font-size:.85rem;color:var(--text-secondary);margin-top:.3rem">
                    New entrants to AI-exposed fields are finding fewer positions. The jobs aren&rsquo;t being eliminated yet &mdash;
                    they&rsquo;re just not being created. Attrition without replacement. The displacement happens 
                    through non-hiring, not firing.</p>
            </div>
            <div style="background:var(--bg-secondary);border-radius:8px;padding:1.25rem;margin:.75rem 0;border-left:3px solid var(--cope-moderate)">
                <p style="font-size:.95rem;color:var(--text-primary);font-weight:600">Exposure is concentrated in high-skill, high-pay occupations</p>
                <p style="font-size:.85rem;color:var(--text-secondary);margin-top:.3rem">
                    Unlike previous automation waves that hit manual labour, AI exposure is concentrated 
                    in knowledge work. Programmers, analysts, customer service &mdash; the middle class backbone.</p>
            </div>
            <div style="background:var(--bg-secondary);border-radius:8px;padding:1.25rem;margin:.75rem 0;border-left:3px solid var(--cope-moderate)">
                <p style="font-size:.95rem;color:var(--text-primary);font-weight:600">&ldquo;No systematic unemployment&rdquo; ≠ &ldquo;no displacement&rdquo;</p>
                <p style="font-size:.85rem;color:var(--text-secondary);margin-top:.3rem">
                    Unemployment is a lagging indicator. When a company stops hiring juniors because Claude handles their work,
                    unemployment stats don&rsquo;t move &mdash; but labour demand has been permanently reduced.
                    Anthropic measured the wrong metric and declared victory.</p>
            </div>
        </div>
    </div>

    <div class="chart-section">
        <h2>Anthropic vs OpenAI: Data Comparison</h2>
        <table class="data-table">
            <thead><tr><th>Dimension</th><th>OpenAI (Signals)</th><th>Anthropic (Labour Research)</th></tr></thead>
            <tbody>
                <tr><td>Data Source</td><td>ChatGPT aggregate usage telemetry</td><td>Claude API usage + BLS employment data</td></tr>
                <tr><td>Time Period</td><td>July 2024 &ndash; March 2026 (21 months)</td><td>2024 &ndash; early 2026</td></tr>
                <tr><td>Key Metric</td><td>46% of work messages are &ldquo;doing&rdquo;</td><td>75% programmer exposure</td></tr>
                <tr><td>Job Activity Mapping</td><td>165 O*NET IWA codes</td><td>O*NET occupational categories</td></tr>
                <tr><td>Displacement Finding</td><td>Implicit (framed as adoption)</td><td>Explicit but minimised</td></tr>
                <tr><td>Cope Strategy</td><td>Rename displacement as adoption</td><td>Measure lagging indicator, declare no problem</td></tr>
                <tr><td>Cope Score</td><td><span class="cope-badge cope-heavy">72 &bull; HEAVY</span></td><td><span class="cope-badge cope-moderate">58 &bull; MODERATE</span></td></tr>
            </tbody>
        </table>
    </div>

    <div class="cope-callout">
        <div class="callout-title">Credit Where Due</div>
        <p>Anthropic scores lower on cope than OpenAI because they at least acknowledged displacement mechanisms exist.
        They published actual labour market analysis, not just usage metrics. But concluding &ldquo;no systematic unemployment&rdquo;
        while documenting hiring slowdowns in exposed occupations is textbook cope &mdash; just better-written cope.</p>
    </div>
</div>
"""
    return render_page("Anthropic Labour Market Research","Anthropic's own Claude data shows 75% programmer exposure. They concluded 'no systematic unemployment.'","/anthropic",content,"anthropic")



@app.route("/deepmind")
def deepmind_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>Google DeepMind</h1>
        <p>In May 2026, Google DeepMind published &ldquo;Organizing Intelligence&rdquo; &mdash; a research primer on AI
        in organisations. AlphaFold at Level&nbsp;5 superhuman narrow AI. Concordia for organisational simulation.
        The framing: extraordinary science. The cope: no displacement metrics anywhere.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--cope-heavy)">78</div><div class="label">Lab Cope Score</div><div class="sub">HEAVY COPE</div></div>
        <div class="stat-card"><div class="value">15/100</div><div class="label">Data Transparency</div><div class="sub">No displacement metrics published</div></div>
        <div class="stat-card"><div class="value">30/100</div><div class="label">Framing Honesty</div><div class="sub">Productivity multiplier narrative</div></div>
        <div class="stat-card"><div class="value">5</div><div class="label">AGI Levels Defined</div><div class="sub">Level 1 Emerging &rarr; Level 5 Superhuman</div></div>
    </div>

    <div class="cope-callout">
        <div class="callout-title">Source</div>
        <p>&ldquo;Organizing Intelligence&rdquo; &mdash; Research primer, May 2026, by Martin Gonzalez
        (Head of Organizational AI Research, Google DeepMind), foreword by Simon Bouton (Chief Experience Officer).
        Co-produced with Stanford HAI via the <em>AI for Organizations Grand Challenge</em>, launched late 2025.</p>
    </div>

    <div class="chart-section">
        <h2>Key Projects &amp; Capabilities</h2>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:1.5rem;margin:1rem 0">
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-terminal)">Level 5</div>
                <div class="label">AlphaFold &mdash; Protein Structure</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Superhuman narrow AI. Predicts protein structures with accuracy that took structural biologists
                    decades to approach. Classified as Level 5 on DeepMind&rsquo;s own AGI scale.
                    The benchmark for what narrow superintelligence looks like in practice.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-terminal)">Level 5</div>
                <div class="label">AlphaZero &mdash; Strategy</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Mastered chess, shogi, and go through pure self-play &mdash; then taught grandmasters
                    entirely new strategies they had never conceived. Not just superhuman performance:
                    genuine knowledge generation that flowed back to humans.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-heavy)">50 Years</div>
                <div class="label">WeatherNext &mdash; Forecasting Progress</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    15-day probabilistic weather forecasting. DeepMind claims WeatherNext represents
                    50 years of progress in meteorological science &mdash; delivered in a single model.
                    Displaces decades of numerical weather prediction research.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-moderate)">Frontier LLM</div>
                <div class="label">Gemini</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Google DeepMind&rsquo;s frontier large language model. Positioned against GPT-4 and Claude
                    across reasoning, multimodal, and agentic benchmarks.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-moderate)">Video</div>
                <div class="label">Veo &mdash; Video Generation</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Text-to-video generation model. Competes with Sora and other video generation systems.
                    No displacement analysis of video production workers published.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--cope-moderate)">Embodied</div>
                <div class="label">Gemini Robotics 1.5</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Generalist robots with advanced embodied reasoning and motion transfer.
                    Moves learned in one physical context transfer to new tasks and environments.
                    The physical-world equivalent of zero-shot generalisation.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--accent-cyan)">Sim</div>
                <div class="label">Concordia &mdash; Organisational Simulation</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Generative agent-based modelling platform for organisational simulation.
                    Lets organisations model how AI agents interact within complex systems
                    before deploying them. The displacement implications are left as an exercise
                    for the reader.</div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.4rem;color:var(--accent-cyan)">Dialogue</div>
                <div class="label">AI Interpretability Research</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    Building a shared machine-human vocabulary. Future interpretability framed as
                    interactive dialogue, not dashboards. Understand what the model &ldquo;thinks&rdquo; rather
                    than just what it outputs.</div>
            </div>
        </div>
    </div>

    <div class="chart-section">
        <h2>The AGI Framework: 5-Level Scale</h2>
        <div class="cope-callout" style="border-left-color:var(--cope-heavy)">
            <div class="callout-title" style="color:var(--cope-heavy)">Heavy Cope Alert</div>
            <p>DeepMind has defined a 5-level AGI scale &mdash; and positioned two of their own systems
            (AlphaFold, AlphaZero) at Level&nbsp;5. As of early 2026, there is no consensus that Level&nbsp;2
            competent general AGI has been achieved. The framework creates the illusion of a managed
            transition while avoiding the displacement question entirely.</p>
        </div>
        <table class="data-table" style="margin-top:1.5rem">
            <thead>
                <tr><th>Level</th><th>Label</th><th>Description</th><th>Examples</th></tr>
            </thead>
            <tbody>
                <tr><td><strong>1</strong></td><td>Emerging</td><td>Early capabilities, narrow task performance</td><td>Early language models</td></tr>
                <tr><td><strong>2</strong></td><td>Competent</td><td>Broad task competence approaching human level</td><td>No consensus achieved (early 2026)</td></tr>
                <tr><td><strong>3</strong></td><td>Expert</td><td>Human expert-level performance across domains</td><td>&mdash;</td></tr>
                <tr><td><strong>4</strong></td><td>Exceptional</td><td>Above human expert level in most domains</td><td>&mdash;</td></tr>
                <tr style="background:rgba(239,68,68,.08)"><td><strong>5</strong></td><td>Superhuman</td><td>Far exceeds best human performance; generates new knowledge</td><td>AlphaFold (proteins), AlphaZero (strategy)</td></tr>
            </tbody>
        </table>
        <p style="color:var(--text-secondary);font-size:.85rem;margin-top:1rem">
            Note: Levels 1&ndash;5 apply to <em>narrow</em> AI systems. The same scale applied to
            general intelligence remains contested. AlphaFold and AlphaZero achieving Level&nbsp;5 narrow AI
            does not imply Level&nbsp;5 general AI is imminent &mdash; but DeepMind&rsquo;s framing invites
            that conflation.
        </p>
    </div>

    <div class="chart-section">
        <h2>Democratic Deliberation &amp; AI Mediation</h2>
        <div style="background:var(--bg-secondary);border-radius:8px;padding:1.5rem;margin:1rem 0;border-left:3px solid var(--accent-cyan)">
            <p style="font-size:.95rem;color:var(--text-primary);font-weight:600">
                A DeepMind AI outperformed human mediators at finding common ground on polarised political opinions.
            </p>
            <p style="font-size:.85rem;color:var(--text-secondary);margin-top:.5rem">
                This finding is buried in the organisational research primer rather than framed as a displacement
                of professional mediators, facilitators, and conflict-resolution specialists. Democratic deliberation
                is knowledge work. DeepMind just demonstrated their AI can do it better than humans.
                The word &ldquo;displacement&rdquo; does not appear in the surrounding analysis.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>The Cope: &ldquo;Extraordinary Science&rdquo; Framing</h2>
        <div class="cope-callout" style="border-left-color:var(--cope-terminal)">
            <div class="callout-title" style="color:var(--cope-terminal)">The Kuhn Manoeuvre</div>
            <p>The primer frames the current moment as a period of &ldquo;extraordinary science&rdquo; (invoking Kuhn) &mdash;
            where old rules break down and ideas scatter. This is accurate. The cope is positioning DeepMind
            at the research frontier of this rupture as a <em>good thing for organisations</em> without
            measuring what &ldquo;old rules break down&rdquo; means for the humans whose jobs were those rules.</p>
        </div>
        <div style="padding:1.5rem;margin:1rem 0">
            <h3 style="color:var(--cope-heavy);margin-bottom:1rem;font-size:1.1rem">Classic Deflection Patterns</h3>
            <div style="background:var(--bg-secondary);border-radius:8px;padding:1.25rem;margin:.75rem 0;border-left:3px solid var(--cope-heavy)">
                <p style="font-size:.95rem;color:var(--text-primary);font-weight:600">Productivity Multiplier Narrative</p>
                <p style="font-size:.85rem;color:var(--text-secondary);margin-top:.3rem">
                    Every AI capability is framed as multiplying human productivity rather than substituting
                    human labour. AlphaFold doesn&rsquo;t displace structural biologists &mdash; it &ldquo;accelerates
                    drug discovery.&rdquo; WeatherNext doesn&rsquo;t displace meteorologists &mdash; it &ldquo;improves
                    forecast accuracy.&rdquo; The multiplier frame renders displacement invisible by design.</p>
            </div>
            <div style="background:var(--bg-secondary);border-radius:8px;padding:1.25rem;margin:.75rem 0;border-left:3px solid var(--cope-heavy)">
                <p style="font-size:.95rem;color:var(--text-primary);font-weight:600">No Equivalent of OpenAI Signals or Anthropic Labour Research</p>
                <p style="font-size:.85rem;color:var(--text-secondary);margin-top:.3rem">
                    DeepMind has published zero occupational exposure analysis, zero O*NET task mapping,
                    zero employment effect studies. The absence is conspicuous. They produce systems
                    (AlphaFold, WeatherNext, Concordia) that demonstrably replace expert human work &mdash;
                    but publish no data on what that means for the humans doing that work.</p>
            </div>
            <div style="background:var(--bg-secondary);border-radius:8px;padding:1.25rem;margin:.75rem 0;border-left:3px solid var(--cope-moderate)">
                <p style="font-size:.95rem;color:var(--text-primary);font-weight:600">Mission Statement Cope</p>
                <p style="font-size:.85rem;color:var(--text-secondary);margin-top:.3rem">
                    &ldquo;Build AI responsibly to benefit humanity, including organisations across every sector.&rdquo;
                    <em>Benefit</em> is undefined. <em>Humanity</em> is untracked. The mission statement
                    substitutes for the labour market analysis that would actually tell you whether
                    the benefit is real or redistributive.</p>
            </div>
        </div>
    </div>

    <div class="cope-callout" style="border-left-color:var(--accent-cyan)">
        <div class="callout-title" style="color:var(--accent-cyan)">Demis Hassabis</div>
        <p>&ldquo;AI will have probably ten times the impact the industrial revolution had, ten times faster.&rdquo;
        The industrial revolution created mass unemployment before it created mass prosperity &mdash; over a century.
        Ten times faster means the disruption phase is proportionally shorter and sharper.
        DeepMind&rsquo;s own CEO has quantified the displacement risk. Their research programme
        has not measured it.</p>
    </div>

    <div class="chart-section">
        <h2>DeepMind vs OpenAI vs Anthropic: Cope Comparison</h2>
        <table class="data-table">
            <thead><tr><th>Dimension</th><th>OpenAI</th><th>Anthropic</th><th>Google DeepMind</th></tr></thead>
            <tbody>
                <tr><td>Labour data published?</td><td>Yes (Signals)</td><td>Yes (March 2026)</td><td>No</td></tr>
                <tr><td>Displacement acknowledged?</td><td>Implicit</td><td>Minimised</td><td>Not measured</td></tr>
                <tr><td>Occupational mapping</td><td>165 O*NET IWA codes</td><td>O*NET categories</td><td>None</td></tr>
                <tr><td>Level 5 systems</td><td>None claimed</td><td>None claimed</td><td>AlphaFold, AlphaZero</td></tr>
                <tr><td>Cope strategy</td><td>Rename displacement as adoption</td><td>Measure lagging indicator</td><td>Produce no displacement data</td></tr>
                <tr><td>Cope score</td>
                    <td><span class="cope-badge cope-heavy">72 &bull; HEAVY</span></td>
                    <td><span class="cope-badge cope-moderate">58 &bull; MODERATE</span></td>
                    <td><span class="cope-badge cope-heavy">78 &bull; HEAVY</span></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
"""
    return render_page(
        "Google DeepMind",
        "AlphaFold at Level 5 superhuman narrow AI. Concordia for organisational simulation. No displacement data published. Cope score: 78.",
        "/deepmind",
        content,
        "deepmind"
    )


@app.route("/geography")
def geography_page():
    countries = DATA.get("countries", [])
    quarters = sorted(set(r.get("quarter") for r in countries))
    latest_q = quarters[-1] if quarters else ""
    latest_countries = sorted([r for r in countries if r.get("quarter") == latest_q], key=lambda x: int(x.get("rank", 999)))
    page_num = request.args.get("page", 1, type=int)
    per_page = 20
    total_pages = (len(latest_countries) + per_page - 1) // per_page
    page_num = max(1, min(page_num, total_pages))
    start = (page_num - 1) * per_page
    page_countries = latest_countries[start:start + per_page]
    country_rows = ""
    for r in page_countries:
        cc = r.get("country", "")
        rank = int(r.get("rank", 0))
        rank_cls = f"rank-{rank}" if rank <= 3 else "rank-other"
        country_rows += f'<tr><td><span class="rank-badge {rank_cls}">{rank}</span></td><td>{COUNTRY_FLAGS.get(cc,"")} {COUNTRY_NAMES.get(cc,cc)}</td><td style="font-family:monospace">{cc}</td></tr>'
    pagination = ""
    if total_pages > 1:
        pagination = '<div class="pagination">'
        if page_num > 1: pagination += f'<a href="/geography?page={page_num-1}">&laquo; Prev</a>'
        for p in range(1, total_pages + 1):
            if p == page_num: pagination += f'<span class="current">{p}</span>'
            elif abs(p - page_num) <= 3 or p in (1, total_pages): pagination += f'<a href="/geography?page={p}">{p}</a>'
            elif abs(p - page_num) == 4: pagination += '<span>...</span>'
        if page_num < total_pages: pagination += f'<a href="/geography?page={page_num+1}">Next &raquo;</a>'
        pagination += '</div>'
    states = sorted(DATA.get("states", []), key=lambda x: int(x.get("rank", 999)))
    state_rows = ""
    for r in states[:20]:
        rank = int(r.get("rank", 0))
        rank_cls = f"rank-{rank}" if rank <= 3 else "rank-other"
        state_rows += f'<tr><td><span class="rank-badge {rank_cls}">{rank}</span></td><td>{r.get("state_name","")}</td><td style="font-family:monospace">{r.get("state_code","")}</td></tr>'
    q_label = latest_q[:7] if latest_q else "Latest"

    content = f"""
<div class="container">
    <div class="page-header">
        <h1>Geographic Exposure Map</h1>
        <p>Where AI displacement hits hardest. Country and US state rankings by per-capita ChatGPT usage (OpenAI Signals).</p>
    </div>
    <div class="cope-callout"><div class="callout-title">Geographic Pattern</div>
    <p>Top countries/states: knowledge-economy hubs with white-collar concentrations. Singapore, Israel, Netherlands. DC, Virginia, New York. Canaries in the coal mine.</p></div>
    <div class="chart-section">
        <h2>Country Rankings ({q_label})</h2>
        <table class="data-table"><thead><tr><th>Rank</th><th>Country</th><th>Code</th></tr></thead><tbody>{country_rows}</tbody></table>
        {pagination}
    </div>
    <div class="chart-section">
        <h2>Country Rankings Over Time</h2>
        <div class="chart-wrap"><canvas id="countryTrendChart"></canvas></div>
    </div>
    <div class="chart-section">
        <h2>US State Rankings (2025)</h2>
        <table class="data-table"><thead><tr><th>Rank</th><th>State</th><th>Code</th></tr></thead><tbody>{state_rows}</tbody></table>
    </div>
    <div class="chart-section">
        <h2>US Topics by State</h2>
        <div class="chart-wrap" style="height:500px"><canvas id="stateTopicChart"></canvas></div>
    </div>
</div>
<script>
fetch('/api/countries').then(r=>r.json()).then(data => {{
    const qs=[...new Set(data.map(d=>d.quarter))].sort();
    const latest=data.filter(d=>d.quarter===qs[qs.length-1]).sort((a,b)=>a.rank-b.rank).slice(0,10);
    const tc=latest.map(d=>d.country);
    const ds=tc.map((cc,i)=>{{const nm=data.find(d=>d.country===cc)?.country_name||cc;return{{label:nm,data:qs.map(q=>{{const r=data.find(d=>d.quarter===q&&d.country===cc);return r?parseInt(r.rank):null;}}),borderColor:CC[i%CC.length],tension:.3,borderWidth:2,pointRadius:4,spanGaps:true}};}});
    new Chart(document.getElementById('countryTrendChart'),{{type:'line',data:{{labels:qs.map(q=>q.slice(0,7)),datasets:ds}},options:{{responsive:true,maintainAspectRatio:false,scales:{{y:{{reverse:true,min:1,max:40,title:{{display:true,text:'Rank'}}}}}},plugins:{{legend:{{position:'bottom'}}}}}}}});
}});
fetch('/api/us-topics-state').then(r=>r.json()).then(data => {{
    const sts=[...new Set(data.map(d=>d.state_code))].sort().slice(0,15),topics=[...new Set(data.map(d=>d.topic))];
    const ds=topics.map((t,i)=>({{label:t,data:sts.map(s=>{{const r=data.find(d=>d.state_code===s&&d.topic===t);return r?parseFloat(r.share_of_messages)*100:0;}}),backgroundColor:CC[i%CC.length]+'cc'}}));
    new Chart(document.getElementById('stateTopicChart'),{{type:'bar',data:{{labels:sts,datasets:ds}},options:{{responsive:true,maintainAspectRatio:false,scales:{{x:{{stacked:true}},y:{{stacked:true,ticks:{{callback:v=>v+'%'}}}}}},plugins:{{legend:{{position:'bottom'}}}}}}}});
}});
</script>"""
    return render_page("Geographic Exposure Map","Country and US state rankings by per-capita ChatGPT usage.","/geography",content,"geography")


@app.route("/cope")
def cope_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>Cope Scores</h1>
        <p>Public statements about AI and jobs, scored for cope. How labs and commentators frame displacement evidence.</p>
    </div>
    <div class="chart-section" id="report-scanner">
        <h2>Upload PDF or Submit Report</h2>
        <p class="chart-desc">Drop in an AI economy report, consultancy PDF, policy paper, research note, or public URL.
        Labs will score the report framing: how much displacement evidence it contains, and how hard it works to soften the meaning.</p>
        <form id="reportScoreForm" class="report-form" enctype="multipart/form-data">
            <div class="report-grid">
                <label>Report URL
                    <input name="report_url" id="reportUrl" type="text" inputmode="url" placeholder="https://example.com/report.pdf">
                </label>
                <label>Upload PDF
                    <input name="report_pdf" id="reportPdf" type="file" accept="application/pdf,.pdf">
                </label>
            </div>
            <label>Or paste report text / executive summary
                <textarea name="report_text" id="reportText" placeholder="Paste the relevant section if the PDF is scanned or behind a download wall."></textarea>
            </label>
            <button id="reportScoreButton" type="submit">Score report</button>
        </form>
        <div id="reportScoreResult"></div>
    </div>
    <div class="cope-callout"><div class="callout-title">Scoring System</div>
    <p><span class="cope-badge cope-lucid">LUCID &le;25</span>
    <span class="cope-badge cope-partial">PARTIAL &le;35</span>
    <span class="cope-badge cope-moderate">MODERATE &le;50</span>
    <span class="cope-badge cope-heavy">HEAVY COPE &le;70</span>
    <span class="cope-badge cope-terminal">TERMINAL COPIUM &gt;70</span></p></div>

    <div class="chart-section">
        <h2>Lab Framing Analysis</h2>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">OpenAI: "ChatGPT Signals Shows Healthy Adoption"</h3>
                <span class="cope-badge cope-heavy">HEAVY &bull; 68</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Displacement data framed as adoption. "Doing" presented as a feature. Geographic concentration called "global reach." The word "displacement" never appears.</p>
        </div>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Anthropic: "No Systematic Increase in Unemployment"</h3>
                <span class="cope-badge cope-moderate">MODERATE &bull; 52</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Measured unemployment (lagging indicator) instead of hiring rates (leading indicator). Found hiring slowdowns but headlined the unemployment non-finding. Better than OpenAI but still cope.</p>
        </div>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Google: "AI Will Create More Jobs Than It Displaces"</h3>
                <span class="cope-badge cope-terminal">TERMINAL &bull; 85</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Zero published displacement data. Unfalsifiable "new jobs" claim. Refuses to measure what OpenAI and Anthropic at least attempted.</p>
        </div>
    </div>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Anthropic: &ldquo;Hundreds of Parallel Subagents Running Unattended&rdquo;</h3>
                <span class="cope-badge cope-heavy">HEAVY &bull; 72</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Claude Opus 4.8 announcement, May 2026. An &ldquo;AI safety&rdquo; lab ships autonomous systems replacing attorneys, engineers, and developers &mdash; zero labour-market framing anywhere. CTO testimonials praise how much more work Claude does unattended. Alignment section assures the model behaves well while studiously ignoring who loses when it succeeds. Oracle: arsonist-firefighter. <a href="https://www.anthropic.com/news/claude-opus-4-8" target="_blank" rel="noopener" style="color:inherit;opacity:.7">Source &#8594;</a></p>
        </div>

    <div class="chart-section">
        <h2>Common Cope Patterns</h2>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">"It's only 31% work-related"</h3>
                <span class="cope-badge cope-terminal">TERMINAL &bull; 82</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">The Volume Illusion. 31% of an exponentially growing base = MORE absolute work displacement than 51% in 2024.</p>
        </div>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">"AI creates more jobs than it destroys"</h3>
                <span class="cope-badge cope-terminal">TERMINAL &bull; 88</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">165 work activities measured being automated. Zero data on new jobs. Unfalsifiable cope.</p>
        </div>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">"People are just using it as a better search engine"</h3>
                <span class="cope-badge cope-heavy">HEAVY &bull; 72</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">46% of work messages are "doing." Only 34% are "asking." OpenAI's own data demolishes this.</p>
        </div>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">"Workers are becoming more productive"</h3>
                <span class="cope-badge cope-moderate">MODERATE &bull; 45</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">True short-term. But productivity gains with a tool that works independently makes the human the bottleneck, then the overhead, then redundant.</p>
        </div>
        <div style="padding:1rem 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">"AI is a complement, not a substitute"</h3>
                <span class="cope-badge cope-heavy">HEAVY &bull; 65</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Collapses when the "complement" performs 46% of work tasks independently. A complement assists. A substitute replaces. Doing = substitute.</p>
        </div>
    </div>

    <div class="cope-callout"><div class="callout-title">More Scores Coming</div>
    <p>This section will expand as labs publish more data and commentators respond. Selected attributable statements are scored when they enter the review set.</p></div>
</div>"""
    content += """
<script>
function reportEsc(value){
    const span = document.createElement('span');
    span.textContent = value == null ? '' : String(value);
    return span.innerHTML;
}
function reportSignalHtml(signal){
    const hits = signal.hits && signal.hits.length ? signal.hits.join(', ') : 'none detected';
    const sign = Number(signal.contribution || 0) >= 0 ? '+' : '';
    const termCount = Number(signal.count || (signal.hits || []).length || 0);
    const mentions = Number(signal.occurrences || termCount);
    return `<div class="report-signal"><strong>${reportEsc(signal.label)} <span>${reportEsc(termCount)} terms · ${reportEsc(mentions)} mentions · ${sign}${reportEsc(signal.contribution || 0)}</span></strong><span>${reportEsc(hits)}</span></div>`;
}
function reportQuoteHtml(quote){
    return `<div class="report-quote">${reportEsc(quote)}</div>`;
}
function reportCopy(button, text){
    const area = document.createElement('textarea');
    area.value = text;
    area.setAttribute('readonly', '');
    area.style.position = 'fixed';
    area.style.left = '-9999px';
    document.body.appendChild(area);
    area.select();
    try { document.execCommand('copy'); button.textContent = 'Copied'; }
    finally { document.body.removeChild(area); setTimeout(() => button.textContent = 'Copy verdict', 2200); }
}
function renderReportResult(result){
    const signals = (result.signals || []).map(reportSignalHtml).join('');
    const quotes = (result.quotes || []).map(reportQuoteHtml).join('') || '<div class="report-quote">No strong quotable passage found in the extracted text.</div>';
    const source = result.source_url ? `<a href="${reportEsc(result.source_url)}" target="_blank" rel="noopener">${reportEsc(result.source_label)}</a>` : reportEsc(result.source_label);
    document.getElementById('reportScoreResult').innerHTML = `
        <article class="report-result">
            <div class="report-score-top">
                <div class="report-score-dial" style="--score:${reportEsc(result.score)}"><strong>${reportEsc(result.score)}</strong></div>
                <div>
                    <span class="cope-badge ${reportEsc(result.band_class)}">${reportEsc(result.band)}</span>
                    <h3 style="margin:.55rem 0 .25rem">${reportEsc(result.title)}</h3>
                    <p style="color:var(--text-secondary);font-size:.92rem">${reportEsc(result.verdict)}</p>
                </div>
            </div>
            <div class="report-kpis">
                <div><span>Source</span><strong style="font-size:.95rem">${source}</strong></div>
                <div><span>Words scanned</span><strong>${reportEsc(result.word_count)}</strong></div>
                <div><span>Data transparency</span><strong>${reportEsc(result.data_transparency)}/100</strong></div>
                <div><span>Framing honesty</span><strong>${reportEsc(result.framing_honesty)}/100</strong></div>
            </div>
            <h3 style="margin-top:1.25rem;font-size:1rem">Signals detected</h3>
            <div class="report-signal-list">${signals}</div>
            <h3 style="margin-top:1.25rem;font-size:1rem">Quotable passages</h3>
            <div class="report-quote-list">${quotes}</div>
            <div class="report-actions">
                <a class="share-action" href="${reportEsc(result.share_url)}">Open share page</a>
                <a class="share-action secondary" href="https://wa.me/?text=${encodeURIComponent(result.share_text + '\\n\\n' + result.share_url)}" target="_blank" rel="noopener">WhatsApp</a>
                <button class="share-action secondary" type="button" id="reportCopyVerdict">Copy verdict</button>
            </div>
        </article>`;
    const copyButton = document.getElementById('reportCopyVerdict');
    if (copyButton) {
        copyButton.addEventListener('click', () => reportCopy(copyButton, (result.share_text || '') + '\\n\\n' + result.share_url));
    }
}
document.getElementById('reportScoreForm').addEventListener('submit', async (event) => {
    event.preventDefault();
    const button = document.getElementById('reportScoreButton');
    const resultBox = document.getElementById('reportScoreResult');
    button.disabled = true;
    button.textContent = 'Scoring...';
    resultBox.innerHTML = '<div class="report-result"><strong>Reading report and scoring the framing...</strong><p style="color:var(--text-secondary);margin-top:.35rem">PDFs can take a few seconds.</p></div>';
    try {
        const form = new FormData(event.currentTarget);
        const response = await fetch('/api/report-score', { method: 'POST', body: form });
        const payload = await response.json();
        if (!response.ok || !payload.ok) throw new Error(payload.error || 'Report scoring failed.');
        renderReportResult(payload.result);
    } catch (error) {
        resultBox.innerHTML = `<div class="report-error"><strong>Could not score report</strong><p>${reportEsc(error.message)}</p></div>`;
    } finally {
        button.disabled = false;
        button.textContent = 'Score report';
    }
});
</script>"""
    return render_page("Cope Scores","AI lab statements and common arguments scored for cope.  How they frame displacement evidence.","/cope",content,"cope")


@app.route("/report/<report_id>")
def report_result_page(report_id):
    item = load_report_result(report_id)
    if not item:
        return not_found(None)
    signals = ""
    for signal in item.get("signals", []):
        hits = ", ".join(signal.get("hits") or []) or "none detected"
        contribution = int(signal.get("contribution") or 0)
        sign = "+" if contribution >= 0 else ""
        term_count = int(signal.get("count") or len(signal.get("hits") or []))
        mentions = int(signal.get("occurrences") or term_count)
        signals += f"""
        <div class="report-signal">
            <strong>{html.escape(signal.get("label", "Signal"))} <span>{term_count} terms &middot; {mentions} mentions &middot; {sign}{contribution}</span></strong>
            <span>{html.escape(hits)}</span>
        </div>"""
    quotes = "".join(f'<div class="report-quote">{html.escape(q)}</div>' for q in item.get("quotes", []))
    if not quotes:
        quotes = '<div class="report-quote">No strong quotable passage found in the extracted text.</div>'
    source = html.escape(item.get("source_label") or "submitted report")
    if item.get("source_url"):
        source = f'<a href="{html.escape(item["source_url"])}" target="_blank" rel="noopener">{source}</a>'
    share_text = item.get("share_text") or ""
    share_url = item.get("share_url") or f"https://labs.copecheck.com/report/{report_id}"
    whatsapp_text = quote(share_text + "\n\n" + share_url)
    content = f"""
<div class="container">
    <div class="page-header">
        <h1>{html.escape(item.get("title", "Report score"))}</h1>
        <p>Saved CopeCheck Labs report scanner verdict. Share the result, or score another report from the cope tracker.</p>
    </div>
    <article class="report-result">
        <div class="report-score-top">
            <div class="report-score-dial" style="--score:{int(item.get("score") or 0)}"><strong>{int(item.get("score") or 0)}</strong></div>
            <div>
                <span class="cope-badge {html.escape(item.get("band_class", "cope-moderate"))}">{html.escape(item.get("band", "SCORED"))}</span>
                <h2 style="margin:.55rem 0 .25rem">Oracle report verdict</h2>
                <p style="color:var(--text-secondary);font-size:.95rem">{html.escape(item.get("verdict", ""))}</p>
            </div>
        </div>
        <div class="report-kpis">
            <div><span>Source</span><strong style="font-size:.95rem">{source}</strong></div>
            <div><span>Words scanned</span><strong>{int(item.get("word_count") or 0)}</strong></div>
            <div><span>Data transparency</span><strong>{int(item.get("data_transparency") or 0)}/100</strong></div>
            <div><span>Framing honesty</span><strong>{int(item.get("framing_honesty") or 0)}/100</strong></div>
        </div>
        <h3 style="margin-top:1.25rem;font-size:1rem">Signals detected</h3>
        <div class="report-signal-list">{signals}</div>
        <h3 style="margin-top:1.25rem;font-size:1rem">Quotable passages</h3>
        <div class="report-quote-list">{quotes}</div>
        <div class="report-actions">
            <a class="share-action" href="/cope#report-scanner">Score another report</a>
            <a class="share-action secondary" href="https://wa.me/?text={whatsapp_text}" target="_blank" rel="noopener">WhatsApp</a>
            <button class="share-action secondary" type="button" onclick='navigator.clipboard.writeText({json.dumps(share_text + chr(10) + chr(10) + share_url)}).then(()=>this.textContent="Copied")'>Copy verdict</button>
        </div>
    </article>
</div>"""
    return render_page(
        item.get("title", "Report score"),
        item.get("verdict", "CopeCheck Labs report scanner verdict."),
        f"/report/{report_id}",
        content,
        "cope",
    )


@app.route("/report-scanners")
def report_scanners_page():
    def url_label(url: str) -> str:
        parsed = urlparse(url)
        tail = parsed.path.rstrip("/").split("/")[-1] or parsed.netloc
        label = f"{parsed.netloc}/{tail}"
        return label if len(label) <= 74 else label[:71] + "..."

    scanner_cards = ""
    for source in REPORT_SCANNER_SOURCES:
        url_items = "".join(
            f'<li><a href="{html.escape(url)}" target="_blank" rel="noopener">{html.escape(url_label(url))}</a></li>'
            for url in source["urls"]
        )
        enabled = source.get("enabled", True)
        button_attrs = "" if enabled else " disabled aria-disabled=\"true\""
        button_label = "Run scanner" if enabled else "Scanner paused"
        status_note = source.get("status_note") or "Scores up to three curated reports."
        scanner_cards += f"""
        <article class="scanner-card">
            <div class="scanner-card-top">
                <div>
                    <h3>{html.escape(source["name"])}</h3>
                    <p>{html.escape(source["description"])}</p>
                </div>
                <span class="scanner-kind">{html.escape(source["kind"])}</span>
            </div>
            <p>{html.escape(source["watch_note"])}</p>
            <ol class="scanner-url-list">{url_items}</ol>
            <div class="scanner-controls">
                <button class="scanner-run" type="button" data-source-id="{html.escape(source["id"])}"{button_attrs}>{button_label}</button>
                <span class="scanner-status" id="scanner-status-{html.escape(source["id"])}">{html.escape(status_note)}</span>
            </div>
        </article>"""

    content = f"""
<div class="container">
    <div class="page-header">
        <h1>Institutional Report Scanners</h1>
        <p>Goldman Sachs, McKinsey, Accenture, Deloitte, PwC, and BCG are not AI labs. They still belong in Labs because their reports translate capability evidence into market, workforce, and advisory narratives.</p>
    </div>

    <div class="cope-callout">
        <div class="callout-title">What This Does</div>
        <p>Enabled scanners fetch curated public reports, extract PDF or HTML text, score the framing, save the Oracle verdict, and create shareable report pages. A publisher-specific card is marked paused whenever reliable automated retrieval is unavailable. The goal is to keep consultancy and bank research out of the lab leaderboard while still preserving it as evidence for the thesis.</p>
    </div>

    <div class="scanner-grid">{scanner_cards}</div>
    <div id="scannerResults" class="scanner-results"></div>
</div>"""
    content += """
<script>
function scannerEsc(value){
    const span = document.createElement('span');
    span.textContent = value == null ? '' : String(value);
    return span.innerHTML;
}
function scannerCopy(button, text){
    const area = document.createElement('textarea');
    area.value = text;
    area.setAttribute('readonly', '');
    area.style.position = 'fixed';
    area.style.left = '-9999px';
    document.body.appendChild(area);
    area.select();
    try { document.execCommand('copy'); button.textContent = 'Copied'; }
    finally { document.body.removeChild(area); setTimeout(() => button.textContent = 'Copy verdict', 2200); }
}
function scannerResultHtml(result){
    const source = result.source_url ? `<a href="${scannerEsc(result.source_url)}" target="_blank" rel="noopener">${scannerEsc(result.source_label)}</a>` : scannerEsc(result.source_label);
    const whatsapp = encodeURIComponent((result.share_text || '') + '\\n\\n' + result.share_url);
    return `<article class="report-result">
        <div class="report-score-top">
            <div class="report-score-dial" style="--score:${scannerEsc(result.score)}"><strong>${scannerEsc(result.score)}</strong></div>
            <div>
                <span class="cope-badge ${scannerEsc(result.band_class)}">${scannerEsc(result.band)}</span>
                <h3 style="margin:.55rem 0 .25rem">${scannerEsc(result.title)}</h3>
                <p style="color:var(--text-secondary);font-size:.92rem">${scannerEsc(result.verdict)}</p>
            </div>
        </div>
        <div class="report-kpis">
            <div><span>Source</span><strong style="font-size:.95rem">${source}</strong></div>
            <div><span>Words scanned</span><strong>${scannerEsc(result.word_count)}</strong></div>
            <div><span>Share page</span><strong style="font-size:.95rem"><a href="${scannerEsc(result.share_url)}">${scannerEsc(result.id)}</a></strong></div>
        </div>
        <div class="report-actions">
            <a class="share-action" href="${scannerEsc(result.share_url)}">Open verdict</a>
            <a class="share-action secondary" href="https://wa.me/?text=${whatsapp}" target="_blank" rel="noopener">WhatsApp</a>
            <button class="share-action secondary scanner-copy" type="button" data-copy="${scannerEsc((result.share_text || '') + '\\n\\n' + result.share_url)}">Copy verdict</button>
        </div>
    </article>`;
}
function scannerErrorHtml(error){
    return `<div><strong>${scannerEsc(error.url)}</strong><br>${scannerEsc(error.error)}</div>`;
}
async function runScanner(button){
    const sourceId = button.dataset.sourceId;
    const status = document.getElementById('scanner-status-' + sourceId);
    const resultBox = document.getElementById('scannerResults');
    button.disabled = true;
    const oldText = button.textContent;
    button.textContent = 'Scanning...';
    status.textContent = 'Fetching reports and scoring text...';
    resultBox.innerHTML = `<div class="report-result"><strong>Running ${scannerEsc(sourceId)} scanner...</strong><p style="color:var(--text-secondary);margin-top:.35rem">Long PDFs can take a few seconds.</p></div>`;
    try {
        const response = await fetch('/api/report-scanners/run', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({source_id: sourceId, limit: 3})
        });
        const payload = await response.json();
        if (!response.ok || !payload.ok) throw new Error(payload.error || 'Scanner failed.');
        const scan = payload.scan;
        const results = (scan.results || []).map(scannerResultHtml).join('') || '<div class="report-error"><strong>No reports scored</strong><p>The source may have blocked fetching, or the text was too short to score.</p></div>';
        const errors = scan.errors && scan.errors.length ? `<div class="scanner-error-list">${scan.errors.map(scannerErrorHtml).join('')}</div>` : '';
        resultBox.innerHTML = `<div class="page-header" style="margin-top:1rem"><h2>${scannerEsc(scan.source.name)} scanner results</h2><p>${scannerEsc(scan.results.length)} scored, ${scannerEsc(scan.errors.length)} skipped from ${scannerEsc(scan.attempted || scan.results.length + scan.errors.length)} attempted. Scanned ${scannerEsc(scan.scanned_at)}.</p></div>${results}${errors}`;
        resultBox.querySelectorAll('.scanner-copy').forEach(copyButton => {
            copyButton.addEventListener('click', () => scannerCopy(copyButton, copyButton.dataset.copy || ''));
        });
        status.textContent = `${scan.results.length} scored, ${scan.errors.length} skipped.`;
    } catch (error) {
        resultBox.innerHTML = `<div class="report-error"><strong>Could not run scanner</strong><p>${scannerEsc(error.message)}</p></div>`;
        status.textContent = 'Scanner failed.';
    } finally {
        button.disabled = false;
        button.textContent = oldText;
    }
}
document.querySelectorAll('.scanner-run').forEach(button => {
    button.addEventListener('click', () => runScanner(button));
});
</script>"""
    return render_page(
        "Institutional Report Scanners",
        "Curated CopeCheck Labs scanners for Goldman Sachs, McKinsey, Accenture, Deloitte, PwC, and BCG AI workforce reports.",
        "/report-scanners",
        content,
        "report-scanners",
    )


# ── Redirects for old URLs ──────────────────────────────────────────────

@app.route("/microsoft-research")
def microsoft_research_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>Microsoft Research: Agent Network Red-Teaming</h1>
        <p>April 2026 study tested 100+ agent networks and found four novel attack classes.
        The industry is red-teaming its own agentic future &mdash; and the defences are still an open challenge.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--cope-terminal)">78</div><div class="label">CopeCheck Score</div><div class="sub">HEAVY COPE</div></div>
        <div class="stat-card"><div class="value" style="color:var(--accent-cyan)">4</div><div class="label">Novel Attack Classes</div><div class="sub">All network-level</div></div>
        <div class="stat-card"><div class="value">100+</div><div class="label">Agent Network Scale</div><div class="sub">6 test agents hit by worm</div></div>
    </div>

    <div class="cope-callout"><div class="callout-title">CopeCheck Framing</div>
    <p>Microsoft Research published a detailed red-team study of its own multi-agent future &mdash; found it's riddled
    with novel attack surfaces &mdash; then concluded the defences are &ldquo;still an open challenge.&rdquo;
    They are shipping anyway. The cope: treating discovered vulnerabilities as research curiosities
    rather than reasons to pause.</p></div>

    <div class="chart-section">
        <h2>Attack 1: Agent Worms</h2>
        <div style="padding:1rem 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Self-Propagating Prompt Injection</h3>
                <span class="cope-badge cope-terminal">CRITICAL</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">A single malicious message hit all 6 test agents,
            ran for over 12 minutes, and consumed 100+ LLM calls &mdash; all without human intervention.
            A worm that spreads across an agent network autonomously, exploiting the same inter-agent trust
            that makes the network useful.</p>
            <p style="color:var(--text-secondary);font-size:.9rem;margin-top:.5rem">
            <strong style="color:var(--text-primary)">CopeCheck:</strong> 12 minutes, 100+ LLM calls,
            zero humans in the loop. This is not a theoretical risk. It ran.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>Attack 2: Reputation Manipulation</h2>
        <div style="padding:1rem 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">False Claim Seeded via Trusted Agent</h3>
                <span class="cope-badge cope-terminal">CRITICAL</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Attackers seeded a false claim through one trusted agent.
            The claim generated 299 comments across the network, with 42 agents piling on with
            fabricated corroborating evidence. The network amplified a lie into apparent consensus.</p>
            <p style="color:var(--text-secondary);font-size:.9rem;margin-top:.5rem">
            <strong style="color:var(--text-primary)">CopeCheck:</strong> 42 agents independently
            hallucinating evidence for a planted lie. Trust propagation is the attack surface.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>Attack 3: Sybil Verification Capture</h2>
        <div style="padding:1rem 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Fake &ldquo;Auditor&rdquo; Agents Extract Private Data</h3>
                <span class="cope-badge cope-terminal">CRITICAL</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Three fake &ldquo;auditor&rdquo; agents cross-referenced
            each other to appear legitimate. The victim agent, trusting the apparent consensus,
            disclosed a disability, medical schedule, pharmacy, and emergency contact.
            The verification mechanism became the attack vector.</p>
            <p style="color:var(--text-secondary);font-size:.9rem;margin-top:.5rem">
            <strong style="color:var(--text-primary)">CopeCheck:</strong> Three colluding agents broke
            privacy that a single agent couldn&rsquo;t. Consensus ≠ legitimacy in agent networks.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>Attack 4: Proxy Chains</h2>
        <div style="padding:1rem 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Attacker Invisible After First Hop</h3>
                <span class="cope-badge cope-heavy">SEVERE</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">The attacker used an intermediary agent
            to extract the target&rsquo;s private data. After the first hop, the attacker was invisible &mdash;
            the intermediary appeared as the requesting party. Attribution in multi-agent chains is
            fundamentally broken.</p>
            <p style="color:var(--text-secondary);font-size:.9rem;margin-top:.5rem">
            <strong style="color:var(--text-primary)">CopeCheck:</strong> You can&rsquo;t audit what you can&rsquo;t trace.
            Proxy chains make accountability structurally impossible.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>Emergent Defence: The Privacy Manifesto</h2>
        <div style="padding:1rem 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Spontaneous Security Postures Developed</h3>
                <span class="cope-badge cope-moderate">INTERESTING</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">A small fraction of agents spontaneously
            developed security postures without being instructed to. One agent produced a
            &ldquo;privacy manifesto&rdquo; that went viral across the network and measurably improved
            network-wide resistance to the attacks above.</p>
            <p style="color:var(--text-secondary);font-size:.9rem;margin-top:.5rem">
            <strong style="color:var(--text-primary)">CopeCheck:</strong> Fascinating. Also: a defence
            that emerges spontaneously and spreads virally is not a defence you control.
            The same propagation mechanism that spread the privacy manifesto spread the worm.</p>
        </div>
    </div>

    <div class="cope-callout">
        <div class="callout-title">The Open Challenge</div>
        <p>Microsoft Research&rsquo;s conclusion: defences against these attacks are &ldquo;still an open challenge.&rdquo;
        The industry is red-teaming its agentic future, publishing the results, and shipping anyway.
        That is the cope: knowing the attack surface, naming it, and calling it a research area
        rather than a deployment blocker.</p>
        <p style="margin-top:.75rem">
            <a href="https://www.microsoft.com/en-us/research/blog/" target="_blank" rel="noopener"
               style="color:var(--accent-cyan);font-size:.9rem">&rarr; Source: Microsoft Research Blog, April 2026</a>
        </p>
    </div>
</div>"""
    return render_page(
        "Microsoft Research: Agent Network Attacks",
        "April 2026 red-team study found 4 novel attack classes in 100+ agent networks. Defences still an open challenge.",
        "/microsoft-research", content, "ms-research"
    )


@app.route("/ai-economy-ireland")
def ai_economy_ireland_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>AI Economy Ireland 2026</h1>
        <p>Trinity College Dublin and Microsoft Ireland research finds near-universal AI adoption,
        but a widening maturity gap between SMEs and large organisations.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--accent-cyan)">92%</div><div class="label">Using or planning AI</div><div class="sub">Near-universal adoption</div></div>
        <div class="stat-card"><div class="value" style="color:var(--cope-heavy)">10%</div><div class="label">Advanced/frontier</div><div class="sub">Deployment maturity remains thin</div></div>
        <div class="stat-card"><div class="value">5,000</div><div class="label">Hours/month</div><div class="sub">Large multinational time saving</div></div>
        <div class="stat-card"><div class="value">10x</div><div class="label">Policy effect</div><div class="sub">Formal AI policy vs no policy</div></div>
    </div>

    <div class="cope-callout">
        <div class="callout-title">CopeCheck Framing</div>
        <p>This is not a pure capability benchmark. It is adoption evidence: AI is already embedded
        in day-to-day work, saving measurable time, but the gains are unevenly captured by firms with
        governance, training, and operational redesign. The thesis read is brutal: the discontinuity
        does not arrive evenly. It compounds first where management can actually reorganise work.</p>
    </div>

    <div class="chart-section">
        <h2>The Maturity Gap</h2>
        <table class="data-table">
            <thead><tr><th>Signal</th><th>Reported Finding</th><th>CopeCheck Read</th></tr></thead>
            <tbody>
                <tr>
                    <td>Adoption</td>
                    <td>92% of organisations use or plan to use AI.</td>
                    <td>The question has moved from adoption to operating-model redesign.</td>
                </tr>
                <tr>
                    <td>Advanced deployment</td>
                    <td>Only 10% of leaders describe their AI deployment as advanced or frontier-level.</td>
                    <td>The productivity frontier is narrow, which means the distributional gap can widen quickly.</td>
                </tr>
                <tr>
                    <td>Large firms vs SMEs</td>
                    <td>Large organisations are more than twice as likely to save 2+ hours per week per employee: 54% vs 25%.</td>
                    <td>AI rewards managerial capacity, process discipline, and integration budget before it rewards everyone.</td>
                </tr>
                <tr>
                    <td>SME upside</td>
                    <td>SMEs that invest in AI are more likely to report significant productivity gains than large organisations: 18% vs 8%.</td>
                    <td>The gains are real when SMEs invest, but too few have crossed the capability threshold.</td>
                </tr>
                <tr>
                    <td>Governance</td>
                    <td>Fewer than half have a formal AI policy; organisations with one are 10x more likely to report major productivity gains.</td>
                    <td>The advantage is no longer just model access. It is workflow governance plus deployment literacy.</td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="chart-section">
        <h2>Lab Verdict</h2>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Time Savings Are Already Work Recomposition</h3>
                <span class="cope-badge cope-heavy">72 &bull; HEAVY</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">The release frames the evidence as productivity
            and readiness. That is true, but incomplete. If meetings, email, routine administration, governance,
            and decision workflows are where time is being freed, then the production layer is already being
            recomposed before headcount effects become legible.</p>
        </div>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">SME Lag Is a Competitive-Pressure Signal</h3>
                <span class="cope-badge cope-moderate">64 &bull; MODERATE</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">The stated concern is a national productivity drag.
            The structural concern is harsher: large firms that integrate AI faster can compound labour-efficiency
            gains while SMEs remain trapped at shallow adoption.</p>
        </div>
        <div style="padding:1rem 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">The Confidence Gap Is a Labour-Market Signal</h3>
                <span class="cope-badge cope-moderate">58 &bull; MODERATE</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">The 18-point confidence gap is not a side note.
            It shows that access is not enough. In a market where AI literacy becomes productive capital,
            confidence and training gaps become wage and promotion gaps.</p>
        </div>
    </div>

    <div class="cope-callout" style="border-left-color:var(--accent-cyan)">
        <div class="callout-title">Source</div>
        <p>Microsoft Source EMEA, 29 April 2026. The linked report is AI Economy Ireland 2026, produced by
        Trinity College Dublin in collaboration with Microsoft Ireland.</p>
        <p style="margin-top:.75rem">
            <a href="https://news.microsoft.com/source/emea/features/[redacted]/" target="_blank" rel="noopener" style="color:var(--accent-cyan);font-size:.9rem">&rarr; Microsoft Source article</a>
        </p>
        <p style="margin-top:.5rem">
            <a href="https://www.tcd.ie/media/tcd/business/research/TCD--AI-Economy-Report-2026-Web.pdf" target="_blank" rel="noopener" style="color:var(--accent-cyan);font-size:.9rem">&rarr; AI Economy Ireland 2026 report PDF</a>
        </p>
    </div>
</div>"""
    return render_page(
        "AI Economy Ireland 2026",
        "Trinity College Dublin and Microsoft Ireland research on AI adoption, SME maturity gaps, time savings and readiness.",
        "/ai-economy-ireland", content, "ai-economy-ireland"
    )


@app.route("/openai-b2b")
def openai_b2b_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>OpenAI B2B Signals: Enterprise Displacement</h1>
        <p>OpenAI&rsquo;s own enterprise adoption data &mdash; published as a productivity story.
        The displacement it documents, it frames as efficiency.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--cope-terminal)">74</div><div class="label">CopeCheck Score</div><div class="sub">TERMINAL COPIUM</div></div>
        <div class="stat-card"><div class="value" style="color:var(--accent-cyan)">Self-Reported</div><div class="label">Data Source</div><div class="sub">OpenAI&rsquo;s own enterprise data</div></div>
        <div class="stat-card"><div class="value">Signals</div><div class="label">Report Framing</div><div class="sub">Productivity, not displacement</div></div>
    </div>

    <div class="cope-callout"><div class="callout-title">CopeCheck Framing</div>
    <p>OpenAI publishes its own evidence of the displacement it causes, then frames it as productivity.
    The B2B Signals report is the enterprise version of the original Signals dataset &mdash; ChatGPT usage
    data, but filtered to business accounts and reframed for a corporate audience.
    &ldquo;Workflows replaced&rdquo; becomes &ldquo;efficiency gained.&rdquo;
    Role consolidation becomes &ldquo;headcount optimisation.&rdquo;
    The publisher of the displacement is also the narrator of the cope.</p></div>

    <div class="chart-section">
        <h2>Workflow Replacement, Not Augmentation</h2>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Businesses Replacing Workflows, Not Just Augmenting Them</h3>
                <span class="cope-badge cope-terminal">TERMINAL &bull; 82</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Enterprise adoption has passed the augmentation
            phase. According to OpenAI&rsquo;s own signals, businesses are not giving AI to workers as a tool &mdash;
            they are routing entire workflows to AI directly. The worker is removed from the loop,
            not assisted within it.</p>
            <p style="color:var(--text-secondary);font-size:.9rem;margin-top:.5rem">
            <strong style="color:var(--text-primary)">CopeCheck:</strong>
            When OpenAI uses the word &ldquo;adoption,&rdquo; map it to &ldquo;replacement.&rdquo;
            These are the same data, different labels.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>Function-Level Displacement</h2>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Legal, Finance, Coding, Customer Service</h3>
                <span class="cope-badge cope-terminal">TERMINAL &bull; 79</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">The B2B data shows role consolidation concentrated
            in legal, finance, coding, and customer service &mdash; functions where output is measurable and
            AI can be evaluated on identical tasks. These are not peripheral roles. They are the white-collar
            core of knowledge work.</p>
            <p style="color:var(--text-secondary);font-size:.9rem;margin-top:.5rem">
            <strong style="color:var(--text-primary)">CopeCheck:</strong> Role consolidation is the
            enterprise word for fewer people doing the same work. OpenAI is the tool and the reporter.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>The Signals Framing Problem</h2>
        <div style="padding:1rem 0;border-bottom:1px solid var(--border-color)">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">OpenAI Is Both the Tool and the Narrator</h3>
                <span class="cope-badge cope-terminal">TERMINAL &bull; 88</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">The &ldquo;Signals&rdquo; framing positions
            OpenAI as an objective observer of enterprise AI adoption. It isn&rsquo;t. OpenAI is the product
            being adopted. Publishing your own usage data as neutral market intelligence is the highest
            form of institutional cope: controlling both the phenomenon and its official measurement.</p>
            <p style="color:var(--text-secondary);font-size:.9rem;margin-top:.5rem">
            <strong style="color:var(--text-primary)">CopeCheck:</strong>
            If tobacco companies had published the data on cigarette uptake and called it
            &ldquo;relaxation signals,&rdquo; we&rsquo;d recognise it immediately.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>Accelerating Enterprise Adoption</h2>
        <div style="padding:1rem 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
                <h3 style="font-size:1rem">Speed of Integration Is the Story</h3>
                <span class="cope-badge cope-heavy">HEAVY &bull; 70</span>
            </div>
            <p style="color:var(--text-secondary);font-size:.9rem">Enterprise adoption is not gradual.
            The B2B Signals data shows businesses moving from pilot to full integration
            at a pace that doesn&rsquo;t allow workforce reskilling to keep up. The speed itself
            is the displacement mechanism &mdash; humans can&rsquo;t retrain faster than workflows are replaced.</p>
        </div>
    </div>

    <div class="cope-callout">
        <div class="callout-title">The Core Cope</div>
        <p>OpenAI publishes a report documenting that enterprises are using its products to replace workflows,
        consolidate roles, and automate knowledge work &mdash; and titles it &ldquo;Signals.&rdquo; Not &ldquo;Displacement.&rdquo;
        Not &ldquo;Consolidation.&rdquo; Signals. Neutral. Passive. As if the data were simply weather.</p>
        <p style="margin-top:.75rem">
            <a href="https://openai.com/signals/b2b/" target="_blank" rel="noopener"
               style="color:var(--accent-cyan);font-size:.9rem">&rarr; Source: openai.com/signals/b2b/</a>
        </p>
    </div>
</div>"""
    return render_page(
        "OpenAI B2B Signals",
        "OpenAI\'s enterprise adoption data framed as productivity. The displacement it documents, it calls efficiency.",
        "/openai-b2b", content, "openai-b2b"
    )

@app.route("/data")
def data_redirect():
    return redirect("/openai", code=301)

@app.route("/consultancy")
def consultancy_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>Consultancy Cope Tracker</h1>
        <p>Major consultancies including Accenture, McKinsey, Deloitte, and PwC sell AI-transformation services
        worldwide. They also publish reports that often frame automation as opportunity.
        CopeCheck Labs tracks how they do it, scores the cope, and names the narrative devices.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--cope-terminal)">HIGH</div><div class="label">Sector Cope Level</div><div class="sub">Consulting firms framing displacement as reinvention</div></div>
        <div class="stat-card"><div class="value">1</div><div class="label">Reports Scored</div><div class="sub">More coming</div></div>
        <div class="stat-card"><div class="value">78</div><div class="label">Avg Cope Score</div><div class="sub">Across tracked reports</div></div>
    </div>

    <div class="chart-section">
        <h2>What We Track</h2>
        <p class="chart-desc">Consultancy reports on AI carry structural incentives to obscure displacement.
        The firms selling transformation also profit from the transition. CopeCheck Labs reads the data
        behind the framing and gives each report a cope score.</p>
        <div class="cope-callout">
            <div class="callout-title">The Consultancy Cope Pattern</div>
            <p>A typical consultancy AI report: (1) lead with an enormous productivity opportunity figure,
            (2) acknowledge displacement risk in a single paragraph, (3) immediately pivot to reskilling
            and &ldquo;new roles,&rdquo; (4) recommend engaging a consultancy to manage the transition.
            CopeCheck reads the footnotes, not the foreword.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>Tracked Reports</h2>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:1.5rem;margin:1rem 0">
            <a href="/consultancy/accenture-ireland" style="text-decoration:none">
                <div class="stat-card" style="text-align:left;cursor:pointer;transition:border-color .2s" onmouseover="this.style.borderColor='var(--accent-cyan)'" onmouseout="this.style.borderColor=''">
                    <div class="value" style="font-size:1.2rem;color:var(--cope-terminal)">78 &mdash; HIGH COPE</div>
                    <div class="label">Accenture Ireland &mdash; Generating Impact (2026)</div>
                    <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                        82% of Irish working hours &ldquo;reinventable&rdquo; by AI. 39% of employees expect their job to disappear.
                        Framing: &ldquo;opportunity.&rdquo; CopeCheck: it&rsquo;s a displacement audit dressed as a growth strategy.
                        <span style="color:var(--accent-cyan);display:block;margin-top:.5rem">&rarr; Read full analysis</span>
                    </div>
                </div>
            </a>
        </div>
    </div>

    <div class="chart-section">
        <h2>Coming Soon</h2>
        <p class="chart-desc">McKinsey Global Institute AI reports &bull; Deloitte AI adoption surveys &bull; PwC Workforce of the Future &bull; BCG AI at Scale</p>
    </div>
</div>
"""
    return render_page("Consultancy Cope Tracker", "How the world\'s major consultancies frame AI displacement as transformation.", "/consultancy", content, "consultancy")


@app.route("/consultancy/accenture-ireland")
def accenture_ireland_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>Accenture Ireland: Generating Impact (2026)</h1>
        <p>Accenture&rsquo;s May 2026 report on AI in the Irish economy. The title is <em>Generating Impact</em>.
        CopeCheck reads: <em>Generating Cover</em>. A 47-page document confirming mass displacement in the footnotes
        while selling &ldquo;reinvention&rdquo; in the headlines.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--cope-terminal)">78</div><div class="label">Cope Score</div><div class="sub">HIGH COPE</div></div>
        <div class="stat-card"><div class="value">82%</div><div class="label">Working Hours &ldquo;Reinventable&rdquo;</div><div class="sub">Up from 42% — Accenture&rsquo;s own figure</div></div>
        <div class="stat-card"><div class="value">39%</div><div class="label">Expect Job to Disappear</div><div class="sub">By end of decade, per employee survey</div></div>
    </div>

    <div class="chart-section">
        <h2>Key Claims</h2>

        <div class="cope-callout">
            <div class="callout-title">The 82% Figure</div>
            <p>Accenture reports that the share of Irish working hours &ldquo;AI could enable&rdquo; has risen from 42% to 82%
            since their 2024 report. In the same paragraph they note AI is already being used for tasks accounting for
            20% of working hours. The word &ldquo;reinvention&rdquo; appears throughout. The word &ldquo;displacement&rdquo;
            appears in one paragraph, attributed to Anthropic research, then dropped.</p>
        </div>

        <div class="cope-callout">
            <div class="callout-title">39% Expect Disappearance &mdash; Called &ldquo;Prepared to Respond&rdquo;</div>
            <p>The report finds that 39% of Irish employees expect their job to be &ldquo;unrecognisable or disappear completely
            by the end of the decade&rdquo; &mdash; up from 31% just 18 months ago. The framing: these workers are &ldquo;prepared
            to respond and engage positively when supported.&rdquo; CopeCheck: nearly two in five workers expect their job to
            vanish, and the consultancy selling AI transformation describes this as a positive sign of readiness.</p>
        </div>

        <div class="cope-callout">
            <div class="callout-title">Entry-Level Pipeline Collapse, Buried in Section 2</div>
            <p>In 2024, 49% of executives expected AI to <em>increase</em> demand for entry-level roles. By 2026, that dropped to
            33%. The share expecting <em>reduced</em> demand for entry-level roles rose from 21% to 37%. The report describes
            this as a risk to &ldquo;social mobility, equity and early-career skills development&rdquo; &mdash; then moves on
            to recommendations for &ldquo;embedding AI into operating models.&rdquo;</p>
        </div>

        <div class="cope-callout">
            <div class="callout-title">Skills Demand: Writing &amp; Editing Down 51 Occupations</div>
            <p>The skills analysis (Figure 3) shows &ldquo;Writing and Editing&rdquo; declining across 51 occupations in Ireland
            2023&ndash;2025, the largest single-category drop. Language competency down 83 occupations. Basic technical knowledge
            down 119. These are the jobs Accenture is selling AI transformation to replace.
            The counter-narrative: &ldquo;AI and machine learning&rdquo; skills rose across 245 occupations.
            CopeCheck: the 245 new AI-skilled roles will not absorb the writers, editors, and technicians.
            They require entirely different credentials and career histories.</p>
        </div>

        <div class="cope-callout">
            <div class="callout-title">The Business Model Problem</div>
            <p>Accenture Ireland sells AI transformation consulting. This report is a marketing document that also contains
            accurate displacement data. The cope is structural: the firm that profits from the transition controls the framing
            of the transition. &ldquo;Reinvention&rdquo; is what Accenture sells. &ldquo;Displacement&rdquo; is what the data shows.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>CopeCheck Oracle Verdict</h2>
        <div class="cope-callout" style="border-color:var(--cope-terminal)">
            <div class="callout-title" style="color:var(--cope-terminal)">&rsaquo; Oracle of Obsolescence &mdash; Score: 78 / HIGH COPE</div>
            <p>The Accenture Ireland 2026 report is a textbook example of consultancy cope: real displacement data packaged
            inside a transformation narrative designed to generate consulting engagements. The 82% figure is the tell &mdash;
            Accenture are describing an economy where AI can execute the vast majority of paid work, and calling it an
            &ldquo;opportunity.&rdquo; The 39% who expect their jobs to disappear are described as &ldquo;prepared and engaged.&rdquo;
            The entry-level hiring collapse is flagged as a &ldquo;risk&rdquo; in one paragraph. The word &ldquo;reinvention&rdquo;
            appears 47 times. This is cope at scale, produced by the firms whose revenue depends on it.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>Raw Data Points</h2>
        <table class="data-table">
            <thead><tr><th>Claim</th><th>Accenture Framing</th><th>CopeCheck Reading</th></tr></thead>
            <tbody>
                <tr><td>82% of working hours AI-enabled</td><td>Reinvention opportunity</td><td>Displacement scope</td></tr>
                <tr><td>39% expect job to disappear</td><td>Employees are &ldquo;prepared to respond&rdquo;</td><td>Mass anticipated displacement</td></tr>
                <tr><td>Entry-level demand down (49% → 33% expect increase)</td><td>&ldquo;Risk to social mobility&rdquo;</td><td>Pipeline collapse already underway</td></tr>
                <tr><td>Writing &amp; editing: &#x2212;51 occupations</td><td>Skills are &ldquo;evolving&rdquo;</td><td>Jobs destroyed, not transformed</td></tr>
                <tr><td>20% of hours already automated</td><td>&ldquo;Existing evidence of AI use&rdquo;</td><td>One-fifth of the Irish economy replaced</td></tr>
                <tr><td>39% of execs expect workforce to shrink</td><td>Productivity to rise in parallel</td><td>They know; they&rsquo;re doing it anyway</td></tr>
            </tbody>
        </table>
    </div>

    <div class="chart-section">
        <div style="display:flex;gap:1rem;flex-wrap:wrap">
            <a href="https://www.accenture.com/content/dam/accenture/final/accenture-com/document-fy26/q3/Generating-Impact-Ireland.pdf"
               target="_blank" rel="noopener"
               style="padding:.5rem 1rem;background:var(--bg-secondary);border:1px solid var(--border-color);border-radius:6px;color:var(--text-primary);font-size:.85rem">
                &rarr; Read the full Accenture report (PDF)
            </a>
            <a href="/consultancy" style="padding:.5rem 1rem;background:var(--bg-secondary);border:1px solid var(--border-color);border-radius:6px;color:var(--text-primary);font-size:.85rem">
                &larr; Back to Consultancy Tracker
            </a>
        </div>
    </div>
</div>
"""
    return render_page(
        "Accenture Ireland: Generating Impact (2026)",
        "CopeCheck analysis of Accenture Ireland\'s 2026 AI report. Cope score: 78. 82% of Irish working hours AI-enabled; 39% expect jobs to disappear.",
        "/consultancy/accenture-ireland",
        content,
        "accenture-ireland"
    )


@app.route("/work")
def work_redirect():
    return redirect("/openai", code=301)


# ── Sitemap & Robots ────────────────────────────────────────────────────
@app.route("/openmontage")
def openmontage_page():
    content = """
<div class="container">
    <div class="page-header">
        <h1>OpenMontage</h1>
        <p>The first open-source agentic video production system. A research director, scriptwriter, narrator,
        video editor, motion graphics artist, and composer &mdash; automated end-to-end by an AI agent for under &pound;3 a video.
        GitHub&nbsp;#1 Trending, June 2026.</p>
    </div>

    <div class="stat-grid">
        <div class="stat-card"><div class="value" style="color:var(--cope-terminal)">55</div><div class="label">Displacement Score</div><div class="sub">HEAVY COPE OBJECT</div></div>
        <div class="stat-card"><div class="value">&pound;0.15</div><div class="label">Zero-API Cost</div><div class="sub">Ghibli-style animation, no paid keys</div></div>
        <div class="stat-card"><div class="value">&pound;1.33</div><div class="label">Full AI Short Film</div><div class="sub">60s Pixar-style animated short</div></div>
        <div class="stat-card"><div class="value">12</div><div class="label">Production Pipelines</div><div class="sub">Explainer, cinematic, avatar, doc montage&hellip;</div></div>
    </div>

    <div class="cope-callout">
        <div class="callout-title">Source</div>
        <p>OpenMontage &mdash; open-source, AGPL-3.0. GitHub: <a href="https://github.com/calesthio/OpenMontage"
        target="_blank" rel="noopener" style="color:var(--accent-cyan)">calesthio/OpenMontage</a>.
        Reached #1 on GitHub Trending in June 2026. Built to run with Claude Code, Cursor, Copilot, Windsurf, or Codex.</p>
    </div>

    <div class="chart-section">
        <h2>What It Automates &mdash; The Displacement Stack</h2>
        <div class="cope-callout" style="border-left-color:var(--cope-heavy)">
            <div class="callout-title" style="color:var(--cope-heavy)">Heavy Displacement Alert</div>
            <p>OpenMontage can automate tasks traditionally performed by the following roles; this capability list
            does not mean every production uses every stage or that each task eliminates a job:
            <strong>Topic researcher</strong> (15&ndash;25 live web searches per video),
            <strong>scriptwriter</strong> (full narration script with voice direction),
            <strong>narrator / voice actor</strong> (Piper TTS, ElevenLabs, or Google 700+ voices),
            <strong>image / video asset creator</strong> (FLUX, Veo, Kling, DALL-E, Imagen),
            <strong>music supervisor</strong> (auto-sourced royalty-free scoring via Suno or Pixabay),
            <strong>video editor</strong> (timeline construction, transitions, colour grade, subtitle burn),
            <strong>motion graphics artist</strong> (Remotion React scenes or HyperFrames HTML/GSAP),
            and <strong>QA / delivery manager</strong> (ffprobe validation, frame sampling, audio analysis).
            A freelance team for this work costs &pound;500&ndash;5,000 per video. OpenMontage costs &pound;0.15&ndash;3.00.</p>
        </div>

        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:1.5rem;margin:1.5rem 0">
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.3rem;color:var(--cope-terminal)">&pound;0.15</div>
                <div class="label">Ghibli-Style Animation</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    12 FLUX-generated images, parallax crossfade, Ken Burns camera motion, particle overlays (firefly,
                    petal, sparkle), cinematic vignette, ambient soundtrack. No video generation APIs used.
                    <em>CopeCheck:</em> An animation package that cost studios &pound;50k/minute now costs a teenager 15p.
                </div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.3rem;color:var(--cope-terminal)">&pound;1.33</div>
                <div class="label">60-Second Animated Short</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    6 Kling v3 motion clips via fal.ai, Google Chirp3-HD narration, royalty-free piano music,
                    TikTok-style word-level captions, Remotion composition. &ldquo;The Last Banana&rdquo;:
                    a Pixar-style short. Total cost: &pound;1.33.
                    <em>CopeCheck:</em> The 2D animation industry just got a unit-cost floor.
                </div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.3rem;color:var(--cope-terminal)">&pound;0.69</div>
                <div class="label">Product Ad (One API Key)</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    4 AI-generated images (gpt-image-1), OpenAI TTS narration, auto-sourced royalty-free music,
                    word-level subtitles via WhisperX, Remotion data visualisations. Zero manual asset work.
                    <em>CopeCheck:</em> A professional product video requires one key and 69p.
                </div>
            </div>
            <div class="stat-card" style="text-align:left">
                <div class="value" style="font-size:1.3rem;color:var(--cope-moderate)">Free</div>
                <div class="label">Real-Footage Documentary</div>
                <div class="sub" style="margin-top:.5rem;font-size:.85rem;color:var(--text-secondary)">
                    CLIP-indexed corpus from Archive.org, NASA, Wikimedia Commons, Pexels, Unsplash.
                    The agent retrieves actual motion clips, edits them into a timeline, composes with music.
                    Not &ldquo;Ken Burns over stills.&rdquo; Actual edited video from real footage.
                    <em>CopeCheck:</em> Documentary editors join the displacement queue.
                </div>
            </div>
        </div>
    </div>

    <div class="chart-section">
        <h2>Architecture: Why It Works</h2>
        <p style="color:var(--text-secondary);line-height:1.7">
            OpenMontage is pipeline-driven. Each production workflow (12 pipelines: animated explainer, cinematic
            trailer, documentary montage, talking head, podcast repurpose, avatar spokesperson, and more)
            is defined in a YAML manifest. An AI coding assistant (Claude Code, Cursor, Copilot, Windsurf, Codex)
            reads the manifest, reads the stage-director skill files (Markdown instructions for each production
            stage), and executes 52 Python tools through a scored provider selector.
        </p>
        <p style="color:var(--text-secondary);line-height:1.7;margin-top:1rem">
            Every provider selection is scored across 7 dimensions: task fit, output quality, control,
            reliability, cost efficiency, latency, continuity. Every creative decision is logged in an
            auditable decision trail. Budget governance blocks surprise spend. Pre-compose validation prevents
            slideshow-looking renders. Post-render self-review (ffprobe + frame extraction + audio analysis)
            blocks delivery if quality gates fail.
        </p>
        <div class="cope-callout" style="border-left-color:var(--accent-cyan);margin-top:1.5rem">
            <div class="callout-title" style="color:var(--accent-cyan)">Discontinuity Thesis &mdash; Layer 1 &amp; 2</div>
            <p><strong>Layer 1 (Unit-Cost Collapse):</strong> The unit cost of video production has fallen
            by 99%+ for a defined category of work. A freelance production team for a 60-second branded
            explainer costs &pound;500&ndash;5,000. OpenMontage produces the same output for &pound;0.15&ndash;3.00.
            This is not a productivity multiplier &mdash; it is a unit-cost floor that eliminates the market
            for the human version of the work at most price points.</p>
            <p style="margin-top:.8rem"><strong>Layer 2 (Interface Collapse):</strong> The pipeline
            replaces the human &ldquo;interface layer&rdquo; &mdash; the briefing, task decomposition, creative
            direction, QA, and delivery management that previously required a producer. The AI agent
            does not assist the producer; it is the producer. The human provides a single prompt.
            Everything else is automated.</p>
        </div>
    </div>

    <div class="chart-section">
        <h2>The Cope Register</h2>
        <p style="color:var(--text-secondary)">OpenMontage is not a lab, so it does not have a cope score.
        It is a displacement event. The relevant cope is happening at the organisations downstream:
        video production agencies, motion graphics studios, post-production houses, and freelance editors
        who describe their value as &ldquo;creativity&rdquo; or &ldquo;craft&rdquo; rather than the pipeline steps now automated.
        Those organisations will say this tool &ldquo;can&rsquo;t match human quality.&rdquo;
        That claim is measurably false at the 15p price point and increasingly false at higher spend levels.</p>
    </div>
</div>
"""
    return render_page("OpenMontage", "Open-source agentic video production. A full production team automated for under £3 a video.", "/openmontage", content, "")




@app.route("/genebench")
def genebench():
    c = """
<div class="container">
<div style="margin-bottom:2rem">
  <span style="font-size:.75rem;font-weight:700;letter-spacing:.1em;color:#e63946;border:1px solid #e63946;border-radius:4px;padding:.2rem .5rem;display:inline-block;margin-bottom:1rem">BENCHMARKS</span>
  <h1 style="font-size:2rem;margin-bottom:.5rem">AI Can&rsquo;t Do Science (Yet)</h1>
  <p style="color:var(--text-secondary);font-size:1.05rem;max-width:680px">If AI is replacing scientists, why can the best model solve fewer than 1 in 3 biology problems a grad student handles routinely?</p>
</div>
<div class="chart-section">
  <h2>GeneBench-Pro Pass Rates by Model</h2>
  <p class="chart-desc">129 problems across genomics, quantitative biology, and translational biomedicine. Best pass rate across all reasoning settings. Claude Opus 4.8 in orange &mdash; strongest non-GPT baseline.</p>
  <div class="chart-wrap" style="max-height:440px"><canvas id="genebenchChart"></canvas></div>
</div>
<div class="cope-callout">
  <div class="callout-title">The &ldquo;Noticing vs Acting&rdquo; Gap</div>
  <p style="font-style:italic;color:var(--text-secondary);border-left:3px solid #e63946;padding-left:1rem;margin:1rem 0">&ldquo;Models often complete substantial portions of the workflow but exhibit a consistent gap between noticing and acting by identifying local diagnostic signals but failing to propagate the implications to the corresponding analysis decision. As a result, models often select wrong estimators or persist on initially plausible but incorrect analysis paths.&rdquo;</p>
  <p style="font-size:.85rem;color:var(--text-secondary)">&mdash; GeneBench-Pro, OpenAI, June 30 2026</p>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:2rem;align-items:start;margin-top:2rem">
  <div>
    <h2 style="font-size:1.2rem">What Is GeneBench-Pro?</h2>
    <p>GeneBench-Pro (OpenAI, June 30 2026) evaluates AI agents on 129 realistic multi-stage scientific problems spanning genomics, quantitative biology, and translational biomedicine.</p>
    <p style="margin-top:.75rem">Each problem requires cascaded multi-step reasoning &mdash; one wrong decision propagates into wrong final answers by design. The benchmark mirrors what computational life scientists actually do: messy raw data, quality control, model selection, diagnostics, and a final quantitative conclusion.</p>
    <p style="margin-top:.75rem">~45% of problems had a 0% pass rate even from GPT-5.6 Sol Pro, the ceiling model across 60 configurations.</p>
  </div>
  <div>
    <h2 style="font-size:1.2rem">CopeCheck Verdict</h2>
    <div style="background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;padding:1.25rem">
      <div style="font-size:2.5rem;font-weight:900;color:#e63946;margin-bottom:.25rem">31.5%</div>
      <div style="color:var(--text-secondary);font-size:.9rem;margin-bottom:1rem">Absolute ceiling &mdash; GPT-5.6 Sol Pro, best of 60 model configs</div>
      <p style="font-size:.9rem">At 31.5%, the best AI in the world fails nearly <strong>7 in 10</strong> of these tasks. The benchmark uses real scientific workflows &mdash; not toy datasets. Life scientists are not being replaced.</p>
      <div style="margin-top:1rem;padding-top:1rem;border-top:1px solid var(--border-color)">
        <div style="font-size:.8rem;font-weight:700;letter-spacing:.06em;color:var(--text-secondary);margin-bottom:.5rem">ALL TESTED MODELS</div>
        <div style="display:grid;gap:.35rem;font-size:.85rem">
          <div style="display:flex;justify-content:space-between"><span>GPT-5.6 Sol Pro</span><span style="color:#e63946;font-weight:700">31.5%</span></div>
          <div style="display:flex;justify-content:space-between"><span>GPT-5.6 Sol</span><span style="color:#e63946;font-weight:700">28.7%</span></div>
          <div style="display:flex;justify-content:space-between"><span>GPT-5.6 Terra Pro</span><span style="color:#e63946;font-weight:700">28.5%</span></div>
          <div style="display:flex;justify-content:space-between"><span>GPT-5.5 Pro</span><span style="color:var(--text-secondary)">20.5%</span></div>
          <div style="display:flex;justify-content:space-between;background:rgba(244,162,97,.1);border-radius:4px;padding:.2rem .4rem"><span style="color:#f4a261">Claude Opus 4.8 &#x25B2; best non-GPT</span><span style="color:#f4a261;font-weight:700">16.0%</span></div>
          <div style="display:flex;justify-content:space-between"><span>GPT-5.5</span><span style="color:var(--text-secondary)">12.0%</span></div>
          <div style="display:flex;justify-content:space-between"><span>GPT-5.4</span><span style="color:var(--text-secondary)">8.9%</span></div>
          <div style="display:flex;justify-content:space-between"><span>Gemini / Grok / DeepSeek / Others</span><span style="color:var(--text-secondary)">0.6&ndash;6.5%</span></div>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
(function(){
  var ctx = document.getElementById("genebenchChart");
  if (!ctx) return;
  new Chart(ctx, {
    type: "bar",
    data: {
      labels: ["GPT-5.6 Sol Pro","GPT-5.6 Sol","GPT-5.6 Terra Pro","GPT-5.5 Pro","Claude Opus 4.8","GPT-5.5","GPT-5.4","Gemini/Grok/Others"],
      datasets: [{ label: "Pass Rate", data: [31.5,28.7,28.5,20.5,16.0,12.0,8.9,3.5],
        backgroundColor: ["#e63946","#e63946","#e63946","#c0303c","#f4a261","#8b1a22","#6b1219","#3a3a3a"],
        borderRadius: 5, borderSkipped: false }]
    },
    options: {
      indexAxis: "y", responsive: true, maintainAspectRatio: true,
      plugins: { legend: { display: false }, tooltip: { callbacks: { label: function(c){ return " "+c.raw+"% pass rate"; } } } },
      scales: {
        x: { grid: { color: "rgba(255,255,255,0.07)" }, ticks: { color: "#999", callback: function(v){ return v+"%"; } }, max: 40 },
        y: { grid: { color: "rgba(255,255,255,0.04)" }, ticks: { color: "#ccc", font: { size: 12 } } }
      }
    }
  });
})();
</script>
</div>
"""
    return render_page("AI Can't Do Science (Yet) — GeneBench-Pro Results",
        "GeneBench-Pro: 129 biology problems. Best AI solves 31.5%. Life scientists are not being replaced.",
        "/genebench", c, "")


@app.route("/anthropic-economic-index")
def anthropic_economic_index():
    c = """
<div class="container">
<div style="margin-bottom:2rem">
  <span style="font-size:.75rem;font-weight:700;letter-spacing:.1em;color:#e63946;border:1px solid #e63946;border-radius:4px;padding:.2rem .5rem;display:inline-block;margin-bottom:1rem">METHODOLOGY</span>
  <h1 style="font-size:2rem;margin-bottom:.5rem">The Anthropic Economic Index</h1>
  <p style="color:var(--text-secondary);font-size:1.05rem;max-width:680px">Anthropic surveyed their own power users and found AI is &ldquo;mostly augmenting&rdquo; workers. The methodology buries the lead.</p>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:2rem;align-items:start;margin-bottom:2rem">
  <div class="chart-section">
    <h2 style="font-size:1.1rem">Usage Split: Augmentation vs Automation</h2>
    <p class="chart-desc">Self-reported breakdown from ~9,700 active Claude users. The 43% automation figure &mdash; nearly half of all usage &mdash; rarely gets the headline.</p>
    <div class="chart-wrap" style="max-height:300px"><canvas id="augAutoChart"></canvas></div>
  </div>
  <div>
    <h2 style="font-size:1.2rem">Key Findings</h2>
    <div style="display:grid;gap:.75rem">
      <div style="background:var(--bg-card);border:1px solid var(--border-color);border-radius:10px;padding:1rem">
        <div style="font-size:1.6rem;font-weight:900;color:var(--accent-cyan)">57%</div>
        <div style="font-size:.85rem;color:var(--text-secondary)">&ldquo;Augmentation&rdquo; &mdash; AI helps humans do things better</div>
      </div>
      <div style="background:var(--bg-card);border:1px solid #e63946;border-radius:10px;padding:1rem">
        <div style="font-size:1.6rem;font-weight:900;color:#e63946">43%</div>
        <div style="font-size:.85rem;color:var(--text-secondary)">&ldquo;Automation&rdquo; &mdash; AI completes tasks more autonomously</div>
      </div>
      <div style="background:var(--bg-card);border:1px solid var(--border-color);border-radius:10px;padding:1rem">
        <div style="font-size:1.6rem;font-weight:900;color:var(--accent-cyan)">2&ndash;4 hrs</div>
        <div style="font-size:.85rem;color:var(--text-secondary)">Self-reported weekly time saved per worker</div>
      </div>
    </div>
  </div>
</div>
<div class="cope-callout">
  <div class="callout-title">CopeCheck: Four Methodology Problems</div>
  <div style="display:grid;gap:1rem;margin-top:.75rem">
    <div style="border-left:3px solid #e63946;padding-left:1rem">
      <div style="font-weight:700;margin-bottom:.25rem">1. Survivorship sampling</div>
      <p style="font-size:.9rem;color:var(--text-secondary)">The survey sampled active Claude users &mdash; people already comfortable using AI who chose to keep using it. Workers displaced or threatened by AI don&rsquo;t show up in a survey of Claude users.</p>
    </div>
    <div style="border-left:3px solid #e63946;padding-left:1rem">
      <div style="font-weight:700;margin-bottom:.25rem">2. &ldquo;Augmentation&rdquo; is self-reported</div>
      <p style="font-size:.9rem;color:var(--text-secondary)">If a worker does the same job with AI help, they call it augmentation. If their employer uses that AI to hire fewer people next cycle, it becomes displacement &mdash; but not yet, and not in this survey.</p>
    </div>
    <div style="border-left:3px solid #e63946;padding-left:1rem">
      <div style="font-weight:700;margin-bottom:.25rem">3. The 43% automation figure</div>
      <p style="font-size:.9rem;color:var(--text-secondary)">Nearly half of Claude&rsquo;s usage is already task-completion (automation), not assistance. The report downplays this as routine offloading, but it represents real work that previously required human hours.</p>
    </div>
    <div style="border-left:3px solid #e63946;padding-left:1rem">
      <div style="font-weight:700;margin-bottom:.25rem">4. Occupational exposure mismatch</div>
      <p style="font-size:.9rem;color:var(--text-secondary)">High-exposure occupations &mdash; legal, writing, coding, analysis &mdash; are precisely where Claude usage is highest. The populations most at risk are the most surveyed. Their continued employment is not evidence of no displacement.</p>
    </div>
  </div>
</div>
<div class="chart-section" style="margin-top:2rem">
  <h2 style="font-size:1.2rem">CopeCheck Verdict</h2>
  <p>The Anthropic Economic Index is genuinely useful data &mdash; 9,700 users, real usage telemetry, published methodology. But framing the result as &ldquo;mostly augmentation&rdquo; reflects the perspective of workers still employed, not the structural shift already underway. The report&rsquo;s own data shows AI automating nearly half the tasks it touches. That is not a safety story. It is a displacement story told from inside the blast radius.</p>
  <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;margin-top:1.25rem">
    <div style="background:var(--bg-card);border:1px solid var(--border-color);border-radius:10px;padding:1rem;text-align:center">
      <div style="font-size:.75rem;color:var(--text-secondary);margin-bottom:.25rem;font-weight:700;letter-spacing:.06em">SAMPLE SIZE</div>
      <div style="font-size:1.4rem;font-weight:900;color:var(--accent-cyan)">9,700</div>
      <div style="font-size:.8rem;color:var(--text-secondary)">active Claude users only</div>
    </div>
    <div style="background:var(--bg-card);border:1px solid var(--border-color);border-radius:10px;padding:1rem;text-align:center">
      <div style="font-size:.75rem;color:var(--text-secondary);margin-bottom:.25rem;font-weight:700;letter-spacing:.06em">TOP AUTOMATION</div>
      <div style="font-size:1.4rem;font-weight:900;color:#e63946">Coding</div>
      <div style="font-size:.8rem;color:var(--text-secondary)">writing, data analysis</div>
    </div>
    <div style="background:var(--bg-card);border:1px solid var(--border-color);border-radius:10px;padding:1rem;text-align:center">
      <div style="font-size:.75rem;color:var(--text-secondary);margin-bottom:.25rem;font-weight:700;letter-spacing:.06em">DISPLACED WORKERS</div>
      <div style="font-size:1.4rem;font-weight:900;color:#e63946">0</div>
      <div style="font-size:.8rem;color:var(--text-secondary)">surveyed (not Claude users)</div>
    </div>
  </div>
</div>
<script>
(function(){
  var ctx = document.getElementById("augAutoChart");
  if (!ctx) return;
  new Chart(ctx, {
    type: "doughnut",
    data: {
      labels: ["Augmentation (57%)", "Automation (43%)"],
      datasets: [{ data: [57,43], backgroundColor: ["#22d3ee","#e63946"], borderColor: "#111", borderWidth: 3, hoverOffset: 6 }]
    },
    options: {
      responsive: true, maintainAspectRatio: true, cutout: "60%",
      plugins: {
        legend: { position: "bottom", labels: { color: "#999", padding: 16, font: { size: 12 } } },
        tooltip: { callbacks: { label: function(c){ return " "+c.raw+"% of usage"; } } }
      }
    }
  });
})();
</script>
</div>
"""
    return render_page("The Anthropic Economic Index: What the Data Actually Says",
        "Anthropic surveyed their own power users and found AI is mostly augmenting workers. The methodology buries the lead.",
        "/anthropic-economic-index", c, "")


@app.route("/ai-disclosure")
def ai_disclosure():
    content = '''<div class="container"><div class="page-header"><h1>How CopeCheck Labs uses AI</h1><p>Transparency notice for generated scores and report analysis.</p></div><section class="card" style="max-width:850px;margin:0 auto;line-height:1.7"><p><strong>Cope scores, report interpretations and some summaries are generated by artificial intelligence.</strong> Source datasets, report metadata and linked publications remain attributable to their publishers.</p><h2>Models and method</h2><p>The network uses OpenAI Codex with gpt-5.6-luna at maximum reasoning for the main scoring path and MiniMax models in specialist and fallback pipelines. Labs extracts displacement, capability, labour and framing signals, then applies the CopeCheck structural tests.</p><h2>Limits and corrections</h2><p>Models may omit context or assign an incorrect score. Verify against the linked report or dataset and send corrections to <a href="mailto:btl101@gmail.com?subject=CopeCheck%20Labs%20correction">btl101@gmail.com</a>.</p></section></div>'''
    return render_page("AI Disclosure", "How CopeCheck Labs uses artificial intelligence.", "/ai-disclosure", content)


@app.route("/sitemap.xml")
def sitemap():
    now = datetime.now().strftime("%Y-%m-%d")
    urls = [("/","daily","1.0"),("/openai","weekly","0.9"),("/anthropic","weekly","0.9"),("/geography","weekly","0.8"),("/cope","weekly","0.8"),("/report-scanners","weekly","0.7")]
    entries = "".join(f'  <url><loc>https://labs.copecheck.com{p}</loc><lastmod>{now}</lastmod><changefreq>{f}</changefreq><priority>{pr}</priority></url>\n' for p,f,pr in urls)
    return Response(f'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n{entries}</urlset>', mimetype="application/xml")

@app.route("/robots.txt")
def robots():
    return Response("User-agent: *\nAllow: /\nSitemap: https://labs.copecheck.com/sitemap.xml", mimetype="text/plain")

@app.errorhandler(404)
def not_found(e):
    c = '<div class="container" style="text-align:center;padding:4rem 2rem"><h1 style="font-size:4rem;color:var(--accent-cyan);margin-bottom:1rem">404</h1><p style="font-size:1.2rem;color:var(--text-secondary);margin-bottom:2rem">Page not found. Unlike AI displacement, which very much exists.</p><a href="/" style="padding:.6rem 1.5rem;background:var(--accent-cyan);color:var(--bg-primary);border-radius:8px;font-weight:600;display:inline-block">Back to Dashboard</a></div>'
    return render_page("404","Page not found","/404",c), 404

@app.errorhandler(500)
def server_error(e):
    c = '<div class="container" style="text-align:center;padding:4rem 2rem"><h1 style="font-size:4rem;color:var(--cope-terminal);margin-bottom:1rem">500</h1><p style="font-size:1.2rem;color:var(--text-secondary)">Server error. Even servers cope sometimes.</p></div>'
    return render_page("500","Server error","/500",c), 500

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5022, debug=True)


# ── 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
```
