GLOBALGRID2050 / EXPLORE CODE

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

Test Acquisition Run and 4 more files

A test in the tests folder of GlobalGrid2050 that checks News — Acquisition and News — Acquisition, using SHA-256.

666 lines of Python from globalgrid2050, in 5 files. Topic: Electricity markets and data pipelines. Section 802 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 Acquisition Run test · globalgrid2050 / automation/news/tests/test_acquisition_run.py lines 1–236
  2. Test Agent7 Dedupe Regressions test · globalgrid2050 / automation/news/tests/test_agent7_dedupe_regressions.py lines 1–61
  3. Test Agent7 Evidence Ledger test · globalgrid2050 / automation/news/tests/test_agent7_evidence_ledger.py lines 1–127
  4. Test Binder test · globalgrid2050 / automation/news/tests/test_binder.py lines 1–131
  5. Test Cop31 Climate Priority test · globalgrid2050 / automation/news/tests/test_cop31_climate_priority.py lines 1–111

Test Acquisition Run

A test in the tests folder of GlobalGrid2050 that checks News — Acquisition and News — Acquisition, using SHA-256.

testglobalgrid2050 / automation/news/tests/test_acquisition_run.py · lines 1–236 of 236 · Entry point

What it does
It tests its inputs. Defines 23 functions or classes, including FrozenClock, now, setup, fixture_fetcher, build. Uses libraries __future__, copy, datetime, hashlib, json. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
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 latest.json; JSON file report.json; SQLite database. Out: Parquet file partial-analytics.parquet.
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 frozen clock class (`FrozenClock`), the now step (`now`) and the setup step (`setup`). End-to-end candidate builds use explicit synthetic feed/rights fixtures only.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
News — Acquisition (import), News — Acquisition (import), Evidence Store (import), Fetch (import), Research Queue (import), Analytics (import), __future__, copy, datetime, hashlib, json, pathlib, sqlite3, sys
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
FrozenClock, setup, fixture_fetcher, build, state_bytes, test_real_seed_synthetic_feed_through_sqlite_and_all_exports, test_probe_returns_health_without_creating_or_changing_state, test_analytics_failure_preserves_accepted_database_snapshots_and_pointer, test_critical_fetch_failure_keeps_previous_state, test_schema_or_rights_failure_keeps_database_and_latest, test_export_validation_failure_does_not_commit_staged_database, test_changed_article_keeps_previous_database_and_pointer
Defines here
FrozenClock, now, setup, fixture_fetcher, build, state_bytes, test_real_seed_synthetic_feed_through_sqlite_and_all_exports, test_probe_returns_health_without_creating_or_changing_state, test_analytics_failure_preserves_accepted_database_snapshots_and_pointer, fail_analytics, test_critical_fetch_failure_keeps_previous_state, failing_fetcher, test_schema_or_rights_failure_keeps_database_and_latest, invalid_fetcher, test_export_validation_failure_does_not_commit_staged_database, fail_export, test_changed_article_keeps_previous_database_and_pointer, changed_fetcher, test_invalid_source_config_fails_before_fetch_or_output, unexpected_fetch, test_disabled_unknown_rights_source_only_allows_probe, test_cli_failure_report_is_redacted_and_requires_manual_review, fail_collect
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_acquisition_run.py:1-236 · blob 890333007bdb695ff9a7d233afe3ee399d449f64 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""End-to-end candidate builds use explicit synthetic feed/rights fixtures only."""
from __future__ import annotations

import copy
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import sqlite3
import sys

import pytest
import yaml

sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from automation.news.acquisition import run
from automation.news.acquisition.evidence_store import EvidenceValidationError, validate_snapshot
from automation.news.acquisition.fetch import FetchError, parse_feed
from automation.news.acquisition.research_queue import load_seed_projects

NOW = "2026-11-16T16:00:00Z"
SOURCE = {
    "id": "pv_magazine_global", "publisher": "PV Magazine", "kind": "rss",
    "url": "https://www.pv-magazine.com/feed/", "technology": ["solar"],
    "interval_hours": 168, "enabled": True, "output_policy": "headline_link_only",
    "rights_status": "accepted", "rights_review_url": "https://fixtures.example/synthetic-rights-review",
}
RSS = b'''<rss><channel><item>
<title>Synthetic fixture: REPD Ref 1018 solar project</title>
<link>https://www.pv-magazine.com/synthetic-test-fixture/</link>
<pubDate>Sun, 15 Nov 2026 12:00:00 GMT</pubDate>
<description>Transient fixture content must not persist.</description>
</item></channel></rss>'''


class FrozenClock:
    @staticmethod
    def now(tz):
        return datetime(2026, 11, 16, 16, 0, 0, tzinfo=timezone.utc)


@pytest.fixture
def setup(tmp_path, monkeypatch):
    # Exercise the real, byte-pinned V9.24 input loader, not a reselected list.
    projects = load_seed_projects()
    monkeypatch.setattr(run, "datetime", FrozenClock)
    config = tmp_path / "synthetic-sources.yaml"
    config.write_text(yaml.safe_dump([SOURCE]), encoding="utf-8")
    return {"out": tmp_path / "evidence", "config": config, "ids": [p["id"] for p in projects]}


def fixture_fetcher(source, *, probe=False):
    return {"articles": parse_feed(RSS, source), "source": {
        "id": source["id"], "publisher": source["publisher"], "url": source["url"],
        "status": "ok", "fetched_at": NOW, "http_status": 200,
        "response_sha256": hashlib.sha256(RSS).hexdigest(),
        "probe_only": probe, "eligible_for_publication": not probe,
        "rights_status": source["rights_status"], "rights_review_url": source["rights_review_url"],
    }}


def build(setup, **kwargs):
    return run.collect(setup["out"], sources_path=setup["config"], fetcher=fixture_fetcher, **kwargs)


def state_bytes(out):
    return {str(path.relative_to(out)): path.read_bytes() for path in out.rglob("*") if path.is_file()}


def test_real_seed_synthetic_feed_through_sqlite_and_all_exports(setup):
    result = build(setup)
    assert result["selected"] == 1000 and result["provisional_matches"] == 1
    assert result["verified"] == 0 and result["probe_only"] is False
    out, pointer = setup["out"], result["pointer"]
    assert json.loads((out / "latest.json").read_text()) == pointer
    payload = json.loads((out / pointer["json"]).read_text(encoding="utf-8"))
    validate_snapshot(payload, setup["ids"])
    row = next(row for row in payload["projects"] if row["project_id"] == "1018")
    assert row["evidence_count"] == 1 and row["evidence"][0]["status"] == "PROVISIONAL"
    assert row["evidence"][0]["match_method"] == "repd_id"
    assert (out / pointer["csv"]).is_file() and (out / pointer["geojson"]).is_file()
    analytics = result["analytics"]
    assert analytics["project_count"] == 1000 and analytics["evidence_count"] == 1
    assert not Path(analytics["manifest"]).is_absolute()
    manifest_bytes = (out / analytics["manifest"]).read_bytes()
    assert hashlib.sha256(manifest_bytes).hexdigest() == analytics["sha256"]
    from automation.news.acquisition.analytics import validate_analytics
    validate_analytics(out / analytics["directory"], payload, expected_project_ids=setup["ids"])
    with sqlite3.connect(out / "evidence.sqlite") as db:
        assert db.execute("SELECT count(*) FROM projects").fetchone()[0] == 1000
        assert db.execute("SELECT count(*) FROM evidence").fetchone()[0] == 1000
        assert db.execute("SELECT count(*) FROM evidence WHERE status='PROVISIONAL'").fetchone()[0] == 1
    assert all(b"Transient fixture content" not in content for content in state_bytes(out).values())
    previous = state_bytes(out)
    assert build(setup)["pointer"] == pointer
    # SQLite may change its page layout on an idempotent rerun; public exports
    # and logical row counts are the invariant, not database file bytes.
    after = state_bytes(out)
    previous.pop("evidence.sqlite")
    after.pop("evidence.sqlite")
    assert after == previous
    with sqlite3.connect(out / "evidence.sqlite") as db:
        assert db.execute("SELECT count(*) FROM evidence").fetchone()[0] == 1000


def test_probe_returns_health_without_creating_or_changing_state(setup):
    result = build(setup, probe=True)
    assert result["probe_only"] is True and "pointer" not in result
    assert not setup["out"].exists()
    build(setup)
    previous = state_bytes(setup["out"])
    build(setup, probe=True)
    assert state_bytes(setup["out"]) == previous


def test_analytics_failure_preserves_accepted_database_snapshots_and_pointer(setup, monkeypatch):
    from automation.news.acquisition import analytics

    build(setup)
    previous = state_bytes(setup["out"])

    def fail_analytics(payload, out, **kwargs):
        # A real adapter failure can occur after partial candidate writes.
        (out / "partial-analytics.parquet").write_bytes(b"synthetic partial artifact")
        raise EvidenceValidationError("Injected analytical readback failure")

    monkeypatch.setattr(analytics, "export_analytics", fail_analytics)
    with pytest.raises(EvidenceValidationError, match="analytical readback"):
        build(setup)
    assert state_bytes(setup["out"]) == previous
    # Health probes must never invoke the failing analytical adapter.
    assert build(setup, probe=True)["probe_only"] is True
    assert state_bytes(setup["out"]) == previous


def test_critical_fetch_failure_keeps_previous_state(setup):
    build(setup)
    previous = state_bytes(setup["out"])

    def failing_fetcher(*args, **kwargs):
        raise FetchError("Critical source HTTP 503")

    with pytest.raises(FetchError):
        run.collect(setup["out"], sources_path=setup["config"], fetcher=failing_fetcher)
    assert state_bytes(setup["out"]) == previous


@pytest.mark.parametrize("mutation", [
    lambda result: result["source"].update(status="failed"),
    lambda result: result["source"].update(rights_status="unknown"),
    lambda result: result["source"].update(probe_only=True),
    lambda result: result["articles"][0].update(pub_date="invalid"),
])
def test_schema_or_rights_failure_keeps_database_and_latest(setup, mutation):
    build(setup)
    previous = state_bytes(setup["out"])

    def invalid_fetcher(source, **kwargs):
        result = fixture_fetcher(source, **kwargs)
        mutation(result)
        return result

    with pytest.raises(EvidenceValidationError):
        run.collect(setup["out"], sources_path=setup["config"], fetcher=invalid_fetcher)
    assert state_bytes(setup["out"]) == previous


def test_export_validation_failure_does_not_commit_staged_database(setup, monkeypatch):
    build(setup)
    previous = state_bytes(setup["out"])

    def fail_export(*args, **kwargs):
        raise EvidenceValidationError("Injected malformed export")

    monkeypatch.setattr(run, "export_snapshot", fail_export)
    with pytest.raises(EvidenceValidationError):
        build(setup)
    assert state_bytes(setup["out"]) == previous


def test_changed_article_keeps_previous_database_and_pointer(setup):
    build(setup)
    previous = state_bytes(setup["out"])

    def changed_fetcher(source, **kwargs):
        result = fixture_fetcher(source, **kwargs)
        result["articles"][0]["title"] += " revised"
        return result

    with pytest.raises(EvidenceValidationError, match="Stored article metadata changed"):
        run.collect(setup["out"], sources_path=setup["config"], fetcher=changed_fetcher)
    assert state_bytes(setup["out"]) == previous


@pytest.mark.parametrize("mutation", [
    lambda sources: sources.append(copy.deepcopy(sources[0])),
    lambda sources: sources[0].update(url="http://127.0.0.1/feed"),
    lambda sources: sources[0].update(rights_status="unknown"),
])
def test_invalid_source_config_fails_before_fetch_or_output(setup, mutation):
    sources = [copy.deepcopy(SOURCE)]
    mutation(sources)
    setup["config"].write_text(yaml.safe_dump(sources), encoding="utf-8")

    def unexpected_fetch(*args, **kwargs):
        pytest.fail("Invalid source must never be fetched")

    with pytest.raises(ValueError):
        run.collect(setup["out"], sources_path=setup["config"], fetcher=unexpected_fetch)
    assert not setup["out"].exists()


def test_disabled_unknown_rights_source_only_allows_probe(setup):
    disabled = {**SOURCE, "enabled": False, "rights_status": "unknown", "rights_review_url": None}
    setup["config"].write_text(yaml.safe_dump([disabled]), encoding="utf-8")
    with pytest.raises(FetchError, match="No enabled source"):
        build(setup)
    assert not setup["out"].exists()
    assert build(setup, probe=True)["probe_only"] is True
    assert not setup["out"].exists()


def test_cli_failure_report_is_redacted_and_requires_manual_review(tmp_path, monkeypatch, capsys):
    report = tmp_path / "report.json"

    def fail_collect(*args, **kwargs):
        raise ValueError("secret-example-token and machine-specific-path")

    monkeypatch.setattr(run, "collect", fail_collect)
    monkeypatch.setattr(sys, "argv", ["run", "--report", str(report), "--out", str(tmp_path / "out")])
    assert run.main() == 1
    payload = json.loads(report.read_text())
    assert payload == {"result": "blocked", "error_type": "ValueError", "manual_review_required": True,
                       "probe_only": False}
    assert "secret-example-token" not in report.read_text() + capsys.readouterr().out
    assert not (tmp_path / "out").exists()

Test Agent7 Dedupe Regressions

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

testglobalgrid2050 / automation/news/tests/test_agent7_dedupe_regressions.py · lines 1–61 of 61 · Entry point

What it does
It tests solar. Defines 8 functions or classes, including item, test_same_title_distinct_years_retains_both, test_generic_same_title_different_repd_projects_retains_both, test_separate_decisions_same_project_retained, test_undated_same_title_separate_urls_retained. Uses libraries sys, pathlib. 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. Domain terms in the code: solar.
Downstream impact
Used directly by 3 files: GlobalGrid2050 Agent7 V922 CI Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Agent 7 regressions: title similarity is not proof of article/event identity.
Why it matters
Run by GlobalGrid2050 Agent7 V922 CI Workflow, GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Pipeline Headlines (sys.path import), sys, pathlib
Used by
run by GlobalGrid2050 Agent7 V922 CI Workflow (workflow run), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
item, test_same_title_distinct_years_retains_both, test_generic_same_title_different_repd_projects_retains_both, test_separate_decisions_same_project_retained, test_undated_same_title_separate_urls_retained, test_same_canonical_article_url_syndicated_collapses, test_two_publishers_same_project_non_decision_near_date_collapses, test_same_title_unknown_project_different_urls_kept
Defines here
item, test_same_title_distinct_years_retains_both, test_generic_same_title_different_repd_projects_retains_both, test_separate_decisions_same_project_retained, test_undated_same_title_separate_urls_retained, test_same_canonical_article_url_syndicated_collapses, test_two_publishers_same_project_non_decision_near_date_collapses, test_same_title_unknown_project_different_urls_kept
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_agent7_dedupe_regressions.py:1-61 · blob 22b885116be0eab34054429945dd11918b328a7f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Agent 7 regressions: title similarity is not proof of article/event identity."""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import pipeline_headlines as P  # noqa: E402


