GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/news/tests

Test Transition Context and 5 more files

A test in the tests folder of GlobalGrid2050 that checks Build Transition Context and Grid, using SHA-256.

677 lines of Python and JavaScript and CSS from globalgrid2050, in 6 files. Topic: Electricity markets and data pipelines. Section 813 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. Test Spp Excluded test · globalgrid2050 / automation/news/tests/test_spp_excluded.py lines 1–102
  2. Test Transition Context test · globalgrid2050 / automation/news/tests/test_transition_context.py lines 1–354
  3. Test V928 DC Data test · globalgrid2050 / automation/news/tests/test_v928_dc_data.py lines 1–143
  4. History Test test · globalgrid2050 / automation/news_history_return/20261118/history.test.mjs lines 1–43
  5. Model transform · globalgrid2050 / automation/news_quality_ui/20261117-v937/model.mjs lines 1–32
  6. News Quality UI — V937 Style Sheet render · globalgrid2050 / automation/news_quality_ui/20261117-v937/styles.css lines 1–3

Test Spp Excluded

A test in the tests folder of GlobalGrid2050 that checks Pipeline Headlines. It is built from the item step (`item`) and the fetch step (`fetch`).

testglobalgrid2050 / automation/news/tests/test_spp_excluded.py · lines 1–102 of 102 · Entry point

What it does
It tests the REPD register. Defines 8 functions or classes, including item, test_config_omits_all_blocked_publisher_feeds, test_source_or_original_publisher_url_exclusion, test_manual_feed_input_does_not_trigger_publisher_network_request, fetch. Uses libraries json, pathlib, sys, pytest. 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: the REPD register.
Inputs & outputs
In: JSON file pipeline_feeds.json; JSON file feeds.json.
Downstream impact
Used directly by 3 files: Compare Legacy Collector (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Pipeline Headlines Workflow (globalgrid2050).
What it achieves
Regression checks: owner-excluded publisher is not fetched or displayed.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow. Checked by Compare Legacy Collector.
Application
globalgrid2050 · automation/news/tests · test
Uses
Pipeline Headlines (sys.path import), json, pathlib, sys, pytest
Used by
run by Compare Legacy Collector (script call), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
item, test_config_omits_all_blocked_publisher_feeds, test_source_or_original_publisher_url_exclusion, test_manual_feed_input_does_not_trigger_publisher_network_request, test_retained_old_headlines_and_syndicated_links_are_purged, test_build_drops_publisher_even_when_previous_snapshot_contains_it, test_load_feeds_filters_disabled_source_from_older_fixture
Defines here
item, test_config_omits_all_blocked_publisher_feeds, test_source_or_original_publisher_url_exclusion, test_manual_feed_input_does_not_trigger_publisher_network_request, fetch, test_retained_old_headlines_and_syndicated_links_are_purged, test_build_drops_publisher_even_when_previous_snapshot_contains_it, test_load_feeds_filters_disabled_source_from_older_fixture
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/tests/test_spp_excluded.py:1-102 · blob 4406efc38005662c38ea99a2ac60c3bfd69774df · 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
"""Regression checks: owner-excluded publisher is not fetched or displayed."""
import json
from pathlib import Path
import sys

import pytest

PKG = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PKG))
import pipeline_headlines as P

NOW = "2026-11-21T22:30:00Z"
BLOCK = "https://www.solarpowerportal.co.uk/solar-projects/uk-solar-farm-approved"
OTHER = "https://www.gov.uk/government/news/uk-solar-farm-approved"


def item(source, link, title="UK solar farm approved in Oxfordshire"):
    return {"title": title, "link": link, "source": source,
            "date": None, "first_seen": NOW, "category": "consent",
            "technology": "solar", "possible_match": None}


def test_config_omits_all_blocked_publisher_feeds():
    config = json.loads((PKG / "pipeline_feeds.json").read_text(encoding="utf-8"))
    assert config["excluded_sources"] == ["Solar Power Portal"]
    assert config["source_patch_id"] == "20261121-exclude-solar-power-portal-v1"
    assert len(config["feeds"]) == 69  # 68 unchanged + independent BBC COP31 link
    assert all(not P.excluded_publisher(f.get("source"), f.get("url")) for f in config["feeds"])
    assert not any(f["url"].startswith("https://www.solarpowerportal.co.uk/") for f in config["feeds"])


@pytest.mark.parametrize("source,url,blocked", [
    ("Solar Power Portal", BLOCK, True),
    ("solar power portal", OTHER, True),
    ("BBC News", BLOCK, True),
    ("BBC News", "https://sub.solarpowerportal.co.uk/solar", True),
    ("BBC News", "https://www.solarpowerportal.co.uk.evil.example/solar", False),
    ("BBC News", OTHER, False),
    ("Swissgrid", "https://www.swissgrid.ch/en/home", False),
])
def test_source_or_original_publisher_url_exclusion(source, url, blocked):
    assert P.excluded_publisher(source, url) is blocked


def test_manual_feed_input_does_not_trigger_publisher_network_request():
    feeds = [
        {"url": "https://www.solarpowerportal.co.uk/rss.xml?content_types=article",
         "source": "Solar Power Portal", "primary": True},
        {"url": "https://www.solarpowerportal.co.uk/solar-finance/a",
         "source": "Solar Power Portal", "kind": "curated",
         "title": "UK solar finance announced"},
        {"url": "https://www.gov.uk/feed.xml", "source": "Government", "uk_only": True},
    ]
    requested = []
    def fetch(url):
        requested.append(url)
        return (b"<rss><channel><item><title>UK solar farm approved in Oxfordshire</title>"
                b"<link>https://www.gov.uk/government/news/uk-solar-farm-approved</link>"
                b"</item></channel></rss>")
    items, health = P.collect(feeds, fetch, P.Repd([]), NOW)
    assert requested == ["https://www.gov.uk/feed.xml"]
    assert len(items) == len(health) == 1
    assert items[0]["source"] == "Government"
    assert all("Solar Power Portal" not in str(h) for h in health)


def test_retained_old_headlines_and_syndicated_links_are_purged():
    past = [
        item("Solar Power Portal", BLOCK),
        item("BBC News", BLOCK),
        item("GOV.UK", OTHER),
    ]
    current = [
        item("Solar Power Portal", BLOCK),
        item("BBC News", BLOCK),
        item("GOV.UK", OTHER),
    ]
    merged = P.merge(past, current, P.Repd([]), NOW)
    assert [x["link"] for x in merged] == [OTHER]
    assert not any(P.excluded_publisher(x["source"], x["link"]) for x in merged)


