""" 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 = [ '
', '

' '🚨 Curium — Real-Time Intelligence Alert

', f'

' 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'

' f'{watch["label"]}

' ) for h in hits: title = h.get("title", "No title") url = h.get("url", "") snippet = h.get("snippet", "") parts.append( f'
' f'
' + (f'{title}' if url else title) + f'
' f'
{snippet}
' f'
' ) # Shared platform feedback footer — every platform email carries it. # Alerts go to several people, so pass no recipient name (the web form # works for anyone). Falls back gracefully if the module isn't importable. fb = "" try: import sys as _sys _sys.path.insert(0, str(REPO_ROOT)) import weekly_digest as _wd fb = _wd._feedback_prompt_html(recipient_name=None) except Exception: fb = "" parts.append(fb) parts.append( '

Curium Lead Intelligence — real-time tier-1 alert

' '
' ) return "".join(parts) # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- def main() -> int: api_key = os.environ.get("ANTHROPIC_API_KEY", "").strip() if not api_key: print("ANTHROPIC_API_KEY not set — exiting") return 1 admin_email = os.environ.get("ADMIN_EMAIL", "").strip() if not admin_email: print("ADMIN_EMAIL not set — nowhere to send alerts") return 1 client = Anthropic(api_key=api_key) seen = _load_seen() new_hits: list[tuple[dict, list[dict]]] = [] for watch in WATCHLIST: print(f"→ Checking: {watch['label']}…") hits = _run_watch(client, watch) fresh = [] for h in hits: key = _event_key(watch["key"], h.get("title", "") + h.get("url", "")) if key not in seen: fresh.append(h) seen.add(key) if fresh: print(f" 🔴 {len(fresh)} new hit(s)") new_hits.append((watch, fresh)) else: print(f" ✓ Nothing new") time.sleep(1) if not new_hits: print("No new tier-1 signals — nothing to send") _save_seen(seen) return 0 # Build and send alert html = _build_alert_html(new_hits) critical = any(w["urgency"] == "critical" for w, _ in new_hits) subject = ( f"🚨 URGENT — Curium tier-1 alert: {new_hits[0][0]['label']}" if critical else f"⚡ Curium intelligence alert: {len(new_hits)} new signal(s)" ) # Alert recipients — explicit list, never auto-broadcast to whole team. # Add/remove names here to control who gets real-time alerts. ALERT_RECIPIENT_NAMES = {"Piers", "Stu", "Henriette", "Jordan"} import yaml try: with open(REPO_ROOT / "config.yaml") as f: cfg = yaml.safe_load(f) or {} alert_emails: list[str] = [] for entry in (cfg.get("team_emails") or []): name = entry.get("name", "") email = entry.get("email", "") if name not in ALERT_RECIPIENT_NAMES: continue if not email or email.startswith("ENV:"): # Resolve ENV: references if email.startswith("ENV:"): email = os.environ.get(email[4:], "").strip() if not email: continue alert_emails.append(email) except Exception as e: print(f" (config read failed, falling back to ADMIN_EMAIL: {e})") alert_emails = [admin_email] # Deduplicate alert_emails = list(dict.fromkeys(e for e in alert_emails if e)) if not alert_emails: alert_emails = [admin_email] for email in alert_emails: result = mailer.send(to_email=email, subject=subject, html=html) if result.get("success"): print(f"✓ Alert sent to {email}") else: print(f"✗ Send failed for {email}: {result.get('message')}") _save_seen(seen) return 0 if __name__ == "__main__": raise SystemExit(main())