def item(*, title="Solar farm planning decision announced", date="2026-11-14T10:00:00Z",
         ref=None, link="https://publisher.example/a", source="Publisher A",
         category="planning_decision", **extra):
    return dict(title=title, date=date, link=link, source=source, category=category,
                first_seen="2026-11-15T12:00:00Z", technology="solar",
                possible_match={"repd_ref": str(ref), "site_name": "Example site", "basis": "county"}
                if ref is not None else None, **extra)


def test_same_title_distinct_years_retains_both():
    a = item(date="2025-01-05T09:00:00Z")
    b = item(date="2026-01-05T09:00:00Z", link="https://publisher.example/b", source="Publisher B")
    assert len(P.dedupe_titles([a, b])) == 2


def test_generic_same_title_different_repd_projects_retains_both():
    a = item(ref=1001)
    b = item(ref=2002, link="https://publisher.example/b", source="Publisher B")
    assert len(P.dedupe_titles([a, b])) == 2


def test_separate_decisions_same_project_retained():
    a = item(ref=1001, decision_reference="P/2026/001")
    b = item(ref=1001, decision_reference="P/2026/002",
             date="2026-11-15T11:00:00Z", link="https://publisher.example/b", source="Publisher B")
    assert len(P.dedupe_titles([a, b])) == 2


