---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" CopeCheck Layoff Scanner — scans for layoff news, extracts data, deduplicates, and updates layoffs.json. Designed to run daily via cron on VPS. Uses Brave Search API (primary) with GNews."
resource: "https://layoffs.copecheck.com"
tags: ["copecheck", "layoffs", "source-file", "py"]
timestamp: "2026-09-25T22:06:34Z"
site: "layoffs"
source_path: "copecheck-layoffs/scanner.py"
---

# !/usr/bin/env python3

Source path: `copecheck-layoffs/scanner.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-25T22:06:34Z`

```py
#!/usr/bin/env python3
"""
CopeCheck Layoff Scanner — scans for layoff news, extracts data, deduplicates,
and updates layoffs.json.

Designed to run daily via cron on VPS. Uses Brave Search API (primary) with
GNews fallback. Fetches full article text via Crawl4AI. Uses MiniMax M2.7
for intelligent extraction including multi-company roundup articles.

Usage:
    python3 scanner.py              # Normal scan
    python3 scanner.py --dry-run    # Preview without writing
    python3 scanner.py --verbose    # Extra logging
"""

import json
import os
import re
import sys
import hashlib
import logging
import time
import gzip
from datetime import datetime, timedelta
from urllib.request import Request, urlopen
from urllib.parse import quote_plus, urlencode
from urllib.error import URLError, HTTPError

from company_validation import validate_company

# --- Config ---
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
CRAWL4AI_URL = os.environ.get("CRAWL4AI_URL", "http://localhost:11235")
DATA_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "layoffs.json")

RSS_FEEDS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "rss_feeds.json")
SEEN_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "seen_articles.json")
LOG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "scanner.log")

# Delay between API calls (seconds) — be polite, this runs as background task
SEARCH_DELAY = 3
CRAWL_DELAY = 2
LLM_DELAY = 1

# Search queries — Brave has generous limits so we can use more
SEARCH_QUERIES = [
    "company lays off employees 2026",
    "layoffs announced workers cut 2026",
    "tech layoffs job cuts May 2026",
    "staff redundancies UK 2026",
    "AI replacing workers layoffs",
    "startup layoffs funding cuts",
    "enterprise layoffs restructuring 2026",
]

# Country detection keywords
COUNTRY_HINTS = {
    "US": ["united states", "us-based", "silicon valley", "san francisco", "new york",
           "seattle", "austin", "california", "american"],
    "UK": ["united kingdom", "uk", "london", "british", "england", "scotland", "wales",
           "manchester", "birmingham", "sunderland"],
    "DE": ["germany", "german", "berlin", "munich", "frankfurt"],
    "AU": ["australia", "australian", "sydney", "melbourne"],
    "CA": ["canada", "canadian", "toronto", "vancouver"],
    "IN": ["india", "indian", "bangalore", "mumbai", "hyderabad"],
    "IE": ["ireland", "irish", "dublin"],
    "FR": ["france", "french", "paris"],
    "JP": ["japan", "japanese", "tokyo"],
    "CN": ["china", "chinese", "beijing", "shanghai"],
}

SECTOR_HINTS = {
    "Technology": ["tech", "software", "saas", "cloud", "platform"],
    "Finance": ["bank", "financial", "fintech", "investment", "insurance"],
    "E-commerce": ["e-commerce", "ecommerce", "online retail", "marketplace"],
    "Social Media": ["social media", "social network"],
    "Gaming": ["game", "gaming", "esports"],
    "Healthcare": ["health", "medical", "pharma", "biotech"],
    "Automotive": ["auto", "car", "vehicle", "ev ", "electric vehicle"],
    "Telecoms": ["telecom", "telco", "mobile network"],
    "Retail": ["retail", "store", "shop", "consumer"],
    "Enterprise Software": ["enterprise", "crm", "erp"],
    "Media": ["media", "news", "publishing", "broadcast"],
    "Crypto / Fintech": ["crypto", "blockchain", "defi", "bitcoin"],
    "Hardware": ["hardware", "chip", "semiconductor", "device"],
}


def setup_logging(verbose=False):
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[
            logging.FileHandler(LOG_FILE),
            logging.StreamHandler()
        ]
    )


def load_data():
    with open(DATA_FILE) as f:
        return json.load(f)


def save_data(data):
    with open(DATA_FILE, "w") as f:
        json.dump(data, f, indent=2)


def load_seen():
    if os.path.exists(SEEN_FILE):
        with open(SEEN_FILE) as f:
            return json.load(f)
    return {"urls": [], "hashes": []}


def save_seen(seen):
    with open(SEEN_FILE, "w") as f:
        json.dump(seen, f, indent=2)


def article_hash(title, source):
    """Create a hash for dedup based on title + source."""
    key = f"{title.lower().strip()}|{source.lower().strip()}"
    return hashlib.md5(key.encode()).hexdigest()


# ---- Search APIs ----

def search_brave(query, count=10):
    """Search Brave Search API for news articles."""
    params = urlencode({
        "q": query,
        "count": count,
        "freshness": "pw",  # past week
        "text_decorations": "false",
        "search_lang": "en",
    })
    url = f"https://api.search.brave.com/res/v1/news/search?{params}"

    try:
        req = Request(url, headers={
            "Accept": "application/json",
            "Accept-Encoding": "gzip",
[redacted secret-like line]
        })
        with urlopen(req, timeout=15) as resp:
            raw = resp.read()
            # Handle gzip encoding
            if resp.headers.get("Content-Encoding") == "gzip" or raw[:2] == b'\x1f\x8b':
                raw = gzip.decompress(raw)
            data = json.loads(raw.decode())
            results = data.get("results", [])
            # Normalize to same format as GNews
            articles = []
            for r in results:
                articles.append({
                    "title": r.get("title", ""),
                    "description": r.get("description", ""),
                    "url": r.get("url", ""),
                    "source": {"name": r.get("meta_url", {}).get("hostname", "") if isinstance(r.get("meta_url"), dict) else ""},
                    "publishedAt": r.get("age", ""),
                })
            return articles
    except Exception as e:
        logging.error(f"Brave Search error for '{query}': {e}")
        return []


def search_gnews(query, max_results=10):
    """Search GNews API for articles (fallback)."""
    params = urlencode({
        "q": query,
        "lang": "en",
        "max": max_results,
[redacted secret-like line]
        "from": (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%dT00:00:00Z"),
    })
    url = f"https://gnews.io/api/v4/search?{params}"

    try:
        req = Request(url, headers={"User-Agent": "CopeCheck-Scanner/1.0"})
        with urlopen(req, timeout=15) as resp:
            data = json.loads(resp.read().decode())
            return data.get("articles", [])
    except (URLError, HTTPError) as e:
        logging.error(f"GNews API error for '{query}': {e}")
        return []
    except json.JSONDecodeError:
        logging.error(f"Invalid JSON from GNews for '{query}'")
        return []



# ---- Google Alerts RSS (Atom) parsing ----

def load_rss_feeds():
    """Load RSS feed URLs from config."""
    if os.path.exists(RSS_FEEDS_FILE):
        with open(RSS_FEEDS_FILE) as f:
            return json.load(f)
    return {"feeds": []}


def fetch_rss_feed(feed_url, timeout=15):
    """Fetch and parse a Google Alerts Atom RSS feed.
    Returns list of articles in same format as search results."""
    import xml.etree.ElementTree as ET

    articles = []
    try:
        req = Request(feed_url, headers={
            "User-Agent": "CopeCheck-Scanner/2.0",
        })
        with urlopen(req, timeout=timeout) as resp:
            raw = resp.read()
            # Handle gzip
            if raw[:2] == b'\x1f\x8b':
                raw = gzip.decompress(raw)
            xml_text = raw.decode("utf-8")

        # Parse Atom XML
        ns = {"atom": "http://www.w3.org/2005/Atom"}
        root = ET.fromstring(xml_text)

        for entry in root.findall("atom:entry", ns):
            title_el = entry.find("atom:title", ns)
            link_el = entry.find("atom:link", ns)
            content_el = entry.find("atom:content", ns)
            published_el = entry.find("atom:published", ns) or entry.find("atom:updated", ns)

            title = title_el.text.strip() if title_el is not None and title_el.text else ""
            # Google Alerts wraps the actual URL in the link href
            url = ""
            if link_el is not None:
                url = link_el.get("href", "")
                # Google Alerts redirects through google.com/url?...&url=ACTUAL
                if "google.com/url" in url:
                    from urllib.parse import urlparse, parse_qs
                    parsed = urlparse(url)
                    params = parse_qs(parsed.query)
                    if "url" in params:
                        url = params["url"][0]

            # Content is HTML, extract text for description
            description = ""
            if content_el is not None and content_el.text:
                import re as _re
                description = _re.sub(r"<[^>]+>", " ", content_el.text).strip()[:300]

            published = ""
            if published_el is not None and published_el.text:
                published = published_el.text.strip()

            if title and url:
                articles.append({
                    "title": title,
                    "description": description,
                    "url": url,
                    "source": {"name": "Google Alerts RSS"},
                    "publishedAt": published,
                })
    except Exception as e:
        logging.warning(f"RSS feed fetch failed for {feed_url[:60]}: {e}")

    return articles


# ---- Article fetching ----

def fetch_article_text(url):
    """Fetch full article text via Crawl4AI."""
    try:
        payload = json.dumps({
            "urls": [url],
            "word_count_threshold": 30,
        })
        req = Request(
            f"{CRAWL4AI_URL}/crawl",
            data=payload.encode(),
            headers={"Content-Type": "application/json"},
        )
        with urlopen(req, timeout=30) as resp:
            data = json.loads(resp.read().decode())
            results = data.get("results", [])
            if results and results[0].get("success"):
                md = results[0].get("markdown", {})
                if isinstance(md, dict):
                    return md.get("raw_markdown", "")
                return str(md) if md else ""
    except Exception as e:
        logging.warning(f"Crawl4AI fetch failed for {url[:80]}: {e}")
    return ""


# ---- Regex extraction helpers ----

def extract_number(text):
    """Extract layoff numbers from text."""
    patterns = [
        r"(?:lay(?:ing)?\s*off|cut(?:ting)?|eliminat(?:e|ing)|slash(?:ing)?|reduc(?:e|ing))\s+(?:about\s+|approximately\s+|around\s+|up\s+to\s+|nearly\s+|over\s+|more\s+than\s+)?(\d[\d,]*)\s*(?:workers?|employees?|jobs?|staff|positions?|roles?|people)",
        r"(\d[\d,]*)\s*(?:workers?|employees?|jobs?|staff|positions?|roles?|people)\s*(?:will be |are being |were |being )?(?:laid off|cut|eliminated|let go|axed|fired|terminated|made redundant)",
        r"(?:plans? to |will |set to |expected to )(?:lay off|cut|eliminate|reduce|slash)\s+(?:about\s+|approximately\s+|around\s+|up\s+to\s+|nearly\s+|over\s+|more\s+than\s+)?(\d[\d,]*)",
        r"(\d[\d,]*)\s*(?:layoffs?|job cuts?|redundanc(?:y|ies))",
    ]
    for pattern in patterns:
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            num_str = match.group(1).replace(",", "")
            num = int(num_str)
            if 10 <= num <= 500000:
                return num
    return None


def extract_percentage(text):
    """Extract workforce percentage from text."""
    patterns = [
        r"(\d+(?:\.\d+)?)\s*%\s*of\s*(?:its\s+)?(?:workforce|employees?|staff|headcount)",
        r"(\d+(?:\.\d+)?)\s*(?:percent|pct)\s*of\s*(?:its\s+)?(?:workforce|employees?|staff)",
    ]
    for pattern in patterns:
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            pct = float(match.group(1))
            if 0.5 <= pct <= 100:
                return f"{pct:.0f}%" if pct == int(pct) else f"{pct}%"
    return None


def extract_company(title, description):
    """Extract company name from article title/description."""
    patterns = [
        r"^([A-Z][A-Za-z0-9\.\-]+(?:\s+[A-Z][A-Za-z0-9\.\-]+){0,3})\s+(?:lays? off|cuts?|to lay off|to cut|announces?|plans?|is laying off|fires?|eliminat)",
        r"^([A-Z][A-Za-z0-9\.\-]+(?:\s+[A-Z][A-Za-z0-9\.\-]+){0,3})\s+(?:will |set to |expected to )?(?:lay off|cut|eliminate|slash|reduce)",
        r"^([A-Z][A-Za-z0-9\.\-]+(?:'s)?)\s+(?:Recent |Latest |New |Mass )?(?:Layoffs?|Job Cuts?|Redundanc)",
    ]
    for pattern in patterns:
        match = re.search(pattern, title)
        if match:
            name = match.group(1).strip().rstrip("'s")
            skip = {"The", "A", "An", "This", "These", "More", "Many", "Several",
                    "Report", "Breaking", "Update", "Why", "How", "What", "Global",
                    "Major", "Big", "Tech", "Exclusive", "After", "From"}
            if name not in skip and len(name) > 1:
                return name
    return None


def detect_country(text):
    text_lower = text.lower()
    scores = {}
    for country, keywords in COUNTRY_HINTS.items():
        score = sum(1 for kw in keywords if kw in text_lower)
        if score > 0:
            scores[country] = score
    if scores:
        return max(scores, key=scores.get)
    return "US"


def detect_sector(text):
    text_lower = text.lower()
    scores = {}
    for sector, keywords in SECTOR_HINTS.items():
        score = sum(1 for kw in keywords if kw in text_lower)
        if score > 0:
            scores[sector] = score
    if scores:
        return max(scores, key=scores.get)
    return "Technology"


def detect_ai_driven(text):
    ai_keywords = [
        "artificial intelligence", " ai ", "ai-driven", "automation",
        "replaced by ai", "ai replac", "machine learning", "chatgpt",
        "generative ai", "ai tool", "ai system", "automat",
        "ai invest", "ai infrastructure", "ai pivot", "ai-powered",
    ]
    text_lower = f" {text.lower()} "
    return any(kw in text_lower for kw in ai_keywords)


# ---- MiniMax LLM extraction ----

def extract_with_minimax(title, description, article_text, source):
    """Use MiniMax M2.7 to extract structured layoff data from article.
    
    Returns a LIST of entries (handles multi-company roundup articles).
    Each entry is a dict with company, laid_off, pct, country, sector, reason, ai_driven.
    Returns [{"skip": True}] if article is not about layoffs.
    Returns None on failure.
    """
[redacted secret-like line]
        return None

    # Use full article text if available, truncated to fit context
    context = article_text[:4000] if article_text else f"Title: {title}\nDescription: {description}"

    prompt = f"""Extract layoff information from this news article. Return ONLY valid JSON, no other text.

Title: {title}
Source: {source}

Article content:
{context}

RULES:
1. If this article announces layoffs at ONE specific company, return a JSON array with one object:
[{{"company": "CompanyName", "laid_off": number_or_null, "pct": "X%" or null, "country": "US", "sector": "Technology", "reason": "brief reason", "ai_driven": true_or_false}}]

2. If this article is a ROUNDUP listing multiple companies with layoff details, return a JSON array with one object per company (only include companies where you can identify a specific layoff number or percentage):
[{{"company": "Company1", "laid_off": 500, ...}}, {{"company": "Company2", "laid_off": 200, ...}}]

3. If this is an opinion piece, general commentary, or has no specific company layoff data, return:
[{{"skip": true}}]

Return ONLY the JSON array, nothing else."""

    payload = json.dumps({
        "model": "minimax-m2.7",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.1,
[redacted secret-like line]
    })

    try:
        req = Request(
            "https://api.minimax.io/v1/chat/completions",
            data=payload.encode(),
            headers={
                "Content-Type": "application/json",
[redacted secret-like line]
            }
        )
        with urlopen(req, timeout=45) as resp:
            result = json.loads(resp.read().decode())
            content = result["choices"][0]["message"]["content"]
            # Strip think tags (MiniMax quirk)
            content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL).strip()
            # Extract JSON array from response
            json_match = re.search(r"\[.*\]", content, re.DOTALL)
            if json_match:
                parsed = json.loads(json_match.group())
                if isinstance(parsed, list):
                    return parsed
            # Try single object fallback
            json_match = re.search(r"\{.*\}", content, re.DOTALL)
            if json_match:
                parsed = json.loads(json_match.group())
                return [parsed]
    except Exception as e:
        logging.warning(f"MiniMax extraction failed: {e}")

    return None


def normalize_laid_off(value):
    """Coerce model output to an integer count; keep qualifiers separately."""
    if value is None or isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        return max(0, int(value))
    match = re.search(r"\d[\d,]*", str(value))
    if not match:
        return None
    return int(match.group(0).replace(",", ""))


# ---- Article processing ----

def process_article(article, seen, existing_companies):
    """Process a single article and return list of extracted layoff entries."""
    title = article.get("title", "")
    description = article.get("description", "")
    url = article.get("url", "")
    source_name = article.get("source", {}).get("name", "") if isinstance(article.get("source"), dict) else str(article.get("source", ""))
    published = article.get("publishedAt", "")

    # Dedup by URL
    if url in seen["urls"]:
        logging.debug(f"  Skipping (seen URL): {title[:60]}")
        return []

    # Dedup by content hash
    ahash = article_hash(title, source_name)
    if ahash in seen["hashes"]:
        logging.debug(f"  Skipping (seen hash): {title[:60]}")
        return []

    # Mark as seen
    seen["urls"].append(url)
    seen["hashes"].append(ahash)

    # Fetch full article text via Crawl4AI
    article_text = ""
    try:
        article_text = fetch_article_text(url)
        if article_text:
            logging.debug(f"  Fetched {len(article_text)} chars from {url[:60]}")
        else:
            logging.debug(f"  No text fetched for {url[:60]}")
    except Exception as e:
        logging.warning(f"  Fetch error: {e}")

    time.sleep(CRAWL_DELAY)
    combined_text = f"{title} {description} {article_text[:5000]}"

    # Try MiniMax extraction (returns list of entries)
    extracted_list = extract_with_minimax(title, description, article_text, source_name)
    time.sleep(LLM_DELAY)

    entries = []

    if extracted_list:
        for extracted in extracted_list:
            if extracted.get("skip"):
                logging.debug(f"  Skipping (not specific layoffs): {title[:60]}")
                continue

            company = extracted.get("company")
            if not company:
                continue

            # Reject descriptive placeholders ("biggest UK vape wholesaler",
            # "University (BBC Essex campus)") before they reach the dataset.
            company_ok, company_reason = validate_company(company)
            if not company_ok:
                logging.info(
                    "  Rejected non-company string (%s): %r", company_reason, company
                )
                continue

            raw_laid_off = extracted.get("laid_off")
            laid_off = normalize_laid_off(raw_laid_off)
            pct = extracted.get("pct")

            if not laid_off and not pct:
                continue

            company_lower = company.lower().strip()
            if company_lower in existing_companies:
                logging.debug(f"  Already tracked: {company}")
                continue

            # Parse date
            date_str = datetime.now().strftime("%Y-%m")
            if published:
                try:
                    dt = datetime.fromisoformat(published.replace("Z", "+00:00"))
                    date_str = dt.strftime("%Y-%m")
                except (ValueError, TypeError):
                    pass

            entry = {
                "company": company,
                "laid_off": laid_off,
                "date": date_str,
                "sector": extracted.get("sector", "Technology"),
                "country": extracted.get("country", "US"),
                "reason": extracted.get("reason", ""),
                "ai_driven": extracted.get("ai_driven", False),
                "source": source_name,
                "source_url": url,
                "added_by": "scanner",
                "added_date": datetime.now().strftime("%Y-%m-%d"),
                "verification_status": "unverified_auto",
            }
            if raw_laid_off is not None and not isinstance(raw_laid_off, (int, float)):
                entry["laid_off_text"] = str(raw_laid_off)
            if pct:
                entry["pct"] = pct

            entries.append(entry)
            existing_companies.add(company_lower)

    else:
        # Regex fallback (single company only)
        company = extract_company(title, description)
        laid_off = extract_number(combined_text)
        pct = extract_percentage(combined_text)

        if not company or (not laid_off and not pct):
            logging.debug(f"  No extraction: {title[:60]}")
            return []

        company_ok, company_reason = validate_company(company)
        if not company_ok:
            logging.info(
                "  Rejected non-company string (%s): %r", company_reason, company
            )
            return []

        company_lower = company.lower().strip()
        if company_lower in existing_companies:
            logging.debug(f"  Already tracked: {company}")
            return []

        date_str = datetime.now().strftime("%Y-%m")
        if published:
            try:
                dt = datetime.fromisoformat(published.replace("Z", "+00:00"))
                date_str = dt.strftime("%Y-%m")
            except (ValueError, TypeError):
                pass

        entry = {
            "company": company,
            "laid_off": laid_off,
            "date": date_str,
            "sector": detect_sector(combined_text),
            "country": detect_country(combined_text),
            "reason": description[:120] if description else title[:120],
            "ai_driven": detect_ai_driven(combined_text),
            "source": source_name,
            "source_url": url,
            "added_by": "scanner",
            "added_date": datetime.now().strftime("%Y-%m-%d"),
            "verification_status": "unverified_auto",
        }
        if pct:
            entry["pct"] = pct
        entries.append(entry)
        existing_companies.add(company_lower)

    return entries


# ---- Summary + main scan ----

def update_summary(data):
    """Record ledger coverage without adding overlapping source claims.

    Scanner rows can describe announced future reductions, aggregate several
    firms, repeat syndicated reporting, or overlap with a curated row.  Their
    headcounts therefore are not a defensible total of distinct people.
    """
    all_2026 = data.get("major_2026", []) + data.get("scanned_2026", [])
    all_2025 = data.get("major_2025", []) + data.get("scanned_2025", [])
    summary = data.setdefault("summary", {})
    for year, entries in (("2026", all_2026), ("2025", all_2025)):
        row = summary.setdefault(year, {})
        row.update({
            "total_layoffs": None,
            "avg_per_day": None,
            "ai_attributed": None,
            "total_events": len(entries),
            "source_linked_events": sum(bool(e.get("source_url")) for e in entries),
            "aggregate_status": "withheld_non_additive",
        })
    summary.setdefault("since_2020", {})["total"] = None


def run_scan(dry_run=False, verbose=False):
    setup_logging(verbose)
    logging.info("=" * 60)
    logging.info("CopeCheck Layoff Scanner v2 starting")
    logging.info(f"Time: {datetime.now().isoformat()}")
    logging.info(f"Dry run: {dry_run}")
    logging.info(f"Search: Brave (primary), GNews (fallback)")
    logging.info(f"Crawl4AI: {CRAWL4AI_URL}")
    logging.info(f"RSS feeds: {RSS_FEEDS_FILE}")
[redacted secret-like line]

    data = load_data()
    seen = load_seen()

    # Build set of existing companies for dedup
    existing_companies = set()
    for key in ["major_2026", "major_2025", "scanned_2026", "scanned_2025"]:
        for entry in data.get(key, []):
            existing_companies.add(entry["company"].lower().strip())
    for entry in data.get("uk_layoffs", []):
        existing_companies.add(entry["company"].lower().strip())

    logging.info(f"Tracking {len(existing_companies)} existing companies")

    if "scanned_2026" not in data:
        data["scanned_2026"] = []
    if "scanned_2025" not in data:
        data["scanned_2025"] = []

    new_entries = []
    total_articles = 0

    for query in SEARCH_QUERIES:
        logging.info(f"Searching: '{query}'")
        # Try Brave first, fall back to GNews
        articles = search_brave(query, count=10)
        if not articles:
            logging.info(f"  Brave returned nothing, trying GNews...")
            articles = search_gnews(query, max_results=10)
        logging.info(f"  Got {len(articles)} articles")
        total_articles += len(articles)
        time.sleep(SEARCH_DELAY)

        for article in articles:
            entries = process_article(article, seen, existing_companies)
            for entry in entries:
                new_entries.append(entry)
                logging.info(f"  NEW: {entry['company']} — {entry.get('laid_off', '?')} laid off ({entry['country']})")


    # --- RSS Feeds (Google Alerts) ---
    rss_config = load_rss_feeds()
    rss_feeds = rss_config.get("feeds", [])
    if rss_feeds:
        logging.info(f"\nScanning {len(rss_feeds)} Google Alerts RSS feeds...")
        for feed in rss_feeds:
            feed_name = feed.get("name", "unnamed")
            feed_url = feed.get("url", "")
            if not feed_url:
                continue
            logging.info(f"  RSS: '{feed_name}'")
            articles = fetch_rss_feed(feed_url, timeout=rss_config.get("fetch_timeout", 15))
            logging.info(f"    Got {len(articles)} articles from RSS")
            total_articles += len(articles)
            time.sleep(SEARCH_DELAY)

            for article in articles[:rss_config.get("max_articles_per_feed", 20)]:
                entries = process_article(article, seen, existing_companies)
                for entry in entries:
                    new_entries.append(entry)
                    logging.info(f"    NEW (RSS): {entry['company']} — {entry.get('laid_off', '?')} laid off ({entry['country']})")
    else:
        logging.info("No RSS feeds configured")

    logging.info(f"\nScan complete: {total_articles} articles processed, {len(new_entries)} new entries")

    if new_entries and not dry_run:
        current_year = datetime.now().year
        for entry in new_entries:
            entry_year = int(entry["date"].split("-")[0]) if entry.get("date") else current_year
            if entry_year >= 2026:
                data["scanned_2026"].append(entry)
            else:
                data["scanned_2025"].append(entry)

        update_summary(data)
        data["meta"]["last_updated"] = datetime.now().strftime("%Y-%m-%d")
        data["meta"]["last_scan"] = datetime.now().isoformat()
        save_data(data)
        save_seen(seen)
        logging.info(f"Saved {len(new_entries)} new entries to layoffs.json")
    elif new_entries and dry_run:
        logging.info("\nDRY RUN — would add:")
        for entry in new_entries:
            logging.info(f"  {entry['company']}: {entry.get('laid_off', '?')} ({entry['country']}, {entry['sector']})")
        save_seen(seen)
    else:
        save_seen(seen)
        logging.info("No new entries to add")

    return new_entries


if __name__ == "__main__":
    dry_run = "--dry-run" in sys.argv
    verbose = "--verbose" in sys.argv
    results = run_scan(dry_run=dry_run, verbose=verbose)
    print(f"\nDone. {len(results)} new layoff entries found.")
```
