""" Real-time tier-1 signal monitor. Runs every 2 hours via GitHub Actions cron. Searches for the highest- priority signals that shouldn't wait until Monday: - S114 / effective bankruptcy notices at UK councils - Government unitary structure decisions (LGR outcomes) - Competitor wins / partnership announcements at target councils - Senior appointments at priority LGR councils On a hit, fires an immediate email to ADMIN_EMAIL (and optionally all enabled team_emails). Uses a state file in HF Dataset to avoid re-alerting on the same event. """ from __future__ import annotations import hashlib import json import os import sys import time from datetime import date, datetime from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(REPO_ROOT)) try: from dotenv import load_dotenv load_dotenv(REPO_ROOT / ".env", override=False) except ImportError: pass import mailer from anthropic import Anthropic # --------------------------------------------------------------------------- # Watchlist — queries run every 2 hours # --------------------------------------------------------------------------- WATCHLIST = [ { "key": "s114", "label": "🚨 Council S114 / Bankruptcy Notice", "urgency": "critical", "query": ( 'UK council "section 114" OR "s114 notice" OR "issued section 114" ' 'OR "declared effective bankruptcy" OR "financial emergency" ' f'site:gov.uk OR site:lgcplus.com OR site:localgov.co.uk ' f'after:{date.today().isoformat()}' ), }, { "key": "lgr_decision", "label": "🏛️ Government LGR Unitary Decision", "urgency": "critical", "query": ( '"local government reorganisation" ("government confirms" OR "minister announces" ' 'OR "approved" OR "unitary authority confirmed" OR "structural changes confirmed") ' f'site:gov.uk OR site:lgcplus.com OR site:bbc.co.uk ' f'after:{date.today().isoformat()}' ), }, { "key": "lgr_appointment", "label": "👤 Senior LGR Appointment", "urgency": "high", "query": ( 'site:linkedin.com ("delighted to join" OR "pleased to announce" OR "excited to share") ' '("programme director" OR "director of transformation" OR "lgr") ' '("county council" OR "unitary authority") ' f'after:{date.today().isoformat()}' ), }, { "key": "competitor_win", "label": "🎯 Competitor Win at LGR Council", "urgency": "high", "query": ( '("county council" OR "local authority") ' '("working with" OR "appointed" OR "partnering with" OR "contract awarded to") ' '("McKinsey" OR "Deloitte" OR "KPMG" OR "PwC" OR "PA Consulting" OR "Optio" ' '"Moorhouse" OR "Arcadis" OR "Mott MacDonald") ' '("transformation" OR "LGR" OR "reorganisation") ' f'after:{date.today().isoformat()}' ), }, { "key": "herts_decision", "label": "🏛️ Hertfordshire LGR — Any Development", "urgency": "high", "query": ( '"Hertfordshire" ("unitary" OR "LGR" OR "reorganisation" OR "programme director") ' '("announces" OR "confirms" OR "appointed" OR "decision") ' f'after:{date.today().isoformat()}' ), }, { "key": "essex_lgr", "label": "🏛️ Essex LGR — Any Development", "urgency": "high", "query": ( '"Essex County Council" ("unitary" OR "LGR" OR "reorganisation" OR "programme director" ' 'OR "transformation") ("announces" OR "confirms" OR "appointed" OR "decision") ' f'after:{date.today().isoformat()}' ), }, { "key": "lancashire_lgr", "label": "🏛️ Lancashire LGR — Any Development", "urgency": "high", "query": ( '"Lancashire County Council" ("unitary" OR "LGR" OR "reorganisation" OR "programme director") ' '("announces" OR "confirms" OR "appointed" OR "decision") ' f'after:{date.today().isoformat()}' ), }, { "key": "priority_counties_lgr", "label": "🏛️ Priority LGR Counties — Surrey/Hampshire/Kent/Norfolk/Suffolk", "urgency": "high", "query": ( '("Surrey County Council" OR "Hampshire County Council" OR "Kent County Council" ' 'OR "Norfolk County Council" OR "Suffolk County Council" OR "Warwickshire County Council" ' 'OR "Gloucestershire County Council" OR "Oxfordshire County Council") ' '("LGR" OR "unitary" OR "reorganisation" OR "programme director" OR "transformation lead") ' '("appointed" OR "confirms" OR "decision" OR "announces" OR "contract") ' f'after:{date.today().isoformat()}' ), }, { "key": "lgr_govt_consultation_outcome", "label": "🏛️ MHCLG — Any LGR Consultation Outcome", "urgency": "critical", "query": ( 'site:gov.uk "local government reorganisation" ' '("consultation outcome" OR "government response" OR "decision letter" ' 'OR "unitary authority order" OR "structural changes order") ' f'after:{date.today().isoformat()}' ), }, ] # --------------------------------------------------------------------------- # Seen-events dedup — stored as a JSON file alongside leads.db # --------------------------------------------------------------------------- _SEEN_PATH = REPO_ROOT / "data" / "realtime_alert_seen.json" def _load_seen() -> set[str]: try: return set(json.loads(_SEEN_PATH.read_text())) except Exception: return set() def _save_seen(seen: set[str]) -> None: _SEEN_PATH.parent.mkdir(parents=True, exist_ok=True) _SEEN_PATH.write_text(json.dumps(sorted(seen))) def _event_key(watch_key: str, text: str) -> str: """Stable hash for a (watch_key, result_text) pair.""" return hashlib.sha1(f"{watch_key}:{text[:200]}".encode()).hexdigest()[:16] # --------------------------------------------------------------------------- # Search + parse # --------------------------------------------------------------------------- def _run_watch(client: Anthropic, watch: dict) -> list[dict]: """Run one watchlist query. Returns list of hit dicts.""" try: resp = client.messages.create( model="claude-haiku-4-5", max_tokens=800, tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 1}], messages=[{ "role": "user", "content": ( f"Search for: {watch['query']}\n\n" f"Return ONLY a JSON array of hits (empty array [] if nothing found today).\n" f"Each hit: {{\"title\": \"...\", \"url\": \"...\", \"snippet\": \"...\"}}\n" f"Maximum 3 hits. Only include items published TODAY or in the last 24 hours.\n" f"If nothing is genuinely new, return []." ), }], ) text = "".join(b.text for b in resp.content if hasattr(b, "text")).strip() # Extract JSON array import re m = re.search(r"\[.*\]", text, re.S) if not m: return [] return json.loads(m.group(0)) or [] except Exception as e: print(f" Watch {watch['key']} error: {e}") return [] # --------------------------------------------------------------------------- # Alert email # --------------------------------------------------------------------------- def _build_alert_html(hits_by_watch: list[tuple[dict, list[dict]]]) -> str: parts = [ '
' f'Generated: {datetime.utcnow().strftime("%Y-%m-%d %H:%M")} UTC
', ] for watch, hits in hits_by_watch: urgency_colour = "#b71c1c" if watch["urgency"] == "critical" else "#e65100" parts.append( f'Curium Lead Intelligence — real-time tier-1 alert
' '