def test_undated_same_title_separate_urls_retained():
    a = item(date=None, ref=1001, category="construction")
    b = item(date=None, ref=1001, category="construction",
             link="https://publisher.example/b", source="Publisher B")
    assert len(P.dedupe_titles([a, b])) == 2


def test_same_canonical_article_url_syndicated_collapses():
    a = item()
    b = item(link=a["link"], source="Syndicated B")
    assert len(P.dedupe_titles([a, b])) == 1


def test_two_publishers_same_project_non_decision_near_date_collapses():
    a = item(ref=1001, category="construction")
    b = item(ref=1001, category="construction",
             date="2026-11-15T10:00:00Z",
             link="https://second.example/b", source="Publisher B")
    assert len(P.dedupe_titles([a, b])) == 1


def test_same_title_unknown_project_different_urls_kept():
    a = item()
    b = item(link="https://publisher-b.example/b", source="Publisher B")
    assert len(P.dedupe_titles([a, b])) == 2

Test Agent7 Evidence Ledger

A test in the tests folder of GlobalGrid2050 that checks Evidence Ledger. It is built from the record step (`record`).

testglobalgrid2050 / automation/news/tests/test_agent7_evidence_ledger.py · lines 1–127 of 127 · Entry point · pattern record (shared by 46 files)