def test_build_drops_publisher_even_when_previous_snapshot_contains_it():
    prior = {"schema": P.SCHEMA, "items": [
        item("Solar Power Portal", BLOCK), item("GOV.UK", OTHER),
    ]}
    fresh, health = [], [{"source": "GOV.UK", "url": "https://www.gov.uk/feed.xml",
                         "status": "ok", "entries": 0, "kept": 0, "newest": None}]
    out = P.build(prior, fresh, health, P.Repd([]), NOW)
    assert out["counts"]["items"] == 1
    assert out["items"][0]["link"] == OTHER
    assert out["counts"]["feeds_failed"] == 0


def test_load_feeds_filters_disabled_source_from_older_fixture(tmp_path):
    config = {"feeds": [
        {"url": "https://www.solarpowerportal.co.uk/rss.xml", "source": "Solar Power Portal"},
        {"url": "https://www.gov.uk/feed.xml", "source": "GOV.UK"},
    ]}
    p = tmp_path / "feeds.json"
    p.write_text(json.dumps(config), encoding="utf-8")
    assert [f["source"] for f in P.load_feeds(p)] == ["GOV.UK"]

Test Transition Context

A test in the tests folder of GlobalGrid2050 that checks Build Transition Context and Grid, using SHA-256.

testglobalgrid2050 / automation/news/tests/test_transition_context.py · lines 1–354 of 354 · Entry point · pattern inputs (shared by 2 files)

