In this section
- Build ingest · globalgrid2050 / automation/v928_context/build.py lines 1–127
- Figures render · globalgrid2050 / automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/figures.css lines 1–108
- Model transform · globalgrid2050 / automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/model.mjs lines 1–216
- Render render · globalgrid2050 / automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/render.mjs lines 1–153
- Verify Imports ingest · globalgrid2050 / automation/v928_intelligence/verify_imports.py lines 1–33
Build
A Python command-line tool in the automation folder of GlobalGrid2050 that reads closure, ledger, grid fixture and solar context, using SHA-256.
ingestglobalgrid2050 / automation/v928_context/build.py · lines 1–127 of 127 · Entry point · pattern assemble (shared by 13 files)
- What it does
- It loads closure, ledger, grid fixture and solar context. Defines digest, source_bytes, assemble, main. Uses libraries __future__, argparse, hashlib, importlib, json. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file closure.json; JSON file sample_ledger.json; JSON file grid-source-fixture.json; JSON file solar-context.json; JSON file transition-context.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It is built from the digest step (`digest`), the source bytes helper (`source_bytes`) and the assemble step (`assemble`). Package the existing, pinned Context producer and renderer for a local preview. It reads `automation/news/policy_commitments/sample_ledger.json`. It accepts `--repository-root`, `--figures-dir` and `--verify-validation`.
- Why it matters
- Run by GlobalGrid2050 V928 Preview Acceptance Workflow.
- Application
- globalgrid2050 · automation/v928_context · Python CLI
- Uses
- __future__, argparse, hashlib, importlib, json, pathlib, sys
- Used by
- run by GlobalGrid2050 V928 Preview Acceptance Workflow (workflow run)
- Produces
- digest, source_bytes, assemble, main
- Defines here
- digest, source_bytes, assemble, 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/v928_context/build.py:1-127 · blob 51612fc97f6b2dd4c32f9969223449d1639af43c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
"""Package the existing, pinned Context producer and renderer for a local preview.
No collection, new project binding, rights decision or publication is performed.
By default only verify dependencies and regenerate the accepted export in memory.
An explicit new output directory stages an unchanged, self-contained browser cache.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib
import json
from pathlib import Path
import sys
DIRECTORY = Path(__file__).resolve().parent
def digest(raw):
return hashlib.sha256(raw).hexdigest()
def source_bytes(path, expected):
"""Accept only exact Git bytes or Windows CRLF-only checkout conversion."""
raw = path.read_bytes()
if digest(raw) != expected:
raw = raw.replace(b"\r\n", b"\n")
if digest(raw) != expected:
raise ValueError("Pinned Context dependency changed")
return raw
def assemble(repository, figures_directory, *, include_validation=False):
closure = json.loads((DIRECTORY / "closure.json").read_text(encoding="utf-8"))
verified = {}
for entry in closure["source_files"]:
if entry["role"] == "validation" and not include_validation:
continue
verified[entry["path"]] = source_bytes(repository / entry["path"], entry["sha256"])
figures = {}
for name, expected in closure["figures"]["files"].items():
raw = (figures_directory / name).read_bytes()
if digest(raw) != expected:
raise ValueError("Pinned FIGURES dependency changed; exact source bytes required")
figures[name] = raw
sys.path.insert(0, str(repository))
composer = importlib.import_module("automation.news.build_transition_context")
read = lambda relative: json.loads(verified[relative])
report = composer.build(
read("automation/news/policy_commitments/sample_ledger.json"),
read("automation/news/dc_context/grid-source-fixture.json"),
read("automation/news/dc_context/fixtures/solar-context.json"),
as_of=closure["export"]["as_of"],
)
raw = composer.dumps(report).encode("utf-8")
if digest(raw) != closure["export"]["sha256"]:
raise ValueError("Actual composer export differs from the independently pinned fixture")
expected = {"records": 14, "families": {"policy": 8, "grid": 2, "solar": 4},
"numeric_claims": 3, "linked_projects": 0,
"scope": "BOUNDED_SUPPLIED_CONTEXT"}
if report["coverage"] != expected or report["status"] != "PROVISIONAL":
raise ValueError("Context coverage or provisional boundary changed")
if any(row["scope"]["canonical_project_id"] is not None
or row["scope"]["binding"] != "UNLINKED" for row in report["records"]):
raise ValueError("Context must not acquire a project association")
files = {"transition-context.json": raw}
for name in ("adapter.mjs", "render.mjs", "context.css"):
files[name] = verified["automation/news/context-ui/" + name]
figures_prefix = "figures/" + closure["figures"]["commit"] + "/"
files.update({figures_prefix + name: value for name, value in figures.items()})
manifest = {
"schema": "globalgrid2050.v928-context-preview.v1",
"preview_only": True,
"publication_authorized": False,
"source_rights_status": "UNASSESSED",
"source_repository": closure["source_repository"],
"source_commit": closure["source_commit"],
"as_of": closure["export"]["as_of"],
"transition_context_sha256": closure["export"]["sha256"],
"coverage": expected,
"figures": {**closure["figures"], "cache_directory": figures_prefix},
"files": {name: {"sha256": digest(data), "bytes": len(data)}
for name, data in sorted(files.items())},
"limitations": report["limitations"],
}
files["manifest.json"] = (json.dumps(manifest, sort_keys=True, indent=2) + "\n").encode("utf-8")
return files, manifest
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repository-root", type=Path, default=DIRECTORY.parents[1])
parser.add_argument("--figures-dir", type=Path, required=True)
parser.add_argument("--verify-validation", action="store_true")
parser.add_argument("--output-dir", type=Path,
help="Explicit NEW local-preview directory; never overwrite")
args = parser.parse_args(argv)
try:
files, manifest = assemble(args.repository_root.resolve(), args.figures_dir.resolve(),
include_validation=args.verify_validation)
if args.output_dir is not None:
# Validate the entire bundle before creating anything. Manifest is last:
# an interrupted staging attempt has no complete consumer manifest.
destination = args.output_dir.resolve()
destination.mkdir(parents=False, exist_ok=False)
for name, raw in files.items():
target = destination / name
target.parent.mkdir(parents=True, exist_ok=True)
with target.open("xb") as handle:
handle.write(raw)
print(json.dumps({"status": "PASS", "scope": "local provisional Context preview only",
"source_commit": manifest["source_commit"],
"export_sha256": manifest["transition_context_sha256"],
"manifest_sha256": digest(files["manifest.json"]),
"coverage": manifest["coverage"],
"source_rights_status": "UNASSESSED", "publication_authorized": False},
indent=2, sort_keys=True))
except (OSError, ValueError, ImportError, KeyError, TypeError) as exc:
parser.exit(2, f"Context preview withheld: {type(exc).__name__}: {exc}\n")
return 0
if __name__ == "__main__":
raise SystemExit(main())Figures
A style sheet in the automation folder of GlobalGrid2050.
renderglobalgrid2050 / automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/figures.css · lines 1–108 of 108 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
- What it achieves
- Scoped inline disclosure; no host, navigation, map or global element styles.
- Why it matters
- Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/.
- Application
- globalgrid2050 · automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20 · style sheet
- Uses
- none found
- Used by
- loaded by GlobalGrid2050 — UK Renewables Pipeline 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/figures.css:1-108 · blob b92df82dcf062d12d406361268aee5bcaa37d9bf · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: production_core
/* Scoped inline disclosure; no host, navigation, map or global element styles. */
[data-filings-figures-root] {
box-sizing: border-box;
min-width: 0;
max-width: 100%;
margin-block: 0.75rem;
border: 1px solid #68798b;
border-radius: 0.5rem;
background: #f7f9fc;
color: #172435;
font: inherit;
line-height: 1.5;
overflow-wrap: anywhere;
}
[data-filings-figures-root] *,
[data-filings-figures-root] *::before,
[data-filings-figures-root] *::after {
box-sizing: border-box;
min-width: 0;
max-width: 100%;
}
[data-filings-figures-root] .ff-summary {
cursor: pointer;
padding: 0.75rem;
font-weight: 650;
}
[data-filings-figures-root] .ff-summary::marker { color: #264c70; }
[data-filings-figures-root] .ff-summary-title { margin-inline-end: 0.5rem; }
[data-filings-figures-root] .ff-badge {
display: inline-block;
margin-block: 0.1rem;
padding: 0.05rem 0.5rem;
border: 1px solid #8b6808;
border-radius: 0.3rem;
background: #fff3c9;
color: #584000;
font-size: 0.8em;
vertical-align: baseline;
}
[data-filings-figures-root] .ff-content { padding: 0 0.75rem 0.75rem; }
[data-filings-figures-root] .ff-notice,
[data-filings-figures-root] .ff-empty { margin: 0.25rem 0 0.5rem; }
[data-filings-figures-root] .ff-claims {
display: grid;
gap: 0.75rem;
margin: 0;
padding: 0;
list-style: none;
}
[data-filings-figures-root] .ff-claim {
margin: 0;
padding: 0.75rem;
border: 1px solid #b0bdca;
border-radius: 0.35rem;
background: #fff;
}
[data-filings-figures-root] .ff-metric { margin: 0; font-weight: 650; }
[data-filings-figures-root] .ff-amount {
margin: 0.15rem 0;
font-size: 1.15em;
font-weight: 700;
font-variant-numeric: tabular-nums;
white-space: normal;
}
[data-filings-figures-root] .ff-original-unit,
[data-filings-figures-root] .ff-status,
[data-filings-figures-root] .ff-source { margin: 0.25rem 0; font-size: 0.9em; }
[data-filings-figures-root] .ff-status { color: #654900; }
[data-filings-figures-root] .ff-inline-label { font-weight: 600; }
[data-filings-figures-root] .ff-fields {
display: grid;
grid-template-columns: minmax(0, 8.5rem) minmax(0, 1fr);
column-gap: 0.75rem;
row-gap: 0.25rem;
margin: 0.75rem 0;
font-size: 0.9em;
}
[data-filings-figures-root] .ff-field-label { margin: 0; color: #43566b; }
[data-filings-figures-root] .ff-field-value { margin: 0; white-space: normal; }
[data-filings-figures-root] .ff-source-link { color: #164d87; text-underline-offset: 0.2em; }
[data-filings-figures-root] .ff-source-link:hover { text-decoration-thickness: 0.15em; }
[data-filings-figures-root] .ff-source-host { color: #43566b; }
[data-filings-figures-root] .ff-summary:focus-visible,
[data-filings-figures-root] .ff-source-link:focus-visible {
outline: 3px solid #1767bd;
outline-offset: 3px;
border-radius: 0.15rem;
}
@media (max-width: 480px) {
[data-filings-figures-root] .ff-fields { grid-template-columns: minmax(0, 1fr); row-gap: 0.1rem; }
[data-filings-figures-root] .ff-field-label { margin-top: 0.35rem; font-weight: 600; }
[data-filings-figures-root] .ff-summary,
[data-filings-figures-root] .ff-claim { padding: 0.625rem; }
[data-filings-figures-root] .ff-content { padding: 0 0.625rem 0.625rem; }
}Model
A JavaScript module in the figures folder of GlobalGrid2050 that validates claim (`validateClaim`), using SHA-256. It validates claim (`validateClaim`) and builds view model (`buildViewModel`).
transformglobalgrid2050 / automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/model.mjs · lines 1–216 of 216 · pattern choice (shared by 2 files)
- What it does
- It calculates its inputs. Defines 14 functions or classes, including FigureModelError, fail, fullMatch, object, claimsArray.
- Downstream impact
- Used directly by 2 files: Preview V928 (globalgrid2050); Render (globalgrid2050). Reached from 5 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents).
- What it achieves
- Offline browser/Node view adapter for pinned FIGURES .
- Why it matters
- Imported by Preview V928 and Render.
- Application
- globalgrid2050 · automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20 · JavaScript module
- Uses
- none found
- Used by
- imported by Preview V928 (dynamic import), imported by Render (import)
- Produces
- MODEL_SCHEMA, CLAIM_SCHEMA, MAX_CLAIMS, FigureModelError, buildViewModel
- Defines here
- FigureModelError, fail, fullMatch, object, claimsArray, text, id, choice, sourceDate, timestampDate, url, validateClaim, row, buildViewModel
- 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/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/model.mjs:1-216 · blob b804f1b50899d5c18b84268e681969ebbcc0cc77 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: production_core
/** Offline browser/Node view adapter for pinned FIGURES e0deabac.
* No extraction, association, number conversion, source fetch or publication.
* Claims remain source assertions. This UI accepts HTTPS DNS URLs only; public
* IP-literal URLs admitted by the Python contract are unsupported in this slice.
*/
export const MODEL_SCHEMA = 'testcode.filing-figures-view.v1';
export const CLAIM_SCHEMA = 'globalgrid2050.filing-figure.v1';
export const MAX_CLAIMS = 100;
const POWER = ['generation_power', 'storage_power', 'it_load', 'project_demand', 'secured_connection', 'energised_load', 'grid_upgrade'];
const ENERGY = ['storage_energy', 'generation_energy', 'energy_procurement'];
const SCOPES = ['issuer', 'consolidated_group', 'project', 'site', 'campus', 'phase', 'public_institution'];
const CLAIM_KEYS = ['schema', 'claim_id', 'status', 'quantity_kind', 'metric', 'value', 'scale', 'unit', 'original_unit', 'currency', 'finance_stage', 'entity', 'reporting_period', 'as_of', 'basis', 'assurance', 'provenance', 'revision'];
const LABELS = {
finance: 'Finance', generation_power: 'Generation power', storage_power: 'Storage power',
it_load: 'IT load', project_demand: 'Project demand', secured_connection: 'Secured connection',
energised_load: 'Energised load', grid_upgrade: 'Grid upgrade', storage_energy: 'Storage energy',
generation_energy: 'Generation energy', energy_procurement: 'Energy procurement',
issuer: 'Issuer', consolidated_group: 'Consolidated group', project: 'Project', site: 'Site',
campus: 'Campus', phase: 'Phase', public_institution: 'Public institution',
forecast: 'Forecast', reported: 'Reported', announced: 'Announced', committed: 'Committed', disbursed: 'Disbursed',
};
const ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
const DECIMAL = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/;
const SOURCE_DATE = /^([0-9]{4})(?:-([0-9]{2})(?:-([0-9]{2}))?)?$/;
const TIMESTAMP = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]{1,6})?(Z|[+-]([0-9]{2}):([0-9]{2}))$/;
export class FigureModelError extends TypeError {}
function fail(field, reason) { throw new FigureModelError(`${field}: ${reason}`); }
function fullMatch(pattern, value) { return pattern.exec(value)?.[0] === value; }
function object(value, keys, field) {
if (!value || typeof value !== 'object' || Array.isArray(value)
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail(field, 'expected a plain object');
const own = Reflect.ownKeys(value);
if (own.length !== keys.length || own.some(key => !keys.includes(key))) fail(field, 'unexpected or missing fields');
for (const key of own) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (!descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) fail(field, 'expected JSON data properties');
}
return value;
}
function claimsArray(value) {
if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || value.length > MAX_CLAIMS) {
fail('claims', 'expected an ordinary dense JSON array of at most 100 claims');
}
// Array.from and iteration would execute caller-controlled Symbol.iterator,
// allowing an empty/short array to yield arbitrary rows after the length gate.
const keys = Reflect.ownKeys(value);
if (keys.length !== value.length + 1 || keys.some(key => typeof key !== 'string')) fail('claims', 'unexpected array properties');
const snapshot = [];
for (let i = 0; i < value.length; i += 1) {
const descriptor = Object.getOwnPropertyDescriptor(value, String(i));
if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {
fail('claims', 'expected dense array data entries');
}
snapshot.push(descriptor.value);
}
// Dense entries + the built-in length exhaust the exact own-key count above;
// no named property, symbol, accessor or custom prototype can pass through.
return snapshot;
}
function text(value, field, max = 200) {
if (typeof value !== 'string' || !value || Array.from(value).length > max || value.trim() !== value
|| value.startsWith('\u0085') || value.endsWith('\u0085')
|| /[\u0000-\u001f\u007f\ud800-\udfff]/u.test(value)) fail(field, 'expected bounded nonempty text');
return value;
}
function id(value, field) {
if (typeof value !== 'string' || !fullMatch(ID, value)) fail(field, 'invalid identifier');
return value;
}
function choice(value, options, field) {
if (typeof value !== 'string' || !options.includes(value)) fail(field, 'unsupported value');
return value;
}
function sourceDate(value, field) {
if (typeof value !== 'string') fail(field, 'expected a source date');
const m = SOURCE_DATE.exec(value);
if (!m || m[0] !== value) fail(field, 'expected YYYY, YYYY-MM or YYYY-MM-DD');
// These are calendar components only. Financial quantity strings never pass
// through Number, parseFloat, Intl.NumberFormat or arithmetic.
const year = Number(m[1]), month = m[2] ? Number(m[2]) : 1, day = m[3] ? Number(m[3]) : 1;
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (year < 1 || month < 1 || month > 12 || day < 1 || day > days[month - 1]) fail(field, 'invalid calendar date');
return `${m[1]}-${m[2] || '01'}-${m[3] || '01'}`;
}
function timestampDate(value, field) {
if (typeof value !== 'string') fail(field, 'timestamp requires timezone');
const m = TIMESTAMP.exec(value);
if (!m || m[0] !== value) fail(field, 'timestamp requires seconds and timezone');
const day = sourceDate(value.slice(0, 10), field);
if (Number(m[4]) > 23 || Number(m[5]) > 59 || Number(m[6]) > 59
|| (m[7] !== 'Z' && (Number(m[8]) > 23 || Number(m[9]) > 59))) fail(field, 'invalid timestamp');
// Python contract compares the retrieval calendar date in its supplied offset.
// Do not silently normalize to UTC and move a source's day boundary.
return day;
}
function url(value, field) {
text(value, field, 2048);
if (!/^[\x21-\x7e]+$/.test(value) || value.includes('\\')) fail(field, 'expected ASCII HTTPS URL');
const authority = /^https:\/\/([^/?#]+)/.exec(value)?.[1];
if (!authority || authority.includes('@')) fail(field, 'expected HTTPS URL without credentials');
const parts = /^([^:]+)(?::(443))?$/.exec(authority);
if (!parts) fail(field, 'IP literals and custom ports are unsupported');
const hostname = parts[1].toLowerCase();
const labels = hostname.split('.');
if (labels.length < 2 || labels.some(label => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))
|| !/^[a-z]{2,63}$/.test(labels.at(-1))
|| ['localhost', 'local', 'internal', 'test', 'invalid'].includes(labels.at(-1))) {
fail(field, 'expected a public DNS-form hostname');
}
let parsed;
try { parsed = new URL(value); } catch { fail(field, 'invalid URL'); }
if (parsed.protocol !== 'https:' || parsed.hostname !== hostname || parsed.username || parsed.password) fail(field, 'ambiguous URL');
return value;
}
function validateClaim(claim, entityId) {
const c = object(claim, CLAIM_KEYS, 'claim');
choice(c.schema, [CLAIM_SCHEMA], 'schema');
choice(c.status, ['machine-provisional'], 'status');
id(c.claim_id, 'claim_id');
const kind = choice(c.quantity_kind, [...POWER, ...ENERGY, 'finance'], 'quantity_kind');
text(c.metric, 'metric');
if (typeof c.value !== 'string' || c.value.length > 100 || !fullMatch(DECIMAL, c.value)) fail('value', 'expected exact decimal string');
if (kind !== 'finance' && c.value.startsWith('-') && /[1-9]/.test(c.value)) fail('value', 'negative power/energy');
choice(c.scale, ['1', '1e3', '1e6', '1e9', '1e12'], 'scale');
text(c.original_unit, 'original_unit', 100);
if (kind === 'finance') {
choice(c.unit, ['currency'], 'unit');
if (typeof c.currency !== 'string' || !fullMatch(/^[A-Z]{3}$/, c.currency)) fail('currency', 'explicit currency label required');
choice(c.finance_stage, ['announced', 'committed', 'disbursed', 'reported'], 'finance_stage');
} else {
choice(c.unit, POWER.includes(kind) ? ['W', 'kW', 'MW', 'GW'] : ['Wh', 'kWh', 'MWh', 'GWh', 'TWh'], 'unit');
if (c.currency !== null || c.finance_stage !== null) fail('currency/finance_stage', 'must be null for power/energy');
}
const entity = object(c.entity, ['scope', 'id', 'consolidation_group_id', 'identity_evidence_url'], 'entity');
choice(entity.scope, SCOPES, 'entity.scope');
id(entity.id, 'entity.id');
if (entity.id !== entityId) fail('entity.id', 'does not match selected entity');
url(entity.identity_evidence_url, 'entity.identity_evidence_url');
if (entity.consolidation_group_id !== null) id(entity.consolidation_group_id, 'entity.consolidation_group_id');
if (entity.scope === 'consolidated_group' && entity.consolidation_group_id !== entity.id) fail('entity.consolidation_group_id', 'group must retain own identity');
choice(c.basis, ['reported', 'forecast'], 'basis');
choice(c.assurance, ['audited', 'unaudited', 'unknown'], 'assurance');
if (c.basis === 'forecast' && c.assurance === 'audited') fail('assurance', 'forecast cannot be audited actual');
const provenance = object(c.provenance, ['document_id', 'document_url', 'sha256', 'page', 'section', 'published_date', 'retrieved_at'], 'provenance');
id(provenance.document_id, 'provenance.document_id');
url(provenance.document_url, 'provenance.document_url');
if (typeof provenance.sha256 !== 'string' || !fullMatch(/^[a-f0-9]{64}$/, provenance.sha256)) fail('provenance.sha256', 'source byte hash required');
for (const key of ['page', 'section']) if (provenance[key] !== null) text(provenance[key], `provenance.${key}`);
if (provenance.page === null && provenance.section === null) fail('provenance', 'page or section required');
const retrievedDate = timestampDate(provenance.retrieved_at, 'provenance.retrieved_at');
if (provenance.published_date !== null && sourceDate(provenance.published_date, 'provenance.published_date') > retrievedDate) fail('provenance.published_date', 'publication follows retrieval');
if (c.as_of !== null && sourceDate(c.as_of, 'as_of') > retrievedDate && c.basis !== 'forecast') fail('as_of', 'future date requires forecast');
if (c.reporting_period !== null) {
const period = object(c.reporting_period, ['start', 'end'], 'reporting_period');
const start = sourceDate(period.start, 'reporting_period.start'), end = sourceDate(period.end, 'reporting_period.end');
if (period.start.length !== period.end.length || end < start) fail('reporting_period', 'ordered equal-precision bounds required');
if (c.basis === 'reported' && end > retrievedDate) fail('reporting_period', 'future period requires forecast');
} else if (c.as_of === null) fail('reporting_period/as_of', 'source temporal basis required');
const revision = object(c.revision, ['id', 'supersedes_claim_id', 'restated'], 'revision');
id(revision.id, 'revision.id');
if (revision.supersedes_claim_id !== null) {
id(revision.supersedes_claim_id, 'revision.supersedes_claim_id');
if (revision.supersedes_claim_id === c.claim_id) fail('revision', 'claim cannot supersede itself');
}
if (typeof revision.restated !== 'boolean' || (revision.restated && revision.supersedes_claim_id === null)) fail('revision', 'restatement requires an earlier claim');
return JSON.parse(JSON.stringify(c));
}
function row(claim) {
const p = claim.provenance, r = claim.revision;
const period = claim.reporting_period;
const amount = `${claim.value}${claim.scale === '1' ? '' : ` × ${claim.scale}`} ${claim.currency || claim.unit}`;
return { id: claim.claim_id, claim, display: {
amount, quantityKind: LABELS[claim.quantity_kind], basis: LABELS[claim.basis],
assurance: claim.assurance === 'unknown' ? 'Unknown' : `${claim.assurance === 'audited' ? 'Audited' : 'Unaudited'} (source assertion)`,
financeStage: claim.finance_stage === null ? 'Not applicable' : LABELS[claim.finance_stage],
entityScope: LABELS[claim.entity.scope],
period: period === null ? 'Unknown' : (period.start === period.end ? period.start : `${period.start} to ${period.end}`),
asOf: claim.as_of ?? 'Unknown',
sourceLocator: [p.page === null ? null : `Page ${p.page}`, p.section].filter(value => value !== null).join(' · '),
publishedDate: p.published_date ?? 'Unknown', retrievedAt: p.retrieved_at,
revision: `${r.id} · ${r.restated ? 'Restated' : 'Restatement not asserted'}${r.supersedes_claim_id === null ? '' : ` · Supersedes ${r.supersedes_claim_id}`}`,
status: 'Provisional; not independently verified',
} };
}
/** Validate the entire input before returning any rows; caller clears stale UI on error. */
export function buildViewModel(input) {
object(input, ['entityId', 'claims', 'state'], 'input');
id(input.entityId, 'entityId');
choice(input.state, ['available', 'unknown', 'unavailable'], 'state');
const claims = claimsArray(input.claims);
if (input.state !== 'available' && claims.length !== 0) fail('claims', 'nonavailable states require empty claims');
const ids = new Set();
const rows = [];
for (let i = 0; i < claims.length; i += 1) {
const validated = validateClaim(claims[i], input.entityId);
if (ids.has(validated.claim_id)) fail('claim_id', 'duplicate claim');
ids.add(validated.claim_id);
rows.push(row(validated));
}
const messages = {
available: rows.length ? 'Source figures are provisional. Each keeps its own unit, scope and period; no total is calculated.' : 'No figures have been supplied.',
unknown: 'No source figures are known for this entity. Unknown does not mean zero.',
unavailable: 'Source figures are currently unavailable. This does not mean zero.',
};
return {
schema: MODEL_SCHEMA, entityId: input.entityId, state: input.state,
stateLabel: { available: rows.length ? 'Figures supplied' : 'No figures supplied', unknown: 'Figures unknown', unavailable: 'Figures unavailable' }[input.state],
message: messages[input.state], rows, publishable: false,
};
}Render
A JavaScript module in the figures folder of GlobalGrid2050 that adds field (`addField`). It adds field (`addField`), renders row (`renderRow`) and renders figures (`renderFigures`).
renderglobalgrid2050 / automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/render.mjs · lines 1–153 of 153 · pattern sourceUrl (shared by 2 files)
- What it does
- It draws its content. Defines 7 functions or classes, including element, knownText, sourceUrl, addField, renderRow. Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: Preview V928 (globalgrid2050). Reached from 5 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents).
- What it achieves
- Inline, provisional filing figures. No extraction or publication authority.
- Why it matters
- Imported by Preview V928.
- Application
- globalgrid2050 · automation/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20 · JavaScript module
- Uses
- Model (import)
- Used by
- imported by Preview V928 (dynamic import)
- Produces
- renderFigures
- Defines here
- element, knownText, sourceUrl, addField, renderRow, detailsRoot, renderFigures
- 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/v928_context/preview/figures/b460cb7f76172691b5ffb6d2a7f1a8e12057ba20/render.mjs:1-153 · blob 14e893f30b85d0a6e12bb9da0ddab5bd38bd350d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: production_core
/** Inline, provisional filing figures. No extraction or publication authority. */
import { buildViewModel } from './model.mjs';
const ROOT_ATTRIBUTE = 'data-filings-figures-root';
function element(document, tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function knownText(value) {
return value === null || value === undefined || value === '' ? 'Unknown' : String(value);
}
function sourceUrl(value) {
if (typeof value !== 'string' || /[\s\\]/u.test(value) || !/^[\x21-\x7e]+$/.test(value)) {
throw new TypeError('Unsupported source link');
}
const url = new URL(value);
if (url.protocol !== 'https:' || url.username || url.password || url.port) {
throw new TypeError('Unsupported source link');
}
// The model validates the source URL too. Keep a separate conservative DOM
// boundary: no local/literal hosts or browser numeric IPv4 aliases.
const labels = url.hostname.split('.');
if (labels.length < 2 || !/^[a-z]{2,63}$/i.test(labels.at(-1))
|| /(?:^|\.)(?:localhost|local|internal|test|invalid)$/i.test(url.hostname)
|| labels.some(label => !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label))) {
throw new TypeError('Unsupported source link');
}
return url;
}
function addField(document, list, label, value, attribute) {
const term = element(document, 'dt', 'ff-field-label', label);
const definition = element(document, 'dd', 'ff-field-value', knownText(value));
if (attribute) definition.setAttribute(attribute, '');
list.append(term, definition);
}
function renderRow(document, row) {
const item = element(document, 'li', 'ff-claim');
item.setAttribute('data-figure-claim', row.id);
const metric = knownText(row.claim.metric);
item.append(element(document, 'p', 'ff-metric', metric));
const amount = element(document, 'p', 'ff-amount', knownText(row.display.amount));
amount.setAttribute('data-figure-value', '');
item.append(amount);
const original = element(document, 'p', 'ff-original-unit');
original.append(element(document, 'span', 'ff-inline-label', 'Original unit: '));
original.append(element(document, 'span', '', knownText(row.claim.original_unit)));
item.append(original);
const status = element(document, 'p', 'ff-status', 'Provisional · requires independent review');
status.setAttribute('data-figure-status', 'provisional');
item.append(status);
const fields = element(document, 'dl', 'ff-fields');
addField(document, fields, 'Quantity', row.display.quantityKind);
addField(document, fields, 'Scope', row.display.entityScope);
addField(document, fields, 'Entity', row.claim.entity.id);
addField(document, fields, 'Group overlap', row.claim.entity.consolidation_group_id);
addField(document, fields, 'Basis', row.display.basis);
addField(document, fields, 'Assurance', row.display.assurance);
addField(document, fields, 'Finance stage', row.display.financeStage);
addField(document, fields, 'Reporting period', row.display.period);
addField(document, fields, 'As of', row.display.asOf);
addField(document, fields, 'Published', row.display.publishedDate);
addField(document, fields, 'Retrieved', row.display.retrievedAt);
addField(document, fields, 'Source location', row.display.sourceLocator);
addField(document, fields, 'Revision', row.display.revision, 'data-figure-revision');
item.append(fields);
const source = sourceUrl(row.claim.provenance.document_url);
const link = element(document, 'a', 'ff-source-link', 'Source document');
link.href = source.href;
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.referrerPolicy = 'no-referrer';
link.setAttribute('data-figure-link', '');
link.setAttribute('aria-label', `Source document for ${metric} (opens in a new tab)`);
const sourceLine = element(document, 'p', 'ff-source');
sourceLine.append(link, element(document, 'span', 'ff-source-host', ` · ${source.hostname}`));
item.append(sourceLine);
return item;
}
function detailsRoot(document, view, wasOpen) {
const root = element(document, 'details', 'filings-figures');
root.setAttribute(ROOT_ATTRIBUTE, '');
root.setAttribute('data-state', view.state);
root.setAttribute('data-entity-id', view.entityId ?? '');
root.open = Boolean(wasOpen);
const summary = element(document, 'summary', 'ff-summary');
summary.append(element(document, 'span', 'ff-summary-title', 'Filing figures'));
const badge = element(document, 'span', 'ff-badge',
view.state === 'available' && view.rows.length ? 'Provisional' : knownText(view.stateLabel));
badge.setAttribute('data-figure-state-badge', '');
summary.append(badge);
root.append(summary);
const body = element(document, 'div', 'ff-content');
if (!view.rows.length) {
const empty = element(document, 'p', 'ff-empty', knownText(view.message));
empty.setAttribute('data-figure-empty', '');
empty.setAttribute('role', 'status');
body.append(empty);
} else {
const note = element(document, 'p', 'ff-notice',
'Source assertions for this entity. Figures remain provisional; source rights and independent review are still required.');
body.append(note);
const list = element(document, 'ul', 'ff-claims');
list.setAttribute('role', 'list');
list.setAttribute('aria-label', 'Provisional filing figures');
for (const row of view.rows) list.append(renderRow(document, row));
body.append(list);
}
root.append(body);
return root;
}
/**
* Replace this adapter's direct child only; host MAP/export controls survive.
* Returns the new details Element, or null for an unusable host container.
* Invalid input clears any prior figures and displays an unavailable state.
*/
export function renderFigures(container, input) {
if (!container || container.nodeType !== 1 || !container.ownerDocument
|| typeof container.append !== 'function') return null;
const document = container.ownerDocument;
const prior = Array.from(container.children).filter(node => node.hasAttribute(ROOT_ATTRIBUTE));
let root;
try {
const view = buildViewModel(input);
const wasOpen = prior.some(node => node.open && node.getAttribute('data-entity-id') === view.entityId);
root = detailsRoot(document, view, wasOpen);
} catch {
// Never leave stale figures from the previously selected entity in view,
// expose untrusted exception values, or label invalid input as empty data.
root = detailsRoot(document, {
entityId: '', state: 'unavailable', stateLabel: 'Unavailable', rows: [],
message: 'Figures are unavailable because the supplied data could not be validated.',
}, prior.some(node => node.open));
}
if (prior.length) {
prior[0].replaceWith(root);
for (const duplicate of prior.slice(1)) duplicate.remove();
} else {
container.append(root);
}
return root;
}Verify Imports
A Python command-line tool in the automation folder of GlobalGrid2050 that reads import pins, using SHA-256.
ingestglobalgrid2050 / automation/v928_intelligence/verify_imports.py · lines 1–33 of 33 · Entry point
- What it does
- It loads import pins. Defines main. Uses libraries __future__, argparse, hashlib, json, pathlib. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file import-pins.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- Verify selected corrected News/Grid import bytes; never fetch or publish. It accepts `--repo`.
- Why it matters
- Run by GlobalGrid2050 V928 Preview Acceptance Workflow.
- Application
- globalgrid2050 · automation/v928_intelligence · Python CLI
- Uses
- __future__, argparse, hashlib, json, pathlib
- Used by
- run by GlobalGrid2050 V928 Preview Acceptance Workflow (workflow run)
- Produces
- main
- Defines here
- 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/v928_intelligence/verify_imports.py:1-33 · blob 6caa8d9b5703dbe9f7c9ce84e7ecae1a882a21ab · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
"""Verify selected corrected News/Grid import bytes; never fetch or publish."""
from __future__ import annotations
import argparse
from hashlib import sha256
import json
from pathlib import Path
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[2])
args = parser.parse_args(argv)
root = args.repo.resolve()
manifest = json.loads(Path(__file__).with_name("import-pins.json").read_text(encoding="utf-8"))
failures = []
for row in manifest["files"]:
path = root / row["path"]
if not path.is_file():
failures.append({"path": row["path"], "reason": "missing"})
elif sha256(path.read_bytes()).hexdigest() != row["sha256"]:
failures.append({"path": row["path"], "reason": "source bytes differ"})
for name in manifest["existing_dependency_paths"]:
if not (root / name).is_file():
failures.append({"path": name, "reason": "existing dependency missing"})
print(json.dumps({"result": "FAIL" if failures else "PASS",
"selected_files": len(manifest["files"]), "failures": failures,
"scope": "Selected source-byte identity only; no evidence, rights, browser or publication acceptance."}, indent=2))
return 2 if failures else 0
if __name__ == "__main__":
raise SystemExit(main())