GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / automation/v923-recovery/templates

Test Verify and 4 more files

A test in the automation folder of GlobalGrid2050 that checks Verify. It sets up (`setUp`) and is built from the encoded step (`encoded`) and the response class (`Response`).

682 lines of Python and JavaScript and CSS from globalgrid2050, in 5 files. Topic: Automation and CI. Section 1744 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. Machine Notes interaction · globalgrid2050 / automation/v923-recovery/templates/machine-notes.js lines 1–138
  2. V9 23 render · globalgrid2050 / automation/v923-recovery/templates/v9-23.css lines 1–7
  3. Test Regressions test · globalgrid2050 / automation/v923-recovery/test_regressions.py lines 1–106
  4. Test Verify test · globalgrid2050 / automation/v924_public/test_verify.py lines 1–236
  5. Verify storage · globalgrid2050 / automation/v924_public/verify.py lines 1–195

Machine Notes

A JavaScript file in the templates folder of GlobalGrid2050 that updates visible notes (`updateVisibleNotes`), covering the Renewable Energy Planning Database (REPD) register.

interactionglobalgrid2050 / automation/v923-recovery/templates/machine-notes.js · lines 1–138 of 138 · Not reached from any entry point (candidate for review) · pattern updateVisibleNotes (shared by 2 files)

What it does
It draws the REPD register. Defines 9 functions or classes, including el, originalLink, headlineSummaryV923, shortHeadlineV923, latestTime. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: the REPD register.
What it achieves
It updates visible notes (`updateVisibleNotes`) and is built from the original link helper (`originalLink`) and the headline summary v923 helper (`headlineSummaryV923`). No original article is republished. It responds to click and pipeline events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/v923-recovery/templates · script
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
el, originalLink, headlineSummaryV923, shortHeadlineV923, latestTime, load, updateVisibleNotes, panel, open
Defines here
el, originalLink, headlineSummaryV923, shortHeadlineV923, latestTime, load, updateVisibleNotes, panel, open
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/v923-recovery/templates/machine-notes.js:1-138 · blob b03637080312c5f88eb23b5ceb601d56b004630c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unreached_review
/* V9.23: candidate-only Machine Read Notes. No original article is republished. */
(function () {
  'use strict';
  var notes = new Map();
  var dialog;
  function el(tag, cls, text) {
    var n = document.createElement(tag);
    if (cls) n.className = cls;
    if (text != null) n.textContent = String(text);
    return n;
  }
  function originalLink(raw) {
    try { var u = new URL(String(raw)); return u.protocol === 'https:' ? u.href : null; }
    catch (_) { return null; }
  }
  function headlineSummaryV923(item) {
    var kind = {
      refusal: 'REFUSAL REPORTED',
      consent: 'CONSENT REPORTED',
      planning_decision: 'PLANNING DECISION REPORTED',
      construction: 'CONSTRUCTION REPORTED',
      finance: 'FINANCING REPORTED',
      grid: 'GRID UPDATE REPORTED',
      energisation: 'ENERGISATION REPORTED',
      dco: 'DCO UPDATE REPORTED',
      datacentre: 'DATA CENTRE UPDATE REPORTED'
    }[item.category] || 'PROJECT HEADLINE';
    var d = new Date(item.published);
    var date = Number.isNaN(d.getTime()) ? 'DATE UNKNOWN' :
      d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' }).toUpperCase();
    return kind + ' · ' + date;
  }
  function shortHeadlineV923(item) {
    // First ten source-title words only, never publisher article text.
    var raw = String(item.title || '').replace(/\s+/g, ' ').trim();
    if (!raw) return 'Headline details available at original source';
    var words = raw.split(' ');
    return words.slice(0, 10).join(' ') + (words.length > 10 ? '…' : '');
  }
  function latestTime(item) {
    var t = Date.parse(item.published || item.observed || '');
    return Number.isFinite(t) ? t : 0;
  }
  function load(doc) {
    notes.clear();
    if (doc && Array.isArray(doc.items)) doc.items.forEach(function (item) {
      var match = item.possible_match;
      if (!match || !/^\d+$/.test(String(match.repd_ref || ''))) return;
      if (item.category === 'policy' || /\b(politics|political|election campaign)\b/i.test(String(item.title || ''))) return;
      var uri = originalLink(item.link);
      if (!uri) return;
      var id = String(match.repd_ref);
      if (!notes.has(id)) notes.set(id, []);
      notes.get(id).push({
        title: String(item.title || ''), publisher: String(item.source || 'Publisher not stated'),
        url: uri, category: String(item.category || 'other'),
        published: String(item.date || ''), observed: String(item.first_seen || '')
      });
    });
    // The first line is useful before any click: short event and publisher date.
    // Never turn an algorithmic name association into an official REPD decision.
    notes.forEach(function (events) { events.sort(function (a, b) {
      return latestTime(b) - latestTime(a) || a.title.localeCompare(b.title);
    }); });
    updateVisibleNotes();
    window.dispatchEvent(new Event('machine-notes-updated'));
  }
  function updateVisibleNotes() {
    document.querySelectorAll('.machine-note-button').forEach(function (b) {
      var items = notes.get(String(b.dataset.noteRef)) || [];
      if (items.length) {
        b.replaceChildren(
          el('span', 'machine-note-kind', 'POSSIBLE · ' + headlineSummaryV923(items[0])),
          el('span', 'machine-note-headline', shortHeadlineV923(items[0]))
        );
      } else {
        b.textContent = 'NO MATCHED HEADLINE';
      }
      b.setAttribute('aria-label', items.length
        ? 'Possible, unverified project headline: ' + headlineSummaryV923(items[0])
          + '. ' + shortHeadlineV923(items[0]) + '. Open evidence brief'
        : 'No matched project headline. Open evidence state');
      b.title = items.length ? 'POSSIBLE MATCH · ' + items[0].publisher + ' · verify at original source'
        : 'No independently evidenced project headline';
      b.dataset.noteCandidate = items.length ? 'possible' : 'none';
    });
  }
  function panel() {
    if (dialog) return dialog;
    dialog = el('dialog', 'machine-note-dialog');
    dialog.setAttribute('aria-labelledby', 'machineNoteTitle');
    var close = el('button', 'machine-note-close', 'CLOSE');
    close.type = 'button';
    close.addEventListener('click', function () { if (dialog.close) dialog.close(); else dialog.removeAttribute('open'); });
    var title = el('h2', null, 'Machine-originated Pipeline Intelligence Brief');
    title.id = 'machineNoteTitle';
    dialog.append(close, title);
    var body = el('div', 'machine-note-body');
    body.id = 'machineNoteBody';
    dialog.appendChild(body);
    document.body.appendChild(dialog);
    return dialog;
  }
  function open(button) {
    var dlg = panel(), body = document.getElementById('machineNoteBody');
    body.replaceChildren();
    var ref = String(button.dataset.noteRef || '');
    var events = notes.get(ref) || [];
    body.appendChild(el('p', 'machine-note-stamp', events.length ?
      'CANDIDATE — NOT INDEPENDENTLY VERIFIED' : 'INSUFFICIENT EVIDENCE'));
    body.appendChild(el('p', null, 'REPD ' + ref + ' · ' + String(button.dataset.noteName || 'Project')));
    body.appendChild(el('p', null, 'OFFICIAL SOURCE STATUS · ' + String(button.dataset.noteStatus || 'Unknown')));
    if (!events.length) {
      body.appendChild(el('p', null, 'No adequate matched headline evidence is currently available. The official source remains unchanged.'));
    } else {
      body.appendChild(el('p', null, 'Machine assessment: a headline may relate to this named project. This is an unverified screening lead, not a new official status or an independently accepted project decision. Check the source and exact REPD binding before relying on it.'));
      events.slice(0, 5).forEach(function (event) {
        var entry = el('section', 'machine-note-source');
        entry.appendChild(el('p', null, event.publisher + ' · PUBLISHED ' + (event.published || 'not independently established') +
          ' · FIRST OBSERVED ' + (event.observed || 'unknown')));
        var a = el('a', null, event.title || 'Publisher headline');
        a.href = event.url; a.target = '_blank'; a.rel = 'noopener noreferrer';
        entry.appendChild(a); body.appendChild(entry);
      });
      body.appendChild(el('p', null, 'Evidence receipt, owner independence, rights and exact REPD identity association: NOT VERIFIED.'));
    }
    if (typeof dlg.showModal === 'function') dlg.showModal(); else dlg.setAttribute('open', '');
    dlg.querySelector('.machine-note-close').focus();
  }
  window.pipelineMachineNotes = { has: function (ref) { return notes.has(String(ref)); } };
  window.addEventListener('pipeline-feed-loaded', function (ev) { load(ev.detail); });
  window.addEventListener('pipeline-projects-rendered', updateVisibleNotes);
  document.addEventListener('click', function (ev) {
    var b = ev.target && ev.target.closest ? ev.target.closest('.machine-note-button') : null;
    if (b) open(b);
  });
  if (window.pipelineHeadlineDocument) load(window.pipelineHeadlineDocument);
})();

