In this section
- Legal render · legislation / engine/legal.py lines 1–254
- Browser Acceptance render · legislation / legal-evidence/browser_acceptance.py lines 1–89
- Legislation — Legal Evidence Page render · legislation / legal-evidence/index.html lines 1–50
- Reader render · legislation / legal-evidence/reader.css lines 1–34
- Reader interaction · legislation / legal-evidence/reader.js lines 1–198
- Legal Evidence transform · legislation / protections/legal-evidence.mjs lines 1–35
- Screen ingest · legislation / protections/screen.mjs lines 1–29
Legal
A Python command-line tool in the engine folder of Legislation that reads catalogue and benchmark receipt, using SHA-256.
renderlegislation / engine/legal.py · lines 1–254 of 254 · Entry point · pattern ingest (shared by 9 files)
- What it does
- It loads catalogue and benchmark receipt. Defines 12 functions or classes, including sha, official_path, tag_end, locate, start_element. Uses libraries argparse, datetime, gzip, hashlib, json. Side effects: changes the web page (DOM); 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; command-line arguments.
- Downstream impact
- Used directly by 4 files: Verify Workflow (legislation); Test Legal (legislation); Replay (legislation); Benchmark (legislation). Reached from 1 other entry point, including Test Replay (legislation).
- What it achieves
- It starts element (`start_element`) and is built from the sha step (`sha`) and the official path helper (`official_path`). Exact byte-range retrieval for publisher-identified CLML provisions. It accepts `--catalogue` and `--xml`.
- Why it matters
- Imported by Replay and Benchmark. Run by Verify Workflow. Checked by Test Legal.
- Application
- legislation · engine · Python CLI
- Uses
- argparse, datetime, gzip, hashlib, json, pathlib, re, sqlite3
- Used by
- run by Verify Workflow (workflow run), imported by Test Legal (import), imported by Replay (sys.path import), imported by Benchmark (import)
- Produces
- sha, official_path, tag_end, locate, ingest, get, search, main
- Defines here
- sha, official_path, tag_end, locate, start_element, end_element, reject_doctype, characters, ingest, get, search, main
- 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/legal.py:1-254 · blob 25eb6f006e899caebc836afcf18e7fd5b2e4edb1 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: unknown · users: none · canonical: unknown
"""Exact byte-range retrieval for publisher-identified CLML provisions. Python >=3.11."""
import argparse
from datetime import date
import gzip
import hashlib
import json
from pathlib import Path
import re
import sqlite3
import sys
from urllib.parse import urlsplit
from xml.parsers import expat
ROOT = Path(__file__).resolve().parents[1]
MODERN_ID = r'/id/[a-z]+/[0-9]{4}/[0-9]+'
REGNAL_ID = r'/id/ukpga/(?:Geo5|Eliz2)/[1-9][0-9]?(?:-[1-9][0-9]?)?/[1-9][0-9]*'
METADATA = 'http://www.legislation.gov.uk/namespaces/metadata Metadata'
ATOM_LINK = 'http://www.w3.org/2005/Atom link'
SCHEMA = """
CREATE TABLE IF NOT EXISTS snapshots(digest TEXT UNIQUE NOT NULL, instrument TEXT NOT NULL,
version TEXT NOT NULL, source_url TEXT NOT NULL, xml BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS observations(digest TEXT, retrieved TEXT, PRIMARY KEY(digest,retrieved));
CREATE TABLE IF NOT EXISTS provisions(digest TEXT, locator TEXT, source_url TEXT NOT NULL,
start INTEGER NOT NULL, size INTEGER NOT NULL, sha256 TEXT NOT NULL,
PRIMARY KEY(digest,locator));
CREATE VIRTUAL TABLE IF NOT EXISTS terms USING fts5(digest UNINDEXED,locator UNINDEXED,body);
"""
def sha(data):
return hashlib.sha256(data).hexdigest()
def official_path(url):
parts = urlsplit(url)
if parts.scheme not in ('http', 'https') or parts.netloc != 'www.legislation.gov.uk' or parts.query or parts.fragment:
raise ValueError(f'unsupported official identifier: {url}')
return parts.path
def tag_end(data, start):
quoted = None
for offset in range(start + 1, len(data)):
b = data[offset]
if b == quoted:
quoted = None
elif quoted is None:
if b in (34, 39):
quoted = b
elif b == 62:
return offset + 1
raise ValueError('unterminated element')
def locate(data, source_url):
parser = expat.ParserCreate(namespace_separator=' ')
stack = []
rows = []
owners = []
terms = []
instrument = version = None
source_path = official_path(source_url)
self_links = []
in_metadata = False
def start_element(name, attrs):
nonlocal instrument, version, in_metadata
if len(stack) == 1 and name == METADATA:
in_metadata = True
if in_metadata and len(stack) == 2 and name == ATOM_LINK and attrs.get('rel') == 'self':
self_links.append(official_path(attrs['href']))
if not stack:
if name != 'http://www.legislation.gov.uk/namespaces/legislation Legislation':
raise ValueError('expected UK legislation XML')
identity = official_path(attrs['IdURI'])
if not (re.fullmatch(MODERN_ID, identity) or re.fullmatch(REGNAL_ID, identity)):
raise ValueError('unsupported instrument identity')
instrument = identity.removeprefix('/id/')
document = official_path(attrs['DocumentURI'])
if source_path != document + '/data.xml':
raise ValueError('source and XML manifestation disagree')
version = document.removeprefix('/' + instrument).lstrip('/') or 'revised-undated'
if document != '/' + instrument and document != '/' + instrument + '/' + version:
raise ValueError('source document identity mismatch')
if version not in ('enacted','made','revised-undated'):
if date.fromisoformat(version).isoformat() != version:
raise ValueError('dated manifestation must use YYYY-MM-DD')
identity = attrs.get('IdURI')
record = None
if identity and attrs.get('DocumentURI'):
path = official_path(identity)
prefix = '/id/' + instrument
if path == prefix or path.startswith(prefix + '/'):
locator = path[len(prefix):].lstrip('/')
url = attrs['DocumentURI']
destination = official_path(url)
expected = path.removeprefix('/id')
if version != 'revised-undated':
expected += '/' + version
if destination != expected:
raise ValueError('provision source path disagrees with its version or identity')
begin = parser.CurrentByteIndex
end = tag_end(data, begin)
record = locator, url.replace('http://', 'https://', 1), begin, end
owners.append((locator, []))
stack.append(record)
def end_element(name):
nonlocal in_metadata
if len(stack) == 2 and name == METADATA:
in_metadata = False
record = stack.pop()
if record:
owner, chunks = owners.pop()
words = ' '.join(''.join(chunks).split())
if words and owner:
terms.append((owner, words))
locator, url, begin, end = record
if data[end-2:end] != b'/>':
end = tag_end(data, parser.CurrentByteIndex)
rows.append((locator, url, begin, end-begin, sha(memoryview(data)[begin:end])))
def reject_doctype(*_args):
raise ValueError('DTD unsupported')
def characters(value):
if owners:
owners[-1][1].append(value)
parser.CharacterDataHandler = characters
parser.StartElementHandler = start_element
parser.EndElementHandler = end_element
parser.StartDoctypeDeclHandler = reject_doctype
parser.Parse(data, True)
if self_links != [source_path]:
raise ValueError('publisher self link does not identify the supplied complete XML manifestation')
return instrument, version, rows, terms
def ingest(db, data, url, retrieved):
day = date.fromisoformat(retrieved).isoformat()
digest = sha(data)
db.executescript(SCHEMA)
with db:
db.execute('BEGIN IMMEDIATE')
previous = db.execute('SELECT source_url FROM snapshots WHERE digest=?', (digest,)).fetchone()
if previous and previous[0] != url:
raise ValueError('source differs from registered manifestation')
if not previous:
instrument, version, rows, terms = locate(data, url)
db.execute('INSERT INTO snapshots VALUES(?,?,?,?,?)', (digest, instrument, version, url, data))
db.executemany('INSERT INTO provisions VALUES(?,?,?,?,?,?)', ((digest, *row) for row in rows))
db.executemany('INSERT INTO terms VALUES(?,?,?)', ((digest, *term) for term in terms))
db.execute('INSERT OR IGNORE INTO observations VALUES(?,?)', (digest, day))
return digest
def get(db, digest, locator):
row = db.execute("""SELECT s.rowid,s.instrument,s.version,s.source_url,p.source_url,p.start,p.size,p.sha256
FROM provisions p JOIN snapshots s ON p.digest=s.digest WHERE p.digest=? AND p.locator=?""",
(digest, locator)).fetchone()
if row is None:
raise LookupError('exact provision and source digest absent')
rowid, instrument, version, source, uri, start, size, expected = row
with db.blobopen('snapshots','xml',rowid,readonly=True) as stream:
stream.seek(start)
data = stream.read(size)
if sha(data) != expected:
raise ValueError('provision digest mismatch')
days = [x[0] for x in db.execute('SELECT retrieved FROM observations WHERE digest=? ORDER BY retrieved',(digest,))]
receipt = dict(instrument=instrument, version=version, locator=locator, document_url=source,
provision_url=uri, document_sha256=digest, provision_sha256=expected,
retrieved_dates=days, byte_offset=start, logical_bytes=size, applicability='unassessed')
return data, receipt
def search(records, query, jurisdiction=None, status=None, dated=None):
results = []
for record in records:
if jurisdiction and jurisdiction.casefold() not in json.dumps(record['jurisdiction']).casefold():
continue
if status and status.casefold() != str(record['status']).casefold():
continue
if dated and dated not in [str(value) for key,value in record.items() if 'date' in key or key=='year']:
continue
exact = query.casefold() in (record['id'].casefold(), record['title'].casefold())
haystack = json.dumps(record, ensure_ascii=False).casefold()
if exact or all(word in haystack for word in query.casefold().split()):
results.append(dict(match='exact_reference' if exact else 'keyword', record=record))
return sorted(results, key=lambda result:(result['match'],result['record']['id']))
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='cmd', required=True)
find = sub.add_parser('search')
find.add_argument('query')
find.add_argument('--catalogue',type=Path,default=ROOT/'data/catalogue.json')
for name in ('jurisdiction','status','date'):
find.add_argument('--'+name)
capture = sub.add_parser('ingest')
capture.add_argument('db')
capture.add_argument('xml',type=Path)
capture.add_argument('source_url')
capture.add_argument('retrieved_date')
lookup = sub.add_parser('terms',help='find literal words within captured provisions')
lookup.add_argument('db')
lookup.add_argument('document_sha256')
lookup.add_argument('query')
example = sub.add_parser('bootstrap', help='index the bundled enacted Electricity Act archive')
example.add_argument('db')
read = sub.add_parser('get')
read.add_argument('db')
read.add_argument('document_sha256')
read.add_argument('locator')
read.add_argument('--xml',action='store_true',help='write exact XML fragment bytes to stdout')
args = parser.parse_args()
if args.cmd == 'search':
print(json.dumps(search(json.loads(args.catalogue.read_text()),args.query,args.jurisdiction,args.status,args.date),indent=2))
return
if args.cmd == 'bootstrap':
folder = Path(__file__).resolve().parent
known = json.loads((folder/'benchmark-receipt.json').read_text())['receipt']
with gzip.open(folder/'electricity-1989-enacted.xml.gz', 'rb') as source:
data = source.read()
if sha(data) != known['document_sha256']:
raise ValueError('archive digest mismatch')
with sqlite3.connect(args.db) as db:
print(ingest(db, data, known['document_url'], known['retrieved_dates'][0]))
return
if args.cmd == 'ingest':
with sqlite3.connect(args.db) as db:
print(ingest(db,args.xml.read_bytes(),args.source_url,args.retrieved_date))
return
with sqlite3.connect(Path(args.db).resolve().as_uri()+'?mode=ro',uri=True) as db:
if args.cmd == 'terms':
words = args.query.split()
if not words:
parser.error('a search term is required')
literal = ' AND '.join('"'+word.replace('"','""')+'"' for word in words)
matches = db.execute("""SELECT locator,snippet(terms,2,'[',']','…',14)
FROM terms WHERE digest=? AND terms MATCH ? ORDER BY rank,locator LIMIT 50""",
(args.document_sha256,literal))
print(json.dumps([dict(match='keyword',locator=k,context=v) for k,v in matches],indent=2))
return
data, receipt = get(db,args.document_sha256,args.locator)
if args.xml:
sys.stdout.buffer.write(data)
else:
print(json.dumps(receipt,indent=2))
if __name__ == '__main__':
main()Browser Acceptance
A Python command-line tool in the legal evidence folder of Legislation that draws catalogue, regulatory references and project review, and uses data from the GridAtlas repository.
renderlegislation / legal-evidence/browser_acceptance.py · lines 1–89 of 89 · Entry point · pattern Quiet (shared by 9 files)
- What it does
- It draws catalogue, regulatory references, project review and the REPD register. Defines Quiet, log_message, main. Uses libraries functools, http.server, pathlib, json, os. 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.
- Inputs & outputs
- In: data source: gridatlas data; JSON file catalogue.json; JSON file regulatory-references.json; JSON file homepage.json; CSV file project-review.csv.
- Downstream impact
- Used directly by 1 file: Verify Workflow (legislation). It is itself an entry point, published at https://ventusltd.github.io/legislation/legal-evidence/.
- What it achieves
- It is built from the quiet class (`Quiet`) and the log message helper (`log_message`). Browser acceptance for the static legal evidence reader (requires Playwright + Chromium).
- Why it matters
- Run by Verify Workflow.
- Application
- legislation · legal-evidence · Python CLI
- Uses
- functools, http.server, pathlib, json, os, threading, urllib.parse, playwright.sync_api
- Used by
- run by Verify Workflow (workflow run)
- Produces
- Quiet, main
- Defines here
- Quiet, log_message, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 legal-evidence/browser_acceptance.py:1-89 · blob 33b156cd07f5746e9b62bf1cd1c2b2c95c761682 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
"""Browser acceptance for the static legal evidence reader (requires Playwright + Chromium)."""
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import json
import os
from threading import Thread
from urllib.parse import urlencode
from playwright.sync_api import expect, sync_playwright
class Quiet(SimpleHTTPRequestHandler):
def log_message(self, *args):
pass
def main():
root = Path(__file__).resolve().parents[1]
statute_count = len(json.loads((root / "data/catalogue.json").read_text()))
external_count = len(json.loads((root / "data/regulatory-references.json").read_text()))
total = statute_count + external_count
handler = partial(Quiet, directory=root)
with ThreadingHTTPServer(('127.0.0.1', 0), handler) as server, sync_playwright() as playwright:
Thread(target=server.serve_forever, daemon=True).start()
browser = playwright.chromium.launch(executable_path=os.environ.get('LEGISLATION_CHROMIUM'), headless=True)
address = f'http://127.0.0.1:{server.server_port}/legal-evidence/'
page = browser.new_page(viewport={'width':390,'height':844})
register_url = 'https://globalgrid2050.com/homepage-shell/data/homepage.json'
old = '202611232245'
new = '202611280048'
releases = [dict(id=r,url=f'https://globalgrid2050.com/uk_renewables_pipeline/{r}/') for r in (old,new)]
registry = dict(entities=[dict(id='pipeline-news',operative_release_id=new,releases=releases)])
page.route(register_url, lambda route: route.fulfill(json=registry,
headers={'access-control-allow-origin':'*'}))
errors = []
page.on('pageerror', lambda err: errors.append(str(err)))
payload = '<img src=x onerror=alert(1)>'
page.goto(address + '?' + urlencode(dict(project=payload, repd_ref='REF-42',technology='Solar PV',
status='Planning submitted',source_app='PipelineNews',mw='49.9')))
expect(page.locator('#context')).to_contain_text('Unknown')
expect(page.locator('#context')).to_contain_text(payload)
expect(page.locator('#context img')).to_have_count(0)
expect(page.locator('#context')).to_contain_text('49.9')
expect(page.locator('#count')).to_have_text(f'{total} sources')
expect(page.get_by_role('link',name='Published impact assessment')).to_have_attribute('href',
'https://publications.parliament.uk/pa/bills/cbill/59-02/0176/IA6Electricitynetworkinfrastructure-consentslandaccessandrights.pdf')
page.get_by_role('button',name='solar photovoltaic development').click()
assert page.locator('article').count() > 0
assert page.locator('article').count() < total
page.locator('#subject').select_option('')
page.locator('#query').fill('ukpga/1989/29')
expect(page.locator('article')).to_have_count(1)
expect(page.get_by_role('link',name='Electricity Act 1989')).to_have_attribute('href','https://www.legislation.gov.uk/ukpga/1989/29')
page.get_by_text('Evidence details').click()
expect(page.get_by_role('link',name='Changes recorded')).to_be_visible()
page.locator('#query').fill('')
page.locator('#kind').select_option('other')
expect(page.locator('article')).to_have_count(external_count)
page.locator('#query').fill('zzzzz')
expect(page.locator('#results')).to_contain_text('No sources match')
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth')
page.goto(address + '?source_app=GridAtlas&jurisdiction=Wales&repd_ref=9873&source_release=202611222343')
expect(page.locator('#context')).to_contain_text('202611222343')
expect(page.locator('#pipeline')).to_have_attribute('href', f'https://globalgrid2050.com/uk_renewables_pipeline/{new}/?technology=all&q=9873')
expect(page.locator('#source-edition')).to_have_attribute('href','https://ventusltd.github.io/gridatlas/atlas/v/202611222343/')
expect(page.get_by_role('link',name='Read the project review')).to_have_attribute('href','../research/repd-top-100-2026-11-28/')
expect(page.get_by_role('link',name='Download all 100 records (CSV)')).to_have_attribute('href','../research/repd-top-100-2026-11-28/project-review.csv')
expect(page.get_by_role('link',name='Archived HM Treasury Data Centre Covenant')).to_have_attribute('href','../research/repd-top-100-2026-11-28/data-centre-covenant.html')
expect(page.locator('#context')).to_contain_text('Wales')
page.goto(address + f'?source_app=pipelinenews&repd_ref=9873&source_release={old}')
expect(page.locator('#source-edition')).to_have_attribute('href', f'https://globalgrid2050.com/uk_renewables_pipeline/{old}/?technology=all&q=9873')
page.goto(address + '?source_app=pipelinenews&source_release=209901010000')
expect(page.locator('#source-edition')).to_be_hidden()
page.route(register_url,lambda route: route.abort())
page.route('**/data/catalogue.json', lambda route: route.fulfill(status=503,body='unavailable'))
page.goto(address)
expect(page.locator('#project-context')).to_be_hidden()
expect(page.locator('#count')).to_contain_text(f'{external_count} sources Unavailable: legislation')
expect(page.locator('#case')).to_contain_text('impact assessment')
expect(page.locator('#pipeline')).to_have_text('Pipeline News · edition 202611232245')
assert errors == [], errors
browser.close()
server.shutdown()
print('PASS: catalogue, named links, source context, mobile layout, filtering, partial failure and safe rendering')
if __name__ == '__main__':
main()Legislation — Legal Evidence Page
A web page that draws project review, catalogue, ia6 and the Renewable Energy Planning Database (REPD) register, and uses data from the GridAtlas repository. Published at https://ventusltd.github.io/legislation/legal-evidence/.
renderlegislation / legal-evidence/index.html · lines 1–50 of 50 · Entry point
- What it does
- It draws project review, catalogue, ia6 and the REPD register. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain terms in the code: the REPD register.
- Inputs & outputs
- In: CSV file project-review.csv; JSON file catalogue.json; JSON file ia6.json; form fields (user input). Out: web page.
- Downstream impact
- Used directly by 5 files: Vicinity Legal Evidence (gridatlas); Vicinity Legal Evidence Proof (gridatlas); GridAtlas Test (legislation); Link (globalgrid2050); and 1 more. Reached from 19 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report A4 (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report Model (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). It is itself an entry point, published at https://ventusltd.github.io/legislation/legal-evidence/.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Imported by Vicinity Legal Evidence, Vicinity Legal Evidence Proof and Link, from GlobalGrid2050 and GridAtlas. Checked by 2 tests, including GridAtlas Test.
- Application
- legislation · legal-evidence · page
- Uses
- Reader (stylesheet), Reader (script src), GridAtlas — Atlas Page (link), Data Centre Covenant (link)
- Used by
- named by URL in Vicinity Legal Evidence (estate URL), named by URL in Vicinity Legal Evidence Proof (estate URL), named by URL in GridAtlas Test (estate URL), named by URL in Link (estate URL), named by URL in A4 Legal Model (estate URL)
- 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 legal-evidence/index.html:1-50 · blob 7f2d806a1b72a59522995b236b72b9f941f5f784 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<meta http-equiv="Content-Security-Policy" content="default-src 'self';script-src 'self';style-src 'self';connect-src 'self' https://globalgrid2050.com/homepage-shell/data/homepage.json;object-src 'none';base-uri 'none'">
<meta name="referrer" content="no-referrer">
<title>Legal evidence | GlobalGrid2050</title>
<link rel="stylesheet" href="reader.css">
<script src="reader.js" defer></script>
</head>
<body>
<header><div class="wrap"><span>GlobalGrid2050</span> / Legislation</div></header>
<main class="wrap">
<h1>Legal evidence</h1>
<section id="project-context" hidden><h2>Project context</h2><dl id="context"></dl></section>
<p class="notice"><strong>Legal applicability is unassessed.</strong> A mapped asset or project record establishes no land right, planning permission, electrical capacity or connection agreement. Check the provision, relevant date, territory and project evidence.</p>
<nav class="registers" aria-label="Project registers">
<a id="pipeline" href="https://globalgrid2050.com/uk_renewables_pipeline/202611232245/">Pipeline News · edition 202611232245</a>
<a href="https://ventusltd.github.io/gridatlas/atlas/">Current GridAtlas</a>
<a id="source-edition" hidden></a>
<a href="https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract">DESNZ · Official REPD extract</a>
<a id="example" href="?source_app=pipelinenews&source_release=202611232245&repd_ref=9873">Open REPD 9873 example</a>
</nav>
<section aria-labelledby="review-heading">
<h2 id="review-heading">Britain’s 100 largest REPD records</h2>
<p>The 28 November 2026 review checks project identity, planning decisions and grid evidence for the largest Q3 records by reported MW.</p>
<nav class="registers" aria-label="Top 100 research">
<a href="../research/repd-top-100-2026-11-28/">Read the project review</a>
<a href="../research/repd-top-100-2026-11-28/project-review.csv" download>Download all 100 records (CSV)</a>
<a href="../research/repd-top-100-2026-11-28/data-centre-covenant.html">Archived HM Treasury Data Centre Covenant</a>
</nav>
</section>
<section aria-labelledby="source-heading">
<h2 id="source-heading">Find official sources</h2>
<div class="filters">
<label>Search titles, references or subjects<input type="search" id="query" autocomplete="off"></label>
<label>Subject<select id="subject"><option value="">All subjects</option></select></label>
<label>Source class<select id="kind"><option value="">All classes</option><option value="legislation">Legislation</option><option value="other">Guidance, policy and other references</option></select></label>
</div>
<div id="suggestion" hidden></div>
<p id="count" role="status">Loading catalogue…</p>
<div id="results"></div>
</section>
<section aria-labelledby="case-heading" class="case"><h2 id="case-heading">IA6 · Consents, land access and rights</h2><div id="case" aria-live="polite">Loading case study…</div></section>
<noscript>Enable JavaScript to search, or open the <a href="../data/catalogue.json">legislation catalogue</a> and <a href="../case/ia6.json">IA6 case record</a>.</noscript>
</main>
</body>
</html>Reader
A style sheet in the legal evidence folder of Legislation. Served with the page at https://ventusltd.github.io/legislation/legal-evidence/.
renderlegislation / legal-evidence/reader.css · lines 1–34 of 34 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: Legislation — Legal Evidence Page (legislation, https://ventusltd.github.io/legislation/legal-evidence/). Reached from 20 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report A4 (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report Model (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). It is itself an entry point, published at https://ventusltd.github.io/legislation/legal-evidence/.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Loaded by the Legal Evidence page at https://ventusltd.github.io/legislation/legal-evidence/.
- Application
- legislation · legal-evidence · style sheet
- Uses
- none found
- Used by
- loaded by Legislation — Legal Evidence Page (stylesheet)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 legal-evidence/reader.css:1-34 · blob 25b14b6e295b7d88886654951cfbaaf97995d170 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
* { box-sizing:border-box }
:root { font: 100%/1.5 "Source Sans 3",system-ui,sans-serif; color:#162c32; background:#f6f8f6 }
body { margin:0 }
.wrap { width:min(74rem,100%); margin:0 auto; padding-inline:clamp(1rem,4vw,3rem) }
header { padding-block:.8rem; background:#173a40; color:#d7e6df; font-size:.9rem }
header span { font-weight:700; color:white }
main { padding-block:clamp(1.5rem,4vw,3.5rem) }
h1,h2,p { margin:0 0 .8rem }
h1 { font: 600 clamp(2.25rem,5vw,3.8rem)/1.05 "Source Sans 3",system-ui,sans-serif; letter-spacing:-.045em }
h2 { font-size:1.35rem; margin-top:1.7rem }
dl { margin:0; display:flex; flex-wrap:wrap; gap:.5rem 1.5rem }
dt,.meta,#count { color:#435b60; font-size:.875rem }
dd { margin:0; font-weight:600; overflow-wrap:anywhere }
.notice { padding:.9rem 1rem; margin-top:1.3rem; border-inline-start:.26rem solid #976f2a; background:#fbf2df }
.filters { display:grid; grid-template-columns: 1.5fr 1fr 1fr; gap:.8rem }
label { display:block; font-size:.875rem; font-weight:600 }
input,select,button { font:inherit; color:inherit; padding:.58rem .75rem; background:white; border:1px solid #879c9d; border-radius:.2rem }
input,select { width:100%; margin-top:.25rem; min-height:2.75rem }
button { cursor:pointer }
:focus-visible { outline:3px solid #b46100; outline-offset:2px }
#suggestion { margin-top:.75rem }
#count { margin:1rem 0 .5rem }
article { border-top:1px solid #b8c8c6; padding:.7rem 0; overflow-wrap:anywhere }
article h3 { font-size:1.02rem; margin:0 0 .13rem }
article p,.case p { margin:0 0 .2rem }
details { font-size:.9rem; margin-top:.3rem }
summary { cursor:pointer; color:#28576a; width:fit-content }
details p { margin-top:.25rem }
a { color:#126376; text-underline-offset:.15em }
.case { border-top:2px solid #173a40; padding-bottom:1rem; margin-top:1.75rem }
.case nav { display:flex; flex-wrap:wrap; gap:.65rem 1.2rem; margin-top:.65rem }
@media(max-width:700px){.filters{grid-template-columns:1fr}.wrap{padding-inline:1rem}}
.registers { display:flex; flex-wrap:wrap; gap:.35rem 1.15rem; font-size:.9rem }Reader
A JavaScript file in the legal evidence folder of Legislation that draws catalogue, regulatory references and ia6, and uses data from the GridAtlas repository. Served with the page at https://ventusltd.github.io/legislation/legal-evidence/.
interactionlegislation / legal-evidence/reader.js · lines 1–198 of 198 · Entry point · pattern loadCatalogue (shared by 4 files)
- What it does
- It draws catalogue, regulatory references, ia6 and wind. Defines 13 functions or classes, including byId, element, officialLink, getJson, pipelineLocation. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: wind.
- Inputs & outputs
- In: data source: gridatlas data; JSON file homepage.json; JSON file catalogue.json; JSON file regulatory-references.json; JSON file ia6.json.
- Downstream impact
- Used directly by 1 file: Legislation — Legal Evidence Page (legislation, https://ventusltd.github.io/legislation/legal-evidence/). Reached from 20 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report A4 (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report Model (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). It is itself an entry point, published at https://ventusltd.github.io/legislation/legal-evidence/.
- What it achieves
- It gets JSON (`getJson`), shows source edition (`showSourceEdition`) and loads catalogue (`loadCatalogue`). Defines `byId`, `element`, `officialLink` and 10 more. It responds to click and input events.
- Why it matters
- Loaded by the Legal Evidence page at https://ventusltd.github.io/legislation/legal-evidence/.
- Application
- legislation · legal-evidence · script
- Uses
- none found
- Used by
- loaded by Legislation — Legal Evidence Page (script src)
- Produces
- byId, element, officialLink, getJson, pipelineLocation, showSourceEdition, releaseLinks, context, subjectChoice, sourceCard, render, loadCatalogue
- Defines here
- byId, element, officialLink, getJson, pipelineLocation, showSourceEdition, releaseLinks, context, subjectChoice, sourceCard, render, loadCatalogue, loadCase
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 legal-evidence/reader.js:1-198 · blob 75bec6d968d553173c80df13155a46baa19f939f · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
'use strict';
const byId = id => document.getElementById(id);
const query = new URLSearchParams(location.search);
const catalogue = [];
const failed = [];
function element(name, text) {
const result = document.createElement(name);
if (text !== undefined) result.textContent = text;
return result;
}
function officialLink(label, address) {
const url = new URL(address);
const official = ['gov.uk', 'parliament.uk'].some(host => url.hostname === host || url.hostname.endsWith('.' + host));
if (url.protocol !== 'https:' || !official || url.username || url.password) return element('span', label);
const anchor = element('a', label);
anchor.href = url.href;
return anchor;
}
async function getJson(path) {
const response = await fetch(path);
if (!response.ok) throw new Error('HTTP ' + response.status);
return response.json();
}
const releaseRegister = 'https://globalgrid2050.com/homepage-shell/data/homepage.json';
const pipelineBase = 'https://globalgrid2050.com/uk_renewables_pipeline/';
const knownPipeline = '202611232245';
function pipelineLocation(release) {
const url = new URL(pipelineBase + release + '/');
const ref = query.get('repd_ref');
if (/^[1-9]\d{0,11}$/.test(ref || '')) {
url.searchParams.set('technology','all');
url.searchParams.set('q',ref);
}
return url;
}
function showSourceEdition(knownReleases) {
const source = (query.get('source_app') || '').toLowerCase();
const release = query.get('source_release');
const link = byId('source-edition');
if (source === 'pipelinenews' && knownReleases.has(release)) {
link.href = pipelineLocation(release).href;
link.textContent = 'Pipeline News source edition · ' + release;
} else if (source === 'gridatlas' && ['202611222343','202611280016'].includes(release)) {
link.href = 'https://ventusltd.github.io/gridatlas/atlas/v/' + release + '/';
link.textContent = 'GridAtlas source edition · ' + release;
} else {
return;
}
link.hidden = false;
}
async function releaseLinks() {
const link = byId('pipeline');
link.href = pipelineLocation(knownPipeline).href;
showSourceEdition(new Set([knownPipeline]));
try {
const register = await getJson(releaseRegister);
const app = register.entities.find(entity => entity.id === 'pipeline-news');
const releases = new Set(app.releases
.filter(item => /^\d{12}$/.test(item.id) && item.url === pipelineBase + item.id + '/')
.map(item => item.id));
if (!releases.has(app.operative_release_id)) return;
link.href = pipelineLocation(app.operative_release_id).href;
link.textContent = 'Current Pipeline News · ' + app.operative_release_id;
showSourceEdition(releases);
} catch {
// The explicitly labelled local edition remains usable when the register is offline.
}
}
function context() {
const fields = [
['Project', 'project'], ['REPD reference', 'repd_ref'], ['Source release', 'source_release'], ['Technology', 'technology'],
['Project status', 'status'], ['Capacity (MW)', query.has('mw') ? 'mw' : 'MW'],
['Jurisdiction supplied by source', 'jurisdiction'], ['Source application', 'source_app']
];
if (!fields.some(([, key]) => query.get(key)?.trim())) return;
byId('project-context').hidden = false;
byId('example').hidden = true;
for (const [label, key] of fields) {
const value = query.get(key)?.trim();
if (key === 'source_release' && !/^\d{12}$/.test(value || '')) continue;
if (!value && key !== 'jurisdiction') continue;
const pair = element('div');
pair.append(element('dt',label),element('dd',value?.slice(0,300) || 'Unknown'));
byId('context').append(pair);
}
}
function subjectChoice(subjects) {
for (const subject of subjects) {
const option = element('option',subject);
option.value = subject;
byId('subject').append(option);
}
const technology = query.get('technology') || '';
const choices = [
[/solar|photovoltaic/i,'solar photovoltaic development'],
[/battery|bess/i,'battery energy storage'],
[/offshore.*wind|wind.*offshore/i,'offshore wind'],
[/onshore.*wind|wind.*onshore/i,'onshore wind'],
[/data cent(?:er|re)/i,'data centre planning']
].filter(([regex, subject]) => regex.test(technology) && subjects.includes(subject));
if (choices.length) {
const box = byId('suggestion');
box.hidden = false;
box.append(document.createTextNode('Explore by technology '));
for (const [, subject] of choices) {
const button = element('button',subject);
button.type = 'button';
button.addEventListener('click',() => {
byId('subject').value = subject;
render();
});
box.append(button,document.createTextNode(' '));
}
}
}
function sourceCard(record) {
const article = element('article');
const heading = element('h3');
heading.append(officialLink(record.title, record.source_url));
const type = record.document_class ? record.document_class.replaceAll('_',' ') : 'legislation';
const labels = [type, record.id, record.responsible_authority, record.retrieval_date && 'Retrieved ' + record.retrieval_date].filter(Boolean);
const meta = element('p',labels.join(' · '));
meta.className = 'meta';
const detail = element('details');
detail.append(element('summary','Evidence details'),element('p',record.subjects.join(' · ')));
if (record.id) {
detail.append(element('p','Published extent: ' + (record.extent_as_published || 'unknown') + '. Project applicability: unassessed.'));
if (record.original_version_url) detail.append(officialLink('Original version',record.original_version_url));
if (record.changes_url) detail.append(document.createTextNode(' · '),officialLink('Changes recorded',record.changes_url));
} else {
detail.append(element('p','Legal effect for this project: unassessed.'));
}
article.append(heading,meta,detail);
return article;
}
function render() {
const words = byId('query').value.trim().toLowerCase().split(/\s+/).filter(Boolean);
const subject = byId('subject').value;
const kind = byId('kind').value;
const records = catalogue.filter(record => {
if (subject && !record.subjects.includes(subject)) return false;
if (kind && (record.document_class ? 'other' : 'legislation') !== kind) return false;
const terms = [record.id,record.title,record.jurisdiction,...record.subjects].filter(Boolean).join(' ').toLowerCase();
return words.every(word => terms.includes(word));
});
const note = failed.length ? ' Unavailable: ' + failed.join(', ') + '.' : '';
byId('count').textContent = records.length + (records.length === 1 ? ' source' : ' sources') + note;
byId('results').replaceChildren(...records.map(sourceCard));
if (!records.length) byId('results').append(element('p',failed.length ? 'Some evidence could not be loaded.' : 'No sources match these filters.'));
}
async function loadCatalogue() {
const datasets = [['legislation','../data/catalogue.json'],['regulatory references','../data/regulatory-references.json']];
const loads = await Promise.allSettled(datasets.map(([,url]) => getJson(url)));
loads.forEach((load,i) => {
if (load.status === 'fulfilled') catalogue.push(...load.value);
else failed.push(datasets[i][0]);
});
catalogue.sort((a,b) => a.title.localeCompare(b.title,'en-GB'));
subjectChoice([...new Set(catalogue.flatMap(record => record.subjects))].sort());
for (const id of ['query','subject','kind']) byId(id).addEventListener('input',render);
render();
}
async function loadCase() {
const region = byId('case');
try {
const evidence = await getJson('../case/ia6.json');
const doc = evidence.document;
const bill = evidence.bill;
const links = element('nav');
links.setAttribute('aria-label','IA6 source documents');
links.append(officialLink('Published impact assessment',doc.url),officialLink('Bill text',bill.text),
officialLink('Parliamentary stages',bill.stages),officialLink('Consultation response',evidence.policy.response));
region.replaceChildren(element('p',doc.author + ' · ' + doc.type + ' · ' + doc.identity),
element('p',bill.title + ' · ' + bill.status + ' as recorded ' + evidence.research_date + '.'),
element('p','The assessment describes proposed reforms. Check the Parliamentary record and commencement evidence before relying on a change.'),links);
} catch {
region.textContent = 'The IA6 case record could not be loaded.';
}
}
context();
releaseLinks();
loadCatalogue();
loadCase();Legal Evidence
A JavaScript module in the protections folder of Legislation that uses SHA-256. It is built from the has text helper (`hasText`), the date step (`date`) and the within step (`within`).
transformlegislation / protections/legal-evidence.mjs · lines 1–35 of 35 · pattern hasText (shared by 2 files)
- What it does
- It calculates its inputs. Defines hasText, date, within.
- Why it exists in the grid workflow
- README: "CVAA's data-only antibody applies the same declaration checks to `.cvaa/contracts/legal-evidence.json` when present."
- Inputs & outputs
- In: JSON file legal-evidence.json.
- Downstream impact
- Used directly by 1 file: Screen (legislation). Reached from 2 other entry points, including Verify Workflow (legislation); Verify (legislation).
- What it achieves
- A receipt checks the support recorded for a screening result.
- Why it matters
- Imported by Screen.
- Application
- legislation · protections · JavaScript module
- Uses
- none found
- Used by
- imported by Screen (import)
- Produces
- hasText, date, within
- Defines here
- hasText, date, within
- 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/legal-evidence.mjs:1-35 · blob 19d409a8f3186e463ae82b4aeb25a10563929a8d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
// A receipt checks the support recorded for a screening result. It cannot confer a right.
export default ({ controlContracts }) => {
const file = 'legal-evidence.json';
const receipt = controlContracts.find(item => item.file === file);
if (!receipt) return [];
const data = receipt.document;
if (receipt.error || data?.schema !== 'ventus.legal-evidence.v1') return ['invalid-receipt'];
const { claim, evidence } = data;
if (!claim || !evidence || !Array.isArray(claim.open_questions)) return ['incomplete-receipt'];
if (claim.result === 'unresolved') return claim.open_questions.some(q => typeof q === 'string' && q.trim()) ? [] : ['unexplained-uncertainty'];
if (claim.result !== 'supported-screening' || claim.open_questions.length) return ['unsupported-conclusion'];
const problems = [];
const hasText = value => typeof value === 'string' && value.trim().length > 0;
const date = value => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)
&& Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
const within = (from, until, when) => date(when) && date(from) && from <= when && (until === null || (date(until) && when < until));
if (!date(claim.as_of) || !hasText(claim.provision) || claim.provision !== evidence.provision) problems.push('provision-identity');
if (evidence.kind !== 'enacted-legislation') problems.push('source-kind');
if (!within(evidence.commenced_on, evidence.repealed_on, claim.as_of)) problems.push('commencement-or-repeal');
if (!within(evidence.version_from, evidence.version_until, claim.as_of)) problems.push('outdated-version');
if (!hasText(claim.territory) || !Array.isArray(evidence.territories) || !evidence.territories.includes(claim.territory)) problems.push('territory');
if (!hasText(claim.actor) || !Array.isArray(evidence.actors) || !evidence.actors.includes(claim.actor)) problems.push('actor');
if (!hasText(claim.land_interest) || !Array.isArray(evidence.land_interests) || !evidence.land_interests.includes(claim.land_interest)) problems.push('land-interest');
if (!hasText(claim.authority) || claim.authority !== evidence.authority) problems.push('authority');
if (evidence.exceptions !== 'reviewed-and-resolved') problems.push('exceptions');
if (evidence.amendments !== 'verified-through-query-date') problems.push('amendments');
if (!date(evidence.checked_through) || evidence.checked_through < claim.as_of) problems.push('stale-review');
if (evidence.conflicts !== 'reviewed-and-resolved') problems.push('conflicting-evidence');
if (!/^https:\/\/www\.legislation\.gov\.uk\/(?:[a-z]+)\/[0-9]{4}\/[^\s?#]+$/.test(evidence.source_url)) problems.push('source-url');
if (!hasText(evidence.citation) || !hasText(evidence.review_reference)) problems.push('missing-citation');
if (evidence.last_http_status !== 200 || !date(evidence.retrieved_on) || evidence.retrieved_on < claim.as_of) problems.push('source-unverified');
if (!/^[a-f0-9]{64}$/.test(evidence.sha256)) problems.push('missing-digest');
if (claim.basis !== 'documentary-review') problems.push('unsupported-basis');
return problems;
};Screen
A JavaScript module in the protections folder of Legislation that reads legal evidence, using SHA-256.
ingestlegislation / protections/screen.mjs · lines 1–29 of 29 · Entry point
- What it does
- It loads legal evidence. Defines check, load. Uses libraries node:fs, node:path, node:crypto, node:url. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file legal-evidence.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: Verify Workflow (legislation); Test (legislation). Reached from 1 other entry point, including Verify (legislation).
- What it achieves
- Defines `check` and `load`.
- Why it matters
- Run by Verify Workflow. Checked by Test.
- Application
- legislation · protections · JavaScript module
- Uses
- Legal Evidence (import), node:fs, node:path, node:crypto, node:url
- Used by
- run by Verify Workflow (workflow run), imported by Test (import)
- Produces
- check
- Defines here
- check, load
- 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/screen.mjs:1-29 · blob 4471021557182ec5bd2e8642d7e386d3569dc268 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
// Usage: node protections/screen.mjs RECEIPT CONTENT_STORE [PRIOR_RECEIPT]
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { createHash } from 'node:crypto';
import screen from './legal-evidence.mjs';
export function check(receipt, directory, prior) {
const problems = screen({controlContracts: [{file: 'legal-evidence.json', document: receipt}]});
if (receipt?.claim?.result !== 'supported-screening' || problems.length) return problems;
const source = receipt.evidence;
try {
const digest = createHash('sha256').update(readFileSync(join(directory, source.sha256))).digest('hex');
if (digest !== source.sha256) problems.push('source-corrupted');
} catch {
problems.push('source-missing');
}
if (prior && prior.evidence.provision === source.provision && prior.evidence.version_from === source.version_from
&& prior.evidence.source_url === source.source_url && prior.evidence.sha256 !== source.sha256)
problems.push('historical-bytes-changed');
return problems;
}
if (process.argv[1] && import.meta.url === (await import('node:url')).pathToFileURL(process.argv[1]).href) {
const [path, directory, previous] = process.argv.slice(2);
const load = name => JSON.parse(readFileSync(name, 'utf8'));
const findings = check(load(path), directory, previous && load(previous));
console.log(JSON.stringify({findings}));
process.exitCode = findings.length ? 1 : 0;
}