What it does
It tests solar. Defines 11 functions or classes, including record, test_completely_filled_synthetic_contract_is_still_not_accepted, test_original_source_hash_and_http_response_required, test_redirected_article_identity_and_provenance_cannot_be_omitted, test_article_b_about_project_b_cannot_bind_project_a. Uses libraries __future__, copy, sys, pathlib. 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. Domain terms in the code: solar.
Inputs & outputs
In: JSON file receipt.json.
Downstream impact
Used directly by 3 files: GlobalGrid2050 Agent7 V922 CI Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Evidence ledger: structural checks are not article, publisher or legal verification.
Why it matters
Run by GlobalGrid2050 Agent7 V922 CI Workflow, GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Evidence Ledger (sys.path import), __future__, copy, sys, pathlib
Used by
run by GlobalGrid2050 Agent7 V922 CI Workflow (workflow run), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
record, test_completely_filled_synthetic_contract_is_still_not_accepted, test_original_source_hash_and_http_response_required, test_redirected_article_identity_and_provenance_cannot_be_omitted, test_article_b_about_project_b_cannot_bind_project_a, test_one_article_about_two_projects_needs_two_separate_bindings, test_reviewed_boolean_does_not_substitute_for_independent_review, test_producer_cannot_structurally_self_review, test_undocumented_rights_and_article_body_storage_withheld, test_event_requires_actual_date_and_planning_reference, test_news_is_withheld_when_raw_record_unavailable
Defines here
record, test_completely_filled_synthetic_contract_is_still_not_accepted, test_original_source_hash_and_http_response_required, test_redirected_article_identity_and_provenance_cannot_be_omitted, test_article_b_about_project_b_cannot_bind_project_a, test_one_article_about_two_projects_needs_two_separate_bindings, test_reviewed_boolean_does_not_substitute_for_independent_review, test_producer_cannot_structurally_self_review, test_undocumented_rights_and_article_body_storage_withheld, test_event_requires_actual_date_and_planning_reference, test_news_is_withheld_when_raw_record_unavailable
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_agent7_evidence_ledger.py:1-127 · blob 39c5c3f54805f96a3f40fea38d60a4fb88681904 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Evidence ledger: structural checks are not article, publisher or legal verification."""
from __future__ import annotations

import copy
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import evidence_ledger as L  # noqa: E402


def record(ref="1001"):
    article = "https://publisher.example/projects/solar"
    return {
        "proposing_role": "Agent7",
        "ArticleReceipt": {
            "publisher": "Example Publisher",
            "requested_url": article, "final_url": article,
            "http_status": 200, "fetched_at": "2026-11-15T12:00:00Z",
            "response_sha256": "a" * 64, "retrieval_log_sha256": "b" * 64,
            "retrieval_log_url": "https://github.com/Ventusltd/evidence/blob/abc/receipt.json",
            "parser_identity": "html5-parser/1",
        },
        "ProjectBinding": {
            "repd_ref": ref, "project_name": "Example Solar Park",
            "contrary_evidence": [],
            "supporting_evidence": [
                {"repd_ref": ref, "article_url": article,
                 "extract": "Example Solar Park (REPD " + ref + ") was granted consent."}
            ],
            "independent_review": {
                "decision": "accepted", "evidence_url": "https://github.com/Ventusltd/reviews/issues/1",
                "reviewer_role": "Agent2", "reviewed_at": "2026-11-15T13:00:00Z",
            },
        },
        "EventAssertion": {
            "event_type": "consent", "actual_event_date": "2026-11-14",
            "event_evidence_url": article, "planning_reference": "P/2026/0001",
        },
        "RightsAssessment": {
            "publisher_owner": "Example Publisher",
            "basis": "headline_link_only",
            "basis_evidence_url": "https://publisher.example/terms",
            "display_scope": "headline_link", "stores_article_body": False,
            "independent_review": {
                "decision": "accepted", "evidence_url": "https://github.com/Ventusltd/reviews/issues/2",
                "reviewer_role": "Agent2", "reviewed_at": "2026-11-15T13:00:00Z",
            },
        },
    }


def test_completely_filled_synthetic_contract_is_still_not_accepted():
    item = record()
    assert L.check_proposal(item) == []
    result = L.assess(item)["PublicationEligibility"]
    assert result["status"] == "independent_external_acceptance_required"
    assert result["accepted_for_publication"] is False


def test_original_source_hash_and_http_response_required():
    item = record()
    item["ArticleReceipt"].update(response_sha256="", http_status=None)
    errs = L.check_proposal(item)
    assert "ArticleReceipt.response_sha256" in errs
    assert "ArticleReceipt.http_status" in errs
    assert L.assess(item)["PublicationEligibility"]["status"] == "withheld"


def test_redirected_article_identity_and_provenance_cannot_be_omitted():
    item = record()
    item["ArticleReceipt"]["final_url"] = "http://publisher.example/other"
    item["ArticleReceipt"]["retrieval_log_url"] = ""
    errs = L.check_proposal(item)
    assert "ArticleReceipt.final_url" in errs
    assert "ArticleReceipt.retrieval_log_url" in errs


def test_article_b_about_project_b_cannot_bind_project_a():
    item = record("1001")
    item["ProjectBinding"]["supporting_evidence"][0]["repd_ref"] = "2002"
    assert "ProjectBinding.supporting_evidence[0]" in L.check_proposal(item)


def test_one_article_about_two_projects_needs_two_separate_bindings():
    one = record("1001")
    two = record("2002")
    two["ArticleReceipt"] = copy.deepcopy(one["ArticleReceipt"])
    two["ProjectBinding"]["supporting_evidence"][0]["repd_ref"] = "1001"
    assert L.check_proposal(one) == []
    assert "ProjectBinding.supporting_evidence[0]" in L.check_proposal(two)


def test_reviewed_boolean_does_not_substitute_for_independent_review():
    item = record()
    item["ProjectBinding"]["independent_review"] = {"reviewed": True}
    assert "ProjectBinding.independent_review" in L.check_proposal(item)


def test_producer_cannot_structurally_self_review():
    item = record()
    item["ProjectBinding"]["independent_review"]["reviewer_role"] = "Agent7"
    item["RightsAssessment"]["independent_review"]["reviewer_role"] = "Agent7"
    errs = L.check_proposal(item)
    assert "ProjectBinding.independent_review" in errs
    assert "RightsAssessment.independent_review" in errs


def test_undocumented_rights_and_article_body_storage_withheld():
    item = record()
    item["RightsAssessment"]["basis"] = "AI confidence high"
    item["RightsAssessment"]["stores_article_body"] = True
    errs = L.check_proposal(item)
    assert "RightsAssessment.basis" in errs
    assert "RightsAssessment.stores_article_body" in errs


def test_event_requires_actual_date_and_planning_reference():
    item = record()
    item["EventAssertion"].update(actual_event_date="not known", planning_reference="")
    errs = L.check_proposal(item)
    assert "EventAssertion.actual_event_date" in errs
    assert "EventAssertion.planning_reference" in errs


def test_news_is_withheld_when_raw_record_unavailable():
    assert L.assess(None)["PublicationEligibility"]["status"] == "withheld"

Test Binder

A test in the tests folder of GlobalGrid2050 that checks Renewable Energy Planning Database (REPD) Diff and Binder.

testglobalgrid2050 / automation/news/tests/test_binder.py · lines 1–131 of 131 · Entry point

What it does
It tests the REPD register, solar and battery storage (BESS). Defines 15 functions or classes, including index, b, test_longest_name_wins, test_ambiguous_name_resolved_by_technology_and_capacity, test_ambiguous_name_left_as_candidate. Uses libraries json, pytest.
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, battery storage (BESS).
Inputs & outputs
In: CSV file repd.csv; GeoJSON file dc.geojson.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Defines `index`, `test_longest_name_wins`, `test_ambiguous_name_resolved_by_technology_and_capacity` and 11 more. Its code works with 500 MW, 1 GWh and 1.2 GW.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Renewable Energy Planning Database (REPD) Diff (import), Binder (import), Conftest (import), json, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
index, b, test_longest_name_wins, test_ambiguous_name_resolved_by_technology_and_capacity, test_ambiguous_name_left_as_candidate, test_planning_reference_is_exact_and_sibling_primary_is_solar, test_generic_names_never_bind, test_foreign_place_downgrades, test_one_word_name_needs_technology_word, test_operator_words_inside_the_site_name_prove_nothing, test_capacity_mismatch_keeps_ambiguity, test_tech_contradiction
Defines here
index, b, test_longest_name_wins, test_ambiguous_name_resolved_by_technology_and_capacity, test_ambiguous_name_left_as_candidate, test_planning_reference_is_exact_and_sibling_primary_is_solar, test_generic_names_never_bind, test_foreign_place_downgrades, test_one_word_name_needs_technology_word, test_operator_words_inside_the_site_name_prove_nothing, test_capacity_mismatch_keeps_ambiguity, test_tech_contradiction, test_news_capacities, test_evaluate_counts, test_datacentre_binding_is_separate_category
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_binder.py:1-131 · blob 4fbeb495e47d0ba507708978ef8012a8e485ff42 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import json

import pytest

from automation.repd import diff as repd
from automation.news import binder as B
from automation.news.tests.conftest import row, write_csv

PROJECTS = [
    row(11034, "Coalburn Energy -  Battery Storage", "Battery", 500, "Operational", county="Strathclyde",
        operator="Zenobe Energy"),
    row(12206, "Coalburn II Energy Storage Facility - Battery Storage Facility", "Battery", 1000,
        "Under Construction", county="Lanarkshire"),
    row(6920, "West Burton", "Battery", 49, "Operational", county="Nottinghamshire"),
    row(10916, "West Burton Solar Project", "Solar Photovoltaics", 480, "Awaiting Construction"),
    row(10917, "West Burton Solar Project", "Battery", 20, "Awaiting Construction"),
    row(11928, "West Burton Power Station, North Road - Battery Storage", "Battery", 500,
        "Awaiting Construction", county="Nottinghamshire"),
    row(13599, "Beacon Fen Energy Park", "Solar Photovoltaics", 400, "Awaiting Construction", pref="EN010151"),
    row(13600, "Beacon Fen Energy Park", "Battery", 600, "Awaiting Construction", pref="EN010151"),
    row(500, "The Grange", "Solar Photovoltaics", 49.9, "Awaiting Construction"),
    row(5967, "Kells Solar Farm", "Solar Photovoltaics", 25, "Revised", county="Co. Derry / Londonderry",
        country="Northern Ireland"),
    row(11974, " Hessay Solar Farm", "Solar Photovoltaics", 40, "Awaiting Construction", county="North Yorkshire"),
    row(13003, "Eccles Substation, Eccles - Battery Energy Storage System", "Battery", 50, "Under Construction",
        operator="Eccles Grid Stability Limited", county="Borders"),
    row(11867, "Eccles Battery Energy Storage System", "Battery", 400, "Under Construction", county="Borders"),
    row(700, "Carlton Solar Farm", "Solar Photovoltaics", 49.99, "Awaiting Construction", county="North Yorkshire"),
    row(701, "Carlton Solar Farm", "Solar Photovoltaics", 30, "Application Submitted", county="Bedfordshire"),
]


@pytest.fixture(scope="module")
def index(tmp_path_factory):
    p = write_csv(tmp_path_factory.mktemp("b") / "repd.csv", PROJECTS)
    return B.ProjectIndex(repd.load_csv(p))


def b(index, headline, source="Solar Power Portal"):
    return B.bind({"headline": headline, "source": source}, index)


def test_longest_name_wins(index):
    r = b(index, "Meadow Partners acquires ground lease for Coalburn II battery storage project")
    assert (r["class"], r["ref"]) == ("STRONG", "12206")
    r = b(index, "1GWh Coalburn 1 battery energy storage enters operations in Scotland")
    assert r["ref"] == "11034"


def test_ambiguous_name_resolved_by_technology_and_capacity(index):
    r = b(index, "Fidra Energy reaches financial close on 500 MW West Burton C BESS project")
    assert (r["class"], r["ref"]) == ("STRONG", "11928")
    assert "capacity" in r["evidence"]["resolved_by"]


def test_ambiguous_name_left_as_candidate(index):
    r = b(index, "Lender advises on West Burton C BESS financing")
    assert r["class"] == "CANDIDATE" and r["ref"] is None
    assert len(r["candidates"]) >= 2


def test_planning_reference_is_exact_and_sibling_primary_is_solar(index):
    r = b(index, "Decision on EN010151 published", source="GOV.UK")
    assert r["class"] == "EXACT" and r["ref"] == "13599" and r["related_refs"] == ["13600"]
    r = b(index, "Beacon Fen Energy Park battery storage plans")
    assert r["ref"] == "13600"


def test_generic_names_never_bind(index):
    assert b(index, "The Grange celebrates national care award")["class"] == "UNBOUND"


def test_foreign_place_downgrades(index):
    r = b(index, "Kells solar farm plan setback after archaeological find", source="Meath Chronicle")
    assert r["class"] == "CANDIDATE"


def test_one_word_name_needs_technology_word(index):
    assert b(index, "Triple Point acquires 49.2MW Hessay Solar project")["ref"] == "11974"
    assert b(index, "Hessay village hall reopens")["class"] == "UNBOUND"


def test_operator_words_inside_the_site_name_prove_nothing(index):
    r = b(index, "Eccles battery storage system plan secures finance deal")
    assert r["class"] == "CANDIDATE"


def test_capacity_mismatch_keeps_ambiguity(index):
    r = b(index, "Greencells signs 71 MW Carlton solar farm EPC deal")
    assert r["class"] == "CANDIDATE"
    r = b(index, "Carlton solar farm in North Yorkshire secures financing")
    assert (r["class"], r["ref"]) == ("STRONG", "700")


def test_tech_contradiction(index):
    r = b(index, "Hessay Solar wind turbine plan")
    assert r["class"] in ("STRONG", "CANDIDATE")  # both families named: solar keeps it


def test_news_capacities():
    assert B.news_capacities("500MW/1,000MWh and 1.2GW, 49.9MWp, 1,000 MW") == [500.0, 1200.0, 49.9, 1000.0]
    assert B.capacity_corroborates(400, [395.0]) and not B.capacity_corroborates(40, [49.2])
    assert not B.capacity_corroborates(None, [10.0])


def test_evaluate_counts(index):
    labels = [
        {"id": "a", "headline": "Coalburn II battery storage acquired", "gold_ref": "12206", "label": "bind", "baseline_ref": "11034"},
        {"id": "b", "headline": "The Grange care award", "gold_ref": None, "label": "none", "baseline_ref": "500"},
        {"id": "c", "headline": "West Burton C BESS financing", "gold_ref": "11928", "label": "bind"},
        {"id": "d", "headline": "Something unclear", "gold_ref": None, "label": "unsure"},
    ]
    ev = B.evaluate(labels, index)
    assert ev["n_scored"] == 3 and ev["n_unsure"] == 1
    assert ev["signal_metrics"]["tp"] == 1 and ev["signal_metrics"]["fp"] == 0 and ev["signal_metrics"]["fn"] == 1
    assert ev["baseline_v9_5_1_primary_match_metrics"]["fp"] == 2


def test_datacentre_binding_is_separate_category(tmp_path):
    g = {"type": "FeatureCollection", "features": [
        {"type": "Feature", "geometry": None, "properties": {"id": "dcuk-aaaa", "name": "Cobalt Park Data Centres", "status": "operational"}},
        {"type": "Feature", "geometry": None, "properties": {"id": "dcuk-bbbb", "name": "Unnamed data centre", "status": "operational"}},
        {"type": "Feature", "geometry": None, "properties": {"id": "dcuk-cccc", "name": "Hertfordshire Data Centre", "status": "operational"}}]}
    p = tmp_path / "dc.geojson"
    p.write_text(json.dumps(g))
    dci = B.DatacentreIndex(p)
    r = dci.bind({"headline": "Cobalt Park data centres to host new GPUs"})
    assert r["topic_datacentres"] and r["bindings"][0]["id"] == "dcuk-aaaa"
    assert r["bindings"][0]["entity_type"] == "DATA_CENTRE" and "ref" not in r["bindings"][0]
    assert dci.bind({"headline": "Hertfordshire solar farm approved"})["bindings"] == []
    assert "dcuk-bbbb" not in dci.sites

Test Cop31 Climate Priority

A test in the tests folder of GlobalGrid2050 that checks Pipeline Headlines and News Algorithm.

testglobalgrid2050 / automation/news/tests/test_cop31_climate_priority.py · lines 1–111 of 111 · Entry point · pattern forbidden (shared by 2 files)

What it does
It tests the REPD register and solar. Defines 10 functions or classes, including test_bounded_climate_policy_detection, test_bbc_fossil_fuels_story_kept_without_solar_or_data_centre, fetch, test_global_cop_policy_not_discarded_as_foreign_or_unknown_repd, 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, solar.
Inputs & outputs
In: JSON file pipeline_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
It is built from the fetch step (`fetch`), the forbidden step (`forbidden`) and the article step (`article`). COP31 news-priority contract: international diplomacy is not an Renewable Energy Planning Database (REPD) fact.
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), News Algorithm (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
test_bounded_climate_policy_detection, test_bbc_fossil_fuels_story_kept_without_solar_or_data_centre, test_global_cop_policy_not_discarded_as_foreign_or_unknown_repd, test_curated_owner_link_publishes_without_fetching_article_body, article, test_cop31_ranks_above_standard_news_without_inventing_verification, test_rejected_publisher_and_general_climate_headlines_remain_rejected
Defines here
test_bounded_climate_policy_detection, test_bbc_fossil_fuels_story_kept_without_solar_or_data_centre, fetch, test_global_cop_policy_not_discarded_as_foreign_or_unknown_repd, fetch, test_curated_owner_link_publishes_without_fetching_article_body, forbidden, article, test_cop31_ranks_above_standard_news_without_inventing_verification, test_rejected_publisher_and_general_climate_headlines_remain_rejected
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_cop31_climate_priority.py:1-111 · blob aeea606b642bfd11366844ede1a7532bddf16e71 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""COP31 news-priority contract: international diplomacy is not an REPD fact."""
import json
from pathlib import Path
import sys
import pytest

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT))
import pipeline_headlines as P
from automation.news import news_algorithm as N