V9 23

A style sheet in the templates folder of GlobalGrid2050.

renderglobalgrid2050 / automation/v923-recovery/templates/v9-23.css · lines 1–7 of 7 · Not reached from any entry point (candidate for review)

What it does
Side effects: changes the web page (DOM).
What it achieves
V9.23 nonlive briefing; full text is present before any animation.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/v923-recovery/templates · style sheet
Uses
none found
Used by
none found
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/v923-recovery/templates/v9-23.css:1-7 · blob 7942dcdd330f554a432eb95bd7ec89d4d338bc31 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unreached_review
/* V9.23 nonlive briefing; full text is present before any animation. */
.machine-note-cell{min-width:118px}.machine-note-button,.machine-note-close{min-width:88px;min-height:44px;padding:8px 10px;border:1px solid #c4ab72;background:#28251d;color:#fff0ca;font:600 12px ui-monospace,monospace;cursor:pointer}.machine-note-button:focus-visible,.machine-note-close:focus-visible{outline:3px solid #cda84e;outline-offset:3px}
.machine-note-dialog{box-sizing:border-box;width:min(700px,calc(100vw - 12px));max-height:94dvh;background:#f3ecdc;color:#262116;padding:clamp(12px,3vw,30px);border:2px solid #66553c;font:14px/1.6 ui-monospace,monospace;overflow-y:auto}
.machine-note-dialog::backdrop{background:rgba(0,0,0,.8)}.machine-note-dialog h2{font:700 22px/1.3 ui-monospace,monospace;margin:14px 0}.machine-note-dialog a{overflow-wrap:anywhere;color:#164a78}.machine-note-dialog .machine-note-stamp{font-weight:700;border-block:2px solid #62573f;padding:8px 0}.machine-note-source{border-top:1px solid #aa9b7a;padding:12px 0}.machine-note-close{float:right;margi  … [line shortened here: 415 characters; full line on GitHub]
@media(max-width:600px){.machine-note-dialog h2{font-size:18px;clear:both}.machine-note-button{min-width:86px}.machine-note-cell{min-width:100px}}
@media(prefers-reduced-motion:reduce){.machine-note-dialog *{animation:none!important;transition:none!important}}
@media print{.machine-note-dialog{position:static;max-height:none;overflow:visible;border:0;width:auto}.machine-note-close{display:none}}

Test Regressions

A test in the automation folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register. It is built from the incomplete build tests class (`IncompleteBuildTests`).

testglobalgrid2050 / automation/v923-recovery/test_regressions.py · lines 1–106 of 106 · Entry point

What it does
It tests the REPD register. Defines 10 functions or classes, including IncompleteBuildTests, test_interrupted_after_create_must_fail, test_unregistered_candidate_must_fail, test_inline_headline_summary_exists_and_is_candidate_only, test_late_gridatlas_card_collapse_must_be_checked. Uses libraries importlib.util, tempfile, unittest, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: the REPD register.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V923 Six Hour Python Repair Workflow (globalgrid2050).
What it achieves
CVAA fail-closed checks: interrupted builds and two-vertical REPD table cells.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow and GlobalGrid2050 V923 Six Hour Python Repair Workflow.
Application
globalgrid2050 · automation/v923-recovery · test
Uses
importlib.util, tempfile, unittest, pathlib
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 V923 Six Hour Python Repair Workflow (workflow run)
Produces
IncompleteBuildTests
Defines here
IncompleteBuildTests, test_interrupted_after_create_must_fail, test_unregistered_candidate_must_fail, test_inline_headline_summary_exists_and_is_candidate_only, test_late_gridatlas_card_collapse_must_be_checked, test_feedback_keeps_failed_browser_probe_red, test_feedback_missing_mandatory_checks_is_incomplete, test_feedback_static_pass_is_not_a_browser_pass, test_feedback_missing_verdict_is_not_success, test_candidate_columns_are_one_per_vertical
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/v923-recovery/test_regressions.py:1-106 · blob e7bf418b49539f8687b5f9043a2fa5120a43a5f4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""CVAA fail-closed checks: interrupted builds and two-vertical REPD table cells."""
import importlib.util
import tempfile
import unittest
from pathlib import Path

SOURCE=Path(__file__).resolve().parent/"repair.py"
spec=importlib.util.spec_from_file_location("v923_repair_under_test",SOURCE)
repair=importlib.util.module_from_spec(spec)
spec.loader.exec_module(repair)

class IncompleteBuildTests(unittest.TestCase):
    def test_interrupted_after_create_must_fail(self):
        with tempfile.TemporaryDirectory() as d:
            root=Path(d)
            (root/"index.html").write_text("partial")
            with self.assertRaisesRegex(RuntimeError,"PARTIAL_CANDIDATE"):
                repair.require_completed_candidate(root,{"id":repair.NEW,"version":"V9.23","parent":repair.OLD,"runner":"tests/run_v9_23.sh","trees":["digest"]})

    def test_unregistered_candidate_must_fail(self):
        with tempfile.TemporaryDirectory() as d:
            with self.assertRaisesRegex(RuntimeError,"PARTIAL_CANDIDATE"):
                repair.require_completed_candidate(Path(d),{"id":repair.OLD,"version":"V9.22"})


    def test_inline_headline_summary_exists_and_is_candidate_only(self):
        notes=(repair.B/"scripts/plugins/machine-notes-v923.js").read_text()
        self.assertIn("headlineSummaryV923",notes)
        self.assertIn("shortHeadlineV923",notes)
        self.assertIn("machine-note-headline",notes)
        self.assertIn("pipeline-projects-rendered", notes)
        self.assertIn("Possible, unverified project headline",notes)
        self.assertNotIn("CONFIRMED BY MACHINE",notes)



    def test_late_gridatlas_card_collapse_must_be_checked(self):
        script=(repair.B/"tests/browser_real_map_to_engine_agent7.mjs").read_text()
        self.assertIn("visibility_stability",script)
        self.assertIn("visibilityStability.every",script)
        self.assertIn("1700, 4000, 4400",script)

    def test_feedback_keeps_failed_browser_probe_red(self):
        spec2=importlib.util.spec_from_file_location(
            "v923_feedback_under_test",SOURCE.parent/"feedback.py")
        feedback=importlib.util.module_from_spec(spec2)
        spec2.loader.exec_module(feedback)
        record={"versions":[{"id":repair.NEW,"checks":{
            "feature_probes":{"pass":False,"results":[
                {"name":"Native notes column","viewport":"phone","pass":False,
                 "detail":"Missing row cell"}]},
            "map_contract":{"pass":True},
            "tree_unchanged":{"pass":True},
            "runner":{"pass":True},
            "grid_engine_contract":{"pass":True},
            "map_links_identical_to_parent":{"pass":True},
            "data_unchanged_from_parent":{"pass":True},
            "features_kept":{"pass":True}
        }}]}
        outcome=feedback.analyse(record, "frozen-test-sha")
        self.assertEqual(outcome["verdict"],"PRODUCT_CI_FAIL")
        self.assertEqual(outcome["failed_checks"],["feature_probes"])
        self.assertEqual(outcome["failed_browser_probes"][0]["viewport"],"phone")
        self.assertNotEqual(outcome["verdict"],"PRODUCT_CI_PASS_WITH_OPEN_EXTERNAL_HOLDS")

    def test_feedback_missing_mandatory_checks_is_incomplete(self):
        spec2=importlib.util.spec_from_file_location(
            "v923_feedback_under_test",SOURCE.parent/"feedback.py")
        feedback=importlib.util.module_from_spec(spec2)
        spec2.loader.exec_module(feedback)
        outcome=feedback.analyse({"versions":[{"id":repair.NEW,"checks":{}}]})
        self.assertEqual(outcome["verdict"],"INCOMPLETE_VERDICT")

    def test_feedback_static_pass_is_not_a_browser_pass(self):
        spec2=importlib.util.spec_from_file_location(
            "v923_feedback_under_test",SOURCE.parent/"feedback.py")
        feedback=importlib.util.module_from_spec(spec2)
        spec2.loader.exec_module(feedback)
        names=("tree_unchanged","runner","map_contract","grid_engine_contract",
               "map_links_identical_to_parent","data_unchanged_from_parent","features_kept")
        doc={"versions":[{"id":repair.NEW,"browser_checked":False,
              "checks":{n:{"pass":True} for n in names}}]}
        outcome=feedback.analyse(doc)
        self.assertEqual(outcome["verdict"],
          "STATIC_PARITY_PASS_BROWSER_AND_GRIDATLAS_PENDING")
        self.assertFalse(outcome["browser_checked"])

    def test_feedback_missing_verdict_is_not_success(self):
        spec2=importlib.util.spec_from_file_location(
            "v923_feedback_under_test",SOURCE.parent/"feedback.py")
        feedback=importlib.util.module_from_spec(spec2)
        spec2.loader.exec_module(feedback)
        self.assertEqual(feedback.analyse(None)["verdict"],"UNVERIFIED")
    def test_candidate_columns_are_one_per_vertical(self):
        content=(repair.B/"scripts/plugins/projects-v9-8.js").read_text()
        marker="\nfunction projectRowHtml(project) {"
        self.assertEqual(content.count(marker),1)
        inter,repd=content.split(marker,1)
        self.assertEqual(inter.count('class="machine-note-cell"'),1)
        self.assertEqual(repd.count('class="machine-note-cell"'),1)
        self.assertNotIn('data-note-ref',inter)
        self.assertIn('data-note-ref=',repd)

if __name__=="__main__":
    unittest.main()

Test Verify

A test in the automation folder of GlobalGrid2050 that checks Verify. It sets up (`setUp`) and is built from the encoded step (`encoded`) and the response class (`Response`).

testglobalgrid2050 / automation/v924_public/test_verify.py · lines 1–236 of 236 · Entry point · pattern Response (shared by 4 files)

What it does
It tests its inputs. Defines 34 functions or classes, including encoded, Response, __init__, ReadbackTests, setUp. Uses libraries copy, importlib.util, io, json, os. Side effects: reads or writes files; makes network requests.
Inputs & outputs
In: JSON file homepage.json; JSON file registry.json; JSON file versions.json; JSON file homepage-owner.json; JSON file receipt.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V924 Public Readback Workflow (globalgrid2050).
What it achieves
Offline contract and importer-parity tests; no public source claims. It writes `automation/pipeline_release/registry.json`.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow and GlobalGrid2050 V924 Public Readback Workflow.
Application
globalgrid2050 · automation/v924_public · test
Uses
Verify (import), copy, importlib.util, io, json, os, pathlib, tempfile, unittest
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 V924 Public Readback Workflow (workflow run)
Produces
encoded, Response, ReadbackTests, TransportTests
Defines here
encoded, Response, __init__, ReadbackTests, setUp, write, repin, git, prepare, check, test_registry_tail_does_not_promote_operative_release, test_later_owner_promotion_selects_new_version, test_transformation_matches_real_importer, response, test_wrong_source_pin_fails, test_unpinned_owner_commit_fails, test_untransformed_root_fails, test_malformed_importer_references_fail, test_every_served_bundle_asset_is_pinned, test_wrong_release_and_rollbacks_fail, test_current_manifest_must_equal_frozen_baseline, test_missing_or_changed_ledger_fails, test_ledger_semantics_are_checked_even_with_identical_bytes, test_owner_wrong_url_candidate_and_duplicate_rejected, test_unregistered_tree_fails, test_source_and_public_fetch_failure_cannot_pass, fail, test_main_writes_failure_receipt_and_exits_nonzero, TransportTests, test_http_url_and_unknown_host_rejected_before_network
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/v924_public/test_verify.py:1-236 · blob f1510d382d24e279904704102414be3c6b05ba1b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: production_core
"""Offline contract and importer-parity tests; no public source claims."""
import copy
import importlib.util
import io
import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch

import verify as v


def encoded(obj):
    return (json.dumps(obj, sort_keys=True) + "\n").encode()


class Response(io.BytesIO):
    status = 200
    def __init__(self, body, length=None):
        super().__init__(body)
        self.headers = {} if length is None else {"Content-Length": str(length)}


class ReadbackTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        self.current = "202611161244"
        self.new = "202611161630"
        self.ids = (self.new, *v.ROLLBACKS)
        self.registry = {"versions": [{"id": rid, "version": ver, "trees": [rid * 3 + "abcd"]}
            for rid, ver in zip(self.ids, ("V9.25", "V9.24", "V9.23"))]}
        self.owner = {"schema_version": 1, "entities": [{"id": "pipeline-news", "operative_release_id": self.current,
            "releases": [{"id": rid, "status": "available", "url": v.BASE + f"uk_renewables_pipeline/{rid}/"} for rid in self.ids]}]}
        self.raw = b'\xef\xbb\xbf<html><link href="./assets/versioned-homepage.css"><script src="./assets/versioned-homepage.js"></script><a href="data/homepage.json">Data</a></html>  \r\n'
        self.bundle = {name: (self.raw if name == "index.html" else b"{}\n") for name in v.FILES}
        self.bundle["data/homepage.json"] = encoded(self.owner)
        seed = {"selection": "numeric-repd-ref-ascending", "ids": [str(i) for i in range(1018, 2017)] + ["2325"],
                "record_count": 7775, "solar_count": 3604, "provisional_candidates": 2, "not_researched": 998, "independently_verified": 0}
        self.manifest = encoded(seed)
        self.remote = {}
        for entry in self.registry["versions"]:
            rid = entry["id"]
            self.write(f"uk_renewables_pipeline/{rid}/index.html", f'<html>{entry["version"]} {rid}</html>'.encode())
            if rid != v.ROLLBACKS[1]:
                self.write(f"uk_renewables_pipeline/{rid}/solar1000/manifest.json", self.manifest)
        self.ledger = {"versions": [{"id": e["id"], "version": e["version"], "verdict": "PASS", "tree": e["trees"]} for e in self.registry["versions"]]}
        self.write("automation/pipeline_release/registry.json", encoded(self.registry))
        self.write("uk_renewables_pipeline/versions.json", encoded(self.ledger))
        self.repin()

    def write(self, name, body):
        target = self.root / name
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_bytes(body)
        self.remote[v.BASE + name] = body

    def repin(self):
        self.bundle["data/homepage.json"] = encoded(self.owner)
        self.pin = {"repository": "Ventusltd/globalgrid2050-homepage", "commit": "a" * 40,
                    "files": {name: v.sha(body) for name, body in self.bundle.items()}}
        self.write("catalogue/homepage-owner.json", encoded(self.pin))
        for name, body in self.bundle.items():
            self.remote[f'https://raw.githubusercontent.com/{self.pin["repository"]}/{self.pin["commit"]}/{name}'] = body
            if name != "index.html":
                self.remote[v.BASE + "homepage-shell/" + name] = body
        self.remote[v.BASE] = v.transformed_index(self.bundle["index.html"])

    def git(self, root, command, ref):
        if ref == "HEAD":
            return "b" * 40
        rid = ref.rsplit("/", 1)[-1]
        return next(e["trees"][0] for e in self.registry["versions"] if e["id"] == rid)

    def prepare(self):
        return v.prepare(self.root, self.remote.__getitem__, self.git)

    def check(self):
        return v.check_once(self.prepare(), self.remote.__getitem__)

    def test_registry_tail_does_not_promote_operative_release(self):
        result = self.check()
        self.assertEqual(result["release"], self.current)
        self.assertNotEqual(result["owner_source_index_sha256"], result["transformed_root_sha256"])
        self.assertEqual(result["rollback_releases"], list(v.ROLLBACKS))

    def test_later_owner_promotion_selects_new_version(self):
        self.owner["entities"][0]["operative_release_id"] = self.new
        self.repin()
        self.assertEqual(self.check()["version"], "V9.25")

    def test_transformation_matches_real_importer(self):
        spec = importlib.util.spec_from_file_location("real_importer", Path(__file__).resolve().parents[2] / "scripts/import_homepage_owner.py")
        importer = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(importer)
        def response(url, **kwargs):
            return Response(self.remote[url])
        with patch.object(importer, "ROOT", self.root), patch.object(importer.urllib.request, "urlopen", response):
            importer.main()
        self.assertEqual((self.root / "index.html").read_bytes(), v.transformed_index(self.raw))
        for name in v.FILES - {"index.html"}:
            self.assertEqual((self.root / "homepage-shell" / name).read_bytes(), self.bundle[name])

    def test_wrong_source_pin_fails(self):
        self.pin["files"]["index.html"] = "0" * 64
        self.write("catalogue/homepage-owner.json", encoded(self.pin))
        with self.assertRaisesRegex(ValueError, "source hash mismatch"):
            self.prepare()

    def test_unpinned_owner_commit_fails(self):
        self.pin["commit"] = "main"
        self.write("catalogue/homepage-owner.json", encoded(self.pin))
        with self.assertRaisesRegex(ValueError, "invalid owner pin"):
            self.prepare()

    def test_untransformed_root_fails(self):
        self.remote[v.BASE] = self.raw
        with self.assertRaisesRegex(ValueError, "served byte mismatch"):
            self.check()

    def test_malformed_importer_references_fail(self):
        for body in (self.raw.replace(b'./assets/versioned-homepage.js', b'wrong.js'), self.raw + b'href="data/homepage.json"'):
            with self.subTest(body=body), self.assertRaises(ValueError):
                v.transformed_index(body)

    def test_every_served_bundle_asset_is_pinned(self):
        for name in v.FILES - {"index.html"}:
            with self.subTest(name=name):
                url = v.BASE + "homepage-shell/" + name
                original = self.remote[url]
                self.remote[url] += b"x"
                with self.assertRaisesRegex(ValueError, "served byte mismatch"):
                    self.check()
                self.remote[url] = original

    def test_wrong_release_and_rollbacks_fail(self):
        for rid in (self.new, *v.ROLLBACKS):
            with self.subTest(rid=rid):
                self.owner["entities"][0]["operative_release_id"] = self.new
                self.repin()
                url = v.BASE + f"uk_renewables_pipeline/{rid}/index.html"
                original = self.remote[url]
                self.remote[url] = b"wrong release"
                with self.assertRaisesRegex(ValueError, "served byte mismatch"):
                    self.check()
                self.remote[url] = original

    def test_current_manifest_must_equal_frozen_baseline(self):
        self.owner["entities"][0]["operative_release_id"] = self.new
        self.repin()
        self.write(f"uk_renewables_pipeline/{self.new}/solar1000/manifest.json", self.manifest + b" ")
        with self.assertRaisesRegex(ValueError, "differs from frozen"):
            self.prepare()

    def test_missing_or_changed_ledger_fails(self):
        self.remote[v.BASE + "uk_renewables_pipeline/versions.json"] = b"{}"
        with self.assertRaisesRegex(ValueError, "served byte mismatch"):
            self.check()

    def test_ledger_semantics_are_checked_even_with_identical_bytes(self):
        for key, value in (("verdict", "FAIL"), ("version", "V9.99"), ("tree", ["wrong"])):
            with self.subTest(key=key):
                ledger = copy.deepcopy(self.ledger)
                ledger["versions"][1][key] = value
                self.write("uk_renewables_pipeline/versions.json", encoded(ledger))
                with self.assertRaisesRegex(ValueError, "ledger identity/tree/verdict"):
                    self.check()

    def test_owner_wrong_url_candidate_and_duplicate_rejected(self):
        original = copy.deepcopy(self.owner)
        for change in ("url", "status", "duplicate"):
            with self.subTest(change=change):
                self.owner = copy.deepcopy(original)
                release = self.owner["entities"][0]["releases"][1]
                if change == "duplicate":
                    self.owner["entities"].append(copy.deepcopy(self.owner["entities"][0]))
                else:
                    release[change] = "candidate" if change == "status" else v.BASE + "wrong/"
                self.repin()
                with self.assertRaises(ValueError):
                    self.prepare()

    def test_unregistered_tree_fails(self):
        with self.assertRaisesRegex(ValueError, "unregistered source tree"):
            v.prepare(self.root, self.remote.__getitem__, lambda *args: "0" * 40)

    def test_source_and_public_fetch_failure_cannot_pass(self):
        def fail(url):
            raise TimeoutError("bounded fetch timed out")
        with self.assertRaises(TimeoutError):
            v.prepare(self.root, fail, self.git)
        with self.assertRaises(TimeoutError):
            v.check_once(self.prepare(), fail)

    def test_main_writes_failure_receipt_and_exits_nonzero(self):
        output = self.root / "receipt.json"
        with patch.dict(os.environ, {"PIPELINE_RECEIPT_PATH": str(output)}), patch.object(v, "prepare", side_effect=TimeoutError("offline")):
            self.assertEqual(v.main(), 1)
        self.assertEqual(json.loads(output.read_text())["status"], "FAIL")


class TransportTests(unittest.TestCase):
    def test_http_url_and_unknown_host_rejected_before_network(self):
        for url in ("http://globalgrid2050.com/", "https://localhost/", "https://globalgrid2050.com:8443/", "https://user@globalgrid2050.com/"):
            with self.subTest(url=url), self.assertRaises(ValueError):
                v.read(url)

    def test_redirect_is_rejected(self):
        with self.assertRaisesRegex(ValueError, "redirect"):
            v.NoRedirects().redirect_request(None, None, 302, "", {}, "https://localhost/")

    def test_size_limits_and_http_failure(self):
        for body, length, status in ((b"x", v.MAX_BYTES + 1, 200), (b"x" * (v.MAX_BYTES + 1), None, 200), (b"denied", None, 403)):
            response = Response(body, length)
            response.status = status
            with self.subTest(length=length, status=status), patch.object(v.urllib.request, "build_opener") as factory:
                factory.return_value.open.return_value = response
                with self.assertRaises(ValueError):
                    v.read(v.BASE)
                self.assertEqual(factory.return_value.open.call_args.kwargs["timeout"], 10)

    def test_retry_budget_is_bounded(self):
        for value in ("0", "5", "-1", "not-a-number"):
            with self.subTest(value=value), patch.dict(os.environ, {"PIPELINE_VERIFY_ATTEMPTS": value}), self.assertRaises(ValueError):
                v.bounded_env("PIPELINE_VERIFY_ATTEMPTS", 3, 1, 4)

    def test_duplicate_json_keys_rejected(self):
        with self.assertRaisesRegex(ValueError, "duplicate JSON key"):
            v.decode(b'{"a":1,"a":2}')


if __name__ == "__main__":
    unittest.main()

Verify

A Python command-line tool in the automation folder of GlobalGrid2050 that fetches homepage owner and active pages, using SHA-256 from raw.githubusercontent.com.

storageglobalgrid2050 / automation/v924_public/verify.py · lines 1–195 of 195 · Entry point · pattern unique_object (shared by 2 files)

What it does
It fetches homepage owner and active pages. Defines 14 functions or classes, including sha, require, unique_object, decode, NoRedirects. Uses libraries __future__, datetime, hashlib, json, os. Side effects: reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: data source: raw.githubusercontent.com; JSON file homepage.json; JSON file active-pages.json; JSON file presentation.json; JSON file entity-types.json; JSON file homepage-owner.json; JSON file registry.json; JSON file versions.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 V924 Public Readback Workflow (globalgrid2050); Test Verify (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It checks once (`check_once`) and is built from the sha step (`sha`) and the require step (`require`). Read-only current Pipeline News/owner bundle and immutable rollback readback.
Why it matters
Run by GlobalGrid2050 V924 Public Readback Workflow. Checked by Test Verify.
Application
globalgrid2050 · automation/v924_public · Python CLI
Uses
__future__, datetime, hashlib, json, os, pathlib, re, subprocess
Used by
run by GlobalGrid2050 V924 Public Readback Workflow (workflow run), imported by Test Verify (import)
Produces
sha, require, unique_object, decode, NoRedirects, read, transformed_index, git_value, prepare, check_once, bounded_env, main
Defines here
sha, require, unique_object, decode, NoRedirects, redirect_request, read, transformed_index, git_value, prepare, check_once, exact, bounded_env, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/v924_public/verify.py:1-195 · blob 7f1f2668bb150cb21fe2c5a74c508625f7d9a4ec · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""Read-only current Pipeline News/owner bundle and immutable rollback readback.

The legacy directory name is retained. The hash-pinned homepage owner, not the
registry tail or newest public URL, selects the operative release.
"""
from __future__ import annotations
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import time
import urllib.parse
import urllib.request

ROOT = Path(__file__).resolve().parents[2]
BASE = "https://globalgrid2050.com/"
ROLLBACKS = ("202611161244", "202611160020")
FILES = {"index.html", "assets/versioned-homepage.css", "assets/versioned-homepage.js",
         "data/homepage.json", "data/active-pages.json", "data/presentation.json", "data/entity-types.json"}
MAX_BYTES = 2_000_000


def sha(data):
    return hashlib.sha256(data).hexdigest()


def require(condition, message):
    if not condition:
        raise ValueError(message)


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        require(key not in result, f"duplicate JSON key: {key}")
        result[key] = value
    return result


def decode(data):
    return json.loads(data.decode("utf-8-sig"), object_pairs_hook=unique_object)


class NoRedirects(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise ValueError("readback redirects are not permitted")


def read(url):
    parsed = urllib.parse.urlsplit(url)
    require(parsed.scheme == "https" and parsed.hostname in {"globalgrid2050.com", "raw.githubusercontent.com"}
            and not parsed.username and not parsed.password and parsed.port in (None, 443), "unsafe readback URL")
    request = urllib.request.Request(url, headers={"User-Agent": "GlobalGrid2050-Public-Readback/2.0", "Cache-Control": "no-cache"})
    with urllib.request.build_opener(NoRedirects()).open(request, timeout=10) as response:
        require(response.status == 200, f"HTTP {response.status}: {url}")
        length = response.headers.get("Content-Length")
        require(length is None or int(length) <= MAX_BYTES, "oversized response header")
        body = response.read(MAX_BYTES + 1)
        require(len(body) <= MAX_BYTES, "oversized response body")
        return body


def transformed_index(raw):
    """Match scripts/import_homepage_owner.py; parity-tested against its real main."""
    index = raw.decode("utf-8-sig")
    for name in ("versioned-homepage.css", "versioned-homepage.js"):
        source = f"./assets/{name}"
        require(index.count(source) == 1, f"unexpected index reference: {name}")
        index = index.replace(source, f"./homepage-shell/assets/{name}")
    source = 'href="data/homepage.json"'
    require(index.count(source) == 1, "unexpected catalogue fallback reference")
    return (index.replace(source, 'href="./homepage-shell/data/homepage.json"').rstrip() + "\n").encode("utf-8")


def git_value(root, *args):
    return subprocess.check_output(["git", "-C", str(root), *args], text=True).strip()


def prepare(root=ROOT, fetch=read, git=git_value):
    pin = decode((root / "catalogue/homepage-owner.json").read_bytes())
    require(pin.get("repository") == "Ventusltd/globalgrid2050-homepage"
            and re.fullmatch(r"[0-9a-f]{40}", pin.get("commit", "")), "invalid owner pin")
    require(set(pin.get("files", {})) == FILES, "unexpected owner bundle files")
    bundle = {}
    for name, digest in pin["files"].items():
        require(isinstance(digest, str) and re.fullmatch(r"[0-9a-f]{64}", digest), "invalid owner digest")
        body = fetch(f'https://raw.githubusercontent.com/{pin["repository"]}/{pin["commit"]}/{name}')
        require(len(body) <= 1_000_000 and sha(body) == digest, f"owner source hash mismatch: {name}")
        bundle[name] = body
    require(sum(map(len, bundle.values())) < 1_000_000, "owner bundle exceeds size limit")
    config = decode(bundle["data/homepage.json"])
    require(config.get("schema_version") == 1, "unsupported owner catalogue")
    entities = [e for e in config["entities"] if e.get("id") == "pipeline-news"]
    require(len(entities) == 1, "pipeline owner identity missing or ambiguous")
    entity = entities[0]
    current = entity.get("operative_release_id", "")
    require(re.fullmatch(r"[0-9]{12}", current), "invalid operative release identity")
    owner_releases = [r for r in entity["releases"] if r.get("id") == current]
    require(len(owner_releases) == 1 and owner_releases[0].get("status") == "available", "operative release is not available")
    require(owner_releases[0].get("url") == BASE + f"uk_renewables_pipeline/{current}/", "operative release URL mismatch")
    registry = decode((root / "automation/pipeline_release/registry.json").read_bytes())
    records = registry["versions"]
    selected = {}
    for release_id in dict.fromkeys((current, *ROLLBACKS)):
        matches = [v for v in records if v.get("id") == release_id]
        require(len(matches) == 1, "registered release missing or ambiguous")
        entry = matches[0]
        actual_tree = git(root, "rev-parse", f"HEAD:uk_renewables_pipeline/{release_id}")
        require(actual_tree in entry["trees"], f"unregistered source tree: {release_id}")
        html = (root / "uk_renewables_pipeline" / release_id / "index.html").read_bytes()
        require(entry["version"].encode() in html and release_id.encode() in html, "local release identity absent")
        selected[release_id] = {"version": entry["version"], "tree": actual_tree, "html": html}
    manifest = (root / "uk_renewables_pipeline" / ROLLBACKS[0] / "solar1000/manifest.json").read_bytes()
    seed = decode(manifest)
    require(seed["selection"] == "numeric-repd-ref-ascending" and len(seed["ids"]) == len(set(seed["ids"])) == 1000,
            "invalid frozen Solar-1000 selection")
    require(seed["ids"][0] == "1018" and seed["ids"][-1] == "2325" and seed["record_count"] == 7775
            and seed["solar_count"] == 3604 and seed["provisional_candidates"] == 2
            and seed["not_researched"] == 998 and seed["independently_verified"] == 0, "frozen baseline counts changed")
    require((root / "uk_renewables_pipeline" / current / "solar1000/manifest.json").read_bytes() == manifest,
            "operative Solar-1000 differs from frozen baseline")
    ledger = (root / "uk_renewables_pipeline/versions.json").read_bytes()
    return {"source_commit": git(root, "rev-parse", "HEAD"), "pin": pin, "bundle": bundle,
            "root_html": transformed_index(bundle["index.html"]), "current": current,
            "selected": selected, "manifest": manifest, "ledger": ledger}


def check_once(expected, fetch=read):
    observed = {}
    def exact(path, original):
        body = fetch(BASE + path)
        require(body == original, f"served byte mismatch: {path or 'index.html'}")
        observed[path or "index.html"] = sha(body)
        return body
    exact("", expected["root_html"])
    for name, body in expected["bundle"].items():
        if name != "index.html":
            exact("homepage-shell/" + name, body)
    for release_id, source in expected["selected"].items():
        exact(f"uk_renewables_pipeline/{release_id}/index.html", source["html"])
    for release_id in dict.fromkeys((expected["current"], ROLLBACKS[0])):
        exact(f"uk_renewables_pipeline/{release_id}/solar1000/manifest.json", expected["manifest"])
    ledger = decode(exact("uk_renewables_pipeline/versions.json", expected["ledger"]))
    for release_id, source in expected["selected"].items():
        matches = [v for v in ledger["versions"] if v.get("id") == release_id]
        require(len(matches) == 1, "served ledger release missing or ambiguous")
        entry = matches[0]
        require(entry.get("version") == source["version"] and entry.get("verdict") == "PASS"
                and source["tree"] in entry.get("tree", []), "served ledger identity/tree/verdict mismatch")
    return {"status": "PASS", "checked_at": dt.datetime.now(dt.timezone.utc).isoformat(),
            "source_commit": expected["source_commit"], "homepage_owner_commit": expected["pin"]["commit"],
            "release": expected["current"], "version": expected["selected"][expected["current"]]["version"],
            "owner_source_index_sha256": sha(expected["bundle"]["index.html"]),
            "transformed_root_sha256": sha(expected["root_html"]), "served_sha256": observed,
            "rollback_releases": list(ROLLBACKS), "solar_1000": 1000,
            "scope": "Exact source-pinned HTTP bytes, operative owner release, ledger and V9.24/V9.23 rollback. Not rights approval, project verification, live MAP/browser acceptance or promotion."}


def bounded_env(name, default, low, high):
    value = int(os.environ.get(name, str(default)))
    require(low <= value <= high, f"{name} outside allowed bounds")
    return value


def main():
    out = Path(os.environ.get("PIPELINE_RECEIPT_PATH", str(Path(tempfile.gettempdir()) / "pipeline-public-receipt.json")))
    receipt = {"status": "FAIL", "scope": "public readback"}
    try:
        attempts = bounded_env("PIPELINE_VERIFY_ATTEMPTS", 3, 1, 4)
        delay = bounded_env("PIPELINE_VERIFY_DELAY_SECONDS", 8, 0, 15)
        expected = prepare()
        for attempt in range(1, attempts + 1):
            try:
                receipt = check_once(expected)
                break
            except (ValueError, OSError, KeyError, TypeError) as exc:
                receipt = {"status": "FAIL", "attempt": attempt, "source_commit": expected["source_commit"], "error": str(exc)}
                print(f"Public readback attempt {attempt}/{attempts}: {exc}", flush=True)
                if attempt < attempts:
                    time.sleep(delay)
    except (ValueError, OSError, KeyError, TypeError, subprocess.CalledProcessError) as exc:
        receipt = {"status": "FAIL", "error": str(exc)}
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(receipt))
    return 0 if receipt["status"] == "PASS" else 1


if __name__ == "__main__":
    raise SystemExit(main())