In this section
- Contracts transform · globalgrid2050 / automation/news/filings/contracts.py lines 1–295
- Documents storage · globalgrid2050 / automation/news/filings/documents.py lines 1–250
- Policy Context transform · globalgrid2050 / automation/news/filings/policy_context.py lines 1–78
- News — Grid Watch other · globalgrid2050 / automation/news/grid_watch/__init__.py lines 1–4
Contracts
A Python module in the filings folder of GlobalGrid2050 that validates claim (`validate_claim`) (units: MW), using SHA-256.
transformglobalgrid2050 / automation/news/filings/contracts.py · lines 1–295 of 295 · pattern _identifier (shared by 2 files)
- What it does
- It calculates its inputs. Defines 11 functions or classes, including ClaimValidationError, _fail, _object, _text, _identifier. Uses libraries __future__, collections.abc, copy, datetime, decimal.
- 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.
- Downstream impact
- Used directly by 6 files: Solar (globalgrid2050); Build Transition Context (globalgrid2050); Grid (globalgrid2050); Documents (globalgrid2050); and 2 more. Reached from 9 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It is built from the claim validation error class (`ClaimValidationError`) and the dumps claim helper (`dumps_claim`). Exact, provisional numerical claims for successor filings and project inputs.
- Why it matters
- Imported by 5 files, including Solar, Build Transition Context and Grid. Checked by Test Filing Figures.
- Application
- globalgrid2050 · automation/news/filings · Python module
- Uses
- __future__, collections.abc, copy, datetime, decimal, ipaddress, json, re
- Used by
- imported by Solar (import), imported by Build Transition Context (import), imported by Grid (import), imported by Documents (relative import), imported by Ledger (import), imported by Test Filing Figures (import)
- Produces
- ClaimValidationError, validate_claim, dumps_claim
- Defines here
- ClaimValidationError, _fail, _object, _text, _identifier, _choice, _source_date, _timestamp, _url, validate_claim, dumps_claim
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/filings/contracts.py:1-295 · blob 2ebc0984ce3d033e92bcfcd521e5890e20f825c5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Exact, provisional numerical claims for successor filings and project inputs.
Public API: ``validate_claim(mapping)`` returns an independent validated dict;
``dumps_claim(mapping)`` returns deterministic JSON. Invalid input raises
``ClaimValidationError`` (a ValueError). Standard library only; no I/O.
All keys below are required (nullable means an explicit JSON null). Unknown keys
are rejected at every level. The schema is ``globalgrid2050.filing-figure.v1``::
{
"schema": "globalgrid2050.filing-figure.v1",
"claim_id": "sec:example-filing:capex:1",
"status": "machine-provisional",
"quantity_kind": "finance", "metric": "Capital expenditure",
"value": "1.20", "scale": "1e9",
"unit": "currency", "original_unit": "billion US dollars",
"currency": "USD", "finance_stage": "announced",
"entity": {"scope": "consolidated_group", "id": "group:example",
"consolidation_group_id": "group:example",
"identity_evidence_url": "https://www.sec.gov/example"},
"reporting_period": {"start": "2026", "end": "2026"},
"as_of": "2026-10-31", "basis": "forecast", "assurance": "unknown",
"provenance": {"document_id": "sec:example-filing",
"document_url": "https://www.sec.gov/example",
"sha256": "<64 lowercase hex characters>",
"page": "12", "section": "Capital expenditure",
"published_date": "2026-11-01",
"retrieved_at": "2026-11-16T12:00:00Z"},
"revision": {"id": "original", "supersedes_claim_id": null,
"restated": false}
}
The example is synthetic documentation, not a claim about a real company.
Dates retain their source precision: YYYY, YYYY-MM or YYYY-MM-DD. Period ends
must have the same precision; absent period/as_of can be null, but not both.
Source publication may be null. Retrieval requires a timezone-aware timestamp.
Dates are not expanded in output. Forecast periods/as_of may be in the future;
source publication must still precede retrieval. ``metric`` retains the source's
measure label (for example capital expenditure versus revenue); no metric is
inferred from the number or its unit.
Calendar-only comparisons use the supplied retrieval offset. When a source
uses a different calendar timezone, callers must express the retrieval instant
in that evidenced source timezone. Unknown source timezone can produce a
conservative rejection at a day boundary; this validator does not infer it.
``value`` is an exact plain decimal string (signed financial values supported).
``scale`` is one of 1/1e3/1e6/1e9/1e12; source spelling is in original_unit.
No numerical transformation is performed: 1.20 billion is not rounded to 1.2.
Power kinds accept W/kW/MW/GW; storage_energy/generation_energy/
energy_procurement accept Wh/kWh/MWh/GWh/TWh. Finance requires unit=currency,
an explicit three-letter uppercase currency label, and finance_stage of
announced/committed/disbursed/reported. A label is not a currency-registry check.
Nonfinance claims require currency and finance_stage to be null. Source-reported
power/energy quantities cannot be negative. Unknown quantities are omitted by
the upstream adapter, never represented by fabricated zero or a null value.
Entity scopes: issuer, consolidated_group, project, site, campus, phase,
public_institution. Group totals stay at group scope; the explicit nullable
consolidation_group_id preserves known overlap with subsidiaries. No summation,
FX, inference, extraction, verified-state transition, or aggregation API exists.
In particular, two individually valid claims are NOT automatically additive.
Use a separate evidenced group/project association before displaying a figure
on a project; a shared name or nearby grid asset is insufficient.
Regional aggregate scopes are not supported by v1 and must not be relabelled as
projects or sites to pass validation.
This validator checks shape and internal semantics, not truth, identity,
publisher rights, audit validity, source accessibility, or DNS. Source-policy
and independent-review gates belong to the calling producer. HTTPS URLs get a
conservative syntax/public-literal check only; this module never fetches them.
Provenance hashes are required but must be matched to publisher bytes upstream.
The provenance document must support this particular number and scope; a
secondary discovery link alone is not numerical evidence. Discovery/reporting
links belong in the caller's separate metadata, not invented claim provenance.
Caller-provided assurance=audited remains a provisional *source assertion*.
The contract never certifies rights or allows publication by itself.
"""
from __future__ import annotations
from collections.abc import Mapping
from copy import deepcopy
from datetime import date, datetime
from decimal import Decimal
import ipaddress
import json
import re
from typing import Any
from urllib.parse import urlsplit
SCHEMA = "globalgrid2050.filing-figure.v1"
STATUS = "machine-provisional"
POWER_KINDS = frozenset({
"generation_power", "storage_power", "it_load", "project_demand",
"secured_connection", "energised_load", "grid_upgrade",
})
ENERGY_KINDS = frozenset({"storage_energy", "generation_energy", "energy_procurement"})
QUANTITY_KINDS = POWER_KINDS | ENERGY_KINDS | {"finance"}
ENTITY_SCOPES = frozenset({
"issuer", "consolidated_group", "project", "site", "campus", "phase",
"public_institution",
})
_TOP_KEYS = frozenset({
"schema", "claim_id", "status", "quantity_kind", "metric", "value", "scale", "unit",
"original_unit", "currency", "finance_stage", "entity", "reporting_period",
"as_of", "basis", "assurance", "provenance", "revision",
})
_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}\Z")
_DECIMAL = re.compile(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?\Z")
_DATE = re.compile(r"[0-9]{4}(?:-[0-9]{2}(?:-[0-9]{2})?)?\Z")
_TIME = re.compile(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
r"(?:\.[0-9]{1,6})?(?:Z|[+-][0-9]{2}:[0-9]{2})\Z"
)
_HOST_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z")
class ClaimValidationError(ValueError):
"""A claim is malformed or has incompatible numerical semantics."""
def _fail(field: str, reason: str) -> None:
# Do not echo an untrusted value, document body or URL into logs.
raise ClaimValidationError(f"{field}: {reason}")
def _object(value: Any, keys: frozenset[str] | set[str], field: str) -> dict:
if not isinstance(value, Mapping) or set(value) != keys:
_fail(field, "expected exactly the documented fields")
return dict(value)
def _text(value: Any, field: str, max_length: int = 200) -> str:
if (not isinstance(value, str) or not value or len(value) > max_length
or value != value.strip() or any(ord(c) < 32 or ord(c) == 127
or 0xD800 <= ord(c) <= 0xDFFF for c in value)):
_fail(field, "expected bounded nonempty text without control characters")
return value
def _identifier(value: Any, field: str) -> str:
if not isinstance(value, str) or not _ID.fullmatch(value):
_fail(field, "expected a bounded source-namespaced identifier")
return value
def _choice(value: Any, choices: set[str] | frozenset[str], field: str) -> str:
if not isinstance(value, str) or value not in choices:
_fail(field, "unsupported value")
return value
def _source_date(value: Any, field: str) -> date:
"""Return earliest possible day for comparison, never for serialization."""
if not isinstance(value, str) or not _DATE.fullmatch(value):
_fail(field, "expected YYYY, YYYY-MM or YYYY-MM-DD")
parts = [int(p) for p in value.split("-")]
try:
return date(*parts, *([1] * (3 - len(parts))))
except ValueError:
_fail(field, "invalid calendar date")
def _timestamp(value: Any, field: str) -> datetime:
if not isinstance(value, str) or not _TIME.fullmatch(value):
_fail(field, "expected a timestamp with explicit UTC offset")
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
_fail(field, "invalid timestamp")
def _url(value: Any, field: str) -> str:
_text(value, field, 2048)
if any(c.isspace() for c in value) or "\\" in value or not value.isascii():
_fail(field, "expected an ASCII HTTPS URL without whitespace or backslashes")
try:
parsed = urlsplit(value)
host = parsed.hostname
port = parsed.port
except ValueError:
_fail(field, "invalid URL")
if (parsed.scheme != "https" or not host or parsed.username is not None
or parsed.password is not None or port not in (None, 443)):
_fail(field, "expected public HTTPS URL without credentials/custom port")
try:
address = ipaddress.ip_address(host)
except ValueError:
labels = host.split(".")
# Numeric last labels include browser IPv4 aliases: 127.1, octal/hex,
# one-number IPv4 and dotted variants. No IDNA or DNS is performed.
if (len(labels) < 2 or not all(_HOST_LABEL.fullmatch(p) for p in labels)
or not re.fullmatch(r"[a-z]{2,63}", labels[-1])
or labels[-1] in {"localhost", "local", "internal", "test", "invalid"}):
_fail(field, "expected a public DNS-form hostname")
else:
if not address.is_global or address.is_multicast:
_fail(field, "nonpublic IP literal")
return value
def validate_claim(claim: Mapping[str, Any]) -> dict[str, Any]:
"""Validate one claim, retaining source precision and returning a deep copy.
Does not fetch, verify, aggregate, convert, or mutate its input. Unknown keys
fail closed instead of passing through personal fields or hidden extras.
"""
c = _object(claim, _TOP_KEYS, "claim")
_choice(c["schema"], {SCHEMA}, "schema")
_choice(c["status"], {STATUS}, "status")
_identifier(c["claim_id"], "claim_id")
kind = _choice(c["quantity_kind"], QUANTITY_KINDS, "quantity_kind")
_text(c["metric"], "metric", 200)
value = c["value"]
if not isinstance(value, str) or len(value) > 100 or not _DECIMAL.fullmatch(value):
_fail("value", "expected an exact plain decimal string of at most 100 characters")
if kind != "finance" and Decimal(value) < 0:
_fail("value", "power/energy quantities cannot be negative")
_choice(c["scale"], {"1", "1e3", "1e6", "1e9", "1e12"}, "scale")
_text(c["original_unit"], "original_unit", 100)
if kind == "finance":
_choice(c["unit"], {"currency"}, "unit")
if not isinstance(c["currency"], str) or not re.fullmatch(r"[A-Z]{3}", c["currency"]):
_fail("currency", "finance requires the source's three-letter currency label")
_choice(c["finance_stage"], {"announced", "committed", "disbursed", "reported"},
"finance_stage")
else:
units = {"W", "kW", "MW", "GW"} if kind in POWER_KINDS else {"Wh", "kWh", "MWh", "GWh", "TWh"}
_choice(c["unit"], units, "unit")
if c["currency"] is not None or c["finance_stage"] is not None:
_fail("currency/finance_stage", "must be null for power/energy claims")
entity = _object(c["entity"], {"scope", "id", "consolidation_group_id", "identity_evidence_url"}, "entity")
scope = _choice(entity["scope"], ENTITY_SCOPES, "entity.scope")
_identifier(entity["id"], "entity.id")
_url(entity["identity_evidence_url"], "entity.identity_evidence_url")
group_id = entity["consolidation_group_id"]
if group_id is not None:
_identifier(group_id, "entity.consolidation_group_id")
if scope == "consolidated_group" and group_id != entity["id"]:
_fail("entity.consolidation_group_id", "group totals must retain their own group identity")
_choice(c["basis"], {"reported", "forecast"}, "basis")
_choice(c["assurance"], {"audited", "unaudited", "unknown"}, "assurance")
if c["basis"] == "forecast" and c["assurance"] == "audited":
_fail("assurance", "forecast must not be represented as an audited actual")
provenance = _object(c["provenance"], {
"document_id", "document_url", "sha256", "page", "section", "published_date", "retrieved_at",
}, "provenance")
_identifier(provenance["document_id"], "provenance.document_id")
_url(provenance["document_url"], "provenance.document_url")
digest = provenance["sha256"]
if not isinstance(digest, str) or not re.fullmatch(r"[a-f0-9]{64}", digest):
_fail("provenance.sha256", "expected lowercase SHA256 of source bytes")
for locator in ("page", "section"):
if provenance[locator] is not None:
_text(provenance[locator], f"provenance.{locator}")
if provenance["page"] is None and provenance["section"] is None:
_fail("provenance", "a page or section locator is required")
retrieved = _timestamp(provenance["retrieved_at"], "provenance.retrieved_at").date()
if provenance["published_date"] is not None:
if _source_date(provenance["published_date"], "provenance.published_date") > retrieved:
_fail("provenance.published_date", "publication cannot follow retrieval")
if c["as_of"] is not None:
if _source_date(c["as_of"], "as_of") > retrieved and c["basis"] != "forecast":
_fail("as_of", "future observation/target date requires explicit forecast basis")
period = c["reporting_period"]
if period is not None:
period = _object(period, {"start", "end"}, "reporting_period")
start = _source_date(period["start"], "reporting_period.start")
end = _source_date(period["end"], "reporting_period.end")
if len(period["start"]) != len(period["end"]) or end < start:
_fail("reporting_period", "ordered bounds with equal source precision required")
if c["basis"] == "reported" and end > retrieved:
_fail("reporting_period", "future period requires explicit forecast basis")
elif c["as_of"] is None:
_fail("reporting_period/as_of", "at least one source-stated temporal basis is required")
revision = _object(c["revision"], {"id", "supersedes_claim_id", "restated"}, "revision")
_identifier(revision["id"], "revision.id")
previous = revision["supersedes_claim_id"]
if previous is not None:
_identifier(previous, "revision.supersedes_claim_id")
if previous == c["claim_id"]:
_fail("revision.supersedes_claim_id", "a new claim cannot supersede itself")
if not isinstance(revision["restated"], bool):
_fail("revision.restated", "expected a boolean")
if revision["restated"] and previous is None:
_fail("revision.supersedes_claim_id", "restatement requires an explicit earlier claim")
# Normalize Mapping containers, not numerical/date/source lexemes.
c["entity"], c["provenance"], c["revision"], c["reporting_period"] = entity, provenance, revision, period
return deepcopy(c)
def dumps_claim(claim: Mapping[str, Any]) -> str:
"""Canonical UTF-8-compatible JSON; decimal values remain strings."""
return json.dumps(validate_claim(claim), ensure_ascii=False, sort_keys=True,
separators=(",", ":"), allow_nan=False)Documents
A Python command-line tool in the filings folder of GlobalGrid2050 that works with distil document (`distil_document`), using SHA-256.
storageglobalgrid2050 / automation/news/filings/documents.py · lines 1–250 of 250 · Entry point · pattern handle_startendtag (shared by 2 files)
- What it does
- It loads data. Defines 18 functions or classes, including Node, text, walk, selector, BoundedHTML. Uses libraries __future__, dataclasses, datetime, hashlib, html.parser. Side effects: reads or writes files.
- 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.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 2 files: Policy Context (globalgrid2050); Test Documents (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It is built from the node class (`Node`), the text step (`text`) and the walk step (`walk`). Bounded, offline distillation of two reviewed government HTML publications. It accepts `--source-dir`, `--receipts` and `--output`.
- Why it matters
- Imported by Policy Context. Checked by Test Documents.
- Application
- globalgrid2050 · automation/news/filings · Python CLI
- Uses
- Contracts (relative import), __future__, dataclasses, datetime, hashlib, html.parser, re, argparse, json
- Used by
- imported by Policy Context (relative import), imported by Test Documents (import)
- Produces
- Node, BoundedHTML, day, unavailable, distil_document, main
- Defines here
- Node, text, walk, selector, BoundedHTML, __init__, handle_starttag, handle_startendtag, handle_endtag, handle_data, day, unavailable, _distil_html, fact, unique, _ancestors, distil_document, 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 automation/news/filings/documents.py:1-250 · blob f36592e573e76824949da7f42c2986509de827ce · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Bounded, offline distillation of two reviewed government HTML publications.
No fetching, OCR, joins or authority transitions. Changed documents require review.
Only short typed facts and content-addressed DOM locators leave this module.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from hashlib import sha256
from html.parser import HTMLParser
import re
from .contracts import validate_claim
OGL = "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/"
SCOPE = "government_html_facts_only_no_images_or_third_party_material"
POLICIES = {
"https://www.gov.uk/government/news/sea-link-development-consent-decision-announced": {
"sha256": "b9ba26b90820292e0b181da7993d2d3a2180fc2de0ac53cc6239adeb4cccfaeb", "bytes": 68432,
"publisher": "Planning Inspectorate", "title": "Sea Link development consent decision announced", "kind": "pins"},
"https://www.gov.uk/government/publications/sea-link-development-consent-order-planning-act-2008": {
"sha256": "c26f93aa307740f8b4ec8ad150b152fb6d30e77f201e5bc31a6da52bba16e0d0", "bytes": 69536,
"publisher": "Department for Energy Security and Net Zero", "title": "Sea Link: development consent order, Planning Act 2008", "kind": "desnz"},
}
VOID = frozenset("area base br col embed hr img input link meta param source track wbr".split())
IGNORED = frozenset("script style svg template nav footer form iframe noscript".split())
@dataclass(eq=False)
class Node:
tag: str
attrs: dict = field(default_factory=dict)
parent: object = None
children: list = field(default_factory=list)
def text(self):
if self.tag in IGNORED:
return ""
return " ".join(" ".join(c if isinstance(c, str) else c.text() for c in self.children).split())
def walk(self):
if self.tag in IGNORED:
return
yield self
for child in self.children:
if isinstance(child, Node):
yield from child.walk()
def selector(self):
if self.tag == "main" and self.attrs.get("id") == "content":
return "main#content"
siblings = [c for c in self.parent.children if isinstance(c, Node) and c.tag == self.tag]
return self.parent.selector() + f" > {self.tag}:nth-of-type({siblings.index(self) + 1})"
class BoundedHTML(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.root = Node("root")
self.stack = [self.root]
self.count = 0
def handle_starttag(self, tag, attrs):
self.count += 1
if self.count > 20000 or len(self.stack) > 100:
raise ValueError("HTML structural bound exceeded")
if len(attrs) != len(dict(attrs)):
raise ValueError("duplicate HTML attribute")
node = Node(tag, dict(attrs), self.stack[-1])
self.stack[-1].children.append(node)
if tag not in VOID:
self.stack.append(node)
def handle_startendtag(self, tag, attrs):
self.handle_starttag(tag, attrs)
if tag not in VOID:
self.handle_endtag(tag)
def handle_endtag(self, tag):
for i in range(len(self.stack) - 1, 0, -1):
if self.stack[i].tag == tag:
del self.stack[i:]
break
def handle_data(self, data):
self.stack[-1].children.append(data)
def day(text):
"""DAY only; never manufacture a midnight instant or expand partial dates."""
if not re.fullmatch(r"\d{1,2} [A-Z][a-z]+ \d{4}", text):
raise ValueError("source date is not an explicit English DAY")
return {"value": datetime.strptime(text, "%d %B %Y").date().isoformat(), "precision": "DAY"}
def unavailable(reason, **extra):
return {"schema": "globalgrid2050.document-facts.v1", "status": "unavailable", "reason": reason,
"facts": [], "claims": [], "publishable": False, **extra}
def _distil_html(payload, policy, url, retrieved_at):
"""Internal parser; public entry additionally enforces immutable source/rights pins."""
parser = BoundedHTML()
parser.feed(payload.decode("utf-8", errors="strict"))
mains = [n for n in parser.root.walk() if n.tag == "main" and n.attrs.get("id") == "content"]
if len(mains) != 1:
raise ValueError("one visible main#content required")
main = mains[0]
nodes = list(main.walk())
headings = [n.text() for n in nodes if n.tag == "h1"]
if headings != [policy["title"]]:
raise ValueError("wrong or ambiguous document title")
project_ids = set(re.findall(r"\bEN\d{6}\b", main.text() + " " + " ".join(n.attrs.get("href", "") for n in nodes)))
if project_ids != {"EN020026"}:
raise ValueError("wrong or ambiguous project identity")
published = []
publishers = []
for n in nodes:
if n.tag != "dt" or n.text() not in ("Published:", "From:"):
continue
siblings = [c for c in n.parent.children if isinstance(c, Node)]
i = siblings.index(n)
if i + 1 < len(siblings) and siblings[i + 1].tag == "dd":
(published if n.text() == "Published:" else publishers).append(siblings[i + 1].text())
if publishers != [policy["publisher"]] or len(published) != 1:
raise ValueError("publisher/publication unavailable or ambiguous")
publication = day(published[0])
if publication["value"] > datetime.fromisoformat(retrieved_at.replace("Z", "+00:00")).date().isoformat():
raise ValueError("publication after retrieval")
paragraphs = [n for n in nodes if n.tag == "p" and any("gem-c-govspeak" in a.attrs.get("class", "").split() for a in _ancestors(n))]
digest = sha256(payload).hexdigest()
facts = []
def fact(name, value, node, unit=None, meaning=None):
text = node.text()
facts.append({"id": name, "value": value, "unit": unit, "meaning": meaning,
"locator": {"kind": "HTML_PARAGRAPH", "selector": node.selector(),
"paragraph": paragraphs.index(node) + 1,
"text_sha256": sha256(text.encode()).hexdigest(), "document_sha256": digest}})
def unique(pattern):
matches = [(n, re.search(pattern, n.text())) for n in paragraphs]
matches = [(n, m) for n, m in matches if m]
if len(matches) != 1:
raise ValueError("missing or ambiguous source fact")
return matches[0]
claims = []
if policy["kind"] == "pins":
node, match = unique(r"submitted to the Planning Inspectorate for consideration by National Grid Electricity Transmission \(NGET\) Plc on (\d{1,2} \w+ \d{4}) and accepted for examination on (\d{1,2} \w+ \d{4})\.")
fact("application_submitted", day(match[1]), node)
fact("application_accepted", day(match[2]), node)
fact("reported_network_operator", "National Grid Electricity Transmission (NGET) Plc", node)
node, match = unique(r"recommendations were made to the Secretary of State on (\d{1,2} \w+ \d{4})\.")
fact("recommendation", day(match[1]), node)
dates = [f["value"]["value"] for f in facts if isinstance(f["value"], dict)]
if dates != sorted(dates) or dates[-1] > publication["value"]:
raise ValueError("milestone chronology ambiguous")
else:
labels = [i for i, n in enumerate(paragraphs) if n.text() == "Date of decision"]
if len(labels) != 1 or labels[0] + 1 >= len(paragraphs):
raise ValueError("decision DAY unavailable")
date_node = paragraphs[labels[0] + 1]
decision = day(date_node.text())
if decision["value"] > publication["value"]:
raise ValueError("decision after publication")
fact("consent_decision", decision, date_node)
node, match = unique(r"It will have a transmission capacity of up to (\d+(?:\.\d+)?) gigawatts\.")
if not all(s in node.text() for s in ("Kent and Suffolk", "high voltage direct current")):
raise ValueError("capacity context unavailable")
fact("planned_transmission_upper_bound", match[1], node, "GW", "forecast upper bound; not current, available or commissioned capacity")
claim = {"schema": "globalgrid2050.filing-figure.v1", "claim_id": "planning:EN020026:planned-transmission:" + digest[:16],
"status": "machine-provisional", "quantity_kind": "grid_upgrade", "metric": "Planned transmission capacity upper bound",
"value": match[1], "scale": "1", "unit": "GW", "original_unit": "up to " + match[1] + " gigawatts",
"currency": None, "finance_stage": None,
"entity": {"scope": "project", "id": "planning:EN020026", "consolidation_group_id": None, "identity_evidence_url": url},
"reporting_period": None, "as_of": decision["value"], "basis": "forecast", "assurance": "unknown",
"provenance": {"document_id": "planning:EN020026:" + digest, "document_url": url, "sha256": digest,
"page": None, "section": node.selector(), "published_date": publication["value"], "retrieved_at": retrieved_at},
"revision": {"id": digest, "supersedes_claim_id": None, "restated": False}}
claims.append(validate_claim(claim))
return {"schema": "globalgrid2050.document-facts.v1", "status": "machine-provisional", "publishable": False,
"project": "planning:EN020026", "title": policy["title"], "publisher": policy["publisher"],
"authority_role": "government_authority", "source_url": url, "source_version": digest,
"retrieved_at": retrieved_at, "published_date": publication, "document_type": "HTML",
"rights": {"licence_url": OGL, "scope": SCOPE, "state": "REVIEW_REQUIRED"},
"facts": facts, "claims": claims, "unknowns": {"commissioned_date": None, "current_capacity": None,
"coordinates": None, "repd_join": None}, "revision": {"state": "pinned_original", "supersedes": None}}
def _ancestors(node):
while node.parent:
node = node.parent
yield node
def distil_document(payload: bytes, *, source_url: str, receipt: dict, content_type="text/html"):
"""Read caller-provided bytes only. Receipts are evidence, never review approval."""
policy = POLICIES.get(source_url)
if policy is None:
return unavailable("source_not_approved")
if not isinstance(payload, bytes) or len(payload) > 1_000_000:
return unavailable("document_size_or_type")
if content_type != "text/html":
return unavailable("pdf_extraction_unavailable_no_approved_pdf_or_extractor")
digest = sha256(payload).hexdigest()
if digest != policy["sha256"] or len(payload) != policy["bytes"]:
return unavailable("source_revision_requires_review", observed_sha256=digest, accepted_sha256=policy["sha256"])
if not isinstance(receipt, dict) or any(receipt.get(k) != v for k, v in {
"source_url": source_url, "sha256": digest, "bytes": len(payload), "http_status": 200,
"licence_url": OGL}.items()) or not str(receipt.get("content_type", "")).startswith("text/html"):
return unavailable("retrieval_or_rights_receipt_invalid")
try:
stamp = receipt["retrieved_at"]
parsed = datetime.fromisoformat(stamp.replace("Z", "+00:00"))
if parsed.tzinfo is None:
raise ValueError("retrieval timezone unavailable")
return _distil_html(payload, policy, source_url, stamp)
except (ValueError, KeyError, UnicodeError, RecursionError) as error:
return unavailable("distillation_abstained", detail=str(error)[:180])
def main(argv=None):
"""Explicit offline reproduction, not a collector or scheduled publication path."""
import argparse
import json
from pathlib import Path
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-dir", required=True, type=Path)
parser.add_argument("--receipts", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args(argv)
rows = json.loads(args.receipts.read_text(encoding="utf-8"))["records"]
if len(rows) != 2 or {r.get("source_url") for r in rows} != set(POLICIES):
parser.error("exact two approved source receipts required")
documents = []
for i, row in enumerate(rows, 1):
source = args.source_dir / f"source-{i}.html"
if source.stat().st_size > 1_000_000:
parser.error("source exceeds byte bound")
documents.append(distil_document(source.read_bytes(), source_url=row["source_url"], receipt=row["source_receipt"]))
payload = {"schema": "globalgrid2050.distilled-document-bundle.v1", "documents": documents,
"pdf_status": "unavailable: no approved local PDF and no installed extractor; no OCR attempted"}
args.output.write_text(json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n", encoding="utf-8", newline="\n")
return 0 if all(d["status"] == "machine-provisional" for d in documents) else 2
if __name__ == "__main__":
raise SystemExit(main())Policy Context
A Python module in the filings folder of GlobalGrid2050 that extracts covenant (`extract_covenant`), using SHA-256.
transformglobalgrid2050 / automation/news/filings/policy_context.py · lines 1–78 of 78
- What it does
- It calculates its inputs. Defines extract_covenant. Uses libraries __future__, datetime, hashlib, re.
- 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.
- Downstream impact
- Used directly by 1 file: Test Policy Context (globalgrid2050). Reached from 3 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- Offline, bounded GOV.UK policy facts; never project compliance or connectivity.
- Why it matters
- Checked by Test Policy Context.
- Application
- globalgrid2050 · automation/news/filings · Python module
- Uses
- Documents (relative import), __future__, datetime, hashlib, re
- Used by
- imported by Test Policy Context (import)
- Produces
- extract_covenant
- Defines here
- extract_covenant
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/filings/policy_context.py:1-78 · blob f509cadfc5ef6dd847c87a3171daa163f6959831 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Offline, bounded GOV.UK policy facts; never project compliance or connectivity."""
from __future__ import annotations
from datetime import datetime
from hashlib import sha256
import re
from .documents import BoundedHTML, day
SOURCE = 'https://www.gov.uk/government/publications/data-centre-covenant/the-data-centre-covenant'
OGL = 'https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/'
HEADINGS = (
('energy', '1. Lower electricity bills', 'Energy-system costs, clean power and flexibility'),
('community', '2. Invest in improving local communities', 'Benefits for host communities'),
('environment', '3. Adhere to the highest environmental standards', 'Energy, water and heat-reuse context'),
('jobs', '4. Create jobs, apprenticeships, and drive reindustrialisation', 'Jobs, skills and supply chains'),
('resilience', '5. Strengthen Britain’s security', 'Reliable infrastructure and resilience'),
)
def extract_covenant(payload: bytes, *, source_url: str, retrieved_at: str) -> dict:
"""Extract only the named document; output retains locators and policy scope."""
if source_url != SOURCE:
raise ValueError('source_not_approved')
if not isinstance(payload, bytes) or not 100 <= len(payload) <= 250_000:
raise ValueError('document_size_bound')
retrieved = datetime.fromisoformat(retrieved_at.replace('Z', '+00:00'))
if retrieved.tzinfo is None:
raise ValueError('retrieval_requires_timezone')
parser = BoundedHTML()
parser.feed(payload.decode('utf-8', errors='strict'))
mains = [n for n in parser.root.walk() if n.tag == 'main' and n.attrs.get('id') == 'content']
if len(mains) != 1:
raise ValueError('one_main_required')
nodes = list(mains[0].walk())
if [n.text() for n in nodes if n.tag == 'h1'] != ['The Data Centre Covenant']:
raise ValueError('wrong_document_title')
dates = [n.text().removeprefix('Published ') for n in nodes if n.tag == 'p' and n.text().startswith('Published ')]
if len(dates) != 1 or day(dates[0])['value'] != '2026-10-28':
raise ValueError('publication_date_unavailable')
publishers = [n.attrs.get('content') for n in parser.root.walk() if n.tag == 'meta' and n.attrs.get('name') == 'govuk:primary-publishing-organisation']
if publishers != ['HM Treasury']:
raise ValueError('publisher_missing_or_ambiguous')
if retrieved.date().isoformat() < '2026-10-28':
raise ValueError('publication_after_retrieval')
links = {n.attrs.get('href') for n in parser.root.walk() if n.tag == 'a'}
if not any(isinstance(link, str) and link.rstrip('/') == OGL.rstrip('/') for link in links):
raise ValueError('licence_link_unavailable')
headings = []
for theme, expected, label in HEADINGS:
found = [n for n in nodes if n.tag == 'h2' and n.text() == expected]
if len(found) != 1:
raise ValueError('policy_heading_missing_or_ambiguous')
node = found[0]
headings.append({'id': theme, 'label': label, 'locator': node.selector(),
'text_sha256': sha256(node.text().encode()).hexdigest(),
'fragment': node.attrs.get('id')})
paragraphs = [n for n in nodes if n.tag == 'p']
quantities = []
for name, expression, value, unit, meaning in (
('national_ai_capacity', r'\b6\s+GW\b.*\b2030\b', '6', 'GW', 'Government estimate of national AI data-centre capacity required by 2030; not existing capacity'),
('new_facility_pue', r'Power Usage Effectiveness of 1\.3 or better', '1.3', 'ratio', 'Policy design expectation of PUE 1.3 or better for new facilities; not a measured project efficiency'),
):
found = [n for n in paragraphs if re.search(expression, n.text())]
if len(found) != 1:
raise ValueError('policy_quantity_missing_or_ambiguous')
node = found[0]
quantities.append({'id': name, 'value': value, 'unit': unit, 'meaning': meaning,
'comparison': 'AT_MOST' if name == 'new_facility_pue' else 'ESTIMATE',
'locator': node.selector(), 'text_sha256': sha256(node.text().encode()).hexdigest()})
return {'schema': 'globalgrid2050.energy-policy-context.v1', 'title': 'The Data Centre Covenant',
'publisher': 'HM Treasury', 'source_url': SOURCE, 'source_sha256': sha256(payload).hexdigest(),
'source_bytes': len(payload), 'retrieved_at': retrieved_at,
'published_date': {'value': '2026-10-28', 'precision': 'DAY'},
'rights': {'licence_url': OGL, 'scope': 'government_authored_facts_only_no_images_or_third_party_material', 'review_state': 'REVIEW_REQUIRED'},
'themes': headings, 'quantities': quantities,
'scope': 'NATIONAL_POLICY_CONTEXT_ONLY', 'project_compliance': None,
'asset_associations': [], 'connections': [], 'available_capacity': None}News — Grid Watch
A Python module in the automation folder of GlobalGrid2050.
otherglobalgrid2050 / automation/news/grid_watch/__init__.py · lines 1–4 of 4
- 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.
- Downstream impact
- Used directly by 1 file: Test Grid Watch (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- Offline UK operator-source evidence adapter (review only).
- Why it matters
- Checked by Test Grid Watch.
- Application
- globalgrid2050 · automation/news/grid_watch · Python module
- Uses
- Adapter (relative import)
- Used by
- imported by Test Grid Watch (import)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/grid_watch/__init__.py:1-4 · blob 348c0a07a9181235ca82bb84910509cec8e18315 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Offline UK operator-source evidence adapter (review only)."""
from .adapter import build_grid_rows, normalise
__all__ = ["build_grid_rows", "normalise"]