NOW="2026-11-22T00:12:00Z"
BBC="https://www.bbc.co.uk/news/articles/c6ly5w40eg07o"
TITLE="Fight over fossil fuels leaves COP31 climate talks in deadlock"
FEED={"source":"BBC News","url":"https://feeds.bbci.co.uk/news/science_and_environment/rss.xml",
      "uk_only":True,"lane":"keywords","primary":True}
REPD=P.Repd([])


@pytest.mark.parametrize("headline,level",[
    (TITLE,2),
    ("COP31 summit agrees new fossil fuel transition language",2),
    ("Cop 31 climate finance commitments disputed by negotiators",2),
    ("COP32 climate talks end with emissions deal",1),
    ("UN climate summit agrees new coal phase-out timetable",1),
    ("COP31 solar flare observations released",0),
    ("COP31 football fans fly to Turkey",0),
    ("Climate change makes spring flowers bloom early",0),
    ("French energy firm approves a solar farm",0),
])
def test_bounded_climate_policy_detection(headline,level):
    assert P.climate_policy_priority(headline)==level


def test_bbc_fossil_fuels_story_kept_without_solar_or_data_centre():
    assert P.topics_of(TITLE)==[]
    assert P.category_of(TITLE)=="policy"
    assert P.label(TITLE,REPD)==("policy",None,None)
    assert P.priority_label(TITLE,"",REPD) is None  # normal BBC lane needs no bypass here
    def fetch(url):
        assert url==FEED["url"]
        xml=("<rss><channel><item><title>"+TITLE+"</title><link>"+BBC+
             "</link><pubDate>Sat, 21 Nov 2026 07:31:05 GMT</pubDate>"+
             "</item></channel></rss>")
        return xml.encode()
    items,health=P.collect([FEED],fetch,REPD,NOW)
    assert len(items)==1
    assert items[0]["title"]==TITLE
    assert items[0]["category"]=="policy"
    assert items[0]["possible_match"] is None
    assert items[0]["technology"] is None
    assert health[0]["kept"]==1


