Spaces:
Sleeping

curium-intel / scripts /lgr_deep_research.py
mipwr-admin's picture
Sync from GitHub main β€” ERP priority, WMCA/Shropshire watchlist, network preserve-owners fix (a7395ea)
a87217c verified
Raw History Blame Contribute Delete
36.1 kB
#!/usr/bin/env python3
"""
Deep one-off research sweep on UK Local Government Reorganisation.
Uses Anthropic web_search across five focused passes to build a
comprehensive view of every UK council planning, consulting, or
mobilising under LGR. Outputs:
- intel_assets/lgr_landscape_YYYY-MM-DD.md β€” human-readable report
with per-council status, key dates, controversies, hiring activity
- lgr_tracker table in leads.db β€” structured rows the weekly digest
can reference (one row per council)
Run:
cd /Users/pierslyon/Documents/AI-sales-tool
venv/bin/python scripts/lgr_deep_research.py
Cost: ~Β£3 in Claude tokens (~40 web searches across 5 passes + a
consolidation call). Re-run quarterly to refresh the landscape.
"""
from __future__ import annotations
import json
import os
import sqlite3
import sys
import time
from datetime import datetime
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT))
# Load .env locally
try:
from dotenv import load_dotenv
load_dotenv(REPO_ROOT / ".env", override=False)
except ImportError:
pass
from anthropic import Anthropic
MODEL = "claude-sonnet-4-5-20250929"
DATABASE = REPO_ROOT / "leads.db"
INTEL_DIR = REPO_ROOT / "intel_assets"
TODAY = datetime.now().strftime("%Y-%m-%d")
def _load_curium_contacts() -> list[dict]:
"""Read curium_contacts from config.yaml AND the DB-backed store, merged.
YAML = curated seed contacts (e.g. Pete Shakespeare / Staffs / ex-Essex)
DB = anything added at runtime via the Stakeholders UI
Either source feeds warm-route dot-joining in the consolidator."""
yaml_contacts: list[dict] = []
try:
import yaml
with open(REPO_ROOT / "config.yaml", "r", encoding="utf-8") as f:
cfg = yaml.safe_load(f) or {}
yaml_contacts = cfg.get("curium_contacts") or []
except Exception as e:
print(f" (curium_contacts yaml unavailable: {e})")
try:
import contacts_store
return contacts_store.load_merged_with_yaml(yaml_contacts)
except Exception as e:
print(f" (curium_contacts db unavailable, yaml-only: {e})")
return yaml_contacts
def _format_warm_routes(contacts: list[dict]) -> str:
"""Render contacts as a compact bullet list for prompt injection."""
if not contacts:
return "(none provided)"
lines = []
for c in contacts:
priors = ", ".join(
f"{p.get('org','?')}" + (f" ({p['role']})" if p.get("role") else "")
for p in (c.get("prior_employers") or [])
) or "(none recorded)"
lines.append(
f"- {c.get('name','?')} β€” {c.get('current_role','?')} at "
f"{c.get('current_client','?')}. Prior: {priors}."
+ (f" Notes: {c['notes']}" if c.get("notes") else "")
)
return "\n".join(lines)
# Five research passes, each scoped tightly so Claude can spend its
# search budget productively rather than wandering.
PASSES = [
{
"key": "landscape",
"title": "Current LGR landscape β€” every council planning/mobilising",
"max_searches": 10,
"prompt": """Today is {today}. Conduct a comprehensive search on the current state of UK Local Government Reorganisation (LGR). The 2024-2026 wave was triggered by the May 2024 Section 7 invitation. Identify EVERY UK two-tier county council, district council, or unitary authority that is currently engaged in LGR.
For each council, find:
- Council name (official)
- Current LGR stage. Use one of:
"considering" | "consulting" | "proposal_submitted" | "awaiting_decision" |
"approved" | "shadow_authority" | "mobilising" | "vested" | "completed" |
"rejected" | "withdrew"
- Preferred option (e.g. "One Hampshire", "Two unitaries for Sussex", "Status quo")
- Key dates (proposal date, decision date, vesting day target if known)
- Notable controversies / public opposition / inter-council disagreement
Use web_search ({max_searches} searches). Focus on official sources:
gov.uk announcements, MHCLG publications, Local Government Chronicle,
The MJ, council press releases. UK only.
Return a JSON array (no prose, no code fences):
{{
"councils": [
{{
"name": "...",
"type": "county" | "district" | "unitary" | "metropolitan" | "london_borough",
"stage": "...",
"preferred_option": "...",
"key_dates": {{"proposal": "YYYY-MM-DD", "decision": "...", "vesting_day": "..."}},
"controversies": "1-2 sentences if any, empty string otherwise",
"source_url": "best primary source"
}}
]
}}"""
},
{
"key": "ministerial",
"title": "Ministerial decisions + funding triggers in last 90 days",
"max_searches": 6,
"prompt": """Today is {today}. Find UK government ministerial decisions on Local Government Reorganisation (LGR) in the past 90 days. Also identify major UK government funding allocations to councils β€” Levelling Up Fund, Towns Fund, devolution deals, Long Term Plan for Towns β€” that have been announced or paid out recently and will trigger transformation programmes.
Use web_search ({max_searches} searches). Focus on gov.uk announcements, MHCLG, and reliable trade press.
Return a JSON array of decision/funding events (no prose, no fences):
{{
"events": [
{{
"date": "YYYY-MM-DD",
"event_type": "ministerial_decision" | "funding_allocation" | "consultation_opened" | "consultation_closed",
"councils_affected": ["name", "name"],
"summary": "2 sentences: what was decided/funded and what it triggers",
"source_url": "..."
}}
]
}}"""
},
{
"key": "hires",
"title": "Transformation / programme / change leadership hires at councils",
"max_searches": 8,
"prompt": """Today is {today}. In the past 90 days, which UK councils have appointed, are actively recruiting, or have had departures in these roles:
- Programme Director (transformation / LGR / change)
- Director of Transformation / Director of Change
- Chief Operating Officer (interim or permanent, council)
- Chief Executive (during LGR transition or after S114)
- Director of Resources / Section 151 Officer (during financial stress)
- LGR Transition Lead / LGR Programme Director
Use web_search ({max_searches} searches). Search LinkedIn-via-Google ("site:linkedin.com {{council name}} appointed transformation"), gov.uk, council press releases, Local Government Chronicle.
Return a JSON array (no prose, no fences):
{{
"hires": [
{{
"date": "YYYY-MM-DD",
"council": "...",
"role_title": "...",
"person_name": "if known, else empty string",
"movement": "appointed" | "departed" | "interim" | "actively recruiting",
"context_signal": "1 sentence: any LGR / transformation context",
"source_url": "..."
}}
]
}}"""
},
{
"key": "crisis",
"title": "Councils in Section 114 / Best Value / commissioner intervention",
"max_searches": 6,
"prompt": """Today is {today}. Which UK councils are currently under:
- Section 114 notice (effectively bankrupt)
- Best Value notice
- Statutory intervention by central government
- Commissioners appointed by Secretary of State
Find all currently-active interventions plus any that have begun or concluded in the past 12 months. Each is a forced multi-year transformation programme.
Use web_search ({max_searches} searches). Focus on gov.uk's intervention collection and recent news. UK only.
Return a JSON array (no prose, no fences):
{{
"interventions": [
{{
"council": "...",
"intervention_type": "section_114" | "best_value_notice" | "commissioners" | "statutory_intervention",
"status": "active" | "begun_recently" | "concluded" | "withdrawn",
"start_date": "YYYY-MM-DD",
"end_date": "if concluded, else empty",
"summary": "2 sentences",
"source_url": "..."
}}
]
}}"""
},
{
"key": "erp",
"title": "Major ERP rollouts coinciding with LGR activity",
"max_searches": 6,
"prompt": """Today is {today}. Which UK councils are currently implementing or have recently begun rolling out major ERP / finance / HR systems β€” Unit4, Oracle Fusion / Oracle Cloud, SAP, Workday, Agresso, Civica β€” that coincide with LGR activity?
This is Curium's sweet spot: when a council is rolling out new systems AND going through LGR, the integration risk creates a delivery-partner opportunity.
Use web_search ({max_searches} searches). Focus on council tender notices, Local Government Chronicle, Public Sector Executive, council press releases. UK only.
Return a JSON array (no prose, no fences):
{{
"erp_rollouts": [
{{
"council": "...",
"system": "Unit4" | "Oracle" | "SAP" | "Workday" | "Agresso" | "Civica" | "other",
"stage": "planning" | "procurement" | "implementation" | "go_live" | "post_go_live",
"go_live_date": "YYYY-MM if known else empty",
"lgr_overlap": "1 sentence β€” how does this overlap with the council's LGR activity?",
"source_url": "..."
}}
]
}}"""
},
# ========================================================================
# DEEPER PASSES β€” added for the "leave no stone unturned" run
# ========================================================================
{
"key": "jobs_uk_boards",
"title": "UK job boards + public-sector aggregators β€” council LGR/change roles (last 90d)",
"max_searches": 10,
"prompt": """Today is {today}. Conduct a thorough job-board sweep for senior LGR / transformation / change / programme leadership roles at UK councils in the last 90 days. Cover ALL of these sources:
- **JobsGoPublic** (jobsgopublic.com) β€” UK public-sector specialist
- **LG Jobs** (lgjobs.com) β€” Local Government Jobs aggregator
- **MJ Recruitment** (themj.co.uk/jobs) β€” Municipal Journal jobs board
- **LGC Jobs** (jobs.lgcplus.com) β€” Local Government Chronicle jobs
- **gov.uk Civil Service Jobs** (civilservicejobs.service.gov.uk) β€” search for council secondments and dual-hatted roles
- **Reed.co.uk** β€” site:reed.co.uk + "programme director" + council
- **Totaljobs**, **Indeed UK**, **CV-Library** β€” same approach
- Direct council careers pages where prominent (Hampshire, Surrey, Essex, Hertfordshire have well-indexed sites)
Roles to find:
- Programme Director (LGR / transformation / change)
- Director of Transformation / Director of Change
- LGR Transition Lead / LGR Programme Director
- Chief Executive (interim or new, council)
- Chief Operating Officer (council)
- s151 Officer / Director of Resources (where financial stress visible)
- Head of Operating Model / Head of Service Design
Return a JSON array (no prose, no fences) with EVERY role found, not a summary:
{{
"jobs": [
{{
"council": "...",
"title": "exact job title",
"salary": "if known, e.g. Β£135,000",
"posted_date": "YYYY-MM-DD if known",
"closing_date": "YYYY-MM-DD if known",
"permanent_or_interim": "permanent | interim | fixed_term | unknown",
"platform": "Reed | LGC | MJ | JobsGoPublic | LG Jobs | gov.uk | council direct | LinkedIn-via-Google | other",
"source_url": "direct link to the posting",
"lgr_context": "1 sentence about LGR / transformation relevance"
}}
]
}}"""
},
{
"key": "tenders_deep",
"title": "Tender sweep β€” FTS + Contracts Finder + council e-tendering PORTALS (ProContract etc.)",
"max_searches": 12,
"prompt": """Today is {today}. Conduct a thorough public-sector tender sweep for UK councils procuring LGR / transformation / change / operating-model services.
CRITICAL LESSON β€” DO NOT MISS PORTAL-ONLY OPPORTUNITIES: A large share of council procurement (especially LGR "strategic delivery partner" and "transformation partner" work) is posted ONLY on council e-tendering portals, NOT on Find a Tender. You MUST search these portals directly by domain, not just FTS/Contracts Finder. Run explicit site: searches against EACH of these:
- **ProContract / Due North** β€” site:procontract.due-north.com (VERY IMPORTANT β€” many councils use this)
- **In-Tend** β€” site:in-tendhost.co.uk
- **Proactis / ProContract P2P** β€” site:supplierlive.proactisp2p.com OR "proactis" council tender
- **Jaggaer / BravoSolution** β€” site:uk.eu-supply.com
- **Delta eSourcing** β€” site:delta-esourcing.com
- **Find a Tender** (find-tender.service.gov.uk) and **Contracts Finder** (contractsfinder.service.gov.uk)
- **Crown Commercial Service** frameworks β€” RM6187 MCF3, others
- **NEPO / YPO / ESPO / Pro5** consortia
Run searches like: `site:procontract.due-north.com "local government reorganisation"`, `"LGR strategic delivery partner" council`, `council "transformation partner" OR "strategic delivery partner" tender 2026`, `site:procontract.due-north.com transformation OR "operating model"`.
TIME WINDOW: prioritise OPEN opportunities (EOI/ITT still accepting) and anything published in the last 6 months. Do NOT restrict to 90 days β€” LGR partnership procurements with long lead times and PINs published earlier are exactly what we must catch.
Signal types: LGR transition/delivery partner, strategic delivery partnership, operating model / target operating model, programme management/PMO, programme assurance/recovery, change management, ERP implementation partner, interim leadership, org design, PINs (early warning).
Return a JSON array (no prose, no fences) with EVERY notice found β€” INCLUDE the portal source:
{{
"tenders": [
{{
"council": "...",
"notice_type": "tender" | "EOI" | "PIN" | "framework_call_off" | "contract_award",
"title": "exact title from notice",
"reference": "procurement ref e.g. CST328 / DN822382 if shown",
"value_gbp": "approximate value if known, else empty",
"publish_date": "YYYY-MM-DD if known",
"deadline": "YYYY-MM-DD if applicable β€” flag if OPEN/closing soon",
"portal": "which portal it was found on (ProContract/FTS/In-Tend/etc.)",
"contact": "named contact + email if shown, else empty",
"source_url": "direct link to the notice/advert",
"lgr_relevance": "1 sentence on why this is relevant to Curium"
}}
]
}}"""
},
{
"key": "linkedin_deep",
"title": "Deep LinkedIn-via-Google sweep for named programme/transformation leaders at councils",
"max_searches": 12,
"prompt": """Today is {today}. Use web_search with `site:linkedin.com` queries (this reads Google's PUBLIC index of LinkedIn β€” no LinkedIn authentication, no account risk) to find specific named individuals currently in or recently appointed to senior transformation/change/programme roles at UK councils involved in LGR.
Run targeted queries like:
- `site:linkedin.com "Programme Director" "{{council name}}"`
- `site:linkedin.com "Director of Transformation" county council`
- `site:linkedin.com "Director of Change" "{{council}}"`
- `site:linkedin.com "LGR" programme director`
- `site:linkedin.com "interim" "{{council}}" transformation`
- Look for both LinkedIn profile URLs (linkedin.com/in/...) and LinkedIn post URLs (linkedin.com/posts/...)
Cover these councils with priority (this is who Curium cares about):
Surrey, Essex, Hampshire, Norfolk, Suffolk, Hertfordshire, Worcestershire, Warwickshire, Nottinghamshire, Lancashire, Oxfordshire, Birmingham, Sussex, Kent, Lincolnshire, Cambridgeshire, Devon, Leicestershire, Gloucestershire, Derbyshire, Staffordshire.
Return a JSON array (no prose, no fences):
{{
"people": [
{{
"name": "Full name",
"council": "Current or most-recent council affiliation",
"role_title": "exact title from LinkedIn",
"role_start": "YYYY-MM if visible",
"is_interim": true/false,
"linkedin_url": "linkedin.com/in/... URL",
"context": "1-2 sentences from their LinkedIn profile or post about their LGR/transformation work",
"source_url": "the specific LinkedIn URL"
}}
]
}}"""
},
{
"key": "moderngov_cabinet",
"title": "Council Cabinet papers / committee agendas mentioning LGR or transformation",
"max_searches": 8,
"prompt": """Today is {today}. UK councils publish Cabinet papers and committee agendas on their websites (typically via ModernGov, CMIS, or Committee Management Information Systems). These leak upcoming transformation programmes 3-6 months before tenders go out.
Use web_search to find recent (last 90 days) Cabinet / Committee papers discussing:
- LGR proposals, options, business cases
- Target operating model design
- Future Council / Future Operating Model programmes
- Transformation strategy refresh
- Programme assurance reviews
- Section 151 budget update papers mentioning transformation
- Devolution business cases
Search patterns to try:
- `site:moderngov.[council].gov.uk LGR cabinet`
- `"cabinet papers" LGR [county name]`
- `"committee agenda" "operating model" council [year]`
- `inurl:moderngov "target operating model"`
Cover the high-priority councils (Surrey, Essex, Hampshire, Norfolk, Suffolk, Hertfordshire, Warwickshire, Worcestershire, Nottinghamshire, Oxfordshire, Birmingham, Sussex).
Return a JSON array (no prose, no fences):
{{
"papers": [
{{
"council": "...",
"meeting_date": "YYYY-MM-DD",
"agenda_title": "exact title of the paper / report",
"decision_required": "what the Cabinet is being asked to decide",
"lgr_signal_strength": "high | medium | low",
"summary": "2-3 sentences on what's in the paper",
"source_url": "direct link to the paper / agenda PDF"
}}
]
}}"""
},
]
def _client() -> Anthropic:
key = os.environ.get("ANTHROPIC_API_KEY")
if not key:
print("ERROR: ANTHROPIC_API_KEY not set", file=sys.stderr)
sys.exit(2)
return Anthropic(api_key=key)
def _strip_fence(s: str) -> str:
s = s.strip()
if s.startswith("```"):
s = s.split("```", 2)[1]
if s.startswith("json"):
s = s[4:]
s = s.strip()
return s
def run_pass(client: Anthropic, pass_def: dict) -> dict:
prompt = pass_def["prompt"].format(today=TODAY, max_searches=pass_def["max_searches"])
print(f"\nβ–Ά Pass: {pass_def['title']}")
print(f" Budget: {pass_def['max_searches']} web searches")
started = time.time()
resp = client.messages.create(
model=MODEL,
max_tokens=8000,
tools=[{"type": "web_search_20250305", "name": "web_search",
"max_uses": pass_def["max_searches"]}],
messages=[{"role": "user", "content": prompt}],
)
elapsed = time.time() - started
# Extract text + citations
text_parts: list[str] = []
citations: list[dict] = []
seen_urls: set[str] = set()
for block in resp.content:
if getattr(block, "type", None) == "text" and getattr(block, "text", None):
text_parts.append(block.text)
for c in (getattr(block, "citations", None) or []):
u = getattr(c, "url", None)
if u and u not in seen_urls:
seen_urls.add(u)
citations.append({"url": u, "title": getattr(c, "title", "") or ""})
elif getattr(block, "type", None) == "web_search_tool_result":
for r in getattr(block, "content", None) or []:
u = getattr(r, "url", None)
if u and u not in seen_urls:
seen_urls.add(u)
citations.append({"url": u, "title": getattr(r, "title", "") or ""})
raw = _strip_fence("\n".join(text_parts).strip())
try:
data = json.loads(raw)
except Exception as e:
print(f" ⚠️ non-JSON response: {e}. First 200 chars: {raw[:200]}")
data = {"error": f"non-JSON: {e}", "raw": raw[:1000]}
n_items = sum(len(v) for v in data.values() if isinstance(v, list))
print(f" βœ“ {n_items} items, {len(citations)} cited sources, {elapsed:.0f}s")
return {"key": pass_def["key"], "title": pass_def["title"],
"data": data, "citations": citations, "elapsed_seconds": elapsed}
CONSOLIDATE_PROMPT = """You are consolidating nine focused research passes on UK Local Government Reorganisation (LGR) into a single canonical view.
═══════════════════════════════════════════════════════════════════
NON-NEGOTIABLE FACTUAL DISCIPLINE β€” READ FIRST
═══════════════════════════════════════════════════════════════════
This report goes to a consultancy's partners who will act on it. A single
fabricated fact destroys its credibility. Follow these rules absolutely:
1. EVERY factual claim β€” a council's LGR status, ANY date, a government
decision, a named person, a job posting, a tender/notice number, a unitary
count β€” MUST be directly supported by one of the cited sources in the PASS
DATA below. If it is not in the sources, DO NOT STATE IT. There are no
exceptions and no "reasonable inferences" for facts.
2. NEVER claim a government decision has been "made", "confirmed", "approved"
or "announced" unless a cited source explicitly says so, with a date. If
sources show only proposals submitted or a consultation running, the status
is "DECISION PENDING" β€” say exactly that. Do NOT invent unitary counts
(e.g. "5 unitaries") unless a source states the confirmed outcome.
3. Distinguish clearly between: (a) proposals SUBMITTED, (b) consultation
RUNNING/CLOSED, (c) decision PENDING/EXPECTED [date], (d) decision MADE
[date, source]. Most English LGR areas as of mid-2026 are at (c) β€” decisions
were widely expected around mid-July 2026. Do not upgrade a council's
status beyond what its sources support.
4. EVERY dated claim and every named person carries an inline citation marker
"[n]" pointing to the numbered References list. If you cannot cite it, you
cannot write it β€” omit it or mark the field "not found in sources".
5. If the pass data is thin or returned errors for a council, say so plainly:
"Limited verified data β€” sources cover X only." Do NOT fill the gap with
plausible-sounding specifics. A shorter, true report beats a fuller, false
one. "Unknown" is an acceptable and expected answer.
6. Begin the report with this exact caveat line, verbatim:
"> ⚠️ AI-synthesised from web search on {today}. Every claim is cited to a
source in the References. Verify decision dates, named contacts and notice
numbers against the cited source before acting on them."
═══════════════════════════════════════════════════════════════════
Source data from each pass is below, each with its Cited URLs. Some councils will appear in multiple passes β€” merge by council name. Resolve conflicting facts by preferring the most recent date and the most authoritative source (gov.uk > BBC/FT > Local Government Chronicle > local press). When sources conflict on a decision/date, report the discrepancy rather than picking one silently.
Produce TWO outputs:
(1) A markdown report titled "UK Local Government Reorganisation Landscape β€” {today} (DEEP SWEEP)". Structure:
- The mandatory caveat line from rule 6 above.
- Executive summary (3-4 paragraphs: scale of opportunity, where Curium's sweet spot is, top 5 highest-priority councils to engage this quarter, what's NEW since the shallower last sweep). EVERY specific in the summary carries a [n] citation. State council statuses precisely per rule 2-3 β€” do not assert decisions that sources don't confirm.
- Section A: Councils by LGR stage (group councils β€” proposals submitted, awaiting decision, mobilising, etc.)
- Section B: Crisis / intervention (Section 114, Best Value, commissioners)
- Section C: Live job-market signal β€” every relevant council role found (with deep-link, salary, platform). This is where the deep sweep adds the most value.
- Section D: Tender / procurement signal β€” every relevant FTS / Contracts Finder / CCS notice. Group by council. Include PINs as early-warning.
- Section E: Named people β€” Programme Directors, Directors of Transformation, interim leadership at councils. ONLY include a person if a cited source names them in that role; add their [n] citation. Do NOT infer or guess names. If no named people are found for a council, omit it from this section rather than inventing one. Include LinkedIn/source profile URLs where found.
- Section F: Cabinet papers / committee agendas signalling upcoming transformation (3-6 months out).
- Section G: ERP-and-LGR overlap (Curium sweet spot)
- Section H: Recommended Curium outreach priority list β€” ranked 1-20 with reasoning per council, including SPECIFIC named contacts and SPECIFIC live job postings/tenders/papers to reference in outreach. CRITICAL: cross-reference each priority council against the "Curium warm-route contacts" block below β€” if any contact's prior employers includes the council, surface this prominently as a "Warm intro available via [name] ([their current Curium client], ex-[council])" line under that council's entry. This is the highest-value dot-join the tool can produce.
- Section I: Warm Routes & Internal Intros β€” a dedicated short table of every warm-route match found between the priority councils and the Curium contacts list. Columns: Target council | Curium contact | Their current Curium client | Their prior link to the target | Suggested ask (e.g. "Ask Pete if he can intro the Chief Exec / Director of Transformation"). If no matches, state "No warm routes identified β€” all engagement is cold this quarter."
- References (numbered list of all cited URLs)
(2) A JSON array of structured rows, one per council mentioned anywhere. Keys: council_name, council_type, lgr_stage (one of "proposals_submitted" | "consultation" | "decision_pending" | "decision_made" | "mobilising" | "unknown" β€” use "decision_made" ONLY with a citation), lgr_stage_source (the source URL backing the stage, or "" if unknown), preferred_option, decision_status (free text, e.g. "Decision expected mid-July 2026 per [url]; not yet made"), key_dates (object β€” each value a string that includes its source), intervention_status, transformation_hires (array β€” names ONLY if cited), erp_systems (array), live_tenders (array of short strings), live_jobs (array of short strings with title + URL), key_people (array of "Name β€” Role [url]" strings, cited only), curium_priority ("high" | "medium" | "low" | "monitor"), reasoning (2-3 sentences), confidence ("high" | "medium" | "low" β€” low if pass data was thin for this council). Never populate a field with an uncited specific; use "" or "not found in sources".
Wrap in this exact structure (no other prose, no fences):
<MARKDOWN_REPORT>
...
</MARKDOWN_REPORT>
<COUNCIL_ROWS_JSON>
[...]
</COUNCIL_ROWS_JSON>
=== CURIUM WARM-ROUTE CONTACTS ===
These are exec sponsors, ambassadors, and ex-employees who give Curium a credible internal intro path into a target council. When a priority council appears in any contact's prior_employers list, that contact is a warm intro route. Surface this aggressively in Section H and Section I.
{warm_routes}
=== PASS DATA ===
{pass_data}
"""
def consolidate(client: Anthropic, pass_results: list[dict]) -> tuple[str, list[dict]]:
pass_data_str = "\n\n".join(
f"## Pass: {p['title']}\n```json\n{json.dumps(p['data'], indent=2)}\n```\n\nCited URLs:\n"
+ "\n".join(f"- {c['url']}" for c in p["citations"])
for p in pass_results
)
print(f"\nβ–Ά Consolidating ({len(pass_data_str):,} chars of input)…")
msg = CONSOLIDATE_PROMPT.format(
today=TODAY, pass_data=pass_data_str,
warm_routes=_format_warm_routes(_load_curium_contacts()))
# Streaming is required by Anthropic SDK for calls that may exceed 10
# minutes β€” the deep sweep's consolidation is large enough to trip that
# threshold even when the actual response comes back faster. A 60k-char
# streaming call can be cut off mid-stream by a transient network drop
# (RemoteProtocolError / incomplete chunked read), which previously
# crashed the whole script after ~10 minutes of passes. Retry the
# consolidation up to 3 times with backoff so one network blip doesn't
# waste the entire run.
import httpx
body = ""
last_err = None
for attempt in range(1, 4):
started = time.time()
body_parts: list[str] = []
try:
with client.messages.stream(
model=MODEL, max_tokens=24000,
messages=[{"role": "user", "content": msg}],
) as stream:
for chunk in stream.text_stream:
body_parts.append(chunk)
body = "".join(body_parts)
elapsed = time.time() - started
print(f" βœ“ Consolidated, {len(body):,} chars, {elapsed:.0f}s")
break
except (httpx.RemoteProtocolError, httpx.ReadError,
httpx.ReadTimeout, httpx.ConnectError) as e:
last_err = e
got = sum(len(p) for p in body_parts)
print(f" ⚠️ Consolidation attempt {attempt}/3 dropped after "
f"{time.time()-started:.0f}s ({got:,} chars received): "
f"{type(e).__name__}. Retrying in {attempt*10}s…")
time.sleep(attempt * 10)
if not body:
raise RuntimeError(f"Consolidation failed after 3 attempts: {last_err}")
# Extract the two segments
import re
md_match = re.search(r"<MARKDOWN_REPORT>(.*?)</MARKDOWN_REPORT>", body, re.S)
json_match = re.search(r"<COUNCIL_ROWS_JSON>(.*?)</COUNCIL_ROWS_JSON>", body, re.S)
markdown = md_match.group(1).strip() if md_match else body
rows_raw = json_match.group(1).strip() if json_match else "[]"
rows_raw = _strip_fence(rows_raw)
try:
rows = json.loads(rows_raw)
except Exception as e:
print(f" ⚠️ Could not parse council rows JSON: {e}")
rows = []
return markdown, rows
def init_lgr_tracker_table():
conn = sqlite3.connect(DATABASE)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS lgr_tracker (
council_name TEXT PRIMARY KEY,
council_type TEXT,
lgr_stage TEXT,
preferred_option TEXT,
key_dates_json TEXT,
intervention_status TEXT,
transformation_hires_json TEXT,
erp_systems_json TEXT,
curium_priority TEXT,
reasoning TEXT,
last_refreshed TEXT NOT NULL
)
"""
)
# Defensive ALTER TABLE for the deep-sweep additions β€” same idempotent
# pattern used elsewhere in the codebase. Safe on schemas that already
# have these columns; safe on the fresh schema above too.
existing = {row[1] for row in conn.execute("PRAGMA table_info(lgr_tracker)").fetchall()}
if "live_tenders_json" not in existing:
conn.execute("ALTER TABLE lgr_tracker ADD COLUMN live_tenders_json TEXT")
if "live_jobs_json" not in existing:
conn.execute("ALTER TABLE lgr_tracker ADD COLUMN live_jobs_json TEXT")
if "key_people_json" not in existing:
conn.execute("ALTER TABLE lgr_tracker ADD COLUMN key_people_json TEXT")
conn.commit()
conn.close()
def persist_rows(rows: list[dict]) -> int:
if not rows:
return 0
init_lgr_tracker_table()
conn = sqlite3.connect(DATABASE)
now = datetime.now().isoformat(timespec="seconds")
n = 0
for r in rows:
name = (r.get("council_name") or "").strip()
if not name:
continue
try:
conn.execute(
"""
INSERT INTO lgr_tracker
(council_name, council_type, lgr_stage, preferred_option,
key_dates_json, intervention_status,
transformation_hires_json, erp_systems_json,
live_tenders_json, live_jobs_json, key_people_json,
curium_priority, reasoning, last_refreshed)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(council_name) DO UPDATE SET
council_type = excluded.council_type,
lgr_stage = excluded.lgr_stage,
preferred_option = excluded.preferred_option,
key_dates_json = excluded.key_dates_json,
intervention_status = excluded.intervention_status,
transformation_hires_json = excluded.transformation_hires_json,
erp_systems_json = excluded.erp_systems_json,
live_tenders_json = excluded.live_tenders_json,
live_jobs_json = excluded.live_jobs_json,
key_people_json = excluded.key_people_json,
curium_priority = excluded.curium_priority,
reasoning = excluded.reasoning,
last_refreshed = excluded.last_refreshed
""",
(
name,
r.get("council_type") or "",
r.get("lgr_stage") or "",
r.get("preferred_option") or "",
json.dumps(r.get("key_dates") or {}),
r.get("intervention_status") or "",
json.dumps(r.get("transformation_hires") or []),
json.dumps(r.get("erp_systems") or []),
json.dumps(r.get("live_tenders") or []),
json.dumps(r.get("live_jobs") or []),
json.dumps(r.get("key_people") or []),
r.get("curium_priority") or "monitor",
r.get("reasoning") or "",
now,
),
)
n += 1
except Exception as e:
print(f" ⚠️ row persist failed for {name}: {e}")
conn.commit()
conn.close()
return n
def main() -> int:
INTEL_DIR.mkdir(exist_ok=True)
client = _client()
pass_results = []
total_searches = 0
for p in PASSES:
try:
result = run_pass(client, p)
pass_results.append(result)
total_searches += p["max_searches"]
except Exception as e:
print(f" ⚠️ pass '{p['key']}' failed: {type(e).__name__}: {e}")
if not pass_results:
print("All passes failed.", file=sys.stderr)
return 1
markdown, rows = consolidate(client, pass_results)
# Persist β€” both Markdown (for git diffs / readability) and Word
# (for sharing with the team) versions of the report.
md_path = INTEL_DIR / f"lgr_landscape_{TODAY}.md"
md_path.write_text(markdown, encoding="utf-8")
docx_path = INTEL_DIR / f"lgr_landscape_{TODAY}.docx"
try:
from md_to_docx import markdown_to_docx
markdown_to_docx(markdown, docx_path,
title=f"UK LGR Landscape β€” {TODAY}")
docx_msg = f" Report (Word): {docx_path}"
except Exception as e:
docx_path = None
docx_msg = f" ⚠️ Word conversion failed: {type(e).__name__}: {e}"
persisted = persist_rows(rows)
print()
print("=" * 72)
print(f"DONE")
print(f" Passes complete: {len(pass_results)}/{len(PASSES)}")
print(f" Search budget used: ~{total_searches}")
print(f" Council rows persisted: {persisted}")
print(f" Report (Markdown): {md_path}")
print(docx_msg)
print(f" DB table: lgr_tracker")
print("=" * 72)
return 0
if __name__ == "__main__":
sys.exit(main())