In this section
- Build Transition Context other · globalgrid2050 / automation/news/build_transition_context.py lines 1–245
- Adapter ingest · globalgrid2050 / automation/news/context-ui/adapter.mjs lines 1–191
- Adapter Test test · globalgrid2050 / automation/news/context-ui/adapter.test.mjs lines 1–126
- Browser interaction · globalgrid2050 / automation/news/context-ui/browser.mjs lines 1–116
Build Transition Context
A Python command-line tool in the news folder of GlobalGrid2050 that works with CSV report (`csv_report`) and bounded output (`BoundedOutput`), covering solar, using SHA-256.
otherglobalgrid2050 / automation/news/build_transition_context.py · lines 1–245 of 245 · Entry point · pattern csv_report (shared by 2 files)
- What it does
- Defines 15 functions or classes, including dumps, _bounded, _scope, _link, _figure. Uses libraries __future__, argparse, copy, csv, hashlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Transition Context (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It is built from the dumps step (`dumps`), the build step (`build`) and the bounded output class (`BoundedOutput`). Bounded offline composition of existing Covenant, Grid and Solar contracts. It accepts `--policy`, `--grid` and `--solar`.
- Why it matters
- Checked by Test Transition Context.
- Application
- globalgrid2050 · automation/news · Python CLI
- Uses
- Grid (import), Solar (import), Contracts (import), Ledger (import), News — Policy Commitments (import), __future__, argparse, copy, csv, hashlib, io, json, os
- Used by
- imported by Test Transition Context (import)
- Produces
- dumps, build, csv_report, main
- Defines here
- dumps, _bounded, _scope, _link, _figure, _policy_row, _context_row, build, csv_report, BoundedOutput, write, _unique_object, _read, _publish_new, 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/news/build_transition_context.py:1-245 · blob 63c6cc57ebb39739c3e04c2eef9ed6037aac1370 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Bounded offline composition of existing Covenant, Grid and Solar contracts.
No collection, project matching, allocation, quantity conversion or publication.
The producer validators remain authoritative; native records are retained intact.
"""
from __future__ import annotations
import argparse
from copy import deepcopy
import csv
import hashlib
import io
import json
import os
from pathlib import Path
import sys
import tempfile
from automation.news.dc_context import grid, solar
from automation.news.filings.contracts import validate_claim
from automation.news.policy_commitments import ledger as policy
SCHEMA = "globalgrid2050.transition-context.v1"
MAX_INPUT_BYTES = 4 * 1024 * 1024
MAX_OUTPUT_BYTES = 16 * 1024 * 1024
COLUMNS = ("id", "family", "title", "scope", "source_state", "evaluation_state",
"applicability_state", "source_links", "numeric_claims", "native_schema", "native_record")
def dumps(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + "\n"
def _bounded(value, limit):
raw = dumps(value).encode("utf-8")
if len(raw) > limit:
raise ValueError("Context exceeds bounded size")
return raw
def _scope(native_scope, entity_id, *, family, relationship=None):
# These are presentation categories only, never an identity crosswalk.
if relationship == "portfolio_storage_access" or native_scope == "consolidated_group":
kind = "portfolio"
elif native_scope == "issuer":
kind = "issuer"
elif native_scope in {"project", "site", "campus", "phase"}:
kind = "project"
elif family == "policy":
kind = "policy"
else:
kind = "UNKNOWN"
return {"kind": kind, "native_scope": native_scope, "entity_id": entity_id,
"canonical_project_id": None, "binding": "UNLINKED"}
def _link(document, *, section=None, page=None, text=None, covenant=False):
return {"document_id": document["id"] if covenant else document["document_id"],
"url": document["url"],
"publisher": document["issuer"] if covenant else document["publisher"],
"published_date": document["published_on"] if covenant else document["published_date"],
"reviewed_at": document["reviewed_at"] if covenant else None,
"retrieved_at": document["retrieved_at"],
"sha256": document["content_sha256"] if covenant else document["sha256"],
"locator": {"section": section, "page": page, "text": text},
"receipt": deepcopy(document)}
def _figure(claim, role, qualifier=None):
# Exact FIGURES validation/copy; no float coercion or parallel quantity model.
return {"role": role, "qualifier": qualifier, "claim": validate_claim(claim)}
def _policy_row(row, documents):
claims = []
references = [row["source"], *row["applicability"]["evidence"],
*(update["source"] for update in row["updates"])]
for role, claim in (("TARGET", row["target"]), ("BASELINE", row["baseline"]),
*(("UPDATE", update["claim"]) for update in row["updates"])):
if claim is not None:
claims.append(_figure(claim, role))
provenance = claim["provenance"]
references.append({"document_id": provenance["document_id"],
"locator": provenance["section"] or "page " + provenance["page"]})
links = {(ref["document_id"], ref["locator"]): _link(documents[ref["document_id"]],
text=ref["locator"], covenant=True) for ref in references}
return {"id": "policy:" + row["commitment_id"], "family": "policy", "title": row["statement"],
"scope": _scope(row["scope"]["figure_entity_scope"], row["scope"]["entity_id"], family="policy"),
"source_state": row["document_state"], "evaluation_state": row["state"],
"applicability_state": row["applicability"]["state"],
"source_links": [links[key] for key in sorted(links)], "numeric_claims": claims,
"native_schema": policy.REPORT_SCHEMA, "native_record": deepcopy(row)}
def _context_row(row, family):
is_solar = family == "solar"
native_scope = row["entity"]["scope"] if is_solar else row["entity_scope"]
entity_id = row["entity"]["id"] if is_solar else row["id"]
figures = [_figure(item["claim"], "CONTEXT", item["qualifier"]) if is_solar
else _figure(item, "CONTEXT") for item in row["numeric_claims"]]
return {"id": family + ":" + row["id"], "family": family, "title": row["name"],
"scope": _scope(native_scope, entity_id, family=family, relationship=row.get("relationship")),
"source_state": row["source_state"], "evaluation_state": "UNKNOWN", "applicability_state": "UNKNOWN",
"source_links": [_link(row["source"], section=row["section"], page=row["page"])],
"numeric_claims": figures, "native_schema": solar.SCHEMA if is_solar else grid.SCHEMA,
"native_record": deepcopy(row)}
def build(policy_input, grid_input, solar_input, *, as_of):
"""Validate all three inputs before returning a complete, unlinked bundle.
Every family is mandatory and nonempty. Input digests cover the entire
supplied JSON value in canonical serialization, not original document bytes.
"""
inputs = {"policy": policy_input, "grid": grid_input, "solar": solar_input}
digests = {family: hashlib.sha256(_bounded(value, MAX_INPUT_BYTES)).hexdigest()
for family, value in inputs.items()}
evaluated = policy.evaluate(policy_input, as_of=as_of)
grid_result = grid.build(grid_input, as_of=as_of)
solar_result = solar.build(solar_input, as_of=as_of)
documents = {document["id"]: document for document in evaluated["documents"]}
records = [_policy_row(row, documents) for row in evaluated["results"]]
records.extend(_context_row(row, "grid") for row in grid_result["records"])
records.extend(_context_row(row, "solar") for row in solar_result["records"])
records.sort(key=lambda row: row["id"])
if not records or len(records) > 3000 or len({row["id"] for row in records}) != len(records):
raise ValueError("Nonempty bounded unique context coverage required")
claim_ids = [figure["claim"]["claim_id"] for row in records for figure in row["numeric_claims"]]
if len(claim_ids) != len(set(claim_ids)):
raise ValueError("Repeated FIGURES identity across context families")
counts = {family: sum(row["family"] == family for row in records) for family in inputs}
if not all(counts.values()):
raise ValueError("All context families require coverage")
receipts = []
for family, result in (("policy", evaluated), ("grid", grid_result), ("solar", solar_result)):
receipts.append({"family": family, "input_schema": inputs[family]["schema"],
"input_sha256": digests[family], "output_schema": result["schema"],
"record_count": counts[family],
"source_count": len(inputs[family]["documents" if family == "policy" else "sources"]),
"source_byte_validation": "RECEIPTS_ONLY",
"native_metadata": {key: deepcopy(value) for key, value in result.items()
if key not in {"records", "results"}}})
report = {"schema": SCHEMA, "as_of": as_of, "status": "PROVISIONAL",
"coverage": {"records": len(records), "families": counts, "numeric_claims": len(claim_ids),
"linked_projects": 0, "scope": "BOUNDED_SUPPLIED_CONTEXT"},
"input_receipts": receipts, "records": records,
"limitations": ["Dated source context; no current project delivery, legal compliance or source truth certified.",
"No identity crosswalk, site allocation, numerical aggregation, conversion or ranking.",
"Receipt hashes are supplied metadata; original source bytes were not reverified.",
"Publication, review, retrieval and figure dates remain distinct; composition time is not source freshness.",
"Historical inventory is separate; no exhaustive treaty history or final COP31 outcome inferred."]}
_bounded(report, MAX_OUTPUT_BYTES)
return report
def csv_report(report):
"""One context per row; nested records/claims retain exact JSON values."""
class BoundedOutput(io.StringIO):
size = 0
def write(self, value):
self.size += len(value.encode("utf-8"))
if self.size > MAX_OUTPUT_BYTES:
raise ValueError("CSV export exceeds bounded size")
return super().write(value)
output = BoundedOutput(newline="")
writer = csv.DictWriter(output, fieldnames=("bundle", *COLUMNS), lineterminator="\n")
writer.writeheader()
metadata = {key: value for key, value in report.items() if key != "records"}
for row in report["records"]:
cells = {}
for name in ("bundle", *COLUMNS):
value = metadata if name == "bundle" else row[name]
if isinstance(value, (dict, list)):
value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
value = "" if value is None else str(value)
cells[name] = "'" + value if value.startswith(("=", "+", "-", "@", "\t", "\r")) else value
writer.writerow(cells)
return output.getvalue()
def _unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("Duplicate JSON key")
result[key] = value
return result
def _read(path):
with path.open("rb") as handle:
raw = handle.read(MAX_INPUT_BYTES + 1)
if len(raw) > MAX_INPUT_BYTES:
raise ValueError("Input exceeds bounded size")
return json.loads(raw, object_pairs_hook=_unique_object)
def _publish_new(path, raw):
"""Publish fully flushed bytes by an atomic, exclusive same-filesystem link.
Unsupported hard links fail closed; never fall back to overwriting/renaming.
Only the uniquely created staging file is removed, never the destination.
"""
descriptor, name = tempfile.mkstemp(prefix=".transition-context-", suffix=".tmp", dir=path.parent)
temporary = Path(name)
try:
with os.fdopen(descriptor, "wb") as handle:
handle.write(raw)
handle.flush()
os.fsync(handle.fileno())
os.link(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--policy", type=Path, required=True)
parser.add_argument("--grid", type=Path, required=True)
parser.add_argument("--solar", type=Path, required=True)
parser.add_argument("--as-of", required=True)
parser.add_argument("--format", choices=("json", "csv"), default="json")
parser.add_argument("--output", type=Path)
args = parser.parse_args(argv)
try:
report = build(_read(args.policy), _read(args.grid), _read(args.solar), as_of=args.as_of)
result = csv_report(report) if args.format == "csv" else dumps(report)
if len(result.encode("utf-8")) > MAX_OUTPUT_BYTES:
raise ValueError("Export exceeds bounded size")
if args.output:
_publish_new(args.output, result.encode("utf-8"))
else:
if hasattr(sys.stdout, "buffer"):
sys.stdout.buffer.write(result.encode("utf-8"))
else:
sys.stdout.write(result)
except (ValueError, TypeError, KeyError, OSError, OverflowError, RecursionError):
parser.exit(2, "Transition context validation/export failed; no replacement or partial report published.\n")
return 0
if __name__ == "__main__":
raise SystemExit(main())Adapter
A JavaScript module in the context ui folder of GlobalGrid2050 that validates link (`validateLink`) and reads context (`readContext`), covering solar, using SHA-256.
ingestglobalgrid2050 / automation/news/context-ui/adapter.mjs · lines 1–191 of 191 · pattern sourceUrl (shared by 2 files)
- What it does
- It lists and searches solar. Defines 10 functions or classes, including requireValue, equal, keys, text, sourceUrl.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
- Downstream impact
- Used directly by 2 files: Adapter Test (globalgrid2050); Render (globalgrid2050). Reached from 7 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It validates link (`validateLink`), reads context (`readContext`) and registers source (`registerSource`). Offline consumer of the pinned SUPPORT composer.
- Why it matters
- Imported by Render. Checked by Adapter Test.
- Application
- globalgrid2050 · automation/news/context-ui · JavaScript module
- Uses
- none found
- Used by
- imported by Adapter Test (import), imported by Render (import), mentioned in Standalone (comment link)
- Produces
- MAX_BYTES, sourceUrl, readContext
- Defines here
- requireValue, equal, keys, text, sourceUrl, date, scope, validateLink, readContext, registerSource
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/context-ui/adapter.mjs:1-191 · blob c1ded334acb95ebba6dfc4e2f708704ba54c42d5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Offline consumer of the pinned SUPPORT composer. FIGURES remains injected. */
export const MAX_BYTES = 16 * 1024 * 1024;
const SCHEMA = 'globalgrid2050.transition-context.v1';
const families = ['policy', 'grid', 'solar'];
const digestPattern = /^[a-f0-9]{64}$/;
function requireValue(ok) { if (!ok) throw new TypeError('Unsupported transition context'); }
function equal(a, b) {
if (a === b) return true;
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
const keys = Object.keys(a);
return keys.length === Object.keys(b).length && keys.every(k => Object.hasOwn(b, k) && equal(a[k], b[k]));
}
function keys(value, names) {
requireValue(value && typeof value === 'object' && !Array.isArray(value));
requireValue(equal(Object.keys(value).sort(), names.split(' ').sort()));
}
function text(value) { requireValue(typeof value === 'string' && value.length > 0 && value.length <= 100000); }
export function sourceUrl(value) {
requireValue(typeof value === 'string' && /^[\x21-\x7e]+$/.test(value) && !/[\\]/.test(value));
const url = new URL(value);
requireValue(url.protocol === 'https:' && !url.username && !url.password && !url.port);
requireValue(/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$/i.test(url.hostname));
requireValue(!/(?:^|\.)(?:localhost|local|internal|test|invalid|example)$/i.test(url.hostname));
return url.href;
}
function date(value, timestamp = false) {
if (value === null) return;
requireValue(typeof value === 'string' && (timestamp
? /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/
: /^\d{4}(?:-\d{2}(?:-\d{2})?)?$/).test(value));
// A well-shaped date such as 2026-02-30 is not a valid source clock.
const [year, month = 1, day = 1] = value.slice(0, 10).split('-').map(Number);
requireValue(month >= 1 && month <= 12 && day >= 1 &&
day <= new Date(Date.UTC(year, month, 0)).getUTCDate());
if (timestamp) requireValue(Number.isFinite(Date.parse(value)));
}
function scope(nativeScope, entity, family, relationship) {
const kind = relationship === 'portfolio_storage_access' || nativeScope === 'consolidated_group'
? 'portfolio' : nativeScope === 'issuer' ? 'issuer'
: ['project', 'site', 'campus', 'phase'].includes(nativeScope) ? 'project'
: family === 'policy' ? 'policy' : 'UNKNOWN';
return {kind, native_scope: nativeScope, entity_id: entity, canonical_project_id: null, binding: 'UNLINKED'};
}
function validateLink(link) {
keys(link, 'document_id url publisher published_date reviewed_at retrieved_at sha256 locator receipt');
text(link.document_id); text(link.publisher); sourceUrl(link.url);
date(link.published_date); date(link.reviewed_at, true); date(link.retrieved_at, true);
requireValue(link.sha256 === null || digestPattern.test(link.sha256));
keys(link.locator, 'section page text');
for (const value of Object.values(link.locator)) if (value !== null) text(value);
const doc = link.receipt;
const policy = Object.hasOwn(doc, 'published_on');
for (const [key, expected] of Object.entries({document_id: policy ? doc.id : doc.document_id,
url: doc.url, publisher: policy ? doc.issuer : doc.publisher,
published_date: policy ? doc.published_on : doc.published_date,
reviewed_at: policy ? doc.reviewed_at : null, retrieved_at: doc.retrieved_at,
sha256: policy ? doc.content_sha256 : doc.sha256})) requireValue(equal(link[key], expected));
}
/** expectedSha256 must come from the host's accepted manifest, never the payload. */
export async function readContext(raw, {expectedSha256, buildViewModel}) {
requireValue(raw instanceof Uint8Array && raw.length > 0 && raw.length <= MAX_BYTES);
requireValue(typeof expectedSha256 === 'string' && digestPattern.test(expectedSha256));
requireValue(typeof buildViewModel === 'function');
const bytes = raw.slice(); // prevent mutation while WebCrypto is pending
const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), b => b.toString(16).padStart(2, '0')).join('');
requireValue(digest === expectedSha256);
const report = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes));
keys(report, 'schema as_of status coverage input_receipts records limitations');
requireValue(report.schema === SCHEMA && report.status === 'PROVISIONAL');
date(report.as_of, true); requireValue(report.as_of !== null);
requireValue(Array.isArray(report.records) && report.records.length > 0 && report.records.length <= 3000);
requireValue(Array.isArray(report.limitations) && report.limitations.length > 0);
report.limitations.forEach(text);
const counts = {policy: 0, grid: 0, solar: 0}, ids = new Set(), claims = new Set();
for (const row of report.records) {
keys(row, 'id family title scope source_state evaluation_state applicability_state source_links numeric_claims native_schema native_record');
requireValue(families.includes(row.family)); counts[row.family]++;
text(row.id); text(row.title); requireValue(!ids.has(row.id)); ids.add(row.id);
const n = row.native_record, policy = row.family === 'policy', solar = row.family === 'solar';
requireValue(row.id === row.family + ':' + (policy ? n.commitment_id : n.id));
requireValue(row.title === (policy ? n.statement : n.name));
requireValue(row.native_schema === (policy ? 'globalgrid2050.policy-commitment-evaluation.v1' : `globalgrid2050.${row.family}-dc-context.v1`));
requireValue(equal(row.scope, scope(policy ? n.scope.figure_entity_scope : solar ? n.entity.scope : n.entity_scope,
policy ? n.scope.entity_id : solar ? n.entity.id : n.id, row.family, n.relationship)));
requireValue(row.source_state === (policy ? n.document_state : n.source_state));
requireValue(row.evaluation_state === (policy ? n.state : 'UNKNOWN'));
requireValue(row.applicability_state === (policy ? n.applicability.state : 'UNKNOWN'));
if (policy) requireValue(n.legal_compliance === 'NOT_ASSESSED');
else requireValue(n.canonical_project_id === null && (solar ? n.current_delivery : n.current_project_state) === 'UNKNOWN');
const nativeFigures = policy
? [['TARGET', n.target], ['BASELINE', n.baseline], ...n.updates.map(u => ['UPDATE', u.claim])]
.filter(([, claim]) => claim !== null).map(([role, claim]) => ({role, qualifier: null, claim}))
: n.numeric_claims.map(item => ({role: 'CONTEXT', qualifier: solar ? item.qualifier : null, claim: solar ? item.claim : item}));
requireValue(equal(row.numeric_claims, nativeFigures));
for (const figure of row.numeric_claims) {
requireValue([null, 'stated', 'upper_bound', 'approximate'].includes(figure.qualifier));
requireValue(!claims.has(figure.claim.claim_id)); claims.add(figure.claim.claim_id);
requireValue(figure.claim.entity.id === row.scope.entity_id && figure.claim.entity.scope === row.scope.native_scope);
buildViewModel({entityId: row.scope.entity_id, state: 'available', claims: [figure.claim]});
}
requireValue(Array.isArray(row.source_links) && row.source_links.length > 0);
row.source_links.forEach(validateLink);
}
requireValue(families.every(f => counts[f] > 0));
requireValue(equal(report.coverage, {records: report.records.length, families: counts,
numeric_claims: claims.size, linked_projects: 0, scope: 'BOUNDED_SUPPLIED_CONTEXT'}));
requireValue(Array.isArray(report.input_receipts) && report.input_receipts.length === 3);
const receipts = new Set();
for (const receipt of report.input_receipts) {
keys(receipt, 'family input_schema input_sha256 output_schema record_count source_count source_byte_validation native_metadata');
requireValue(families.includes(receipt.family) && !receipts.has(receipt.family)); receipts.add(receipt.family);
requireValue(receipt.record_count === counts[receipt.family] && digestPattern.test(receipt.input_sha256));
requireValue(receipt.source_byte_validation === 'RECEIPTS_ONLY');
requireValue(receipt.native_metadata.schema === receipt.output_schema && receipt.native_metadata.as_of === report.as_of);
for (const doc of receipt.native_metadata.documents ?? []) {
sourceUrl(doc.url); date(doc.published_on); date(doc.reviewed_at, true); date(doc.retrieved_at, true);
requireValue(doc.content_sha256 === null || digestPattern.test(doc.content_sha256));
}
}
// The payload is already hash-pinned by the host. Still fail closed when
// multiple *internal* copies of the same source contradict each other.
// Neither matching receipts nor a hash pin amounts to source-truth review.
const sourceDocuments = new Map();
const registerSource = (id, receipt) => {
text(id);
const prior = sourceDocuments.get(id);
requireValue(prior === undefined || equal(prior, receipt));
sourceDocuments.set(id, receipt);
};
const policyReceipt = report.input_receipts.find(r => r.family === 'policy');
requireValue(Array.isArray(policyReceipt.native_metadata.documents) &&
policyReceipt.native_metadata.documents.length === policyReceipt.source_count);
for (const doc of policyReceipt.native_metadata.documents) {
sourceUrl(doc.url); date(doc.published_on); date(doc.reviewed_at, true); date(doc.retrieved_at, true);
registerSource(doc.id, doc);
}
for (const family of ['grid', 'solar']) {
const receipt = report.input_receipts.find(r => r.family === family);
const familyRows = report.records.filter(r => r.family === family);
const meta = receipt.native_metadata;
requireValue(meta.context_count === familyRows.length &&
meta.numeric_claim_count === familyRows.reduce((n, row) => n + row.numeric_claims.length, 0) &&
meta.linked_project_count === 0 &&
(meta.source_byte_validation === undefined || meta.source_byte_validation === 'RECEIPTS_ONLY'));
requireValue(Array.isArray(meta.limitations) && meta.limitations.length > 0);
meta.limitations.forEach(text);
for (const row of familyRows) {
const native = row.native_record;
requireValue(row.source_links.length === 1 && native.source && native.source_id === native.source.id);
const link = row.source_links[0];
requireValue(equal(link.receipt, native.source) &&
link.document_id === native.source.document_id &&
link.locator.section === native.section && link.locator.page === native.page);
registerSource(link.document_id, link.receipt);
// A FIGURES claim may not borrow another source's identity, date or locator.
for (const {claim} of row.numeric_claims) {
const p = claim.provenance;
requireValue(p.document_id === link.document_id && p.document_url === link.url &&
p.sha256 === link.sha256 && p.published_date === link.published_date &&
p.retrieved_at === link.retrieved_at && p.section === link.locator.section &&
p.page === link.locator.page);
}
}
}
const asOfTime = Date.parse(report.as_of);
for (const row of report.records) {
if (row.family === 'policy') {
const native = row.native_record;
const references = [native.source, ...native.applicability.evidence,
...native.updates.map(u => u.source)];
for (const ref of references) requireValue(row.source_links.some(link =>
link.document_id === ref.document_id && link.locator.text === ref.locator));
}
for (const link of row.source_links) {
requireValue(equal(sourceDocuments.get(link.document_id), link.receipt));
for (const clock of [link.reviewed_at, link.retrieved_at]) {
if (clock !== null) requireValue(Date.parse(clock) <= asOfTime);
}
if (link.published_date !== null) {
date(link.published_date);
// Date precision may be year, month or day. Reject source publications
// whose earliest possible date is later than the evaluation clock.
const earliestDay = link.published_date.length === 4
? link.published_date + '-01-01'
: link.published_date.length === 7 ? link.published_date + '-01' : link.published_date;
requireValue(Date.parse(earliestDay + 'T00:00:00Z') <= asOfTime);
}
}
}
return report; // untouched native records, nulls, source clocks and metadata
}Adapter Test
A test in the context ui folder of GlobalGrid2050 that checks Adapter and Render, using SHA-256.
testglobalgrid2050 / automation/news/context-ui/adapter.test.mjs · lines 1–126 of 126 · Entry point
- What it does
- It tests solar and the REPD register. Uses libraries node:test, node:assert/strict.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, the REPD register.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- 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 GlobalGrid2050 V928 Preview Acceptance Workflow.
- Application
- globalgrid2050 · automation/news/context-ui · test
- Uses
- Adapter (import), Render (import), Test Support (import), node:test, node:assert/strict
- Used by
- run by GlobalGrid2050 V928 Preview Acceptance 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/context-ui/adapter.test.mjs:1-126 · blob e072452d4dfa295a57a968db10e7fc3b35c9e5c3 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import {readContext, MAX_BYTES, sourceUrl} from './adapter.mjs';
import {evidenceValue, limitationText, isContextHost} from './render.mjs';
import {buildViewModel, raw, report, pins, encode, sha} from './test-support.mjs';
const options = {expectedSha256: pins.fixture_sha256, buildViewModel};
test('existing News or Pipeline tabs may opt in, unrelated hosts may not', () => {
assert.equal(isContextHost({hasAttribute: name => name === 'data-news-context-host'}), true);
assert.equal(isContextHost({hasAttribute: name => name === 'data-pipeline-context-host'}), true);
assert.equal(isContextHost({hasAttribute: () => false}), false);
assert.equal(isContextHost(null), false);
});
test('source acronyms remain exact and unrecognized source limitations survive', () => {
for (const [key, value] of [['country', 'US'], ['country', 'GB'], ['currency', 'GBP'], ['unit', 'MW'], ['id', 'FERC']]) {
assert.equal(evidenceValue(key, value), value);
}
assert.equal(evidenceValue('source_state', 'REJECTED'), 'Rejected');
assert.equal(limitationText('Source excludes developments after 2024.'), 'Source excludes developments after 2024.');
assert.match(limitationText(report.limitations[2]), /Original source files were not checked again/);
assert.match(limitationText(report.limitations[4]), /not a complete treaty history/);
});
test('actual composer export: complete native record and receipt preservation', async () => {
const actual = await readContext(raw, options);
assert.deepEqual(actual, report);
assert.deepEqual(actual.coverage.families, {policy: 8, grid: 2, solar: 4});
assert.equal(actual.coverage.numeric_claims, 3);
assert.equal(actual.coverage.linked_projects, 0);
const policy = actual.records.filter(r => r.family === 'policy');
assert.equal(policy.filter(r => r.evaluation_state === 'UNKNOWN').length, 7);
assert.equal(policy.filter(r => r.evaluation_state === 'REPORTED_PROGRESS').length, 1);
const cop = actual.input_receipts[0].native_metadata.documents.find(d => d.id.startsWith('unfccc:cop31'));
assert.equal(cop.document_state, 'IN_PROGRESS'); assert.equal(cop.content_sha256, null); assert.equal(cop.retrieved_at, null);
assert.ok(actual.records.some(r => r.source_state === 'REJECTED'));
assert.ok(actual.records.some(r => r.scope.kind === 'portfolio' && r.scope.native_scope === 'issuer'));
});
test('pin required, changed bytes rejected, bounded UTF-8 input', async () => {
await assert.rejects(readContext(raw, {buildViewModel}));
await assert.rejects(readContext(raw, {...options, expectedSha256: '0'.repeat(64)}));
await assert.rejects(readContext(new Uint8Array(MAX_BYTES + 1), options));
const bad = new Uint8Array([0xff]);
await assert.rejects(readContext(bad, {...options, expectedSha256: sha(bad)}));
});
const mutations = {
'coverage overstatement': r => r.coverage.records++,
'missing family': r => {r.records = r.records.filter(x => x.family !== 'solar');},
'duplicate row': r => r.records.push(r.records[0]),
'scope inflated to site binding': r => r.records[0].scope.canonical_project_id = 'site:123',
'scope changed to issuer': r => r.records[0].scope.kind = 'issuer',
'native scope disagrees': r => r.records[0].scope.native_scope = 'issuer',
'rejected amendment converted to delivery': r => r.records[0].source_state = 'DELIVERED',
'unknown evaluation promoted': r => r.records[0].evaluation_state = 'EVIDENCE_SUPPORTED_RESULT',
'source clock rewritten': r => r.records[0].source_links[0].published_date = '2026-11-16',
'source URL executable': r => r.records[0].source_links[0].url = 'javascript:alert(1)',
'qualifier stripped': r => r.records.find(x => x.numeric_claims.some(f => f.qualifier === 'upper_bound')).numeric_claims[0].qualifier = 'stated',
'numeric scalar coerced': r => {const f = r.records[0]; f.numeric_claims[0].claim.value = 480; f.native_record.numeric_claims[0].value = 480;},
'figure scope reassigned': r => {const f = r.records[0]; f.numeric_claims[0].claim.entity.scope = 'issuer'; f.native_record.numeric_claims[0].entity.scope = 'issuer';},
'source receipt replaced': r => r.records[0].source_links[0].receipt.sha256 = '0'.repeat(64),
'duplicate input family': r => r.input_receipts[1] = r.input_receipts[0],
'source bytes marked verified': r => r.input_receipts[0].source_byte_validation = 'VERIFIED',
'missing original source record': r => {r.records.find(x => x.family === 'grid').native_record.source = null;},
'fabricated native REPD association': r => {r.records.find(x => x.family === 'solar').native_record.canonical_project_id = 'GG2050-REPD-1234';},
'conflicting source receipt and original context': r => {
const row = r.records.find(x => x.family === 'grid');
row.source_links[0].receipt.sha256 = '0'.repeat(64);
row.source_links[0].sha256 = '0'.repeat(64);
},
'conflicting policy document catalogue': r => {
const row = r.records.find(x => x.family === 'policy');
row.source_links[0].receipt.content_sha256 = '0'.repeat(64);
row.source_links[0].sha256 = '0'.repeat(64);
},
'mismatched producer coverage': r => {r.input_receipts.find(x => x.family === 'solar').native_metadata.context_count++;},
'native source ID disagrees with context': r => {r.records.find(x => x.family === 'solar').native_record.source_id = 'different-source';},
'source timestamp after evaluation': r => {
const row = r.records.find(x => x.family === 'grid' && x.numeric_claims.length);
const stamp = '2027-01-01T00:00:00Z';
row.source_links[0].retrieved_at = stamp;
row.source_links[0].receipt.retrieved_at = stamp;
row.native_record.source.retrieved_at = stamp;
row.numeric_claims[0].claim.provenance.retrieved_at = stamp;
row.native_record.numeric_claims[0].provenance.retrieved_at = stamp;
},
'future source publication day within assessment year': r => {
const row = r.records.find(x => x.family === 'grid' && x.numeric_claims.length === 0);
const future = '2026-11-17'; // as_of is 2026-11-16T18:00:00Z
row.source_links[0].published_date = future;
row.source_links[0].receipt.published_date = future;
row.native_record.source.published_date = future;
},
'future source publication month within assessment year': r => {
const row = r.records.find(x => x.family === 'grid' && x.numeric_claims.length === 0);
const future = '2026-12'; // precision is month, not an assumed current day
row.source_links[0].published_date = future;
row.source_links[0].receipt.published_date = future;
row.native_record.source.published_date = future;
},
'impossible source calendar day': r => {
const row = r.records.find(x => x.family === 'grid');
row.source_links[0].published_date = '2026-02-30';
row.source_links[0].receipt.published_date = '2026-02-30';
row.native_record.source.published_date = '2026-02-30';
},
'policy source citation silently dropped': r => {
const row = r.records.find(x => x.family === 'policy');
row.native_record.source.locator = 'A citation not in the export';
},
'numeric claim borrows different source': r => {
const row = r.records.find(x => x.family === 'solar' && x.numeric_claims.length);
const forged = 'https://unrelated.example.org/document';
row.numeric_claims[0].claim.provenance.document_url = forged;
row.native_record.numeric_claims[0].claim.provenance.document_url = forged;
},
'COP31 source executable': r => r.input_receipts[0].native_metadata.documents[2].url = 'data:text/html,evil',
};
for (const [name, mutate] of Object.entries(mutations)) test(name, async () => {
const changed = structuredClone(report); mutate(changed); const bytes = encode(changed);
await assert.rejects(readContext(bytes, {...options, expectedSha256: sha(bytes)}));
});
for (const url of ['http://example.org/a', 'https://127.0.0.1/', 'https://[::1]/', 'https://localhost/',
'https://example.org@evil.org/', 'https://evil.org:444/', 'https://evil.local/', 'https://evil.org\\@good.org/', ' javascript:alert(1)']) {
test(`unsupported URL ${url}`, () => assert.throws(() => sourceUrl(url)));
}
test('copied input prevents changes during asynchronous digest', async () => {
const bytes = raw.slice(); const pending = readContext(bytes, options); bytes.fill(0);
assert.deepEqual(await pending, report);
});Browser
A JavaScript module in the context ui folder of GlobalGrid2050 that fetches fixture, using SHA-256.
interactionglobalgrid2050 / automation/news/context-ui/browser.mjs · lines 1–116 of 116 · Not reached from any entry point (candidate for review)
- What it does
- It fetches fixture. Uses libraries node:assert/strict, node:fs/promises, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file fixture.json. Out: JSON file proof.json.
- What it achieves
- Real Chrome proof, using actual exporter bytes and the external pinned renderer. Its code works with 280 MW, 350 MW and 480 MW. It reads `/fixture.json`. It responds to click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · automation/news/context-ui · JavaScript module
- Uses
- Test Support (import), node:assert/strict, node:fs/promises, node:path, node:url, /figures/model.mjs
- 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/news/context-ui/browser.mjs:1-116 · blob a9fde90ca1e9be0ae245fe2a56255d8a4bc594e8 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/** Real Chrome proof, using actual exporter bytes and the external pinned renderer. */
import assert from 'node:assert/strict';
import {readFile, writeFile, mkdir} from 'node:fs/promises';
import {resolve} from 'node:path';
import {pathToFileURL} from 'node:url';
import {directory, figuresDirectory, raw, pins, sha} from './test-support.mjs';
assert.ok(process.env.CONTEXT_UI_ARTIFACTS, 'Explicit CONTEXT_UI_ARTIFACTS directory required');
const artifacts = resolve(process.env.CONTEXT_UI_ARTIFACTS);
const {chromium} = await import(process.env.PLAYWRIGHT_MODULE ? pathToFileURL(resolve(process.env.PLAYWRIGHT_MODULE)).href : 'playwright');
const html = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Context UI integration proof</title><link rel="stylesheet" href="/context.css"><link rel="stylesheet" href="/figures/figures.css">
<body><main><section id="news" aria-label="News" data-news-context-host><h1>News</h1><button id="sentinel">Existing news control</button></section><section id="pipeline" aria-label="Pipeline" data-pipeline-context-host><h1>Pipeline</h1></section></main>
<script type="module" src="/boot.mjs"></script></body></html>`;
const boot = `import {renderContext} from '/render.mjs';
import {buildViewModel} from '/figures/model.mjs'; import {renderFigures} from '/figures/render.mjs';
const host = document.querySelector(location.hash === '#pipeline' ? '#pipeline' : '#news'); window.sentinel = document.querySelector('#sentinel');
window.clicks = 0; sentinel.addEventListener('click', () => window.clicks++);
window.original = new Uint8Array(await (await fetch('/fixture.json')).arrayBuffer());
window.hash = async b => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', b)), x => x.toString(16).padStart(2,'0')).join('');
window.render = (b, pin) => renderContext(host, b, {expectedSha256: pin, figures: {buildViewModel,renderFigures}});
await window.render(window.original, '${pins.fixture_sha256}'); window.ready = true;`;
const resources = new Map([['/', ['text/html', html]], ['/boot.mjs', ['text/javascript', boot]],
['/fixture.json', ['application/json', raw]]]);
for (const name of ['adapter.mjs', 'render.mjs', 'context.css']) resources.set('/' + name,
[name.endsWith('.css') ? 'text/css' : 'text/javascript', await readFile(resolve(directory, name))]);
for (const name of Object.keys(pins.figures_files)) resources.set('/figures/' + name,
[name.endsWith('.css') ? 'text/css' : 'text/javascript', await readFile(resolve(figuresDirectory, name))]);
// Route-only loopback origin: no network sockets or production server required.
const origin = 'http://127.0.0.1:18329';
const results = []; let browser;
try {
await mkdir(artifacts, {recursive: true});
browser = await chromium.launch({headless: true, channel: 'chrome', args: ['--no-proxy-server']});
for (const width of [375, 390, 393, 768, 1440]) {
const context = await browser.newContext({viewport: {width, height: 950}, serviceWorkers: 'block'});
const external = [], errors = [];
await context.route('**/*', route => {
const url = new URL(route.request().url());
const resource = url.origin === origin && route.request().method() === 'GET' && resources.get(url.pathname + url.search);
if (resource) return route.fulfill({status: 200, contentType: resource[0] + '; charset=utf-8',
headers: {'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'none'; object-src 'none'; base-uri 'none'"},
body: typeof resource[1] === 'string' ? resource[1] : Buffer.from(resource[1])});
external.push(route.request().url()); return route.abort();
});
const page = await context.newPage(); page.on('pageerror', error => errors.push(error.message));
const hostSelector = width === 390 || width === 393 ? '#pipeline' : '#news';
await page.goto(origin + (hostSelector === '#pipeline' ? '/#pipeline' : '/')); await page.waitForFunction(() => window.ready);
assert.equal(await page.locator('[data-transition-context-root]').getAttribute('data-state'), 'available');
assert.equal(await page.locator(hostSelector + ' > [data-transition-context-root]').count(), 1);
assert.equal(await page.locator('[data-context-id]').count(), 14);
assert.equal(await page.locator('[data-figure-claim]').count(), 3);
assert.deepEqual(await page.evaluate(() => {
const root = document.querySelector('[data-transition-context-root]');
const figure = root.querySelector('[data-filings-figures-root]');
const amount = figure.querySelector('[data-figure-value]');
const host = getComputedStyle(root.parentElement);
return {font: getComputedStyle(amount).fontSize === host.fontSize,
color: getComputedStyle(figure).color === host.color,
background: getComputedStyle(figure).backgroundColor,
native: root.contextReport.records.length};
}), {font: true, color: true, background: 'rgba(0, 0, 0, 0)', native: 14});
await page.locator('[data-transition-context-root] > summary').click();
// Keyboard access uses native disclosure semantics.
const first = page.locator('[data-context-id]').first();
await first.locator(':scope > summary').focus(); await page.keyboard.press('Enter');
assert.equal(await first.getAttribute('open'), '');
await page.evaluate(() => document.querySelectorAll('[data-context-id] > details.filings-figures, [data-context-figure] > details').forEach(x => x.open = true));
const text = await page.locator('[data-transition-context-root]').textContent();
for (const required of ['Rejected', 'Unknown', 'Reported progress', 'In progress', 'Upper bound (up to)',
'2021-09-22', '2024', 'Published:', 'Reviewed:', 'Retrieved:', 'Not confirmed', 'Not assessed',
'Original source files were not checked again', 'not a complete treaty history', 'Country: US', 'Country: GB']) assert.ok(text.includes(required), required);
assert.equal(await page.locator('[data-figure-value]').allTextContents().then(v => v.join('|')), '480 MW|350 MW|280 MW');
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
for (const a of await page.locator('[data-transition-context-root] a').all()) {
assert.ok((await a.getAttribute('href')).startsWith('https://'));
assert.match(await a.getAttribute('rel'), /noopener/);
}
await page.locator('#sentinel').click(); assert.equal(await page.evaluate(() => clicks), 1);
const screenshot = `context-${width}.png`; await page.screenshot({path: resolve(artifacts, screenshot), fullPage: true});
// Hostile markup is plain text, including native history and background metadata.
await page.evaluate(async () => {
const r = JSON.parse(new TextDecoder().decode(original));
const evil = '<img src=x onerror="window.pwned=1"><script>window.pwned=1</script>';
r.records[0].title = evil; r.records[0].native_record.name = evil;
r.records[0].native_record.research_action = evil;
r.records[0].native_record.revision_history = [{state: 'REJECTED', superseded_by: null, text: evil}];
const bytes = new TextEncoder().encode(JSON.stringify(r)); await render(bytes, await hash(bytes));
});
assert.equal(await page.locator('[data-transition-context-root] img, [data-transition-context-root] script').count(), 0);
assert.equal(await page.evaluate(() => window.pwned), undefined);
assert.ok((await page.locator('[data-transition-context-root]').textContent()).includes('Revision history'));
// Failed refresh must clear every stale value and preserve neighboring controls.
await page.evaluate(async () => render(original, '0'.repeat(64)));
assert.equal(await page.locator('[data-transition-context-root]').getAttribute('data-state'), 'unavailable');
assert.equal(await page.locator('[data-figure-claim], [data-context-id]').count(), 0);
assert.equal(await page.evaluate(() => sentinel === document.querySelector('#sentinel')), true);
await page.locator('#sentinel').click(); assert.equal(await page.evaluate(() => clicks), 2);
// A later bad request wins even if an earlier digest is still pending.
await page.evaluate(async pin => Promise.all([render(original, pin), render(original, 'bad')]), pins.fixture_sha256);
assert.equal(await page.locator('[data-transition-context-root]').getAttribute('data-state'), 'unavailable');
assert.equal(await page.locator('[data-transition-context-root]').count(), 1);
assert.deepEqual(external, []); assert.deepEqual(errors, []);
results.push({width, host: hostSelector, checks: ['actual exporter', '14 contexts', '3 exact figures', 'inherited typography and colors', 'complete native data retained', 'unknown and historical states',
'distinct clocks', 'upper-bound qualifier', 'native keyboard disclosure', 'no horizontal overflow',
'safe source links', 'text escaped', 'history retained', 'stale values cleared', 'neighbor control preserved', 'latest request wins', 'no external requests'],
screenshot, screenshot_sha256: sha(await readFile(resolve(artifacts, screenshot)))});
await context.close();
}
const proof = {browser: 'Chrome', version: browser.version(), actual_export_sha256: pins.fixture_sha256,
renderer_commit: pins.figures_commit, transport: 'Playwright route fulfillment from whitelisted local bytes; no HTTP server',
results, scope: 'Local isolated component; no live release, Android, or project integration acceptance'};
await writeFile(resolve(artifacts, 'proof.json'), JSON.stringify(proof, null, 2) + '\n');
console.log(JSON.stringify(proof, null, 2));
} finally {
await browser?.close();
}