GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / scripts

GlobalGrid2050 Major Project News V6 and 2 more files

A Python command-line tool in the scripts folder that fetches major projects, project news links, solar and battery storage (BESS), using SHA-256.

700 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 878 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. GlobalGrid2050 Major Project News V4 storage · globalgrid2050 / scripts/major_project_news_v4.py lines 1–92
  2. GlobalGrid2050 Major Project News V5 storage · globalgrid2050 / scripts/major_project_news_v5.py lines 1–109
  3. GlobalGrid2050 Major Project News V6 storage · globalgrid2050 / scripts/major_project_news_v6.py lines 1–499

GlobalGrid2050 Major Project News V4

A Python command-line tool in the scripts folder that fetches Renewable Energy Planning Database (REPD) master, major projects, solar and battery storage (BESS).

storageglobalgrid2050 / scripts/major_project_news_v4.py · lines 1–92 of 92 · Entry point · pattern fetch_rss (shared by 3 files)

What it does
It fetches REPD master, major projects, solar and battery storage (BESS). Defines 10 functions or classes, including clean, norm, toks, load_projects, fetch_rss. Uses libraries __future__, json, math, re, time. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, battery storage (BESS).
Inputs & outputs
In: JSON file repd_master.json; JSON file major_project_news_v4.json; JSON file major_projects_v4.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Major Project News V4 Workflow (globalgrid2050).
What it achieves
It loads projects (`load_projects`) and fetches rss (`fetch_rss`). Defines `clean`, `norm`, `toks` and 6 more.
Why it matters
Run by GlobalGrid2050 Major Project News V4 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, json, math, re, time, xml.etree.ElementTree, datetime, email.utils
Used by
run by GlobalGrid2050 Major Project News V4 Workflow (workflow run)
Produces
clean, norm, toks, load_projects, fetch_rss, event, pub_bonus, score, collect, main
Defines here
clean, norm, toks, load_projects, fetch_rss, event, pub_bonus, score, collect, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/major_project_news_v4.py:1-92 · blob 7822e5bb19f27fd70b62283277d1bdf5fb7e407c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import json, math, re, time, xml.etree.ElementTree as ET
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.parse import quote_plus
import requests
ROOT=Path(__file__).resolve().parents[1]
REPD_PATH=ROOT/'dist'/'repd_master.json'; NEWS_OUT=ROOT/'dist'/'major_project_news_v4.json'; PROJECTS_OUT=ROOT/'dist'/'major_projects_v4.json'
SOLAR_MIN_MW=30.0; BESS_MIN_MW=100.0; MAX_HEADLINES=12; TARGETED_PER_TECH=25; MIN_SCORE=60
RSS_QUERIES=['"solar farm" UK MW','"solar park" UK MW','"battery energy storage" UK MW','BESS UK MW','"development consent" solar UK','"financial close" battery UK','"commercial operation" battery UK']
EVENTS=[('OPERATIONAL',['commercial operation','operational','energised','energized','commissioned']),('CONSTRUCTION',['construction','breaking ground','build begins','under construction']),('CONSENT',['development consent','planning consent','approved','approval','consented']),('FINANCIAL CLOSE',['financial close','financing','funding secured']),('ACQUISITION',['acquires','acquired','acquisition'  … [line shortened here: 622 characters; full line on GitHub]
STOP={'solar','farm','park','energy','battery','storage','bess','project','limited','ltd','plc','the','and','of','at','uk','phase','site','development','power','renewables','renewable'}
def clean(v):
 s=str(v or ''); return '' if s.lower() in {'nan','none','null'} else s.strip()
def norm(v):
 s=clean(v).lower().replace('&',' and '); s=re.sub(r'[^a-z0-9]+',' ',s); return re.sub(r'\s+',' ',s).strip()
def toks(v): return {t for t in norm(v).split() if len(t)>=3 and t not in STOP}
def load_projects():
 data=json.loads(REPD_PATH.read_text(encoding='utf-8')); out=[]; seen=set()
 for f in data.get('features',[]):
  p=f.get('properties',{}); tech=clean(p.get('tech'))
  try: mw=float(p.get('capacity') or 0)
  except: continue
  if not math.isfinite(mw): continue
  if not ((tech in {'solar','solar_roof'} and mw>=SOLAR_MIN_MW) or (tech=='bess' and mw>=BESS_MIN_MW)): continue
  name=clean(p.get('name')) or 'Unknown Site'; cat='solar' if tech in {'solar','solar_roof'} else 'bess'; key=(norm(name),cat,round(mw,3))
  if key in seen: continue
  seen.add(key); operator=clean(p.get('operator')); county=clean(p.get('county') or p.get('local_planning_authority') or p.get('region'))
  out.append({'id':re.sub(r'[^a-z0-9]+','-',norm(name)).strip('-')[:80] or 'project','name':name,'operator':operator,'county':county,'status':clean(p.get('status')),'technology':cat,'capacity_mw':round(mw,3),'_name_norm':norm(name),'_name_tokens':sorted(toks(name)),'_operator_tokens':sorted(toks(operator)),'_county_tokens':sorted(toks(county))})
 out.sort(key=lambda x:(-x['capacity_mw'],x['name'])); return out
def fetch_rss(q):
 url='https://news.google.com/rss/search?q='+quote_plus(q)+'&hl=en-GB&gl=GB&ceid=GB:en'; r=requests.get(url,headers={'User-Agent':'GlobalGrid2050/4.0 (+https://globalgrid2050.com/)'},timeout=25); r.raise_for_status(); root=ET.fromstring(r.content); rows=[]
 for i in root.findall('.//item'):
  title=clean(i.findtext('title')); link=clean(i.findtext('link')); desc=clean(i.findtext('description')); pub=clean(i.findtext('pubDate')); src=i.find('source'); source=clean(src.text if src is not None else ''); source_url=clean(src.attrib.get('url') if src is not None else '')
  if not title or not link: continue
  try:
   dt=parsedate_to_datetime(pub); dt=dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc); dt=dt.astimezone(timezone.utc)
  except: dt=datetime.now(timezone.utc)
  rows.append({'title':title,'link':link,'description':re.sub(r'<[^>]+>',' ',desc),'published':dt,'source':source,'source_url':source_url})
 return rows
def event(text):
 t=norm(text)
 for label,needles in EVENTS:
  if any(norm(n) in t for n in needles): return label
 return 'PROJECT UPDATE'
def pub_bonus(source,url):
 s=norm(source)+' '+norm(url)
 if any(x in s for x in ['gov uk','planning inspectorate','planninginspectorate']): return 18
 if any(x in s for x in ['solar power portal','energy storage news','pv tech']): return 12
 return 5
def score(p,s):
 text=norm(s['title']+' '+s['description']+' '+s['source']); tt=set(text.split()); sc=0
 if p['_name_norm'] and p['_name_norm'] in text: sc+=70
 else:
  ov=len(set(p['_name_tokens']) & tt); sc += 50 if ov>=3 else 35 if ov==2 else 22 if ov==1 and len(p['_name_tokens'])==1 else 0
 op=set(p['_operator_tokens']); co=set(p['_county_tokens']); sc += 18 if op and len(op&tt)>=min(2,len(op)) else 8 if op&tt else 0; sc += 10 if co&tt else 0
 for m in re.findall(r'\b(\d{2,4}(?:\.\d+)?)\s*mw\b',text):
  try:
   if abs(float(m)-p['capacity_mw'])<=max(10,p['capacity_mw']*.2): sc+=15; break
  except: pass
 age=max(0,(datetime.now(timezone.utc)-s['published']).days); sc += 20 if age<=14 else 15 if age<=30 else 8 if age<=90 else -15 if age>365 else 0
 if event(text)!='PROJECT UPDATE': sc+=12
 return sc+pub_bonus(s['source'],s['source_url'])
def collect(projects):
 raw=[]; seen=set(); queries=list(RSS_QUERIES)
 for cat in ('solar','bess'):
  for p in [x for x in projects if x['technology']==cat][:TARGETED_PER_TECH]: queries.append(f'"{p["name"]}" '+('solar UK' if cat=='solar' else '"battery storage" UK'))
 for n,q in enumerate(queries):
  try:
   for s in fetch_rss(q):
    if s['link'] not in seen: seen.add(s['link']); raw.append(s)
  except Exception as e: print('WARN',q,e)
  if n>=len(RSS_QUERIES) and n%8==0: time.sleep(.35)
 matches=[]
 for p in projects:
  best=None
  for s in raw:
   sc=score(p,s)
   if sc<MIN_SCORE: continue
   rank=(sc,s['published'].timestamp())
   if best is None or rank>best[0]: best=(rank,s)
  if best:
   sc=best[0][0]; s=best[1]
   matches.append({'project_id':p['id'],'project':p['name'],'technology':p['technology'],'capacity_mw':p['capacity_mw'],'operator':p['operator'],'county':p['county'],'status':p['status'],'event':event(s['title']+' '+s['description']),'headline':re.sub(r'\s+-\s+[^-]{2,80}$','',s['title']).strip(),'published':s['published'].date().isoformat(),'source':s['source'] or 'Google News','source_url':s['sou  … [line shortened here: 457 characters; full line on GitHub]
 matches.sort(key=lambda x:(x['published'],x['confidence'],x['capacity_mw']),reverse=True); return matches[:MAX_HEADLINES]
def main():
 projects=load_projects(); public=[{k:v for k,v in p.items() if not k.startswith('_')} for p in projects]; now=datetime.now(timezone.utc).isoformat()
 PROJECTS_OUT.write_text(json.dumps({'schema':'globalgrid2050.major-projects.v4','updated':now,'thresholds':{'solar_mw':SOLAR_MIN_MW,'bess_mw':BESS_MIN_MW},'count':len(public),'projects':public},indent=2),encoding='utf-8')
 headlines=collect(projects); NEWS_OUT.write_text(json.dumps({'schema':'globalgrid2050.major-project-news.v4','updated':now,'thresholds':{'solar_mw':SOLAR_MIN_MW,'bess_mw':BESS_MIN_MW},'eligible_projects':len(projects),'headline_count':len(headlines),'method':'REPD eligibility -> RSS discovery -> deterministic entity scoring -> dedupe','items':headlines},indent=2),encoding='utf-8'); print('eligibl  … [line shortened here: 444 characters; full line on GitHub]
if __name__=='__main__': main()

GlobalGrid2050 Major Project News V5

A Python command-line tool in the scripts folder that fetches Renewable Energy Planning Database (REPD) master, major projects, solar and battery storage (BESS).

storageglobalgrid2050 / scripts/major_project_news_v5.py · lines 1–109 of 109 · Entry point · pattern capacity_match (shared by 2 files)

What it does
It fetches REPD master, major projects, solar and battery storage (BESS). Defines 13 functions or classes, including clean, norm, toks, load_projects, fetch_rss. Uses libraries __future__, json, math, re, xml.etree.ElementTree. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, battery storage (BESS).
Inputs & outputs
In: JSON file repd_master.json; JSON file major_project_news_v5.json; JSON file major_projects_v5.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Major Project News V5 Workflow (globalgrid2050).
What it achieves
It loads projects (`load_projects`) and fetches rss (`fetch_rss`). Defines `clean`, `norm`, `toks` and 9 more.
Why it matters
Run by GlobalGrid2050 Major Project News V5 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, json, math, re, xml.etree.ElementTree, concurrent.futures, datetime, email.utils
Used by
run by GlobalGrid2050 Major Project News V5 Workflow (workflow run)
Produces
clean, norm, toks, load_projects, fetch_rss, event, source_bonus, capacity_match, gate, score, queries, collect
Defines here
clean, norm, toks, load_projects, fetch_rss, event, source_bonus, capacity_match, gate, score, queries, collect, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/major_project_news_v5.py:1-109 · blob f9ea204b03a4b554bce13b984485b1837b60d1c8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import json, math, re, xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone, timedelta
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.parse import quote_plus
import requests

ROOT=Path(__file__).resolve().parents[1]
REPD_PATH=ROOT/'dist'/'repd_master.json'; NEWS_OUT=ROOT/'dist'/'major_project_news_v5.json'; PROJECTS_OUT=ROOT/'dist'/'major_projects_v5.json'
SOLAR_MIN_EXCLUSIVE=49.0; BESS_MIN_EXCLUSIVE=100.0; LOOKBACK_DAYS=183; MAX_HEADLINES=200; MAX_PER_PROJECT=4; MIN_SCORE=64; BATCH_SIZE=20; WORKERS=12
PRIORITY_SOURCES={'BBC':'bbc.co.uk','Solar Power Portal':'solarpowerportal.co.uk','Energy-Storage.News':'energy-storage.news','PV Magazine':'pv-magazine.com'}
BROAD_QUERIES=['"solar farm" UK MW','"solar park" UK MW','"solar energy park" UK MW','"battery energy storage" UK MW','BESS UK MW','"battery storage" UK grid','"development consent" solar UK','"planning consent" solar UK','"financial close" solar UK','"financial close" battery UK','"construction" solar farm UK','"construction" battery storage UK','"commercial operation" battery UK','"energised" ba  … [line shortened here: 475 characters; full line on GitHub]
SOURCE_QUERIES=[f'site:{d} UK {t}' for d in PRIORITY_SOURCES.values() for t in ('solar farm MW','solar consent construction operational','battery storage MW','BESS consent construction operational')]
EVENTS=[('OPERATIONAL',['commercial operation','operational','energised','energized','commissioned','goes live','entered operation']),('CONSTRUCTION',['construction','breaking ground','build begins','under construction','construction starts']),('CONSENT',['development consent','planning consent','approved','approval','consented','permission granted']),('FINANCIAL CLOSE',['financial close','financi  … [line shortened here: 772 characters; full line on GitHub]
STOP={'solar','farm','park','energy','battery','storage','bess','project','limited','ltd','plc','the','and','of','at','uk','phase','site','development','power','renewables','renewable'}
GENERIC_SINGLE={'grange','manor','common','lodge','hall','hill','fields','field','wood','woods','green','bridge','bank','brook','mill','moor','marsh','meadow','meadows'}
FOREIGN_PHRASES={'new jersey','california','texas','australia','canada','germany','italy','spain','india','china','south africa','new zealand','ireland','united states','us roundup'}

def clean(v):
 s=str(v or ''); return '' if s.lower() in {'nan','none','null'} else s.strip()
def norm(v): return re.sub(r'\s+',' ',re.sub(r'[^a-z0-9]+',' ',clean(v).lower().replace('&',' and '))).strip()
def toks(v): return {t for t in norm(v).split() if len(t)>=3 and t not in STOP}
def load_projects():
 data=json.loads(REPD_PATH.read_text(encoding='utf-8')); out=[]; seen=set()
 for f in data.get('features',[]):
  p=f.get('properties',{}); tech=clean(p.get('tech'))
  try: mw=float(p.get('capacity') or 0)
  except: continue
  if not math.isfinite(mw): continue
  solar=tech in {'solar','solar_roof'} and mw>SOLAR_MIN_EXCLUSIVE; bess=tech=='bess' and mw>BESS_MIN_EXCLUSIVE
  if not(solar or bess): continue
  name=clean(p.get('name')) or 'Unknown Site'; cat='solar' if solar else 'bess'; key=(norm(name),cat,round(mw,3))
  if key in seen: continue
  seen.add(key); op=clean(p.get('operator')); county=clean(p.get('county') or p.get('local_planning_authority') or p.get('region'))
  out.append({'id':re.sub(r'[^a-z0-9]+','-',norm(name)).strip('-')[:80] or 'project','name':name,'operator':op,'county':county,'status':clean(p.get('status')),'technology':cat,'capacity_mw':round(mw,3),'_name_norm':norm(name),'_name_tokens':sorted(toks(name)),'_operator_tokens':sorted(toks(op)),'_county_tokens':sorted(toks(county))})
 return sorted(out,key=lambda x:(-x['capacity_mw'],x['name']))
def fetch_rss(q):
 url='https://news.google.com/rss/search?q='+quote_plus(f'{q} when:6m')+'&hl=en-GB&gl=GB&ceid=GB:en'; r=requests.get(url,headers={'User-Agent':'GlobalGrid2050/5.4 (+https://globalgrid2050.com/)'},timeout=15); r.raise_for_status(); root=ET.fromstring(r.content); cutoff=datetime.now(timezone.utc)-timedelta(days=LOOKBACK_DAYS); rows=[]
 for i in root.findall('.//item'):
  title=clean(i.findtext('title')); link=clean(i.findtext('link')); desc=clean(i.findtext('description')); src=i.find('source'); source=clean(src.text if src is not None else ''); source_url=clean(src.attrib.get('url') if src is not None else '')
  try: dt=parsedate_to_datetime(clean(i.findtext('pubDate'))); dt=(dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)).astimezone(timezone.utc)
  except: continue
  if title and link and dt>=cutoff: rows.append({'title':title,'link':link,'description':re.sub(r'<[^>]+>',' ',desc),'published':dt,'source':source,'source_url':source_url})
 return rows
def event(text):
 t=norm(text)
 for label,needles in EVENTS:
  if any(norm(n) in t for n in needles): return label
 return 'PROJECT UPDATE'
def source_bonus(s,u):
 x=norm(s)+' '+norm(u)
 if any(v in x for v in ('gov uk','planning inspectorate','planninginspectorate')): return 22
 if any(v in x for v in ('solar power portal','energy storage news','pv magazine','bbc')): return 20
 return 5
def capacity_match(p,text):
 for m in re.findall(r'\b(\d{2,4}(?:\.\d+)?)\s*mw\b',text):
  try:
   if abs(float(m)-p['capacity_mw'])<=max(10,p['capacity_mw']*.2): return True
  except: pass
 return False
def gate(p,s):
 text=norm(s['title']+' '+s['description']+' '+s['source']); tt=set(text.split()); names=set(p['_name_tokens']); op=set(p['_operator_tokens']); county=set(p['_county_tokens']); exact=bool(p['_name_norm'] and p['_name_norm'] in text); overlap=len(names&tt); op_hit=bool(op&tt); county_hit=bool(county&tt); cap_hit=capacity_match(p,text); official=any(x in norm(s['source']+' '+s['source_url']) for x i  … [line shortened here: 595 characters; full line on GitHub]
 foreign=any(norm(x) in text and norm(x) not in p['_name_norm'] for x in FOREIGN_PHRASES)
 if foreign and not(exact and (county_hit or official)): return False
 if not exact and overlap<2: return False
 if len(names)==1 and next(iter(names),'') in GENERIC_SINGLE and not(exact and tech_hit and (op_hit or county_hit or cap_hit or official)): return False
 if not tech_hit and not(official and exact) and not(exact and cap_hit and (op_hit or county_hit)): return False
 return True
def score(p,s):
 if not gate(p,s): return -999
 text=norm(s['title']+' '+s['description']+' '+s['source']); tt=set(text.split()); names=set(p['_name_tokens']); op=set(p['_operator_tokens']); county=set(p['_county_tokens']); exact=p['_name_norm'] in text; ov=len(names&tt); sc=70 if exact else 50 if ov>=3 else 38
 sc+=18 if op and len(op&tt)>=min(2,len(op)) else 8 if op&tt else 0; sc+=12 if county&tt else 0; sc+=15 if capacity_match(p,text) else 0; age=max(0,(datetime.now(timezone.utc)-s['published']).days); sc+=18 if age<=14 else 14 if age<=30 else 10 if age<=90 else 6; sc+=12 if event(text)!='PROJECT UPDATE' else 0
 return sc+source_bonus(s['source'],s['source_url'])
def queries(projects):
 qs=BROAD_QUERIES+SOURCE_QUERIES
 for cat in ('solar','bess'):
  names=[p['name'] for p in projects if p['technology']==cat]; suffix='solar UK' if cat=='solar' else '"battery storage" UK'
  for n in range(0,len(names),BATCH_SIZE): qs.append('('+' OR '.join('"'+x.replace('"','')+'"' for x in names[n:n+BATCH_SIZE])+') '+suffix)
 return qs
def collect(projects):
 raw=[]; seen=set(); qs=queries(projects)
 with ThreadPoolExecutor(max_workers=WORKERS) as ex:
  futs={ex.submit(fetch_rss,q):q for q in qs}
  for f in as_completed(futs):
   try: rows=f.result()
   except Exception as e: print('WARN',futs[f],e); continue
   for s in rows:
    key=(norm(s['title']),s['source_url'] or s['source'])
    if s['link'] not in seen and key not in seen: seen.add(s['link']); seen.add(key); raw.append(s)
 matches=[]; global_seen=set(); rejected=0
 for p in projects:
  cand=[]
  for s in raw:
   if not gate(p,s): rejected+=1; continue
   sc=score(p,s)
   if sc>=MIN_SCORE: cand.append((s['published'].timestamp(),sc,s))
  cand.sort(reverse=True,key=lambda x:(x[0],x[1])); kept=0
  for _,sc,s in cand:
   hk=norm(s['title'])
   if not hk or hk in global_seen: continue
   global_seen.add(hk); matches.append({'project_id':p['id'],'project':p['name'],'technology':p['technology'],'capacity_mw':p['capacity_mw'],'operator':p['operator'],'county':p['county'],'status':p['status'],'event':event(s['title']+' '+s['description']),'headline':re.sub(r'\s+-\s+[^-]{2,80}$','',s['title']).strip(),'published':s['published'].date().isoformat(),'source':s['source'] or 'Google News  … [line shortened here: 487 characters; full line on GitHub]
   if kept>=MAX_PER_PROJECT: break
 matches.sort(key=lambda x:(x['published'],x['confidence'],x['capacity_mw']),reverse=True); print('queries',len(qs),'raw',len(raw),'rejected',rejected); return matches[:MAX_HEADLINES],rejected
def main():
 projects=load_projects(); now=datetime.now(timezone.utc).isoformat(); public=[{k:v for k,v in p.items() if not k.startswith('_')} for p in projects]; PROJECTS_OUT.write_text(json.dumps({'schema':'globalgrid2050.major-projects.v5','updated':now,'thresholds':{'solar_mw_exclusive':49.0,'bess_mw_exclusive':100.0},'count':len(public),'projects':public},indent=2),encoding='utf-8'); headlines,rejected=c  … [line shortened here: 1,148 characters; full line on GitHub]
if __name__=='__main__': main()

GlobalGrid2050 Major Project News V6

A Python command-line tool in the scripts folder that fetches major projects, project news links, solar and battery storage (BESS), using SHA-256.

storageglobalgrid2050 / scripts/major_project_news_v6.py · lines 1–499 of 1099 · Entry point · pattern descriptor_adjacent (shared by 2 files)

What it does
It fetches major projects, project news links, solar and battery storage (BESS). Defines 35 functions or classes, including scoring_reference, pin_scoring_reference, clean, norm, toks. Uses libraries __future__, hashlib, json, os, math. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, battery storage (BESS).
Inputs & outputs
In: JSON file major_projects_v6.json; JSON file manifest_v6.json; JSON file major_project_news_v6.json; JSON file project_news_links_v6.json.
Downstream impact
Used directly by 7 files: GlobalGrid2050 Build News Feed 2026q3 (globalgrid2050); GlobalGrid2050 Build News Feed V9 5 1 (globalgrid2050); GlobalGrid2050 Major Project News V6 Hardened (globalgrid2050); GlobalGrid2050 News Binder Refaware (globalgrid2050); and 3 more. Reached from 3 other entry points, including GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Validate Renewables V6 Integrity (globalgrid2050).
What it achieves
It writes JSON atomic (`write_json_atomic`), loads manifest (`load_manifest`) and loads project snapshot (`load_project_snapshot`). Build the public V6 newspaper from the validated V6 project snapshot. Its code works with 46.5 MW and 5 MW.
Why it matters
Imported by 5 files, including GlobalGrid2050 Build News Feed 2026q3, GlobalGrid2050 Build News Feed V9 5 1 and GlobalGrid2050 Major Project News V6 Hardened. Checked by 2 tests, including GlobalGrid2050 Test News Binder Refaware.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, hashlib, json, os, math, re, time, xml.etree.ElementTree
Used by
imported by GlobalGrid2050 Build News Feed 2026q3 (import), imported by GlobalGrid2050 Build News Feed V9 5 1 (import), imported by GlobalGrid2050 Major Project News V6 Hardened (import), imported by GlobalGrid2050 News Binder Refaware (import), imported by GlobalGrid2050 Test News Binder Refaware (import), imported by GlobalGrid2050 Test News Binder V9 5 (import), imported by GlobalGrid2050 Validate Renewables V6 Scope (import)
Produces
scoring_reference, pin_scoring_reference, clean, norm, toks, distinctive_name_stem, descriptor_adjacent, file_sha256, write_json_atomic, load_manifest, load_project_snapshot, load_projects
Defines here
scoring_reference, pin_scoring_reference, clean, norm, toks, distinctive_name_stem, descriptor_adjacent, file_sha256, write_json_atomic, load_manifest, _phrase_hit, load_project_snapshot, load_projects, fetch_rss, event, source_quality, source_bonus, extract_news_capacities, capacity_match, _contains_normalized_phrase, _foreign_locations
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/major_project_news_v6.py:1-499 · blob 3c7aeccc6fd01f21ca46059a7996b0796bc97556 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Build the public V6 newspaper from the validated V6 project snapshot.

The project snapshot is an immutable input. News is a separate intelligence
layer: every published article has exactly one canonical primary project while
other records in the development are context-only links.
"""
from __future__ import annotations

import hashlib
import json
import os
import math
import re
import time
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError, as_completed
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.parse import quote_plus, urlparse
from urllib.request import Request, urlopen

ROOT = Path(__file__).resolve().parents[1]
PROJECTS_PATH = ROOT / "dist" / "major_projects_v6.json"
MANIFEST_PATH = ROOT / "dist" / "manifest_v6.json"
NEWS_OUT = ROOT / "dist" / "major_project_news_v6.json"
LINKS_OUT = ROOT / "dist" / "project_news_links_v6.json"

SOLAR_MIN_EXCLUSIVE = 1.0
BESS_MIN_EXCLUSIVE = 100.0
EXPECTED_SOURCE_RECORDS = 14_657
EXPECTED_SOLAR_PROJECTS = 3_445
EXPECTED_BESS_PROJECTS = 269
EXPECTED_PROJECTS = EXPECTED_SOLAR_PROJECTS + EXPECTED_BESS_PROJECTS
LOOKBACK_DAYS = 183
MAX_HEADLINES = 300
MAX_REJECTED_ARTICLE_SAMPLES = 50
FLOOR_STRONG = 52
FLOOR_WEAK = 68
AMBIGUITY_MARGIN = 8
BATCH_SIZE = 25
MAX_BATCH_CHARS = 1350
WORKERS = 12
CRAWL_BUDGET_SECONDS = 170
# Leave time for a running 12-second request, global project matching and output
# validation before the outer 170-second workflow timeout. Source failures or a
# quiet period produce valid zero-item output through per-query handling.
NETWORK_BUDGET_SECONDS = 122

PRIORITY_SOURCES = {
    "DESNZ / GOV.UK": "gov.uk",
    "Planning Inspectorate": "planninginspectorate.gov.uk",
    "BBC": "bbc.co.uk",
    "Solar Power Portal": "solarpowerportal.co.uk",
    "Energy-Storage.News": "energy-storage.news",
    "PV Magazine": "pv-magazine.com",
}

BROAD_QUERIES = [
    '"solar farm" UK MW', '"solar park" UK MW', '"solar energy park" UK MW',
    '"solar photovoltaics" UK planning MW', '"battery energy storage" UK MW',
    "BESS UK MW", '"battery storage" UK grid', '"development consent" solar UK',
    '"planning consent" solar UK', '"planning permission" solar farm UK',
    '"financial close" solar UK', '"financial close" battery UK',
    '"construction" solar farm UK', '"construction" battery storage UK',
    '"commercial operation" solar UK', '"commercial operation" battery UK',
    '"energised" battery UK', '"acquisition" solar farm UK',
    '"acquisition" battery storage UK',
]

SOURCE_QUERIES = [
    f"site:{domain} UK {topic}"
    for domain in PRIORITY_SOURCES.values()
    for topic in (
        "solar farm planning construction operational MW",
        "solar park consent approved MW",
        "battery storage BESS construction operational MW",
        "energy storage consent finance acquisition MW",
    )
]

EVENTS = [
    # Negative outcomes precede consent words so "planning permission refused"
    # can never be classified as a consent event merely because it contains
    # "planning permission".
    ("REFUSAL", ["refused", "rejected", "refusal", "turned down", "dismissed"]),
    ("DELAY", ["delayed", "delay", "judicial review", "postponed", "deferred"]),
    ("OPERATIONAL", ["commercial operation", "operational", "energised", "energized", "commissioned", "goes live", "entered operation"]),
    ("CONSTRUCTION", ["construction", "breaking ground", "build begins", "under construction", "construction starts"]),
    ("CONSENT", ["development consent", "consent awarded", "grants dco", "dco granted", "planning consent", "approved", "approval", "consented", "permission granted", "planning permission"]),
    ("FINANCIAL CLOSE", ["financial close", "financing", "funding secured", "debt financing"]),
    ("ACQUISITION", ["acquires", "acquired", "acquisition", "sold to", "sale of", "portfolio sale"]),
    ("GRID CONNECTION", ["grid connection", "connected to the grid", "connection agreement", "grid offer"]),
    ("CONTRACT", ["to optimise", "to optimize", "partner on", "awarded contract", "secures contract"]),
    ("EXPANSION", ["expansion", "expanded", "extension", "upsized"]),
]

STOP = {
    "solar", "farm", "park", "energy", "battery", "storage", "bess", "project",
    "limited", "ltd", "plc", "the", "and", "of", "at", "uk", "phase", "site",
    "development", "power", "renewables", "renewable", "scheme",
}
GENERIC_SINGLE = {
    "grange", "manor", "common", "lodge", "hall", "hill", "fields", "field", "wood",
    "woods", "green", "bridge", "bank", "brook", "mill", "moor", "marsh", "meadow", "meadows",
}

# Bare Ireland is intentionally absent: Northern Ireland is valid UK context.
FOREIGN_RULES = {
    "New Jersey": ("new jersey",), "California": ("california",), "Texas": ("texas",),
    "Australia": ("australia", "new south wales", "queensland", "victoria australia"),
    "Canada": ("canada", "alberta", "ontario", "ontario canada"), "Germany": ("germany",),
    "Italy": ("italy",), "Spain": ("spain",), "India": ("india",), "China": ("china",),
    "South Africa": ("south africa",), "New Zealand": ("new zealand",),
    "Republic of Ireland": ("republic of ireland", "irish republic"),
    "United States": ("united states", "u s roundup"), "New York": ("new york",),
    "Arizona": ("arizona",), "Nevada": ("nevada",), "Florida": ("florida",),
    "Ohio": ("ohio",), "Virginia": ("virginia",), "Massachusetts": ("massachusetts",),
    "Pennsylvania": ("pennsylvania",), "Colorado": ("colorado",),
}

QUERY_PLAN_META: dict[str, object] = {}

# REPD names often append addresses and technology after commas, spaced dashes
# or "near".  The press normally uses only the leading development identity.
SEGMENT_SPLIT_RE = re.compile(r"\s+-\s+|,|\bnear\b", flags=re.I)
NAME_BOILERPLATE = {
    "solar", "farm", "farms", "park", "parks", "battery", "storage", "energy",
    "bess", "pv", "photovoltaic", "photovoltaics", "project", "scheme",
    "development", "renewable", "renewables", "power", "station", "substation",
    "panels", "plant", "works", "hub", "facility", "system", "systems",
    "ltd", "limited", "plc", "site", "the", "and", "of", "at", "on", "in", "for", "to",
    "land", "extension",
}
NEWS_TECHNOLOGY_DESCRIPTORS = (
    "solar", "pv", "photovoltaic", "photovoltaics", "battery", "bess", "storage", "energy"
)
FOREIGN_PHRASES = {
    norm_phrase
    for label, phrases in FOREIGN_RULES.items()
    for norm_phrase in [re.sub(r"\s+", " ", re.sub(r"[^a-z0-9]+", " ", value.lower())).strip()
                        for value in (*phrases, label)]
    if norm_phrase
}
FOREIGN_PHRASES.add("ireland")


# ---------------------------------------------------------------------------
# The instant a story's age is measured from.
#
# WHY THIS IS NOT datetime.now().
#
# A story's recency contributes to its match score:
#
#     recency = 10 if age_days <= 14 else 8 if age_days <= 30 else 5 ... else 2
#
# Measured from the real clock, that makes the SCORE A FUNCTION OF WHEN YOU RUN
# THE CODE. Rebuilding a recorded edition then produces a different number from
# the one recorded in it, on nobody's change, and every gate that compares the
# rebuild against the recorded bytes goes red as time passes.
#
# It did. The V9.5.1 edition was scored on 2026-08-22 against a story published
# 2026-08-21 - one day old, recency 10, total 91. Re-run on 2026-09-06 the same
# story is sixteen days old, recency 8, total 89, and five validation chains
# failed on a repository nobody had touched: v9.5.1, v9.6.1, v9.6.2 and both
# timestamped releases.
#
# CVAA names this class directly (Ventusltd/cvaa, 202608301810-no-time-based-
# gates): a check whose result depends on when it runs is not a check.
#
# So a rebuild scores against the instant the edition was ORIGINALLY scored at.
# The caller pins it from the edition's own `updated` field; SOURCE_DATE_EPOCH
# is honoured second, for the reproducible-builds convention; and only a genuine
# live crawl - which has no recorded instant to inherit - falls through to the
# real clock.
#
# Note the crawl cutoff at the fetch site deliberately still uses the real
# clock: choosing which stories to FETCH is a question about now. Only the
# scoring of an already-recorded story must be reproducible.
SCORING_REFERENCE: datetime | None = None


def scoring_reference() -> datetime:
    if SCORING_REFERENCE is not None:
        return SCORING_REFERENCE
    epoch = os.environ.get("SOURCE_DATE_EPOCH")
    if epoch and epoch.strip().isdigit():
        return datetime.fromtimestamp(int(epoch.strip()), timezone.utc)
    return datetime.now(timezone.utc)


def pin_scoring_reference(value) -> datetime:
    """Pin the scoring instant, from an ISO string or a datetime."""
    global SCORING_REFERENCE
    if isinstance(value, datetime):
        moment = value
    else:
        moment = datetime.fromisoformat(str(value).strip().replace("Z", "+00:00"))
    if moment.tzinfo is None:
        moment = moment.replace(tzinfo=timezone.utc)
    SCORING_REFERENCE = moment
    return moment


def clean(value):
    text = str(value or "").strip()
    return "" if text.lower() in {"nan", "none", "null", "not set"} else text


def norm(value):
    return re.sub(r"\s+", " ", re.sub(r"[^a-z0-9]+", " ", clean(value).lower().replace("&", " and "))).strip()


def toks(value):
    return {token for token in norm(value).split() if len(token) >= 3 and token not in STOP}


def distinctive_name_stem(value) -> str:
    """Return the leading public identity with boilerplate stripped at both ends."""
    head = SEGMENT_SPLIT_RE.split(clean(value), maxsplit=1)[0]
    tokens = norm(head).split()
    while tokens and tokens[0] in NAME_BOILERPLATE:
        tokens.pop(0)
    while tokens and tokens[-1] in NAME_BOILERPLATE:
        tokens.pop()
    if not tokens or (len(tokens) == 1 and tokens[0] in GENERIC_SINGLE):
        return ""
    return " ".join(tokens)


def descriptor_adjacent(padded_text: str, stem: str) -> bool:
    """Require a one-token stem to sit beside public technology wording."""
    if not stem or len(stem.split()) != 1:
        return False
    tokens = padded_text.strip().split()
    descriptors = set(NEWS_TECHNOLOGY_DESCRIPTORS)
    unsafe_predecessors = {"the", "on", "of", "at", "in"}
    for index, token in enumerate(tokens):
        if token != stem or (index and tokens[index - 1] in unsafe_predecessors):
            continue
        next_index = index + 1
        if next_index < len(tokens) and tokens[next_index] in descriptors:
            return True
        if (
            next_index + 1 < len(tokens)
            and len(tokens[next_index]) <= 3
            and tokens[next_index + 1] in descriptors
        ):
            return True
    return False


def file_sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def write_json_atomic(path: Path, payload: dict) -> None:
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    temporary.replace(path)


def load_manifest() -> dict:
    if not MANIFEST_PATH.exists():
        raise RuntimeError("Missing dist/manifest_v6.json; V6 news cannot use a V4/V5 fallback")
    manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
    if manifest.get("schema") != "globalgrid2050.repd-manifest.v6" or int(manifest.get("schema_version") or 0) != 6:
        raise RuntimeError("dist/manifest_v6.json is not a V6 manifest")
    if manifest.get("status") != "VALIDATED":
        raise RuntimeError(f"V6 manifest is not validated: {manifest.get('status')!r}")
    return manifest


def _phrase_hit(value, text: str, text_tokens: set[str]) -> bool:
    phrase = norm(value)
    if not phrase:
        return False
    if f" {phrase} " in f" {text} ":
        return True
    parts = toks(value)
    return bool(parts) and len(parts & text_tokens) >= min(2, len(parts))


def load_project_snapshot() -> tuple[dict, list[dict]]:
    if not PROJECTS_PATH.exists():
        raise RuntimeError("Missing dist/major_projects_v6.json; no V5/private fallback is permitted")
    snapshot = json.loads(PROJECTS_PATH.read_text(encoding="utf-8"))
    if snapshot.get("schema") != "globalgrid2050.major-projects.v6":
        raise RuntimeError("Unexpected V6 project snapshot schema")
    rows = snapshot.get("projects")
    if not isinstance(rows, list):
        raise RuntimeError("V6 project snapshot has no projects array")
    declared_count = snapshot.get("project_count", snapshot.get("count"))
    if declared_count is not None and int(declared_count) != len(rows):
        raise RuntimeError(f"V6 project snapshot count mismatch: declared={declared_count} actual={len(rows)}")
    canonical_projects = json.dumps(rows, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
    actual_projects_hash = hashlib.sha256(canonical_projects.encode("utf-8")).hexdigest()
    if clean(snapshot.get("projects_sha256")) != actual_projects_hash:
        raise RuntimeError("V6 project snapshot projects_sha256 does not match its projects array")

    projects = []
    seen_refs, seen_gg = set(), set()
    for index, source in enumerate(rows):
        repd_ref = clean(source.get("repd_ref"))
        gg_project_id = clean(source.get("gg_project_id"))
        gg_development_id = clean(source.get("gg_development_id"))
        if not repd_ref or not gg_project_id or not gg_development_id:
            raise RuntimeError(f"V6 project row {index} lacks canonical REPD/GlobalGrid identity")
        if repd_ref in seen_refs or gg_project_id in seen_gg:
            raise RuntimeError(f"Duplicate V6 project identity: REPD={repd_ref} GG={gg_project_id}")
        seen_refs.add(repd_ref)
        seen_gg.add(gg_project_id)

        technology = clean(source.get("technology")).lower()
        if technology not in {"solar", "bess"}:
            raise RuntimeError(f"Unsupported V6 news technology {technology!r}: REPD {repd_ref}")
        if source.get("capacity_known") is not True:
            raise RuntimeError(f"Threshold-qualified project has unknown capacity: REPD {repd_ref}")
        try:
            capacity_mw = float(source.get("capacity_mw"))
        except Exception as exc:
            raise RuntimeError(f"Invalid official capacity for REPD {repd_ref}") from exc
        if not math.isfinite(capacity_mw):
            raise RuntimeError(f"Non-finite official capacity for REPD {repd_ref}")
        if technology == "solar" and not capacity_mw > SOLAR_MIN_EXCLUSIVE:
            raise RuntimeError(f"Solar threshold regression for REPD {repd_ref}: {capacity_mw}")
        if technology == "bess" and not capacity_mw > BESS_MIN_EXCLUSIVE:
            raise RuntimeError(f"BESS threshold regression for REPD {repd_ref}: {capacity_mw}")

        name = clean(source.get("name")) or "Unknown Site"
        operator, county = clean(source.get("operator")), clean(source.get("county"))
        region, country = clean(source.get("region")), clean(source.get("country"))
        authority = clean(source.get("planning_authority"))
        planning_ref = clean(source.get("planning_application_reference"))
        project = {
            "project_id": repd_ref, "repd_ref": repd_ref,
            "gg_project_id": gg_project_id, "gg_development_id": gg_development_id,
            "identity_status": clean(source.get("identity_status")) or "REPD_BOUND",
            "repd_record_updated": source.get("repd_record_updated") or None,
            "name": name, "operator": operator, "county": county, "region": region,
            "country": country, "status": clean(source.get("status")),
            "technology": technology, "capacity_mw": capacity_mw, "capacity_known": True,
            "planning_authority": authority, "planning_application_reference": planning_ref,
            "related_repd_refs": [clean(ref) for ref in (source.get("related_repd_refs") or []) if clean(ref)],
            "_name_norm": norm(name), "_name_tokens": toks(name),
            "_name_stem_norm": distinctive_name_stem(name),
            "_planning_ref_norm": norm(planning_ref),
        }
        project["_identity_context"] = norm(" ".join((name, county, region, country, authority, planning_ref)))
        projects.append(project)

    # Duplicate identity is development-scoped. Co-located solar/BESS records
    # with one gg_development_id are components of one public development, not
    # competing names that should invalidate one another.
    name_pairs = {
        (project["_name_norm"], project["gg_development_id"])
        for project in projects if project["_name_norm"]
    }
    stem_pairs = {
        (project["_name_stem_norm"], project["gg_development_id"])
        for project in projects if project["_name_stem_norm"]
    }
    name_counts = Counter(name for name, _development in name_pairs)
    stem_counts = Counter(stem for stem, _development in stem_pairs)
    for project in projects:
        project["_name_stem_tokens"] = toks(project["_name_stem_norm"])
        duplicate_count = name_counts[project["_name_norm"]]
        project["_name_duplicate_count"] = duplicate_count
        project["_name_duplicate"] = duplicate_count > 1
        project["_name_stem_duplicate_count"] = stem_counts.get(project["_name_stem_norm"], 0)
        project["_name_stem_duplicate"] = project["_name_stem_duplicate_count"] > 1
        project["_name_stem_foreign_collision"] = any(
            phrase == project["_name_stem_norm"]
            or f" {phrase} " in f" {project['_name_stem_norm']} "
            for phrase in FOREIGN_PHRASES
        )
        # Names made entirely from technology boilerplate (for example
        # "Solar Farm" or "Battery Storage") have no distinctive tokens and
        # must never pass identity on their text alone. The same applies to a
        # single generic place token such as "Grange" or "Common".
        project["_generic_name"] = not project["_name_tokens"] or (
            len(project["_name_tokens"]) == 1
            and next(iter(project["_name_tokens"])) in GENERIC_SINGLE
        )
    solar_count = sum(project["technology"] == "solar" for project in projects)
    bess_count = sum(project["technology"] == "bess" for project in projects)
    if (len(projects), solar_count, bess_count) != (
        EXPECTED_PROJECTS,
        EXPECTED_SOLAR_PROJECTS,
        EXPECTED_BESS_PROJECTS,
    ):
        raise RuntimeError(
            "V6 Q2 project universe mismatch: "
            f"projects={len(projects)} solar={solar_count} bess={bess_count}"
        )
    projects.sort(key=lambda project: (project["name"].casefold(), project["repd_ref"]))
    return snapshot, projects


def load_projects() -> list[dict]:
    return load_project_snapshot()[1]


def fetch_rss(query: str) -> list[dict]:
    requested = f"{query} when:6m"
    url = "https://news.google.com/rss/search?q=" + quote_plus(requested) + "&hl=en-GB&gl=GB&ceid=GB:en"
    request = Request(url, headers={"User-Agent": "GlobalGrid2050/6.0 (+https://globalgrid2050.com/)"})
    with urlopen(request, timeout=12) as response:
        root = ET.fromstring(response.read())
    cutoff = datetime.now(timezone.utc) - timedelta(days=LOOKBACK_DAYS)
    rows = []
    for item in root.findall(".//item"):
        title, link = clean(item.findtext("title")), clean(item.findtext("link"))
        description = clean(item.findtext("description"))
        source_node = item.find("source")
        source = clean(source_node.text if source_node is not None else "")
        source_url = clean(source_node.attrib.get("url") if source_node is not None else "")
        try:
            published = parsedate_to_datetime(clean(item.findtext("pubDate")))
            published = (published if published.tzinfo else published.replace(tzinfo=timezone.utc)).astimezone(timezone.utc)
        except Exception:
            continue
        if title and link and published >= cutoff:
            rows.append({"title": title, "link": link, "description": re.sub(r"<[^>]+>", " ", description),
                         "published": published, "source": source, "source_url": source_url})
    return rows


def event(text: str) -> str:
    normalized = norm(text)
    for label, needles in EVENTS:
        if any(norm(needle) in normalized for needle in needles):
            return label
    return "PROJECT UPDATE"


def source_quality(source: str, url: str) -> tuple[int, str, bool, bool]:
    """Score provenance by traceability, without making five publishers a gate."""
    source_text = norm(source)
    try:
        hostname = (urlparse(clean(url)).hostname or "").lower()
    except Exception:
        hostname = ""
    official_host = (
        hostname in {"gov.uk", "www.gov.uk"}
        or hostname == "planninginspectorate.gov.uk"
        or hostname.endswith(".planninginspectorate.gov.uk")
    )
    official = official_host
    configured_priority = official or any(
        domain == hostname or hostname.endswith("." + domain)
        for domain in PRIORITY_SOURCES.values()
    )
    if official:
        return 20, "official_government_or_planning", True, True
    if configured_priority:
        return 15, "configured_priority_publication", False, True
    # A named publisher with its own resolvable source URL receives a modest
    # provenance score. This admits reputable trade/local/developer sources
    # without turning the confidence rule into a fixed publisher whitelist;
    # identity must still pass independently before these points can matter.
    if source_text and hostname and "news.google." not in hostname:
        return 10, "traceable_named_public_source", False, False
    if source_text or hostname:
        return 7, "partially_traceable_public_source", False, False
    return 5, "unattributed_public_source", False, False


def source_bonus(source: str, url: str) -> int:
    return source_quality(source, url)[0]


def extract_news_capacities(text: str) -> list[float]:
    values = []
    for match in re.findall(r"\b(\d{1,4}(?:\.\d+)?)\s*mw(?:p)?\b", text, flags=re.I):
        try:
            value = float(match)
        except Exception:
            continue
        if math.isfinite(value) and value not in values:
            values.append(value)
    return values


def capacity_match(project: dict, text: str) -> bool:
    return any(abs(value - project["capacity_mw"]) <= max(2.0, project["capacity_mw"] * 0.15)
               for value in extract_news_capacities(text))


def _contains_normalized_phrase(text: str, phrase: str) -> bool:
    normalized = norm(phrase)
    return bool(normalized) and f" {normalized} " in f" {text} "


def _foreign_locations(text: str, project: dict) -> tuple[list[str], list[str]]:
    detected, unexplained = [], []
    for label, phrases in FOREIGN_RULES.items():