def test_global_cop_policy_not_discarded_as_foreign_or_unknown_repd():
    other={"url":"https://www.un.org/en/climatechange/news.rss",
           "source":"United Nations","uk_only":False}
    def fetch(_):
        return ("<rss><channel><item><title>"
                "COP31 climate deal faces fossil fuel opposition in Turkey"
                "</title><link>https://www.un.org/en/climatechange/negotiations</link>"
                "</item></channel></rss>").encode()
    found,_=P.collect([other],fetch,REPD,NOW)
    assert len(found)==1 and found[0]["possible_match"] is None
    assert found[0]["category"]=="policy"


def test_curated_owner_link_publishes_without_fetching_article_body():
    feeds=json.loads((ROOT/"pipeline_feeds.json").read_text())["feeds"]
    special=[x for x in feeds if x["url"]==BBC]
    assert len(special)==1
    assert special[0]["kind"]=="curated"
    assert special[0]["source"]=="BBC News"
    assert len(feeds)==69
    def forbidden(_):
        raise AssertionError("BBC article body must never be requested")
    items,health=P.collect(special,forbidden,REPD,NOW)
    assert len(items)==1 and len(health)==1 and health[0]["status"]=="ok"
    assert items[0]["link"]==BBC
    assert items[0]["category"]=="policy"
    assert items[0]["possible_match"] is None
    assert items[0]["date"].startswith("2026-11-21T07:31")


