In this section
- Pipeline Headlines energy-data · globalgrid2050 / automation/news/pipeline_headlines.py lines 463–788
- News — Policy Commitments other · globalgrid2050 / automation/news/policy_commitments/__init__.py lines 1–1
- Ledger render · globalgrid2050 / automation/news/policy_commitments/ledger.py lines 1–355
Pipeline Headlines
A Python command-line tool in the news folder of GlobalGrid2050 that fetches pipeline feeds, the Renewable Energy Planning Database (REPD) register, solar and wind, using SHA-256.
energy-dataglobalgrid2050 / automation/news/pipeline_headlines.py · lines 463–788 of 788 (continued from section 785) · Entry point · pattern category_of (shared by 2 files)
- What it does
- It fetches pipeline feeds, the REPD register, solar and wind. Defines 32 functions or classes, including excluded_publisher, _rx, climate_policy_priority, lane_label, topics_of. Uses libraries __future__, argparse, csv, datetime, io. Side effects: reads or writes files; makes network requests; starts processes.
- 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: the REPD register, solar, wind.
- Inputs & outputs
- In: JSON file pipeline_headlines.json; JSON file pipeline_feeds.json; command-line arguments.
- Downstream impact
- Used directly by 9 files: News Algorithm (globalgrid2050); Trade (globalgrid2050); Compare Legacy Collector (globalgrid2050); Test Agent7 Dedupe Regressions (globalgrid2050); and 5 more. Reached from 8 other entry points, including GlobalGrid2050 Agent7 V922 CI Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It loads feeds (`load_feeds`) and is built from the excluded publisher helper (`excluded_publisher`) and the climate policy priority helper (`climate_policy_priority`). Fresh UK renewables, storage, grid and data-centre headlines for Pipeline News. It accepts `--out`, `--feeds` and `--repd`.
- Why it matters
- Imported by News Algorithm and Trade. Run by GlobalGrid2050 Pipeline Headlines Workflow. Checked by 6 tests, including Compare Legacy Collector.
- Application
- globalgrid2050 · automation/news · Python CLI
- Uses
- Datacentre Feed (import), Names (import), Research Indexes (import), __future__, argparse, csv, datetime, io, json, re, sys
- Used by
- imported by News Algorithm (import), imported by Trade (sys.path import), run by Compare Legacy Collector (script call), imported by Test Agent7 Dedupe Regressions (sys.path import), imported by Test Cop31 Climate Priority (sys.path import), imported by Test Pipeline Headlines (sys.path import), imported by Test Research Context (sys.path import), imported by Test Spp Excluded (sys.path import), and 1 more
- Produces
- excluded_publisher, climate_policy_priority, lane_label, topics_of, technology_of, category_of, Repd, newest_repd_csv, is_uk, label, priority_label, load_feeds
- Defines here
- load_feeds, collect, _shift, when, title_key, _publisher_day, _project_ref, _same_documented_event, dedupe_titles, merge, build, probe_report, main, fetch
- 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/pipeline_headlines.py:463-788 · blob f49b65bc28657fdb414c03e577f9b8a3b6002d01 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Priority lane: (category, technology, possible_match) when the title or feed summary says solar or
data centre, with or without an event word; None otherwise."""
text = title + " " + summary
solar, datacentre = TOPICS["solar"].search(text), TOPICS["datacentre"].search(text)
if not (solar or datacentre) or EXCLUDE.search(title):
return None
if not solar:
return "datacentre", None, None
return category_of(title, ["solar"]) or "other", technology_of(title), repd.match(title)
def load_feeds(path):
feeds = json.loads(Path(path).read_text(encoding="utf-8"))["feeds"]
return [f for f in feeds if f.get("url", "").startswith("https://") and f.get("source")
and not excluded_publisher(f.get("source"), f.get("url"))]
def collect(feeds, fetch, repd, now_iso):
"""Returns (items, health). A feed that fails is recorded and skipped; the run carries on."""
items, health = [], []
horizon = _shift(now_iso, days=2)
for feed in feeds:
url, source = feed["url"], feed["source"]
if excluded_publisher(source, url):
continue # No network request and no misleading health result for excluded sources.
try:
kind = feed.get("kind", "rss")
if kind == "curated":
# Curated primary-source lead; no claim of live fetching.
entries = [(feed["title"], url, feed.get("date"), "")]
else:
body = fetch(url)
entries = (R.index_entries(body, feed) if kind == "html_index" else
R.rss1_entries(body) if kind == "rss1" else D.parse_feed(body))
if kind == "html_index" and not entries:
raise ValueError("No eligible index links (possible JS rendering, path mismatch or access block)")
except Exception as error: # one feed failing never stops the run
health.append({"url": url, "source": source, "status": "failed",
"error": (type(error).__name__ + ": " + str(error))[:200]})
continue
kept, newest = 0, None
for title, link, date, summary in entries:
title, link, date = D.clean_text(title, 300), D.canonical_link(link), D.parse_date(date)
if date and (newest is None or date > newest):
newest = date
if not title or not link or excluded_publisher(source, link) or D.SPONSORED_RE.search(title) or BRANDED.search(title):
continue
if date and date > horizon:
continue
if any(h in link for h in OPINION_HOSTS) and " | " in title:
continue
lane = feed.get("lane")
if lane in WORLD_LANES:
verdict = lane_label(title, lane, feed.get("focus"))
else:
if FOREIGN.search(title) and not UK_WORDS.search(title) and not climate_policy_priority(title):
continue
verdict = label(title, repd)
if verdict is None and lane == "keywords":
verdict = priority_label(title, D.clean_text(summary, 2000), repd) # summary read, never stored
if verdict is not None and not feed.get("uk_only") and not is_uk(title, repd) \
and not climate_policy_priority(title):
verdict = None
if verdict is None:
continue
items.append({"_feed": url, "title": title, "link": link, "source": source, "date": date, "first_seen": now_iso,
"category": verdict[0], "technology": verdict[1], "possible_match": verdict[2]})
kept += 1
health.append({"url": url, "source": source + (" (curated; not fetched)" if kind == "curated" else ""), "status": "ok", "entries": len(entries), "kept": kept,
"newest": newest})
return items, health
def _shift(iso, days):
moved = dt.datetime.fromisoformat(iso.replace("Z", "+00:00")) + dt.timedelta(days=days)
return moved.replace(microsecond=0).isoformat().replace("+00:00", "Z")
def when(item):
return item.get("date") or item.get("first_seen") or ""
_SUFFIX = re.compile(r"\s+[|–—-]\s+[^|–—-]{2,40}$")
def title_key(title):
"""Title reduced for comparing two feeds' copies: a trailing " - Publisher" removed, then names.norm."""
return N.norm(_SUFFIX.sub("", title)) or N.norm(title)
def _publisher_day(item):
"""Only publisher-supplied dates may delimit article copies. First-seen is a crawl date."""
raw = item.get("date")
if not isinstance(raw, str) or not raw:
return None
try:
return dt.date.fromisoformat(raw[:10])
except ValueError:
return None
def _project_ref(item):
match = item.get("possible_match") or {}
return str(match.get("repd_ref") or "") if isinstance(match, dict) else ""
def _same_documented_event(item, other):
"""Fail open to TWO headlines when publisher/project/event identity is ambiguous.
A common article URL identifies one article. Two different URLs require a common
candidate REPD Ref, a consistent category and distinct publisher sources; planning
decisions also require the same explicit decision/event reference. This is article
display deduplication, never evidence of verified REPD identity or publisher rights.
"""
for field in ("planning_reference", "decision_reference", "event_reference", "event_type"):
left, right = item.get(field), other.get(field)
if (left or right) and left != right:
return False
left_ref, right_ref = _project_ref(item), _project_ref(other)
if left_ref != right_ref:
return False
if item.get("link") == other.get("link"):
return True
if not left_ref or item.get("source") == other.get("source"):
return False
if item.get("category") != other.get("category"):
return False
if item.get("category") in ("planning_decision", "consent", "refusal", "dco"):
# Two same-named planning decisions can occur days apart: never equate them
# merely because their headlines and candidate project identifiers agree.
return bool(item.get("decision_reference") or item.get("event_reference"))
return True
def dedupe_titles(items):
"""Collapse documented article copies, not unrelated same-title project events.
Require publisher dates within three days for different article URLs and
independently non-conflicting article/project/event identifiers. When evidence
is absent, retaining a repeated-looking headline is safer than losing an event.
"""
kept = []
for item in sorted(items, key=lambda i: (when(i), i["link"])):
key = title_key(item["title"])
words = set(key.split())
day = _publisher_day(item)
duplicate = False
for other in kept:
if not _same_documented_event(item, other):
continue
# Identical canonical URLs were already handled by the upstream link
# merge, but may be present in direct calls to this function.
if item.get("link") != other.get("link"):
other_day = _publisher_day(other)
if day is None or other_day is None or abs((day - other_day).days) > 3:
continue
if key == other["_k"]:
duplicate = True
elif len(words) >= 5:
union = words | other["_w"]
duplicate = bool(union) and len(words & other["_w"]) / len(union) >= 0.85
if duplicate:
break
if not duplicate:
kept.append(dict(item, _k=key, _w=words))
return [{f: k.get(f) for f in ITEM_FIELDS} for k in kept]
def merge(previous, incoming, repd, now_iso, cap=MAX_ITEMS, max_age_days=MAX_AGE_DAYS, lanes=None, focuses=None):
"""Earlier items are kept (a rolling feed must not make a story vanish) and re-labelled with today's rules.
Link merge and first_seen are datacentre_feed.merge; then age limit, title dedupe, newest first, cap.
lanes: {source: lane} from the feed list. A keywords-lane item that was kept on its feed summary keeps the
labels it was given then, because the summary is not stored and cannot be read again. Each world lane is
cut to its newest LANE_CAP items."""
lanes = lanes or {}
focuses = focuses or {}
previous = [i for i in previous if not excluded_publisher(i.get("source"), i.get("link"))]
incoming = [i for i in incoming if not excluded_publisher(i.get("source"), i.get("link"))]
fresh = {i["link"]: i for i in incoming}
by_link = D.merge(previous, incoming, cap=10 ** 6)
cutoff = _shift(now_iso, days=-max_age_days)
out = []
for item in by_link:
lane = lanes.get(item.get("source"))
if lane in WORLD_LANES:
verdict = lane_label(item.get("title", ""), lane, focuses.get(item.get("source")))
else:
verdict = label(item.get("title", ""), repd)
if verdict is None and lane not in WORLD_LANES and (item["link"] in fresh or lane == "keywords") \
and item.get("category") in CATEGORIES:
verdict = (item["category"], item.get("technology"), item.get("possible_match"))
if verdict is None or when(item) < cutoff:
continue
out.append({"title": item["title"], "link": item["link"], "source": item.get("source", ""),
"date": item.get("date"), "first_seen": item.get("first_seen") or now_iso,
"category": verdict[0], "technology": verdict[1], "possible_match": verdict[2]})
out = dedupe_titles(out)
out.sort(key=lambda i: (when(i), i["link"]), reverse=True)
seen, capped = {}, []
for item in out:
lane = lanes.get(item["source"])
if lane in WORLD_LANES:
seen[lane] = seen.get(lane, 0) + 1
if seen[lane] > WORLD_LANE_CAPS.get(lane, LANE_CAP):
continue
capped.append(item)
# New research may use spare room but must never displace a legacy item.
# Final output remains newest-first for the existing client contract.
legacy = [i for i in capped if lanes.get(i["source"]) != "global_context"]
context = [i for i in capped if lanes.get(i["source"]) == "global_context"]
selected = legacy[:cap] + context[:max(0, cap - len(legacy))]
selected.sort(key=lambda i: (when(i), i["link"]), reverse=True)
return selected
def build(previous, items, health, repd, now_iso, cap=MAX_ITEMS, lanes=None, focuses=None):
merged = merge(previous.get("items", []), items, repd, now_iso, cap, lanes=lanes, focuses=focuses)
ok = sum(h["status"] == "ok" for h in health)
by_category = {c: n for c in CATEGORIES if (n := sum(i["category"] == c for i in merged))}
return {
"schema": SCHEMA,
"generated_at": now_iso,
"status": "ok" if ok == len(health) and health else ("partial" if ok else "failed"),
"counts": {"items": len(merged), "with_possible_match": sum(bool(i["possible_match"]) for i in merged),
"feeds_ok": ok, "feeds_failed": len(health) - ok, "by_category": by_category},
"limits": {"max_items": cap, "max_age_days": MAX_AGE_DAYS},
"scope": SCOPE,
"feeds": health,
"items": merged,
}
def probe_report(items, merged, health, now_iso, primary=(), lanes=None):
"""Markdown feed-health report for the pull-request probe job: every feed, then the headlines that would
be published (after merge and dedupe)."""
by_feed = {}
for i in items:
by_feed.setdefault(i["_feed"], []).append(i)
lines = ["# Pipeline headlines feed probe, %s" % now_iso, "",
"%d feeds: %d ok, %d failed. %d headlines kept; %d after merge and dedupe." % (
len(health), sum(h["status"] == "ok" for h in health),
sum(h["status"] != "ok" for h in health), len(items), len(merged)), "",
"| feed | status | items | newest | kept | sample kept titles |", "|---|---|---|---|---|---|"]
for h in health:
samples = [i["title"] for i in by_feed.get(h["url"], [])][:3]
cell = " / ".join(s.replace("|", "/") for s in samples)
lines.append("| %s (%s) | %s | %s | %s | %s | %s |" % (
h["url"], h["source"], h["status"] if h["status"] == "ok" else "FAILED " + h.get("error", "").replace("|", "/"),
h.get("entries", ""), (h.get("newest") or "")[:10], h.get("kept", ""), cell))
primary, lanes = list(primary), lanes or {}
rank = lambda i: primary.index(i["source"]) if i["source"] in primary else len(primary) # noqa: E731
merged = sorted(merged, key=rank) # stable: newest first within each source group
lines += ["", "## Headlines that would be published: %s first, then the rest; newest first within each" % (
", then ".join(primary) or "no primary source"), "",
"The published file itself is ordered newest first. Lanes: " + (", ".join(
"%s = %s" % (s, l) for s, l in lanes.items()) or "none") + ".", "",
"| date | category | technology | possible match | source | title |", "|---|---|---|---|---|---|"]
for i in merged:
m = i["possible_match"]
lines.append("| %s | %s | %s | %s | %s | %s |" % (
(i["date"] or "undated")[:10], i["category"], i["technology"] or "",
"REPD %s %s (%s)" % (m["repd_ref"], m["site_name"].replace("|", "/"), m["basis"]) if m else "",
i["source"], i["title"].replace("|", "/")))
return "\n".join(lines) + "\n"
def main(argv=None):
root = HERE.parents[1]
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--out", default="dist/pipeline_headlines.json")
ap.add_argument("--feeds", default=str(HERE / "pipeline_feeds.json"), help="JSON list of feeds to read")
ap.add_argument("--repd", default=None, help="REPD CSV for possible matches (default: newest repd-<yyyy>q<n>.csv)")
ap.add_argument("--fixtures", default=None,
help="offline: directory of <sha256(url)[:16]>.xml files used instead of the network")
ap.add_argument("--probe", default=None, help="write a Markdown feed-health report here; no data file is written")
ap.add_argument("--now", default=None, help="fixed UTC timestamp (tests)")
ap.add_argument("--max-items", type=int, default=MAX_ITEMS)
args = ap.parse_args(argv)
now_iso = args.now or dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
repd = Repd.load(args.repd or newest_repd_csv(root))
feeds = load_feeds(args.feeds)
if args.fixtures:
fixture_dir = Path(args.fixtures)
def fetch(url):
path = fixture_dir / D.fixture_name(url)
if not path.exists():
raise OSError("no fixture for %s" % url)
return path.read_bytes()
else:
fetch = D.fetch_url
feeds.sort(key=lambda f: not f.get("primary")) # primary sources first; otherwise the order of the list
lanes = {f["source"]: f["lane"] for f in feeds if f.get("lane")}
focuses = {f["source"]: f["focus"] for f in feeds if f.get("focus")}
primary = list(dict.fromkeys(f["source"] for f in feeds if f.get("primary")))
items, health = collect(feeds, fetch, repd, now_iso)
if args.probe:
report = probe_report(items, merge([], items, repd, now_iso, args.max_items, lanes=lanes, focuses=focuses), health, now_iso,
primary, lanes)
Path(args.probe).write_text(report, encoding="utf-8")
print(report)
return 0
out = Path(args.out)
previous = {}
if out.exists():
try:
previous = json.loads(out.read_text(encoding="utf-8"))
if previous.get("schema") != SCHEMA:
previous = {}
except ValueError:
previous = {}
result = build(previous, items, health, repd, now_iso, args.max_items, lanes, focuses=focuses)
out.parent.mkdir(parents=True, exist_ok=True)
tmp = out.with_suffix(".tmp")
tmp.write_text(json.dumps(result, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
tmp.replace(out)
print(json.dumps({"status": result["status"], **result["counts"], "repd_names": len(repd.by_phrase),
"out": str(out)}))
return 1 if result["status"] == "failed" and not previous else 0
if __name__ == "__main__":
sys.exit(main())News — Policy Commitments
A Python module in the automation folder of GlobalGrid2050.
otherglobalgrid2050 / automation/news/policy_commitments/__init__.py · lines 1–1 of 1
- 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 3 files: Build Transition Context (globalgrid2050); Test Policy Commitments (globalgrid2050); Test Transition Context (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Offline, provisional policy commitment and attributable evidence ledger.
- Why it matters
- Imported by Build Transition Context. Checked by 2 tests, including Test Policy Commitments.
- Application
- globalgrid2050 · automation/news/policy_commitments · Python module
- Uses
- none found
- Used by
- imported by Build Transition Context (import), imported by Test Policy Commitments (import), imported by Test Transition Context (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/policy_commitments/__init__.py:1-1 · blob 87f792d0987e2250ac7d84db70d0e73e1d478093 · 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, provisional policy commitment and attributable evidence ledger."""Ledger
A Python command-line tool in the policy commitments folder of GlobalGrid2050 that works with dumps report (`dumps_report`) and CSV report (`csv_report`), using SHA-256.
renderglobalgrid2050 / automation/news/policy_commitments/ledger.py · lines 1–355 of 355 · Entry point · pattern csv_report (shared by 2 files)
- What it does
- Defines 13 functions or classes, including require, fields, choice, strings, index. Uses libraries __future__, argparse, copy, csv, decimal. Side effects: changes the web page (DOM); 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: JSON file sample_ledger.json; command-line arguments.
- Downstream impact
- Used directly by 3 files: Build Transition Context (globalgrid2050); Test Policy Commitments (globalgrid2050); Test Transition Context (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It is built from the require step (`require`), the fields step (`fields`) and the choice step (`choice`). COVENANT AGENT: deterministic source-led comparison, never legal compliance. It accepts `--ledger`, `--as-of` and `--format`.
- Why it matters
- Imported by Build Transition Context. Checked by 2 tests, including Test Policy Commitments.
- Application
- globalgrid2050 · automation/news/policy_commitments · Python CLI
- Uses
- Contracts (import), __future__, argparse, copy, csv, decimal, io, json, pathlib
- Used by
- imported by Build Transition Context (import), imported by Test Policy Commitments (import), imported by Test Transition Context (import)
- Produces
- require, fields, choice, strings, index, reference, quantity, validate_ledger, incompatibilities, evaluate, dumps_report, csv_report
- Defines here
- require, fields, choice, strings, index, reference, quantity, validate_ledger, incompatibilities, evaluate, dumps_report, csv_report, 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/policy_commitments/ledger.py:1-355 · blob eceaad75de63820e37a9b725de4217ebf6af8427 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""COVENANT AGENT: deterministic source-led comparison, never legal compliance.
Public API: validate_ledger(mapping), evaluate(mapping, as_of=UTC),
dumps_report(report), csv_report(report). Quantities use the existing FIGURES
validate_claim contract unchanged. No network, inference of identities, or writes.
"""
from __future__ import annotations
import argparse
from copy import deepcopy
import csv
from decimal import Decimal, localcontext
import io
import json
from pathlib import Path
import re
from automation.news.filings.contracts import (
validate_claim, _identifier, _source_date, _text, _timestamp, _url,
)
SCHEMA = "globalgrid2050.policy-commitments.v1"
REPORT_SCHEMA = "globalgrid2050.policy-commitment-evaluation.v1"
STATES = {"UNKNOWN", "NOT_YET_DUE", "REPORTED_PROGRESS", "EVIDENCE_SUPPORTED_RESULT"}
MAX_BYTES = 4 * 1024 * 1024
def require(condition, message):
if not condition:
raise ValueError(message)
def fields(value, names, label):
require(isinstance(value, dict) and set(value) == set(names.split()), label + ": unexpected fields")
return value
def choice(value, choices, label):
require(isinstance(value, str) and value in choices, label + ": unsupported state")
def strings(value, label, *, empty=True):
require(isinstance(value, list) and len(value) <= 50 and (empty or bool(value)), label + ": bounded list required")
for item in value:
_text(item, label, 500)
require(len(value) == len(set(value)), label + ": duplicate values")
def index(rows, label):
require(isinstance(rows, list) and len(rows) <= 1000, label + ": bounded list required")
result = {}
for row in rows:
require(isinstance(row, dict), label + ": object required")
identity = _identifier(row.get("id"), label + ".id")
require(identity not in result, label + ": duplicate identity")
result[identity] = row
return result
def reference(value, documents):
fields(value, "document_id locator", "source reference")
require(value["document_id"] in documents, "Unknown source document")
document = documents[value["document_id"]]
require(document["read_coverage"]["state"] != "UNREVIEWED"
and value["locator"] in document["read_coverage"]["locators"], "Source locator was not inventoried as read")
return document
def quantity(value, documents, scope):
if value is None:
return None
claim = validate_claim(value)
provenance = claim["provenance"]
require(provenance["document_id"] in documents, "Quantity document missing")
document = documents[provenance["document_id"]]
require(document["content_sha256"] is not None, "Quantity needs original document byte receipt")
require((provenance["document_url"], provenance["sha256"], provenance["published_date"], provenance["retrieved_at"])
== (document["url"], document["content_sha256"], document["published_on"], document["retrieved_at"]),
"Quantity provenance differs from document receipt")
locator = provenance["section"] or ("page " + provenance["page"])
reference({"document_id": document["id"], "locator": locator}, documents)
require(scope["entity_id"] is not None and claim["entity"]["id"] == scope["entity_id"],
"Quantity entity differs from commitment scope")
require(claim["entity"]["scope"] == scope["figure_entity_scope"], "Quantity scope differs from commitment scope")
return claim
def validate_ledger(payload):
"""Fail closed on malformed contracts; retain missing evidence as explicit nulls.
Validation establishes internal consistency, not factual truth, legal force,
audit validity or permission. Caller-supplied receipts require source review.
"""
ledger = deepcopy(payload)
fields(ledger, "schema coverage_note documents scopes commitments updates", "ledger")
require(ledger["schema"] == SCHEMA, "Unsupported ledger schema")
_text(ledger["coverage_note"], "coverage_note", 1000)
documents = index(ledger["documents"], "documents")
scopes = index(ledger["scopes"], "scopes")
commitments = index(ledger["commitments"], "commitments")
updates = index(ledger["updates"], "updates")
require(documents and scopes and commitments, "Empty evidence coverage cannot pass")
for document in documents.values():
fields(document, "id title issuer url version published_on reviewed_at retrieved_at content_sha256 hash_limitation document_state source_kind read_coverage", "document")
for key in ("title", "issuer", "version"):
_text(document[key], "document." + key, 300)
_url(document["url"], "document.url")
reviewed = _timestamp(document["reviewed_at"], "reviewed_at")
if document["published_on"] is not None:
require(_source_date(document["published_on"], "published_on") <= reviewed.date(), "Document publication follows review")
choice(document["document_state"], {"DRAFT", "PUBLISHED", "PUBLISHED_POLICY", "ADOPTED", "IN_PROGRESS", "UNKNOWN"}, "document_state")
choice(document["source_kind"], {"PRIMARY_POLICY", "OFFICIAL_ANSWER", "CONFERENCE_INDEX", "OFFICIAL_MEASUREMENT", "AUDIT_REPORT", "FILING", "ATTRIBUTED_REPORT", "PRESS_RELEASE"}, "source_kind")
coverage = fields(document["read_coverage"], "state locators note", "read_coverage")
choice(coverage["state"], {"READ", "PARTIAL", "UNREVIEWED"}, "read_coverage.state")
strings(coverage["locators"], "locators", empty=coverage["state"] == "UNREVIEWED")
require(coverage["state"] != "UNREVIEWED" or not coverage["locators"], "Unread source cannot assert read locators")
_text(coverage["note"], "coverage note", 500)
if document["content_sha256"] is None:
require(document["retrieved_at"] is None, "Missing original bytes cannot assert a retrieval receipt")
_text(document["hash_limitation"], "hash_limitation", 500)
else:
require(isinstance(document["content_sha256"], str)
and re.fullmatch(r"[a-f0-9]{64}", document["content_sha256"]), "Invalid source SHA256")
require(document["hash_limitation"] is None, "Byte receipt and missing-hash state conflict")
retrieved = _timestamp(document["retrieved_at"], "retrieved_at")
require(retrieved <= reviewed, "Original retrieval follows review")
if document["published_on"] is not None:
require(_source_date(document["published_on"], "published_on") <= retrieved.date(), "Publication follows retrieval")
for scope in scopes.values():
fields(scope, "id jurisdiction description entity_id figure_entity_scope", "scope")
_text(scope["jurisdiction"], "jurisdiction")
_text(scope["description"], "scope description", 500)
if scope["entity_id"] is None:
require(scope["figure_entity_scope"] is None, "Unlinked scope cannot acquire a figure entity scope")
else:
_identifier(scope["entity_id"], "entity_id")
choice(scope["figure_entity_scope"], {"issuer", "consolidated_group", "project", "site", "campus", "phase", "public_institution"}, "figure_entity_scope")
all_claim_ids = set()
for row in commitments.values():
fields(row, "id issuer source scope_id statement_type statement conditions metric target baseline baseline_state deadline reporting_obligation applicability revision", "commitment")
document = reference(row["source"], documents)
require(row["issuer"] == document["issuer"], "Commitment issuer differs from source")
require(row["scope_id"] in scopes, "Unknown commitment scope")
scope = scopes[row["scope_id"]]
choice(row["statement_type"], {"EXPECTATION", "UNDERTAKING", "CONDITIONAL_REQUIREMENT", "CONDITIONAL_OFFER", "REQUIREMENT_STATED", "CONTEXT"}, "statement_type")
_text(row["statement"], "statement", 500)
strings(row["conditions"], "conditions", empty=not row["statement_type"].startswith("CONDITIONAL_"))
metric = fields(row["metric"], "label numeric_support limitation", "metric")
_text(metric["label"], "metric.label")
choice(metric["numeric_support"], {"SUPPORTED", "UNSUPPORTED", "UNSTATED"}, "numeric_support")
if metric["numeric_support"] != "SUPPORTED":
_text(metric["limitation"], "metric limitation", 500)
require(row["target"] is None and row["baseline"] is None, "Unsupported metric cannot carry a parallel quantity")
else:
require(metric["limitation"] is None and row["target"] is not None, "Supported metric requires a target claim")
row["target"] = quantity(row["target"], documents, scope)
row["baseline"] = quantity(row["baseline"], documents, scope)
choice(row["baseline_state"], {"UNKNOWN", "NOT_REQUIRED", "STATED"}, "baseline_state")
require((row["baseline"] is not None) == (row["baseline_state"] == "STATED"), "Baseline state differs from quantity")
if row["target"]:
require(row["target"]["metric"] == metric["label"], "Metric differs from target claim")
provenance = row["target"]["provenance"]
require(provenance["document_id"] == row["source"]["document_id"]
and (provenance["section"] or "page " + provenance["page"]) == row["source"]["locator"],
"Target claim differs from commitment source locator")
deadline = fields(row["deadline"], "value wording", "deadline")
if deadline["value"] is not None:
_source_date(deadline["value"], "deadline.value")
_text(deadline["wording"], "deadline.wording")
else:
require(deadline["wording"] is None, "Unknown deadline cannot assert date wording")
if row["reporting_obligation"] is not None:
_text(row["reporting_obligation"], "reporting_obligation", 500)
applicability = fields(row["applicability"], "state reason evidence", "applicability")
choice(applicability["state"], {"UNKNOWN", "ESTABLISHED"}, "applicability.state")
_text(applicability["reason"], "applicability.reason", 500)
require(isinstance(applicability["evidence"], list) and len(applicability["evidence"]) <= 20, "Applicability evidence list required")
for item in applicability["evidence"]:
reference(item, documents)
if applicability["state"] == "ESTABLISHED":
require(scope["entity_id"] is not None and applicability["evidence"], "Applicability requires stable entity and source evidence")
revision = fields(row["revision"], "id supersedes_commitment_id baseline_changed", "revision")
_identifier(revision["id"], "revision.id")
require(type(revision["baseline_changed"]) is bool, "baseline_changed must be boolean")
prior = revision["supersedes_commitment_id"]
require(prior is None or (prior in commitments and prior != row["id"]), "Superseded commitment missing or self-referential")
require(not revision["baseline_changed"] or prior is not None, "Changed baseline needs retained predecessor")
for claim in (row["target"], row["baseline"]):
if claim:
require(claim["claim_id"] not in all_claim_ids, "Duplicate claim identity")
all_claim_ids.add(claim["claim_id"])
for row in commitments.values():
seen, cursor = set(), row
while cursor["revision"]["supersedes_commitment_id"] is not None:
require(cursor["id"] not in seen, "Cyclic commitment revision")
seen.add(cursor["id"])
cursor = commitments[cursor["revision"]["supersedes_commitment_id"]]
for update in updates.values():
fields(update, "id commitment_id commitment_revision_id baseline_revision_id source reported_on statement kind claim measurement_state", "update")
require(update["commitment_id"] in commitments, "Update commitment missing")
row = commitments[update["commitment_id"]]
document = reference(update["source"], documents)
_source_date(update["reported_on"], "update.reported_on")
require(_source_date(update["reported_on"], "reported_on") <= _timestamp(document["reviewed_at"], "reviewed_at").date(), "Future reported update")
require(document["published_on"] is None or update["reported_on"] == document["published_on"],
"Reported update date differs from source publication")
_text(update["statement"], "update.statement", 500)
for field in ("commitment_revision_id", "baseline_revision_id"):
_identifier(update[field], field)
choice(update["kind"], {"PROCESS_REPORT", "NUMERIC_REPORT", "CORRECTION", "CONTRADICTION"}, "update.kind")
choice(update["measurement_state"], {"UNKNOWN", "REPORTED", "DOCUMENTED_MEASUREMENT"}, "measurement_state")
update["claim"] = quantity(update["claim"], documents, scopes[row["scope_id"]])
require((update["claim"] is not None) == (update["kind"] == "NUMERIC_REPORT"), "Numerical reports require exactly one FIGURES claim")
if update["claim"]:
require(update["claim"]["claim_id"] not in all_claim_ids, "Duplicate claim identity")
all_claim_ids.add(update["claim"]["claim_id"])
provenance = update["claim"]["provenance"]
require(provenance["document_id"] == update["source"]["document_id"]
and (provenance["section"] or "page " + provenance["page"]) == update["source"]["locator"],
"Update claim source differs")
if update["measurement_state"] == "DOCUMENTED_MEASUREMENT":
require(update["claim"] is not None and update["claim"]["basis"] == "reported"
and document["source_kind"] in {"OFFICIAL_MEASUREMENT", "AUDIT_REPORT"}
and document["document_state"] in {"PUBLISHED", "ADOPTED"},
"Press releases and assertions cannot certify a measured outcome")
return ledger
def incompatibilities(target, measured):
"""Exact compatibility only: no currency/unit conversion or scope aggregation."""
mismatches = []
for key in ("metric", "quantity_kind", "unit", "currency", "finance_stage", "reporting_period"):
if target[key] != measured[key]:
mismatches.append(key)
for key in ("id", "scope", "consolidation_group_id"):
if target["entity"][key] != measured["entity"][key]:
mismatches.append("entity." + key)
if target["reporting_period"] is None and target["as_of"] != measured["as_of"]:
mismatches.append("as_of")
return mismatches
def evaluate(payload, *, as_of):
"""Return evidence states and exact numerical relations; never compliance labels."""
ledger = validate_ledger(payload)
reference_time = _timestamp(as_of, "as_of")
documents = {d["id"]: d for d in ledger["documents"]}
scopes = {s["id"]: s for s in ledger["scopes"]}
for document in documents.values():
require(_timestamp(document["reviewed_at"], "reviewed_at") <= reference_time, "Source review follows evaluation clock")
results = []
for row in sorted(ledger["commitments"], key=lambda r: r["id"]):
document = documents[row["source"]["document_id"]]
updates = sorted((u for u in ledger["updates"] if u["commitment_id"] == row["id"]), key=lambda u: (u["reported_on"], u["id"]))
superseded_by = sorted(c["id"] for c in ledger["commitments"] if c["revision"]["supersedes_commitment_id"] == row["id"])
state, reasons, comparison = "UNKNOWN", [], None
if superseded_by:
reasons.append("Superseded version retained for historical review; no current result inferred")
elif document["document_state"] in {"DRAFT", "IN_PROGRESS", "UNKNOWN"}:
reasons.append("Instrument is draft, in progress or unclassified; no adopted outcome inferred")
elif row["applicability"]["state"] != "ESTABLISHED":
reasons.append("Applicability to a stable entity is unknown; conditions do not establish compliance")
elif any(u["kind"] in {"CORRECTION", "CONTRADICTION"} for u in updates):
reasons.append("Unresolved correction or contradiction retained; no automatic evidence reconciliation")
elif any(u["commitment_revision_id"] != row["revision"]["id"] or u["baseline_revision_id"] != row["revision"]["id"] for u in updates):
reasons.append("Update refers to a different commitment or baseline revision")
elif any(u["claim"] and (u["claim"]["revision"]["restated"] or u["claim"]["revision"]["supersedes_claim_id"] is not None) for u in updates):
reasons.append("Figure revision retained for explicit reconciliation; no automatic replacement")
else:
measured = [u for u in updates if u["measurement_state"] == "DOCUMENTED_MEASUREMENT"]
if measured and row["target"] is not None and row["baseline_state"] != "UNKNOWN":
mismatches = sorted({key for u in measured for key in incompatibilities(row["target"], u["claim"])})
if mismatches:
reasons.append("Numerical comparison unavailable: incompatible " + ", ".join(mismatches))
else:
with localcontext() as context:
context.prec = 256
target_value = Decimal(row["target"]["value"]) * Decimal(row["target"]["scale"])
values = {Decimal(u["claim"]["value"]) * Decimal(u["claim"]["scale"]) for u in measured}
if len(values) != 1:
reasons.append("Conflicting measurements retained without selecting a preferred result")
else:
value = next(iter(values))
state = "EVIDENCE_SUPPORTED_RESULT"
comparison = {"relation": "EQUAL" if value == target_value else "LESS_THAN" if value < target_value else "GREATER_THAN",
"target_claim_id": row["target"]["claim_id"],
"measurement_claim_ids": sorted(u["claim"]["claim_id"] for u in measured),
"unit": row["target"]["unit"], "currency": row["target"]["currency"]}
reasons.append("Documented same-scope/metric/unit/stage/period comparison; numerical relation is not a legal compliance verdict")
elif updates:
state = "REPORTED_PROGRESS"
reasons.append("Attributable update recorded; measurement, scope or baseline support is insufficient for a result")
elif row["deadline"]["value"] is not None and reference_time.date() < _source_date(row["deadline"]["value"], "deadline"):
state = "NOT_YET_DUE"
reasons.append("Evaluation precedes the earliest day of the source-stated deadline; no delivery inferred")
else:
reasons.append("No comparable measurement supplied; missing evidence is not failure")
results.append({"commitment_id": row["id"], "issuer": row["issuer"], "scope": scopes[row["scope_id"]],
"statement_type": row["statement_type"], "statement": row["statement"],
"document_state": document["document_state"], "applicability": row["applicability"],
"metric": row["metric"], "target": row["target"], "baseline": row["baseline"],
"baseline_state": row["baseline_state"], "revision": row["revision"], "superseded_by": superseded_by,
"deadline": row["deadline"], "conditions": row["conditions"],
"reporting_obligation": row["reporting_obligation"], "state": state,
"measurement_state": "EVIDENCE_SUPPORTED" if state == "EVIDENCE_SUPPORTED_RESULT" else "UNKNOWN",
"reasons": reasons, "comparison": comparison, "source": {**row["source"], "url": document["url"],
"published_on": document["published_on"], "reviewed_at": document["reviewed_at"],
"retrieved_at": document["retrieved_at"], "content_sha256": document["content_sha256"]},
"updates": updates, "status": "machine-provisional", "legal_compliance": "NOT_ASSESSED"})
return {"schema": REPORT_SCHEMA, "as_of": as_of, "coverage_note": ledger["coverage_note"],
"documents": sorted(ledger["documents"], key=lambda d: d["id"]), "results": results}
def dumps_report(report):
return json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + "\n"
def csv_report(report):
"""One commitment per row; nested evidence stays attributable through JSON cells."""
output = io.StringIO(newline="")
names = ["commitment_id", "issuer", "state", "measurement_state", "statement_type", "document_state", "statement", "deadline", "metric",
"scope", "conditions", "target", "baseline", "baseline_state", "revision", "superseded_by", "reporting_obligation", "applicability", "reasons", "comparison", "source", "updates", "status", "legal_compliance"]
writer = csv.DictWriter(output, fieldnames=names, lineterminator="\n")
writer.writeheader()
for row in report["results"]:
values = {}
for name in names:
value = row[name]
if isinstance(value, (dict, list)):
value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
value = "" if value is None else str(value)
values[name] = "'" + value if value.startswith(("=", "+", "-", "@", "\t", "\r")) else value
writer.writerow(values)
return output.getvalue()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ledger", type=Path, default=Path(__file__).with_name("sample_ledger.json"))
parser.add_argument("--as-of", required=True)
parser.add_argument("--format", choices=("json", "csv"), default="json")
args = parser.parse_args(argv)
try:
with args.ledger.open("rb") as stream:
raw = stream.read(MAX_BYTES + 1)
require(len(raw) <= MAX_BYTES, "Input exceeds bounded size")
result = evaluate(json.loads(raw), as_of=args.as_of)
except (ValueError, TypeError, KeyError, OSError):
parser.exit(2, "Policy ledger validation failed; no report emitted.\n")
print(csv_report(result) if args.format == "csv" else dumps_report(result), end="")
return 0
if __name__ == "__main__":
raise SystemExit(main())