What it does
It tests its inputs. Defines 36 functions or classes, including inputs, compose, rows, grid_claim, command. Uses libraries copy, csv, hashlib, io, json. Side effects: reads or writes files; 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.
Inputs & outputs
In: JSON file sample_ledger.json; JSON file grid-source-fixture.json; JSON file solar-context.json; JSON file invalid.json; JSON file output.json; JSON file missing.json; JSON file policy.json; JSON file new.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the inputs step (`inputs`), the compose step (`compose`) and the rows step (`rows`). Actual typed producers composed offline; no live source acquisition.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Build Transition Context (import), Grid (import), Solar (import), Ledger (import), News — Policy Commitments (import), Test Policy Commitments (import), copy, csv, hashlib, io, json, pathlib, subprocess, sys
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
inputs, compose, rows, grid_claim, command, test_actual_fourteen_contexts_remain_unlinked_and_provisional, test_native_records_and_source_receipts_survive_exactly, test_rejection_forecast_upper_bound_and_missing_capacity_are_not_delivered, test_scope_categories_do_not_allocate_portfolio_to_site, test_unknown_original_hash_and_clocks_are_not_fabricated, test_deterministic_complete_input_digests_and_dates, test_exact_large_decimals_and_comparison_remain_shared_figures
Defines here
inputs, compose, rows, grid_claim, command, test_actual_fourteen_contexts_remain_unlinked_and_provisional, test_native_records_and_source_receipts_survive_exactly, test_rejection_forecast_upper_bound_and_missing_capacity_are_not_delivered, test_scope_categories_do_not_allocate_portfolio_to_site, test_unknown_original_hash_and_clocks_are_not_fabricated, test_deterministic_complete_input_digests_and_dates, test_exact_large_decimals_and_comparison_remain_shared_figures, test_incompatible_measurements_do_not_become_results, test_finance_stages_are_preserved_without_delivery_inference, test_policy_uncertainties_survive_composition, test_issuer_scope_stays_issuer_and_future_deadline_is_not_delivery, test_csv_roundtrip_preserves_whole_bundle_and_formula_safety, test_empty_family_fails_whole_composition, test_invalid_input_fails_closed, test_cross_family_repeated_claim_identity_is_not_corroboration, test_real_cli_utf8_export_and_no_overwrite, test_cli_invalid_input_emits_no_stdout_or_file, test_cli_missing_file_and_oversized_inputs_fail, test_library_size_bound_fails_before_returning_partial_report, test_csv_repeated_metadata_is_bounded_during_serialization, test_cli_unicode_quotes_and_formula_prefix_survive, test_partial_disk_write_leaves_no_published_file_or_staging_file, FailingWriter, __init__, __enter__
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/tests/test_transition_context.py:1-354 · blob 2c0586d174d49c3237306c66c657deed2cb91384 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Actual typed producers composed offline; no live source acquisition."""
from copy import deepcopy
import csv
import hashlib
import io
import json
from pathlib import Path
import subprocess
import sys

import pytest

from automation.news import build_transition_context as context
from automation.news.dc_context import grid, solar
from automation.news.policy_commitments import ledger as policy
from automation.news.tests.test_policy_commitments import numeric  # existing synthetic fixture

HERE = Path(__file__).resolve().parents[1]
ROOT = HERE.parents[1]
AS_OF = "2026-11-16T18:00:00Z"
PATHS = {"policy": HERE / "policy_commitments/sample_ledger.json",
         "grid": HERE / "dc_context/grid-source-fixture.json",
         "solar": HERE / "dc_context/fixtures/solar-context.json"}


@pytest.fixture
def inputs():
    return {name: json.loads(path.read_text(encoding="utf-8")) for name, path in PATHS.items()}


def compose(inputs, **kwargs):
    return context.build(inputs["policy"], inputs["grid"], inputs["solar"], as_of=kwargs.get("as_of", AS_OF))


def rows(report, family):
    return [row for row in report["records"] if row["family"] == family]


def grid_claim(inputs):
    return next(row["numeric_claims"][0] for row in inputs["grid"]["contexts"] if row["numeric_claims"])


def command(paths=None, *extra):
    paths = paths or PATHS
    return [sys.executable, "-B", "-X", "utf8", "-m", "automation.news.build_transition_context",
            "--policy", str(paths["policy"]), "--grid", str(paths["grid"]), "--solar", str(paths["solar"]),
            "--as-of", AS_OF, *extra]


def test_actual_fourteen_contexts_remain_unlinked_and_provisional(inputs):
    before = deepcopy(inputs)
    report = compose(inputs)
    assert report["schema"] == context.SCHEMA and report["status"] == "PROVISIONAL"
    assert report["coverage"] == {"records": 14, "families": {"policy": 8, "grid": 2, "solar": 4},
                                  "numeric_claims": 3, "linked_projects": 0, "scope": "BOUNDED_SUPPLIED_CONTEXT"}
    assert all(row["scope"]["canonical_project_id"] is None and row["scope"]["binding"] == "UNLINKED"
               for row in report["records"])
    assert [row["evaluation_state"] for row in rows(report, "policy")].count("UNKNOWN") == 7
    assert [row["evaluation_state"] for row in rows(report, "policy")].count("REPORTED_PROGRESS") == 1
    assert all(row["evaluation_state"] == row["applicability_state"] == "UNKNOWN"
               for row in rows(report, "grid") + rows(report, "solar"))
    assert inputs == before
    report["records"][0]["native_record"]["name"] = "changed copy"
    assert inputs == before


def test_native_records_and_source_receipts_survive_exactly(inputs):
    report = compose(inputs)
    assert [row["native_record"] for row in rows(report, "policy")] == policy.evaluate(inputs["policy"], as_of=AS_OF)["results"]
    assert [row["native_record"] for row in rows(report, "grid")] == grid.build(inputs["grid"], as_of=AS_OF)["records"]
    assert [row["native_record"] for row in rows(report, "solar")] == solar.build(inputs["solar"], as_of=AS_OF)["records"]
    for row in report["records"]:
        for link in row["source_links"]:
            assert link["url"] == link["receipt"]["url"]
            assert link["retrieved_at"] == link["receipt"]["retrieved_at"]
    assert all(item["source_byte_validation"] == "RECEIPTS_ONLY" for item in report["input_receipts"])
    for receipt in report["input_receipts"]:
        family = receipt["family"]
        reconstructed = {**receipt["native_metadata"],
                         "results" if family == "policy" else "records": [row["native_record"] for row in rows(report, family)]}
        original = (policy.evaluate(inputs[family], as_of=AS_OF) if family == "policy"
                    else (grid if family == "grid" else solar).build(inputs[family], as_of=AS_OF))
        assert reconstructed == original


def test_rejection_forecast_upper_bound_and_missing_capacity_are_not_delivered(inputs):
    report = compose(inputs)
    rejected = next(row for row in rows(report, "grid") if row["source_state"] == "REJECTED")
    figure = rejected["numeric_claims"][0]
    assert figure["qualifier"] is None and figure["claim"]["value"] == "480"
    assert figure["claim"]["basis"] == "forecast" and figure["claim"]["quantity_kind"] == "project_demand"
    battery = next(row for row in rows(report, "solar") if "storage:google-nevada" in row["id"])
    assert battery["numeric_claims"][0]["qualifier"] == "upper_bound"
    assert battery["numeric_claims"][0]["claim"]["as_of"] == "2024"
    assert battery["native_record"]["current_delivery"] == "UNKNOWN"
    missing = next(row for row in rows(report, "solar") if "livingston" in row["id"])
    assert missing["numeric_claims"] == [] and missing["native_record"]["current_site_supply_mw"] is None
    assert missing["source_links"][0]["published_date"] is None


def test_scope_categories_do_not_allocate_portfolio_to_site(inputs):
    report = compose(inputs)
    portfolio = next(row for row in rows(report, "solar") if "shell" in row["id"])
    assert portfolio["scope"]["kind"] == "portfolio"
    assert portfolio["scope"]["native_scope"] == "issuer"
    assert portfolio["numeric_claims"] == []
    zone = next(row for row in rows(report, "grid") if row["scope"]["native_scope"] == "zone")
    assert zone["scope"]["kind"] == "UNKNOWN"
    assert all(row["scope"]["kind"] == "policy" for row in rows(report, "policy"))


def test_unknown_original_hash_and_clocks_are_not_fabricated(inputs):
    report = compose(inputs)
    metadata = report["input_receipts"][0]["native_metadata"]
    cop = next(doc for doc in metadata["documents"] if doc["document_state"] == "IN_PROGRESS")
    assert cop["published_on"] is cop["retrieved_at"] is cop["content_sha256"] is None
    assert cop["reviewed_at"] == "2026-11-16T17:16:51Z" and cop["hash_limitation"]
    answer = next(link for row in rows(report, "policy") for link in row["source_links"]
                  if link["receipt"]["source_kind"] == "OFFICIAL_ANSWER")
    assert answer["sha256"] is answer["retrieved_at"] is None


def test_deterministic_complete_input_digests_and_dates(inputs):
    first = compose(inputs)
    assert context.dumps(first) == context.dumps(compose(inputs))
    for receipt in first["input_receipts"]:
        raw = context.dumps(inputs[receipt["family"]]).encode("utf-8")
        assert receipt["input_sha256"] == hashlib.sha256(raw).hexdigest()
    changed = deepcopy(inputs)
    changed["policy"]["coverage_note"] += " Additional bounded review note."
    second = compose(changed)
    assert first["input_receipts"][0]["input_sha256"] != second["input_receipts"][0]["input_sha256"]
    later = compose(inputs, as_of="2026-12-16T18:00:00Z")
    assert [row["source_links"] for row in first["records"]] == [row["source_links"] for row in later["records"]]


def test_exact_large_decimals_and_comparison_remain_shared_figures(inputs, numeric):
    numeric["commitments"][0]["target"]["value"] = "9007199254740993.010"
    numeric["updates"][0]["claim"]["value"] = "9007199254740993.011"
    inputs["policy"] = numeric
    row = rows(compose(inputs), "policy")[0]
    assert row["evaluation_state"] == "EVIDENCE_SUPPORTED_RESULT"
    assert row["native_record"]["comparison"]["relation"] == "GREATER_THAN"
    assert row["native_record"]["legal_compliance"] == "NOT_ASSESSED"
    assert [(f["role"], f["claim"]["value"]) for f in row["numeric_claims"]] == [
        ("TARGET", "9007199254740993.010"), ("UPDATE", "9007199254740993.011")]
    assert row["scope"]["kind"] == "project" and row["scope"]["binding"] == "UNLINKED"


@pytest.mark.parametrize("field,value", [("unit", "GW"), ("reporting_period", {"start": "2026-01", "end": "2026-10"})])
def test_incompatible_measurements_do_not_become_results(inputs, numeric, field, value):
    numeric["updates"][0]["claim"][field] = value
    inputs["policy"] = numeric
    assert rows(compose(inputs), "policy")[0]["evaluation_state"] == "UNKNOWN"


@pytest.mark.parametrize("observed_stage,expected", [("announced", "UNKNOWN"), ("disbursed", "EVIDENCE_SUPPORTED_RESULT")])
def test_finance_stages_are_preserved_without_delivery_inference(inputs, numeric, observed_stage, expected):
    target, actual = numeric["commitments"][0]["target"], numeric["updates"][0]["claim"]
    for claim in (target, actual):
        claim.update(quantity_kind="finance", unit="currency", original_unit="euros", currency="EUR", finance_stage="disbursed")
    actual["finance_stage"] = observed_stage
    inputs["policy"] = numeric
    row = rows(compose(inputs), "policy")[0]
    assert row["evaluation_state"] == expected
    assert row["numeric_claims"][1]["claim"]["finance_stage"] == observed_stage
    assert row["native_record"]["legal_compliance"] == "NOT_ASSESSED"


@pytest.mark.parametrize("change", ["draft", "unknown_applicability", "baseline_revision"])
def test_policy_uncertainties_survive_composition(inputs, numeric, change):
    if change == "draft":
        numeric["documents"][0]["document_state"] = "DRAFT"
    elif change == "unknown_applicability":
        numeric["commitments"][0]["applicability"]["state"] = "UNKNOWN"
    else:
        numeric["updates"][0]["baseline_revision_id"] = "earlier"
    inputs["policy"] = numeric
    row = rows(compose(inputs), "policy")[0]
    assert row["evaluation_state"] == "UNKNOWN" and row["native_record"]["comparison"] is None


def test_issuer_scope_stays_issuer_and_future_deadline_is_not_delivery(inputs, numeric):
    entity = inputs["solar"]["contexts"][0]["entity"]
    entity["scope"] = "issuer"
    inputs["solar"]["contexts"][0]["numeric_claims"][0]["claim"]["entity"] = deepcopy(entity)
    numeric["updates"] = []
    numeric["commitments"][0]["deadline"] = {"value": "2027", "wording": "by 2027"}
    inputs["policy"] = numeric
    report = compose(inputs)
    assert rows(report, "policy")[0]["evaluation_state"] == "NOT_YET_DUE"
    assert next(row for row in rows(report, "solar") if row["id"] == "solar:solar:google-nevada-2021")["scope"]["kind"] == "issuer"


def test_csv_roundtrip_preserves_whole_bundle_and_formula_safety(inputs):
    inputs["policy"]["commitments"][0]["statement"] = '=SUM(1,2) "Türkiye €"'
    report = compose(inputs)
    exported = list(csv.DictReader(io.StringIO(context.csv_report(report))))
    assert len(exported) == len(report["records"])
    for flat, row in zip(exported, report["records"]):
        assert json.loads(flat["bundle"]) == {k: v for k, v in report.items() if k != "records"}
        for key, value in row.items():
            if isinstance(value, (dict, list)):
                assert json.loads(flat[key]) == value
            else:
                assert flat[key] == ("'" + value if value.startswith(("=", "+", "-", "@", "\t", "\r")) else value)


@pytest.mark.parametrize("family,field", [("policy", "commitments"), ("grid", "contexts"), ("solar", "contexts")])
def test_empty_family_fails_whole_composition(inputs, family, field):
    inputs[family][field] = []
    with pytest.raises(ValueError):
        compose(inputs)


@pytest.mark.parametrize("mutation", [
    lambda x: grid_claim(x).update(value=480),
    lambda x: x["solar"]["contexts"][0]["numeric_claims"][0].update(qualifier="delivered"),
    lambda x: x["grid"]["sources"][0].update(url="javascript:alert(1)"),
    lambda x: x["policy"]["documents"][0].update(reviewed_at="2027-01-01T00:00:00Z"),
    lambda x: x["solar"]["contexts"][0]["numeric_claims"][0]["claim"]["provenance"].update(sha256="0" * 64),
    lambda x: x["grid"]["contexts"][0].update(canonical_project_id="invented"),
])
def test_invalid_input_fails_closed(inputs, mutation):
    mutation(inputs)
    with pytest.raises((ValueError, KeyError, TypeError)):
        compose(inputs)


def test_cross_family_repeated_claim_identity_is_not_corroboration(inputs):
    duplicate = grid_claim(inputs)["claim_id"]
    inputs["solar"]["contexts"][0]["numeric_claims"][0]["claim"]["claim_id"] = duplicate
    with pytest.raises(ValueError, match="Repeated FIGURES"):
        compose(inputs)


@pytest.mark.parametrize("format", ["json", "csv"])
def test_real_cli_utf8_export_and_no_overwrite(tmp_path, format):
    destination = tmp_path / ("context." + format)
    result = subprocess.run(command(None, "--format", format, "--output", str(destination)), cwd=ROOT, capture_output=True)
    assert result.returncode == 0 and result.stdout == b""
    original = destination.read_bytes()
    decoded = original.decode("utf-8")
    assert len(json.loads(decoded)["records"] if format == "json" else list(csv.DictReader(io.StringIO(decoded)))) == 14
    second = subprocess.run(command(None, "--format", format, "--output", str(destination)), cwd=ROOT, capture_output=True)
    assert second.returncode != 0 and second.stdout == b"" and destination.read_bytes() == original


@pytest.mark.parametrize("payload", [b'{"schema":"x","schema":"y"}', b'{bad json', b'{}', b'[]'])
def test_cli_invalid_input_emits_no_stdout_or_file(tmp_path, payload):
    invalid = tmp_path / "invalid.json"
    invalid.write_bytes(payload)
    output = tmp_path / "output.json"
    result = subprocess.run(command({**PATHS, "solar": invalid}, "--output", str(output)), cwd=ROOT, capture_output=True)
    assert result.returncode != 0 and result.stdout == b"" and not output.exists()
    assert b"Traceback" not in result.stderr


def test_cli_missing_file_and_oversized_inputs_fail(tmp_path):
    invalid = tmp_path / "missing.json"
    output = tmp_path / "output.json"
    for raw in (None, b" " * (context.MAX_INPUT_BYTES + 1)):
        if raw is not None:
            invalid.write_bytes(raw)
        result = subprocess.run(command({**PATHS, "grid": invalid}, "--output", str(output)), cwd=ROOT, capture_output=True)
        assert result.returncode != 0 and result.stdout == b"" and not output.exists()


def test_library_size_bound_fails_before_returning_partial_report(inputs, monkeypatch):
    monkeypatch.setattr(context, "MAX_OUTPUT_BYTES", 100)
    with pytest.raises(ValueError, match="bounded size"):
        compose(inputs)


def test_csv_repeated_metadata_is_bounded_during_serialization(inputs, monkeypatch):
    report = compose(inputs)
    monkeypatch.setattr(context, "MAX_OUTPUT_BYTES", 1000)
    with pytest.raises(ValueError, match="CSV export exceeds bounded size"):
        context.csv_report(report)


@pytest.mark.parametrize("format", ["json", "csv"])
def test_cli_unicode_quotes_and_formula_prefix_survive(inputs, tmp_path, format):
    statement = '=SUM(1,2) "Türkiye €"'
    inputs["policy"]["commitments"][0]["statement"] = statement
    input_path = tmp_path / "policy.json"
    input_path.write_text(json.dumps(inputs["policy"], ensure_ascii=False), encoding="utf-8")
    result = subprocess.run(command({**PATHS, "policy": input_path}, "--format", format), cwd=ROOT, capture_output=True)
    assert result.returncode == 0
    text = result.stdout.decode("utf-8")
    if format == "json":
        assert any(row["title"] == statement for row in json.loads(text)["records"])
    else:
        parsed = list(csv.DictReader(io.StringIO(text)))
        assert any(row["title"] == "'" + statement for row in parsed)


def test_partial_disk_write_leaves_no_published_file_or_staging_file(tmp_path, monkeypatch, capsys):
    destination = tmp_path / "new.json"
    original = context.os.fdopen
    observed = []

    class FailingWriter:
        def __init__(self, descriptor, mode):
            self.handle = original(descriptor, mode)

        def __enter__(self):
            return self

        def write(self, raw):
            fragment = raw[:len(raw) // 2]
            self.handle.write(fragment)
            self.handle.flush()
            staged = list(tmp_path.glob(".transition-context-*.tmp"))
            assert len(staged) == 1 and staged[0].read_bytes() == fragment
            observed.append(len(fragment))
            raise OSError("Simulated interrupted disk write")

        def __exit__(self, *args):
            self.handle.close()

    monkeypatch.setattr(context.os, "fdopen", FailingWriter)
    with pytest.raises(SystemExit) as error:
        context.main(command(None, "--output", str(destination))[6:])
    assert error.value.code == 2 and observed and observed[0] > 0
    assert not destination.exists() and list(tmp_path.iterdir()) == []
    assert capsys.readouterr().out == ""


def test_concurrent_destination_creation_is_preserved(tmp_path, monkeypatch):
    destination = tmp_path / "raced.json"
    link = context.os.link

    def race(source, target):
        destination.write_bytes(b"existing winner")
        return link(source, target)

    monkeypatch.setattr(context.os, "link", race)
    with pytest.raises(FileExistsError):
        context._publish_new(destination, b"candidate")
    assert destination.read_bytes() == b"existing winner"
    assert list(tmp_path.iterdir()) == [destination]


def test_unsupported_atomic_link_fails_without_fallback(tmp_path, monkeypatch):
    destination = tmp_path / "unsupported.json"

    def unavailable(*args):
        raise OSError("Hard links unavailable")

    monkeypatch.setattr(context.os, "link", unavailable)
    with pytest.raises(OSError):
        context._publish_new(destination, b"candidate")
    assert not destination.exists() and list(tmp_path.iterdir()) == []

Test V928 DC Data

A test in the tests folder of GlobalGrid2050 that uses SHA-256. It is built from the load step (`load`) and the builder step (`builder`).

testglobalgrid2050 / automation/news/tests/test_v928_dc_data.py · lines 1–143 of 143 · Entry point · pattern builder (shared by 2 files)

What it does
It tests its inputs. Defines 9 functions or classes, including load, builder, test_real_new_edition_100_leads_22_countries_and_quarantine, test_original_twelve_semantic_fields_exact_and_null_measurements_retained, test_compact_sources_keep_full_upstream_objects_and_explicit_hash_bridge. Uses libraries copy, hashlib, importlib.util, json, pathlib. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'dc'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file projects.json; JSON file selection-audit.json; JSON file source-facts.json; JSON file integration-manifest.json; JSON file pipeline-audit.json; JSON file official-projects.json; JSON file project-groups.json; Parquet file global-data-centre-records-v1.parquet.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Real V9.28 cohort/data integration; no browser or facility verification claim.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
copy, hashlib, importlib.util, json, pathlib, subprocess, pytest, duckdb
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
load, builder, test_real_new_edition_100_leads_22_countries_and_quarantine, test_original_twelve_semantic_fields_exact_and_null_measurements_retained, test_compact_sources_keep_full_upstream_objects_and_explicit_hash_bridge, test_official_and_group_records_are_not_extra_facilities, test_pinned_furnace_double_build_readback_and_new_generation, test_source_identity_or_selection_failure_preserves_accepted_output, test_edition_under_existing_18_mib_budget_with_working_data_delta
Defines here
load, builder, test_real_new_edition_100_leads_22_countries_and_quarantine, test_original_twelve_semantic_fields_exact_and_null_measurements_retained, test_compact_sources_keep_full_upstream_objects_and_explicit_hash_bridge, test_official_and_group_records_are_not_extra_facilities, test_pinned_furnace_double_build_readback_and_new_generation, test_source_identity_or_selection_failure_preserves_accepted_output, test_edition_under_existing_18_mib_budget_with_working_data_delta
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/tests/test_v928_dc_data.py:1-143 · blob 712c89b0a796d6ae417ab9dbb73a937b4f283f86 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
"""Real V9.28 cohort/data integration; no browser or facility verification claim."""
from copy import deepcopy
import hashlib
import importlib.util
import json
from pathlib import Path
import subprocess

import pytest

ROOT = Path(__file__).resolve().parents[3]
EDITION = 'uk_renewables_pipeline/202611161757'
DATA = ROOT / EDITION / 'global-datacentres'


def load(name):
    return json.loads((DATA / name).read_bytes())


def builder():
    spec = importlib.util.spec_from_file_location('v928_dc_build', DATA / 'build.py')
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def test_real_new_edition_100_leads_22_countries_and_quarantine():
    data, audit = load('projects.json'), load('selection-audit.json')
    assert len(data['records']) == data['record_count'] == 100
    assert len({r['id'] for r in data['records']}) == 100
    assert len({r['country']['wikidata_id'] for r in data['records']}) == data['country_count'] == 22
    assert audit['candidate_count'] == data['candidate_count'] == 138
    assert len(audit['quarantined']) == audit['quarantined_count'] == data['quarantined_count'] == 38
    assert audit['independently_verified'] is False
    assert not {r['id'] for r in data['records']} & {r['id'] for r in audit['quarantined']}
    assert builder().project(DATA / 'source-facts.json') == data


def test_original_twelve_semantic_fields_exact_and_null_measurements_retained():
    parent = json.loads((ROOT / 'uk_renewables_pipeline/202611161630/global-datacentres/projects.json').read_bytes())
    records = {r['id']: r for r in load('projects.json')['records']}
    assert len(parent['records']) == 12
    for old in parent['records']:
        for key in ('id', 'name', 'country', 'operator', 'location', 'capacity'):
            assert records[old['id']][key] == old[key]
    assert sum(r['location'] is None for r in records.values()) == 61
    for r in records.values():
        assert r['verification_status'] == 'SOURCE_INDEXED'
        assert r['operating_status'] == 'not_assessed'
        assert all(x is None for x in r['capacity'].values())
        assert all(x is None for x in r['capacity_sources'].values())


def test_compact_sources_keep_full_upstream_objects_and_explicit_hash_bridge():
    manifest = load('integration-manifest.json')
    assert manifest['edition'] == '202611161757' and manifest['grains_separate'] is True
    for source in manifest['sources']:
        served = (DATA / source['served_path']).read_bytes()
        assert hashlib.sha256(served).hexdigest() == source['served_sha256']
        assert b'\n  ' not in served
        # Public source object identity is recorded even in shallow CI clones.
        assert len(source['source_commit']) == len(source['source_blob']) == 40
        assert len(source['source_sha256']) == 64
    facts = (DATA / 'source-facts.json').read_bytes()
    assert hashlib.sha256(facts).hexdigest() == load('projects.json')['source_facts_sha256']
    assert load('pipeline-audit.json')['source_facts_sha256'] == load('projects.json')['source_facts_sha256']
    assert len(load('source-facts.json')['candidate_ids']) == 138


def test_official_and_group_records_are_not_extra_facilities():
    official, groups = load('official-projects.json'), load('project-groups.json')
    assert official['schema'] == 'globalgrid2050.dc-official-projects.v1'
    assert official['coverage']['selected_records'] == len(official['projects']) == 3
    assert official['coverage']['physical_facility_count'] is None
    assert {r['entity_scope'] for r in official['projects']} == {'planning_case', 'tax_qualification_record'}
    cohort_ids = {r['id'] for r in load('projects.json')['records']}
    assert not cohort_ids & {r['project_id'] for r in official['projects']}
    for r in official['projects']:
        assert r['review_status'] == 'PROVISIONAL' and r['current_lifecycle'] == 'UNKNOWN'
        assert r['capacity_mw'] is r['latitude'] is r['longitude'] is r['listed_parent'] is None
        assert r['numeric_claims'] == r['crosswalks'] == []
    assert groups['record_count'] == len(groups['records']) == 6
    assert groups['provisional_count'] == groups['unlinked_count'] == 3
    assert {r['project_id'] for r in groups['records']} <= cohort_ids
    assert all(r['numeric_claims'] == [] and r['legal_ownership_verified'] is False for r in groups['records'])
    manifest_source = next(s for s in load('integration-manifest.json')['sources'] if s['served_path'] == 'source-facts.json')
    assert groups['cohort']['source_facts_sha256'] == manifest_source['source_sha256']


def test_pinned_furnace_double_build_readback_and_new_generation(tmp_path):
    import duckdb
    module = builder()
    assert duckdb.__version__ == '1.3.2'
    assert 'generation=202611161757/' in module.PARQUET
    assert module.build(DATA / 'source-facts.json', output_dir=tmp_path) == load('projects.json')
    assert (tmp_path / module.PARQUET).read_bytes() == (DATA / module.PARQUET).read_bytes()
    assert json.loads((tmp_path / 'pipeline-audit.json').read_bytes()) == load('pipeline-audit.json')
    assert json.loads((tmp_path / 'selection-audit.json').read_bytes()) == load('selection-audit.json')
    with duckdb.connect(':memory:') as db:
        result = db.execute('SELECT count(*),count(DISTINCT source_record_id),count(latitude),count(it_load_mw),count(site_demand_mw),count(grid_connection_mw) FROM read_parquet(?,hive_partitioning=false)', [str(DATA / module.PARQUET)]).fetchone()
        assert result == (100, 100, 39, 0, 0, 0)
    assert not (DATA / 'data/facilities/generation=202611161630/source=WIKIDATA/global-data-centre-records-v1.parquet').exists()


@pytest.mark.parametrize('mutate', [
    lambda f: f['selected_ids'].append(f['selected_ids'][0]),
    lambda f: f['baseline_ids'].pop(),
    lambda f: f['entities']['Q12857142'].update(label='Changed original identity'),
    lambda f: f.update(licence='unknown'),
])
def test_source_identity_or_selection_failure_preserves_accepted_output(tmp_path, mutate):
    facts = deepcopy(load('source-facts.json'))
    mutate(facts)
    path = tmp_path / 'bad.json'
    path.write_text(json.dumps(facts), encoding='utf-8')
    out = tmp_path / 'output'
    out.mkdir()
    sentinel = out / 'projects.json'
    sentinel.write_bytes(b'previous accepted bytes')
    with pytest.raises(ValueError):
        builder().build(path, output_dir=out)
    assert sentinel.read_bytes() == b'previous accepted bytes'
    assert not (out / builder().PARQUET).exists()


def test_edition_under_existing_18_mib_budget_with_working_data_delta():
    # The index includes newly staged candidate files before the first commit.
    # Git blob sizes cover sparse files; actual files override sizes and include
    # new UI assets instead of testing an obsolete HEAD-only candidate.
    raw = subprocess.check_output(['git', 'ls-files', '--stage', '--', EDITION], cwd=ROOT).decode()
    entries = []
    for line in raw.splitlines():
        meta, path = line.split('\t', 1)
        entries.append((path, meta.split()[1]))
    sizes = subprocess.check_output(
        ['git', 'cat-file', '--batch-check=%(objectsize)'], cwd=ROOT,
        input=''.join(blob + '\n' for _, blob in entries).encode()).decode().splitlines()
    tracked = {path: int(size) for (path, _), size in zip(entries, sizes)}
    for path in (ROOT / EDITION).rglob('*'):
        if path.is_file() and '__pycache__' not in path.parts:
            tracked[path.relative_to(ROOT).as_posix()] = path.stat().st_size
    assert tracked, 'candidate must exist in the index or working tree'
    assert sum(tracked.values()) <= 18 * 1024 * 1024

History Test

A test in the news history return folder of GlobalGrid2050. It is built from the news query helper (`newsQuery`).

testglobalgrid2050 / automation/news_history_return/20261118/history.test.mjs · lines 1–43 of 43 · version 2026-11-18 · Entry point · pattern newsQuery (shared by 2 files)

What it does
It tests its inputs. Defines declaration, fixture, newsQuery. Uses libraries node:test, node:assert/strict, node:fs, node:vm. 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.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Defines `declaration`, `fixture` and `newsQuery`.
Why it matters
Run by GlobalGrid2050 V934 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/news_history_return/20261118 · test
Uses
node:test, node:assert/strict, node:fs, node:vm
Used by
run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
Produces
declaration, fixture, newsQuery
Defines here
declaration, fixture, newsQuery
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_history_return/20261118/history.test.mjs:1-43 · blob e56a9b561e752b9c12481622f6330e901d962718 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import vm from 'node:vm';

const edition=process.env.PN_NEWS_RETURN_EDITION||'202611180633';
const project=readFileSync(`uk_renewables_pipeline/${edition}/scripts/plugins/projects-v9-8.js`,'utf8');
const energy=readFileSync('automation/energy_context_ui/20261118/view.mjs','utf8');
function declaration(source,name){
 const start=source.indexOf(`function ${name}(`);assert.ok(start>=0,name);
 const open=source.indexOf('{',start);let depth=1,end=open+1;
 while(depth&&end<source.length){if(source[end]==='{')depth++;if(source[end]==='}')depth--;end++;}
 assert.equal(depth,0,name);return source.slice(start,end);
}
const sync=declaration(project,'syncFilterUrl');
const restore=declaration(energy,'restoreNews');
const apply=energy.split('\n').find(line=>line.startsWith('const applyRequest='));assert.ok(apply);
const origin={origin_type:'substation',origin_id:'grid_substations:0'};
const saved={path:`/uk_renewables_pipeline/${edition}/`,filters:{query:'storage',source:'GOV.UK',topic:'grid',category:'policy',kind:'government'},origin,contextTopic:'grid'};
function fixture(){
 const history={state:{pipelineEnergyNewsReturn:structuredClone(saved),pipelineJourneyReturn:{category:'grid'},unrelated:{keep:true}},replaceState(state,_title,url){this.state=structuredClone(state);if(url)location.href=url.href;}};
 const location={pathname:saved.path,href:`https://globalgrid2050.com${saved.path}?news_topic=storage#headlinesHeading`,search:'?news_topic=storage'};
 const query={value:'',dispatchEvent(){}};
 const selects=Object.fromEntries(Object.entries(saved.filters).filter(([k])=>k!=='query').map(([k,value])=>[k,{value:'',options:[{value:''},{value}]}]));
 const tasks=[];const box={window:{location},history,location,URL,query,selects,tasks,Event:class{},structuredClone};
 vm.createContext(box);vm.runInContext(`let technology='wind_offshore',status='All',county='Oxfordshire',query='12588',sortMode='updated_desc',submittedYear='All',updatedYear='All',operationalYear='All';
 const returnKey='pipelineEnergyNewsReturn',filterKinds=['source','topic','category','kind'];let requestApplied=false,feed=null,activeTopic=null,selectedOrigin=null;
 function newsQuery(){return globalThis.query;}function newsSelect(kind){return selects[kind];}function requestedContext(){return {topic:'storage'};}function connectNews(){return true;}function renderMain(){}function selectOrigin(value){selectedOrigin=value;}function topicFilter(topic){activeTopic=topic;return true;}function setTimeout(fn){tasks.push(fn);}
 ${sync}\n${restore}\n${apply}
 globalThis.sync=syncFilterUrl;globalThis.feedReady=()=>{feed={items:[]};applyRequest();};globalThis.drain=()=>{while(tasks.length)tasks.shift()();};globalThis.visible=()=>({topic:activeTopic,origin:selectedOrigin,filters:{query:globalThis.query.value,...Object.fromEntries(filterKinds.map(k=>[k,selects[k].value]))}});`,box);
 return box;
}
for(const order of ['sync-before-feed','feed-captured-before-sync'])test(`real URL sync preserves visible context and second cold return: ${order}`,()=>{
 const f=fixture();const keys=structuredClone(f.history.state);
 if(order==='sync-before-feed'){f.sync();f.feedReady();}else{f.feedReady();f.sync();}
 f.drain();assert.deepEqual(f.history.state,keys);
 assert.equal(new URL(f.location.href).searchParams.get('technology'),'wind_offshore');assert.equal(new URL(f.location.href).searchParams.get('q'),'12588');
 assert.equal(new URL(f.location.href).searchParams.get('news_topic'),'storage');assert.equal(new URL(f.location.href).hash,'#headlinesHeading');
 assert.deepEqual(JSON.parse(JSON.stringify(f.visible())),{topic:'grid',origin,filters:saved.filters});
 const second=fixture();second.history.state=structuredClone(f.history.state);second.sync();second.feedReady();second.drain();
 assert.deepEqual(JSON.parse(JSON.stringify(second.visible())),{topic:'grid',origin,filters:saved.filters});
});
test('a normal filter URL update with no saved return remains usable',()=>{const f=fixture();f.history.state=null;f.sync();assert.equal(f.history.state,null);assert.equal(new URL(f.location.href).searchParams.get('county'),'Oxfordshire');});

Model

A JavaScript module in the news quality ui folder of GlobalGrid2050 that audits health (`auditHealth`) and selects entries (`selectEntries`). It audits health (`auditHealth`) and selects entries (`selectEntries`).

transformglobalgrid2050 / automation/news_quality_ui/20261117-v937/model.mjs · lines 1–32 of 32 · version 2026-11-17

What it does
It calculates its inputs. Defines validClock, feedUrl, auditHealth, classification, selectEntries.
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 2 files: View (globalgrid2050); Contracts Test (globalgrid2050). Reached from 9 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Defines `validClock`, `feedUrl`, `auditHealth` and 2 more.
Why it matters
Imported by View. Checked by Contracts Test.
Application
globalgrid2050 · automation/news_quality_ui/20261117-v937 · JavaScript module
Uses
none found
Used by
imported by View (import), imported by Contracts Test (import)
Produces
validClock, auditHealth, classification, selectEntries
Defines here
validClock, feedUrl, auditHealth, classification, selectEntries
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_quality_ui/20261117-v937/model.mjs:1-32 · blob 4241ae3e5ad0e04ac852031d35ace8d8c811735f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
const kinds=new Set(['government','regulator','institution','listed_parent','reporting','discovery']);
const topics=new Set(['solar','storage','grid','datacentre','wind','renewables']);
export function validClock(value){
 if(typeof value!=='string')return false;
 const m=/^(\d{4})-(\d{2})-(\d{2})(?:T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d))?$/.exec(value);if(!m)return false;
 const [y,month,day]=m.slice(1).map(Number),days=[31,y%4===0&&(y%100!==0||y%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return y>=1900&&month>=1&&month<=12&&day>=1&&day<=days[month-1]&&Number.isFinite(Date.parse(value));
}
function feedUrl(value){try{const u=new URL(value);return typeof value==='string'&&u.protocol==='https:'&&!u.username&&!u.password&&u.hostname.includes('.')&&!/^[\d.]+$/.test(u.hostname)&&!u.hostname.endsWith('.')&&!/(^|\.)(localhost|local|internal)$/.test(u.hostname)&&(!u.port||u.port==='443');}catch{return false;}}
export function auditHealth(doc){
 const items=Array.isArray(doc?.items)?doc.items:[],publishers=new Map();let unknownPublishers=0;
 for(const item of items){const name=typeof item?.source==='string'?item.source.trim():'';if(name)publishers.set(name,(publishers.get(name)||0)+1);else unknownPublishers++;}
 const result={articles:Array.isArray(doc?.items)?items.length:null,publishers:[...publishers].sort((a,b)=>a[0].localeCompare(b[0])),unknownPublishers,collectionClock:validClock(doc?.generated_at)?doc.generated_at:null,status:typeof doc?.status==='string'?doc.status:'unavailable',available:false,reason:'Feed-health metadata unavailable or inconsistent'};
 if(items.some(item=>!item||typeof item!=='object')||!Array.isArray(doc?.feeds)||!doc.feeds.length||doc.feeds.length>500||!doc.counts)return result;
 const seen=new Set();let ok=0,failed=0;
 for(const f of doc.feeds){
  if(!f||!feedUrl(f.url)||seen.has(f.url)||typeof f.source!=='string'||!f.source.trim()||!['ok','failed'].includes(f.status)||!Number.isInteger(f.entries)||f.entries<0||!Number.isInteger(f.kept)||f.kept<0||f.kept>f.entries||(f.newest!==null&&!validClock(f.newest)))return result;
  seen.add(f.url);if(f.status==='ok')ok++;else failed++;
 }
 if(doc.counts.items!==items.length||doc.counts.feeds_ok!==ok||doc.counts.feeds_failed!==failed||doc.status==='ok'&&failed||doc.status==='partial'&&(!ok||!failed)||doc.status==='failed'&&ok||!['ok','partial','failed'].includes(doc.status))return result;
 if(doc.counts.with_possible_match!==undefined&&doc.counts.with_possible_match!==items.filter(item=>item.possible_match).length)return result;
 if(doc.counts.by_category!==undefined){const expected=Object.create(null);for(const item of items){const key=item.category||'other';expected[key]=(expected[key]||0)+1;}const counts=doc.counts.by_category;if(!counts||Array.isArray(counts)||Object.keys(counts).length!==Object.keys(expected).length||Object.entries(expected).some(([key,total])=>counts[key]!==total))return result;}
 return {...result,available:true,reason:null,feeds:seen.size,ok,failed,failedSources:doc.feeds.filter(f=>f.status==='failed').map(f=>({source:f.source,url:f.url}))};
}
export function classification(entry,ranked){
 const p=ranked?entry?.priority:null,item=entry?.item||{};
 const accepted=!!p&&p.link===item.link&&p.title===item.title&&p.source===item.source&&kinds.has(p.source_kind);
 return {kind:accepted?p.source_kind:'Unclassified',topics:[...new Set([...(typeof item.technology==='string'&&item.technology?[item.technology]:[]),...(accepted&&Array.isArray(p.topics)?p.topics.filter(t=>topics.has(t)):[])])]};
}
export function selectEntries(entries,filter={},ranked=false){
 const tokens=String(filter.query||'').trim().toLocaleLowerCase('en-GB').split(/\s+/).filter(Boolean);
 return entries.filter(entry=>{const item=entry.item,c=classification(entry,ranked);const hay=[item.title,item.source,item.category,...c.topics].join(' ').toLocaleLowerCase('en-GB');return tokens.every(token=>hay.includes(token))&&(!filter.source||item.source===filter.source)&&(!filter.category||item.category===filter.category)&&(!filter.topic||c.topics.includes(filter.topic))&&(!filter.kind||c.ki  … [line shortened here: 421 characters; full line on GitHub]
}

News Quality UI — V937 Style Sheet

A style sheet in the automation folder of GlobalGrid2050.

renderglobalgrid2050 / automation/news_quality_ui/20261117-v937/styles.css · lines 1–3 of 3 · version 2026-11-17 · Entry point

What it does
Side effects: changes the web page (DOM).
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: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/.
Application
globalgrid2050 · automation/news_quality_ui/20261117-v937 · style sheet
Uses
none found
Used by
loaded by GlobalGrid2050 — UK Renewables Pipeline Page (stylesheet)
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_quality_ui/20261117-v937/styles.css:1-3 · blob 52782427d049946eaf0114416d7dc2fd5a9f755a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
.pn-news-quality{padding:10px 12px;border-bottom:1px solid #303740;color:#aeb6c1;font-size:11px}.pn-news-filter-tools{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.pn-news-quality input,.pn-news-quality select,.pn-news-quality button{max-width:100%;min-height:44px;background:#000;color:#aab3bf;border:1px solid #343b45;padding:7px;font:inherit;box-sizing:border-box}.pn-news-quality input{  … [line shortened here: 961 characters; full line on GitHub]

.ln-collected{display:block;font-size:9px;color:#8e98a5;margin:3px 0}