def article(title,url,source="BBC News",category="policy"):
    return {"title":title,"link":url,"source":source,
            "date":"2026-11-21T07:31:05Z","first_seen":NOW,
            "category":category,"technology":None,"possible_match":None}


def test_cop31_ranks_above_standard_news_without_inventing_verification():
    items=[
      article("UK solar farm approved in Gloucestershire",
              "https://www.gov.uk/government/news/solar-decision","GOV.UK","consent"),
      article(TITLE,BBC)
    ]
    rows=N.rank_headlines(items,as_of=NOW)["items"]
    assert rows[0]["link"]==BBC
    assert rows[0]["editorial"]["context_bucket"]==-2
    assert rows[0]["editorial"]["category_hint"]=="policy"
    assert rows[0]["editorial"]["topics"]==[]
    assert rows[0]["editorial"]["verification_status"]=="NOT_VERIFIED"
    assert rows[0]["possible_match"] is None
    assert rows[1]["editorial"]["context_bucket"]==0
    assert N.PROFILE["id"]=="uk-transition-global-context.v1"  # published UI accepts profile


def test_rejected_publisher_and_general_climate_headlines_remain_rejected():
    assert P.excluded_publisher("Solar Power Portal","https://www.solarpowerportal.co.uk/solar/")
    assert P.category_of("Climate causes warm November weather") is None
    assert P.category_of("COP31 cultural festival opens in Antalya") is None