GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / legislation / .github/workflows

Backfill Lightning Workflow and 9 more files

A GitHub Actions workflow. Runs by hand.

607 lines of YAML and Python and JavaScript from legislation, lightning, in 10 files. Topic: Automation and CI. Section 1818 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. Tracking Workflow automation · legislation / .github/workflows/tracking.yml lines 1–71
  2. Verify Workflow automation · legislation / .github/workflows/verify.yml lines 1–50
  3. Test Replay test · legislation / case/replay/test_replay.py lines 1–63
  4. Test Screen test · legislation / contracts/test_screen.py lines 1–74
  5. Test Register test · legislation / diary/test_register.py lines 1–12
  6. Test Compare test · legislation / editions/test_compare.py lines 1–21
  7. Test Legal test · legislation / engine/test_legal.py lines 1–92
  8. Test test · legislation / protections/test.mjs lines 1–40
  9. Verify render · legislation / tools/verify.py lines 1–17
  10. Backfill Lightning Workflow automation · lightning / .github/workflows/backfill-lightning.yml lines 1–167

Tracking Workflow

A GitHub Actions workflow in Legislation. Runs on push, on pull requests and on a schedule.

automationlegislation / .github/workflows/tracking.yml · lines 1–71 of 71 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Inputs & outputs
Out: commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Legislative listing monitor”; runs Track (`tracking/track.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
legislation · .github/workflows · workflow
Uses
Test Track (workflow run), Track (workflow run)
Used by
none found
Produces
none declared
Defines here
Legislative listing monitor
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 .github/workflows/tracking.yml:1-71 · blob 810cf420c4698bfed0468bea588c0e74085f1d9b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: Legislative listing monitor
on:
  schedule:
    - cron: '37 3 * * *'
  workflow_dispatch:
  push:
    branches: [main]
    paths:
      - 'tracking/**'
      - '.github/workflows/tracking.yml'
  pull_request:
    paths:
      - 'tracking/**'
      - '.github/workflows/tracking.yml'

permissions:
  contents: read

jobs:
  fixtures:
    runs-on: ubuntu-latest
    timeout-minutes: 3
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - run: python3 -m unittest discover -s tracking -p 'test_*.py' -v

  monitor:
    needs: fixtures
    if: github.event_name != 'pull_request' && github.ref_name == github.event.repository.default_branch
    runs-on: ubuntu-latest
    timeout-minutes: 8
    permissions:
      contents: write
    concurrency:
      group: legislative-tracking-history
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v4
      - name: Open the tracking journal
        shell: bash
        run: |
          set -euo pipefail
          journal="$RUNNER_TEMP/legislative-journal"
          branch=tracking-history
          existing=$(git ls-remote --heads origin "refs/heads/$branch")
          if [[ -n "$existing" ]]; then
            git fetch --depth=1 origin "refs/heads/$branch"
            git worktree add --detach "$journal" FETCH_HEAD
          else
            git worktree add --orphan -b "$branch" "$journal"
          fi
          echo "JOURNAL=$journal" >> "$GITHUB_ENV"
      - name: Fetch official listings
        id: observe
        continue-on-error: true
        run: python3 tracking/track.py "$JOURNAL"
      - name: Commit observations and source failures
        shell: bash
        run: |
          set -euo pipefail
          cd "$JOURNAL"
          git add -A
          if ! git diff --cached --quiet; then
            git -c user.name='Legislative monitor' -c user.email='41898282+github-actions[bot]@users.noreply.github.com' commit -m "Record legislative listing observations ($GITHUB_RUN_ID)"
            git push origin HEAD:refs/heads/tracking-history
          fi
      - name: Surface source failures
        if: steps.observe.outcome == 'failure'
        run: exit 1

Verify Workflow

A GitHub Actions workflow in Legislation. Runs on push, on pull requests and by hand.

automationlegislation / .github/workflows/verify.yml · lines 1–50 of 50 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Verify legislative evidence”; runs Verify (`tools/verify.py`), Verify Catalogue (`data/verify_catalogue.py`) and Legal (`engine/legal.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
legislation · .github/workflows · workflow
Uses
Verify (workflow run), Verify Catalogue (workflow run), Legal (workflow run), Screen (workflow run), Verify Registry (workflow run), Browser Acceptance (workflow run)
Used by
none found
Produces
none declared
Defines here
Verify legislative evidence
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 .github/workflows/verify.yml:1-50 · blob 3388db31076c7df517b76ced1f3a4558c97732f4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: Verify legislative evidence
on: [push, pull_request, workflow_dispatch]
permissions:
  contents: read
jobs:
  verify:
    runs-on: ubuntu-latest
    timeout-minutes: 8
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: python tools/verify.py
      - run: python data/verify_catalogue.py
      - name: Replay the bundled Act and recover a single paragraph
        shell: bash
        run: |
          db="$RUNNER_TEMP/legislation.sqlite"
          digest=$(python engine/legal.py bootstrap "$db")
          python engine/legal.py get "$db" "$digest" schedule/4/paragraph/6 --xml > "$RUNNER_TEMP/paragraph.xml"
          cmp "$RUNNER_TEMP/paragraph.xml" engine/wayleave-enacted.fragment.xml
      - run: node protections/screen.mjs .cvaa/contracts/legal-evidence.json protections/fixtures
      - name: Load the admitted CVAA legal vaccine
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
        with:
          repository: Ventusltd/cvaa
          ref: f14e8fa17d228f2b15fb48570907d9d295292720
          path: .cvaa/registry
          persist-credentials: false
          sparse-checkout-cone-mode: false
          sparse-checkout: |
            /vaccines.lock
            /vaccines/202611280012-legal-evidence-screening.md
            /tools/antibody-runner.mjs
      - name: Replay the registered antibody against the production receipt
        run: node protections/verify-registry.mjs .cvaa/registry .cvaa/contracts/legal-evidence.json
  reader:
    runs-on: ubuntu-24.04
    timeout-minutes: 8
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: pip install playwright==1.56.0
      - name: Check the reader in the runner's installed Chrome
        shell: bash
        run: |
          LEGISLATION_CHROMIUM="$(command -v google-chrome)" python legal-evidence/browser_acceptance.py

Test Replay

A test in the case folder of Legislation that checks Replay. It replays tests (`ReplayTests`).

testlegislation / case/replay/test_replay.py · lines 1–63 of 63 · Entry point

What it does
It tests its inputs. Defines 7 functions or classes, including ReplayTests, test_canonical_fixture_without_expected_answers, test_changed_evidence_refused_by_each_arm, test_changed_artifact_refused_before_cache_use, test_missing_and_ambiguous_dated_provision. Uses libraries copy, json, pathlib, unittest, unittest.mock. Side effects: reads or writes files.
Inputs & outputs
In: JSON file changed.json; JSON file receipt.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Offline regressions; the full historical Act is fetched only for benchmark replay.
Why it matters
Guards the behaviour of Replay.
Application
legislation · case/replay · test
Uses
Replay (import), copy, json, pathlib, unittest, unittest.mock, tempfile
Used by
none found
Produces
ReplayTests
Defines here
ReplayTests, test_canonical_fixture_without_expected_answers, test_changed_evidence_refused_by_each_arm, test_changed_artifact_refused_before_cache_use, test_missing_and_ambiguous_dated_provision, test_wrong_edition_or_bytes_rejected, test_receipt_scope
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 case/replay/test_replay.py:1-63 · blob 9395c4d0312c23715d06a26b465f1ed3d54d2e99 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Offline regressions; the full historical Act is fetched only for benchmark replay."""
import copy
import json
from pathlib import Path
import unittest
from unittest.mock import patch
from tempfile import TemporaryDirectory

import replay


class ReplayTests(unittest.TestCase):
    def test_canonical_fixture_without_expected_answers(self):
        case, question, _ = replay.fixtures()
        for derived in ('result', 'reason', 'unknowns'):
            del case[derived]
        full = replay.full_evidence(case, question)
        self.assertEqual(full, replay.selective_evidence(case, question))
        self.assertEqual(full['finding'], 'insufficient_evidence')
        self.assertEqual(full['missing_for_land_rights'], ['assessed licence', 'grant', 'signed easement'])

    def test_changed_evidence_refused_by_each_arm(self):
        case, question, _ = replay.fixtures()
        changed = copy.deepcopy(case)
        changed['facts'][1] = changed['facts'][1].replace('signed easement, ', '')
        for read in (replay.full_evidence, replay.selective_evidence):
            with self.assertRaises(ValueError):
                read(changed, question)
            with self.assertRaises(ValueError):
                read(case, {**question, 'evidence': {'signed easement': 'new'}})

    def test_changed_artifact_refused_before_cache_use(self):
        with TemporaryDirectory() as tmp:
            path = Path(tmp, 'changed.json')
            path.write_bytes(replay.CASE.read_bytes() + b' ')
            with patch.object(replay, 'CASE', path), self.assertRaises(ValueError):
                replay.fixtures()

    def test_missing_and_ambiguous_dated_provision(self):
        item = b'<p DocumentURI="one">first</p>'
        self.assertEqual(item, replay.full_scan(b'<a>' + item + b'</a>', 'one'))
        for payload in (b'<a/>', b'<a>' + 2 * item + b'</a>'):
            with self.assertRaises(ValueError):
                replay.full_scan(payload, 'one')

    def test_wrong_edition_or_bytes_rejected(self):
        with self.assertRaises(ValueError):
            replay.verify(b'other edition', replay.XML_SHA)
        with self.assertRaises(ValueError):
            replay.verify(b'changed passage', replay.FRAGMENT_SHA)
        with self.assertRaises(ValueError):
            replay.full_scan(b'<p DocumentURI="one">first</p>', 'other')

    def test_receipt_scope(self):
        receipt = json.loads(Path(replay.__file__).with_name('receipt.json').read_text())
        self.assertEqual(receipt['pointer_only'], {'pipeline_news_release': '202611232245', 'repd_reference': '12588'})
        self.assertEqual(receipt['result']['applicability'], 'unassessed')
        self.assertEqual(receipt['source_sha256'], replay.XML_SHA)
        self.assertEqual(receipt['passage_sha256'], replay.FRAGMENT_SHA)


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

Test Screen

A test in the contracts folder of Legislation that checks Screen. It sets up (`setUp`) and is built from the screening test class (`ScreeningTest`).

testlegislation / contracts/test_screen.py · lines 1–74 of 74 · Entry point

What it does
It tests its inputs. Defines 9 functions or classes, including ScreeningTest, setUp, test_fixture, test_two_gate_reference_truth_table, test_stale_proposed_wrong_territory_or_wrong_project. Uses libraries json, unittest, itertools, pathlib. Side effects: reads or writes files.
Inputs & outputs
In: JSON file fictional_solar.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Defines `ScreeningTest`, `setUp`, `test_fixture` and 6 more.
Why it matters
Guards the behaviour of Screen.
Application
legislation · contracts · test
Uses
Screen (import), json, unittest, itertools, pathlib
Used by
none found
Produces
ScreeningTest
Defines here
ScreeningTest, setUp, test_fixture, test_two_gate_reference_truth_table, test_stale_proposed_wrong_territory_or_wrong_project, test_conflicting_evidence, test_positive_appraisal_cannot_clear_unknowns, test_nearby_feature_alone, test_mislabelled_source_or_scope
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 contracts/test_screen.py:1-74 · blob 6010daad72974ce8ceaed879464464c6765fd0f2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
import json
import unittest
from itertools import product
from pathlib import Path

from screen import evaluate

HERE = Path(__file__).resolve().parent


class ScreeningTest(unittest.TestCase):
    def setUp(self):
        self.case = json.loads((HERE / "fictional_solar.json").read_text())

    def test_fixture(self):
        result = evaluate(self.case)
        self.assertEqual(result["unknowns"], ["electrical_capacity", "land"])
        self.assertEqual(result["result"], "insufficient_evidence")

    def test_two_gate_reference_truth_table(self):
        variants = ("unknown", "contradicted", "satisfied")
        reference = [
            "insufficient_evidence", "blocked", "insufficient_evidence",
            "blocked", "blocked", "blocked",
            "insufficient_evidence", "blocked", "screen_passed",
        ]
        for (land, capacity), expected in zip(product(variants, repeat=2), reference):
            self.case["evidence"][2]["state"] = land
            self.case["evidence"][5]["state"] = capacity
            result = evaluate(self.case)
            self.assertEqual(result["result"], expected)
            self.assertEqual(len(result["blockers"]), (land, capacity).count("contradicted"))
            self.assertEqual(len(result["unknowns"]), (land, capacity).count("unknown"))

    def test_stale_proposed_wrong_territory_or_wrong_project(self):
        row = self.case["evidence"][1]
        for field, value in [("through", "2026-11-27"), ("basis", "proposed"),
                             ("territory", "B"), ("project", "another project")]:
            self.case["evidence"][1] = dict(row, **{field: value})
            self.assertIn("planning", evaluate(self.case)["unknowns"])

    def test_conflicting_evidence(self):
        original = self.case["evidence"][1]
        self.case["evidence"].append(dict(original, source="fixture:second", state="contradicted"))
        result = evaluate(self.case)["ledger"]["planning"]
        self.assertEqual(result["state"], "unknown")
        self.assertTrue(result["conflict"])
        self.assertEqual(len(result["sources"]), 2)

    def test_positive_appraisal_cannot_clear_unknowns(self):
        result = evaluate(self.case)
        self.assertEqual(result["scenario_pv_gbp"]["delta"], "10.00")
        self.assertEqual(result["result"], "insufficient_evidence")
        self.case["annual_flows"][1]["option"] = None
        self.assertIsNone(evaluate(self.case)["scenario_pv_gbp"]["delta"])
        self.case["annual_flows"][1]["unit"] = "GBP nominal"
        with self.assertRaisesRegex(ValueError, "price basis"):
            evaluate(self.case)

    def test_nearby_feature_alone(self):
        self.case["evidence"] = self.case["evidence"][:1]
        self.assertEqual(len(evaluate(self.case)["unknowns"]), 5)

    def test_mislabelled_source_or_scope(self):
        self.case["evidence"][1]["gate"] = "land"
        with self.assertRaises(ValueError):
            evaluate(self.case)
        self.case["scope"] = "live asset"
        with self.assertRaisesRegex(ValueError, "fictional"):
            evaluate(self.case)


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

Test Register

A test in the diary folder of Legislation. It registers test (`RegisterTest`).

testlegislation / diary/test_register.py · lines 1–12 of 12 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines RegisterTest, test_all_reviewed_repositories_have_pinned_readmes. Uses libraries json, pathlib, unittest. Side effects: reads or writes files.
Inputs & outputs
In: JSON file repositories.json.
What it achieves
Defines `RegisterTest` and `test_all_reviewed_repositories_have_pinned_readmes`.
Why it matters
No other file in the estate was found to import it.
Application
legislation · diary · test
Uses
json, pathlib, unittest
Used by
none found
Produces
RegisterTest
Defines here
RegisterTest, test_all_reviewed_repositories_have_pinned_readmes
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 diary/test_register.py:1-12 · blob 0bfd1967b88bfdcefeb0074fe944e90f0fc847a3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
import json
from pathlib import Path
import unittest


class RegisterTest(unittest.TestCase):
    def test_all_reviewed_repositories_have_pinned_readmes(self):
        rows = json.loads(Path(__file__).with_name("repositories.json").read_bytes())
        self.assertEqual(len({r["repository"] for r in rows}), 10)
        for row in rows:
            self.assertRegex(row["reviewed_commit"], "^[0-9a-f]{40}$")
            self.assertTrue(row["readme"].endswith("/" + row["reviewed_commit"] + "/README.md"))

Test Compare

A test in the editions folder of Legislation that checks Compare. It is built from the edition tests class (`EditionTests`).

testlegislation / editions/test_compare.py · lines 1–21 of 21 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines EditionTests, test_real_historical_editions, test_reject_changed_input, test_reject_unrelated_provisions. Uses libraries json, pathlib, unittest. Side effects: reads or writes files.
Inputs & outputs
In: JSON file receipt.json.
What it achieves
Defines `EditionTests`, `test_real_historical_editions`, `test_reject_changed_input` and 1 more.
Why it matters
Guards the behaviour of Compare.
Application
legislation · editions · test
Uses
Compare (import), json, pathlib, unittest
Used by
none found
Produces
EditionTests
Defines here
EditionTests, test_real_historical_editions, test_reject_changed_input, test_reject_unrelated_provisions
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 editions/test_compare.py:1-21 · blob e92c7df6717a1b3b9abb42751267a63447467759 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
import json
from pathlib import Path
import unittest

from compare import compare, read_edition, replay


class EditionTests(unittest.TestCase):
    def test_real_historical_editions(self):
        expected = json.loads(Path(__file__).with_name("receipt.json").read_bytes())
        self.assertEqual(replay(), expected)
        self.assertEqual(expected[0]["changed_block_ranges"], [])
        self.assertEqual(len(expected[1]["changed_block_ranges"]), 3)

    def test_reject_changed_input(self):
        with self.assertRaisesRegex(ValueError, "digest"):
            read_edition(Path(__file__).with_name("manifest.json"), "0" * 64)

    def test_reject_unrelated_provisions(self):
        with self.assertRaisesRegex(ValueError, "one provision"):
            compare({"provision": "/A"}, {"provision": "/B"})

Test Legal

A test in the engine folder of Legislation that checks Legal. It sets up (`setUp`) and is built from the retrieval class (`Retrieval`).

testlegislation / engine/test_legal.py · lines 1–92 of 92 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines 12 functions or classes, including Retrieval, setUp, test_exact_multibyte_nested_and_empty, test_unknown_does_not_return_parent, test_digest_pinned_through_reimport. Uses libraries json, pathlib, sqlite3, sys, unittest. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file catalogue.json; JSON file benchmark-receipt.json; SQLite database.
What it achieves
Defines `Retrieval`, `setUp`, `test_exact_multibyte_nested_and_empty` and 9 more.
Why it matters
Guards the behaviour of Legal.
Application
legislation · engine · test
Uses
Legal (import), json, pathlib, sqlite3, sys, unittest
Used by
none found
Produces
Retrieval
Defines here
Retrieval, setUp, test_exact_multibyte_nested_and_empty, test_unknown_does_not_return_parent, test_digest_pinned_through_reimport, test_source_mismatch_and_duplicate_identity_atomic, test_catalogue_identifiers_and_dated_snapshots, test_regnal_refuses_false_identity_and_partial_document, test_corruption, test_indexed_terms, test_search, test_golden_excerpt
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 engine/test_legal.py:1-92 · blob 13bae1309e5c164e76913b6a9aa0ec65eb767253 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: unknown · users: none · canonical: unreached_review
import json
from pathlib import Path
import sqlite3
import sys
import unittest

sys.path.insert(0,str(Path(__file__).resolve().parent))
from legal import get, ingest, search, sha

BASE = 'https://www.legislation.gov.uk'
ID = 'ukpga/1989/29'
URL = f'{BASE}/{ID}/enacted/data.xml'
DATE = '2026-11-28'
CHILD = f'<P2 IdURI="{BASE}/id/{ID}/section/1/1" DocumentURI="{BASE}/{ID}/section/1/1/enacted"/>'
SECTION = f'<P1 IdURI="{BASE}/id/{ID}/section/1" DocumentURI="{BASE}/{ID}/section/1/enacted"><Text test=">">A £1 fixture.</Text>{CHILD}</P1>'
META = f'<m:Metadata xmlns:m="http://www.legislation.gov.uk/namespaces/metadata"><a:link xmlns:a="http://www.w3.org/2005/Atom" rel="self" href="{URL}"/></m:Metadata>'
XML = f'<Legislation xmlns="http://www.legislation.gov.uk/namespaces/legislation" DocumentURI="{URL[:-9]}" IdURI="{BASE}/id/{ID}">{META}{SECTION}</Legislation>'.encode()


class Retrieval(unittest.TestCase):
    def setUp(self):
        self.db = sqlite3.connect(':memory:')
        self.addCleanup(self.db.close)
        self.digest = ingest(self.db,XML,URL,DATE)

    def test_exact_multibyte_nested_and_empty(self):
        for locator, expected in [('section/1',SECTION),('section/1/1',CHILD),('',XML.decode())]:
            data, receipt = get(self.db,self.digest,locator)
            self.assertEqual(data,expected.encode())
            self.assertEqual(receipt['provision_sha256'],sha(data))
            self.assertEqual(receipt['applicability'],'unassessed')

    def test_unknown_does_not_return_parent(self):
        with self.assertRaises(LookupError):
            get(self.db,self.digest,'section/1/2')

    def test_digest_pinned_through_reimport(self):
        ingest(self.db,XML,URL,'2026-11-29')
        altered = ingest(self.db,XML.replace(b'fixture',b'example'),URL,DATE)
        self.assertNotEqual(altered,self.digest)
        old, receipt = get(self.db,self.digest,'section/1')
        self.assertEqual(receipt['retrieved_dates'],[DATE,'2026-11-29'])
        self.assertEqual(old,SECTION.encode())

    def test_source_mismatch_and_duplicate_identity_atomic(self):
        for data,url in [(XML,URL.replace('enacted','2020-01-01')),
                         (XML.replace(SECTION.encode(),SECTION.encode()*2),URL),
                         (b'<!DOCTYPE Legislation>'+XML,URL)]:
            with self.assertRaises((sqlite3.IntegrityError,ValueError)):
                ingest(self.db,data,url,DATE)
        self.assertEqual(self.db.execute('SELECT count(*) FROM snapshots').fetchone()[0],1)

    def test_catalogue_identifiers_and_dated_snapshots(self):
        catalogue = Path(__file__).resolve().parents[1] / 'data/catalogue.json'
        for record in json.loads(catalogue.read_text()):
            with self.subTest(instrument=record['id']):
                url = URL.replace(ID,record['id']).replace('enacted','2024-01-01')
                xml = XML.replace(ID.encode(),record['id'].encode()).replace(b'enacted',b'2024-01-01')
                digest = ingest(self.db,xml,url,DATE)
                _, receipt = get(self.db,digest,'section/1')
                self.assertEqual((receipt['instrument'],receipt['version']),(record['id'],'2024-01-01'))

    def test_regnal_refuses_false_identity_and_partial_document(self):
        for identity in ['ukpga/Geo5/15-16/20/section/1','ukpga/Wrong/15-16/20','uksi/Geo5/15-16/20']:
            with self.subTest(identity=identity), self.assertRaises(ValueError):
                ingest(self.db, XML.replace(ID.encode(),identity.encode()), URL.replace(ID,identity), DATE)
        partial = XML.replace(URL.encode(), URL.replace('/enacted/data.xml','/introduction/enacted/data.xml').encode())
        for xml in [partial, XML.replace(META.encode(), b'')]:
            with self.assertRaisesRegex(ValueError, 'self link'):
                ingest(self.db, xml, URL, DATE)

    def test_corruption(self):
        self.db.execute('UPDATE snapshots SET xml=?',(XML.replace(b'fixture',b'failure'),))
        with self.assertRaises(ValueError):
            get(self.db,self.digest,'section/1')

    def test_indexed_terms(self):
        rows=self.db.execute("SELECT locator FROM terms WHERE terms MATCH ?",('"fixture"',)).fetchall()
        self.assertEqual(rows,[('section/1',)])

    def test_search(self):
        base=dict(id=ID,title='Electricity Act 1989',subjects=['wayleaves'],jurisdiction='unknown',
                  status='unassessed',enactment_date='1989-07-27',source_url=URL)
        self.assertEqual(search([base],ID)[0]['match'],'exact_reference')
        self.assertEqual(search([base],'wayleaves',dated='1989-07-27')[0]['match'],'keyword')
        self.assertEqual(search([base],'Electricity',jurisdiction='NI'),[])
        self.assertEqual(search([base],'Electricity',status='in force'),[])

    def test_golden_excerpt(self):
        root=Path(__file__).parent
        expected=json.loads((root/'benchmark-receipt.json').read_text())['receipt']
        self.assertEqual(expected['provision_sha256'],sha((root/'wayleave-enacted.fragment.xml').read_bytes()))

Test

A JavaScript module in the protections folder of Legislation that tests healthy and diseases, using SHA-256.

testlegislation / protections/test.mjs · lines 1–40 of 40 · pattern fresh (shared by 10 files)

What it does
It tests healthy and diseases. Defines fixture, fresh. Uses libraries node:assert/strict, node:test, node:fs, node:url, node:path. Side effects: reads or writes files.
Inputs & outputs
In: JSON file healthy.json; JSON file diseases.json.
Downstream impact
Used directly by 1 file: Verify (legislation). Reached from 1 other entry point, including Verify Workflow (legislation).
What it achieves
Defines `fixture` and `fresh`.
Why it matters
Run by Verify.
Application
legislation · protections · JavaScript module
Uses
Screen (import), node:assert/strict, node:test, node:fs, node:url, node:path, node:os
Used by
run by Verify (script call)
Produces
fixture, fresh
Defines here
fixture, fresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 protections/test.mjs:1-40 · blob 31fcf7b2ec472196a4dc6acc355785ee6f107bd5 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { readFileSync, writeFileSync, rmSync, mkdtempSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { check } from './screen.mjs';

const source = fileURLToPath(new URL('./fixtures/', import.meta.url));
const fixture = name => JSON.parse(readFileSync(join(source, name)));
const fresh = () => fixture('healthy.json');

test('synthetic support is internally consistent', () => assert.deepEqual(check(fresh(), source), []));
test('documented uncertainty stays unresolved', () => {
  const receipt = fresh();
  receipt.claim = {result: 'unresolved', open_questions: ['Territorial commencement evidence is absent.']};
  receipt.evidence = {};
  assert.deepEqual(check(receipt, source), []);
});
for (const [part, key, replacement, expected] of fixture('diseases.json')) {
  test(`${expected} rejects ${part}.${key} = ${JSON.stringify(replacement)}`, () => {
    const receipt = fresh();
    receipt[part][key] = replacement;
    assert.ok(check(receipt, source).includes(expected));
  });
}
test('unknown source bytes and damaged bytes fail independently', () => {
  const directory = mkdtempSync(join(tmpdir(), 'legal-screen-'));
  try {
    const receipt = fresh();
    assert.deepEqual(check(receipt, directory), ['source-missing']);
    writeFileSync(join(directory, receipt.evidence.sha256), 'damaged');
    assert.deepEqual(check(receipt, directory), ['source-corrupted']);
  } finally { rmSync(directory, {recursive: true, force: true}); }
});
test('unchanged historical identity with replacement bytes fails', () => {
  const old = fresh();
  old.evidence.sha256 = 'a'.repeat(64);
  assert.deepEqual(check(fresh(), source, old), ['historical-bytes-changed']);
});

Verify

A Python module in the tools folder of Legislation that runs each suite in its own directory, then check repository-level references.

renderlegislation / tools/verify.py · lines 1–17 of 17 · Entry point

What it does
Uses libraries json, pathlib, subprocess, sys. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Downstream impact
Used directly by 1 file: Verify Workflow (legislation).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by Verify Workflow.
Application
legislation · tools · Python module
Uses
Test (script call), Verify Ia6 (script call), json, pathlib, subprocess, sys
Used by
run by Verify Workflow (workflow run)
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
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 tools/verify.py:1-17 · blob 88b55cdd8a9e8c2fd04614786ae0680d99742a1f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Run each suite in its own directory, then check repository-level references."""
import json
from pathlib import Path
import subprocess
import sys

root = Path(__file__).resolve().parents[1]
tests = sorted(root.rglob("test_*.py"))
if not tests:
    sys.exit("No regression tests found")
for directory in sorted({test.parent for test in tests}):
    subprocess.run([sys.executable, "-B", "-m", "unittest", "discover", "-v"], cwd=directory, check=True)
subprocess.run(["node", "--test", "protections/test.mjs"], cwd=root, check=True)
subprocess.run([sys.executable, "case/verify_ia6.py"], cwd=root, check=True)
for document in sorted(root.rglob("*.json")):
    json.loads(document.read_bytes())
print(f"Verified {len(tests)} test modules and repository JSON syntax.")

Backfill Lightning Workflow

A GitHub Actions workflow. Runs by hand.

automationlightning / .github/workflows/backfill-lightning.yml · lines 1–167 of 167 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “UK lightning archive backfill”; runs History (`history.py`), Collect (`collect.py`) and Status (`status.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
lightning · .github/workflows · workflow
Uses
Test Backfill (workflow run), Test Backfill Parallel (workflow run), Test Backfill Workflow (workflow run), Test CI Verify (workflow run), Test Collect (workflow run), Test Collector Health (workflow run), Test Concurrent Writers (workflow run), Test Download Retries (workflow run), and 19 more
Used by
none found
Produces
none declared
Defines here
UK lightning archive backfill
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 .github/workflows/backfill-lightning.yml:1-167 · blob 2e7fa578d34872c33dedee5fc453730f343d0350 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: UK lightning archive backfill
# Manual only. Fills UTC dates the archive index marks NEVER SEARCHED
# (coverage none / count null, not shard_lost) from a fresh, independent
# whole-day EUMETSAT search per date, newest first. A date is only ever
# filled with the examined 10-minute slots of that search: gaps stay unknown,
# never zero. See docs/HISTORY_ONE_YEAR.md, "Backfill".
on:
  workflow_dispatch:
    inputs:
      end_date:
        description: "Newest UTC date to consider (YYYY-MM-DD). Empty = yesterday UTC."
        default: ""
        required: false
      days:
        description: "UTC dates to consider back from end_date (1-31). Only never-searched dates are searched."
        default: "7"
        required: false
      dry_run:
        description: "Only list the dates that would be searched: no EUMETSAT calls, no commit."
        type: boolean
        default: false

permissions:
  contents: write

# Its OWN group, never the hourly `uk-lightning-update`: a backfill runs for
# up to ~3.5 h and, while it shared the hourly group, the hourly feed queued
# behind it (27 Oct 2026: run 40476905747 waited 91 min behind backfill
# 40464739813). Two backfills still never overlap. The hourly job and a
# backfill may now run at the same time; both commit with
# ci/push-with-replay.sh, which on a rejected push resets to the new main and
# re-applies this run's dates from the saved run records (no textual merge of
# index.json or status.json).
concurrency:
  group: uk-lightning-backfill
  cancel-in-progress: false

jobs:
  backfill:
    runs-on: ubuntu-latest
    timeout-minutes: 300
    env:
      # Stop starting new dates after this many minutes so the run always ends
      # (and commits what it verified) well inside timeout-minutes.
      BACKFILL_BUDGET_MINUTES: "200"
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: "pip"
      - run: pip install -r requirements.txt
      - name: Test pure-Python data contracts
        run: python -m unittest discover -s tests -v

      # 1. Plan: never-searched dates of the committed index, newest first.
      #    Refuses days outside 1-31, an end_date that is today or later, or a
      #    missing index (the hourly job creates the archive and its seed first).
      - name: Plan never-searched UTC dates
        id: plan
        env:
          END_DATE: ${{ inputs.end_date }}
          DAYS: ${{ inputs.days }}
        run: |
          python history.py backfill-plan --archive-dir data/history \
            --end-date "$END_DATE" --days "$DAYS" > "$RUNNER_TEMP/backfill-plan.txt"
          echo "Never-searched UTC dates to search (newest first):"
          cat "$RUNNER_TEMP/backfill-plan.txt"
          echo "count=$(grep -c . "$RUNNER_TEMP/backfill-plan.txt" || true)" >> "$GITHUB_OUTPUT"

      # 2. Per date: independent whole-day search (run record only, never the
      #    feed), then a gated ingest + verify on a staging copy that replaces
      #    data/history only when both succeed. The first EUMETSAT error (rate
      #    limit, outage, no products) or archive refusal stops the loop; every
      #    later date stays never searched (unknown, not zero).
      - name: Search and ingest each date
        id: backfill
        if: ${{ !inputs.dry_run && steps.plan.outputs.count != '0' }}
        env:
          EUMETSAT_CONSUMER_KEY: ${{ secrets.EUMETSAT_CONSUMER_KEY }}
          EUMETSAT_CONSUMER_SECRET: ${{ secrets.EUMETSAT_CONSUMER_SECRET }}
        run: |
          if [ "$GITHUB_REF" != "refs/heads/main" ]; then
            echo "::error::A backfill writes the archive and must run on main (got $GITHUB_REF); use dry_run elsewhere."
            exit 1
          fi
          started=$(date +%s)
          budget=$(( ${BACKFILL_BUDGET_MINUTES:-200} * 60 ))
          stopped=completed
          error=""
          : > "$RUNNER_TEMP/backfill-filled.txt"
          # Children get /dev/null as stdin: the loop itself reads the plan file.
          while read -r D; do
            [ -n "$D" ] || continue
            if [ $(( $(date +%s) - started )) -ge "$budget" ]; then
              stopped=time_budget
              break
            fi
            rec="$RUNNER_TEMP/rb-$D.json"
            if ! python collect.py --rebuild-day "$D" --run-record "$rec" < /dev/null 2> "$RUNNER_TEMP/rb-$D.log"; then
              cat "$RUNNER_TEMP/rb-$D.log" >&2
              stopped=eumetsat_error
              error="$D: $(tail -n 1 "$RUNNER_TEMP/rb-$D.log")"
              break
            fi
            cat "$RUNNER_TEMP/rb-$D.log" >&2
            if ! python history.py backfill --archive-dir data/history --day "$D" --rebuild-record "$rec" \
                 --result-out "$RUNNER_TEMP/bf-$D.json" < /dev/null 2> "$RUNNER_TEMP/bf-$D.log"; then
              cat "$RUNNER_TEMP/bf-$D.log" >&2
              stopped=archive_refused
              error="$D: $(tail -n 1 "$RUNNER_TEMP/bf-$D.log")"
              break
            fi
            cat "$RUNNER_TEMP/bf-$D.log" >&2
            echo "$D" >> "$RUNNER_TEMP/backfill-filled.txt"
          done < "$RUNNER_TEMP/backfill-plan.txt"
          python status.py backfill --status data/status.json \
            --plan "$RUNNER_TEMP/backfill-plan.txt" --filled "$RUNNER_TEMP/backfill-filled.txt" \
            --stopped "$stopped" --error "$error" --archive-dir data/history
          echo "stopped=$stopped" >> "$GITHUB_OUTPUT"
          echo "filled=$(grep -c . "$RUNNER_TEMP/backfill-filled.txt" || true)" >> "$GITHUB_OUTPUT"
          {
            echo "error<<BACKFILL_EOF"
            echo "$error"
            echo "BACKFILL_EOF"
          } >> "$GITHUB_OUTPUT"

      # 3. One commit per run: verify the whole archive first (nothing
      #    unverified is committed), then commit data/history + data/status.json.
      - name: Verify and commit backfilled dates (one commit)
        if: ${{ steps.backfill.outcome == 'success' }}
        env:
          STOPPED: ${{ steps.backfill.outputs.stopped }}
          ERROR: ${{ steps.backfill.outputs.error }}
          # Quick verify of the staged data before every push attempt (also after a replay).
          PUSH_VERIFY: python ci/verify_data.py --staged
        run: |
          python history.py verify --archive-dir data/history
          filled=$(grep -c . "$RUNNER_TEMP/backfill-filled.txt" || true)
          range=$(paste -sd, "$RUNNER_TEMP/backfill-filled.txt")
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          # On a rejected push (the hourly job committed meanwhile) the helper
          # resets to the new main and replays every filled date from its saved
          # run record; a date the hourly job has since searched is skipped.
          PUSH_BODY="Dates: ${range:-none}. Stopped: ${STOPPED}." \
            bash ci/push-with-replay.sh \
              "data: backfill ${filled} never-searched UTC day(s) of the one-year archive" \
              'bash ci/replay-backfill.sh' \
              data/status.json data/history

      # 4. A stop on an EUMETSAT error or an archive refusal turns the run red
      #    AFTER the verified dates were committed; a time-budget stop warns.
      - name: Surface backfill stop
        if: ${{ always() && steps.backfill.outcome != 'skipped' }}
        env:
          STOPPED: ${{ steps.backfill.outputs.stopped }}
          ERROR: ${{ steps.backfill.outputs.error }}
          OUTCOME: ${{ steps.backfill.outcome }}
        run: |
          case "$STOPPED" in
            completed) echo "Backfill completed" ;;
            time_budget) echo "::warning::Backfill stopped at the time budget; remaining dates stay never searched. Run again." ;;
            *)
              echo "::error::Backfill stopped (${STOPPED:-step $OUTCOME}): $ERROR. Remaining dates stay never searched (unknown, not zero)."
              exit 1 ;;
          esac