GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / data-gridatlas / atman

Current Integrity

A Python command-line tool in the atman folder of Data GridAtlas that writes outputs (`write_outputs`), loads contract (`load_contract`) and assigns Parquet (`assign_parquet`), using SHA-256.

700 lines of Python from data-gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 481 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Current Integrity electrical · data-gridatlas / atman/202608291507-current-integrity.py lines 1–700

Current Integrity

A Python command-line tool in the atman folder of Data GridAtlas that writes outputs (`write_outputs`), loads contract (`load_contract`) and assigns Parquet (`assign_parquet`), using SHA-256.

electricaldata-gridatlas / atman/202608291507-current-integrity.py · lines 1–700 of 1017 · version 2026-08-29 15:07 · Entry point · pattern parquet_schema (shared by 2 files)

What it does
It fetches data. Defines 33 functions or classes, including reject_duplicate_keys, read_json, canonical, require, sha256. Uses libraries __future__, argparse, hashlib, json, os. Side effects: reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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 202608291507-automation.json; JSON file live-set.json; JSON file current.json; JSON file release.json; JSON file browser-layer-registry.json; JSON file projects.json; Parquet file uk_primary_roads.parquet; Parquet file repd_master_v8_oracle.parquet.
Downstream impact
Used directly by 3 files: Contract Guard Workflow (data-gridatlas); Current Integrity Workflow (data-gridatlas); Watchdog Router Workflow (data-gridatlas).
What it achieves
It reads JSON (`read_json`) and writes JSON (`write_json`). Read-only resolver, sharded verifier and watchdog probes for live Data Grid Atlas. It reads `release.json`. It accepts `--repository`, `--contract` and `--expected-head`.
Why it matters
Run by Contract Guard Workflow, Current Integrity Workflow and Watchdog Router Workflow.
Application
data-gridatlas · atman · Python CLI
Uses
Verify Live Data Release (script call), __future__, argparse, hashlib, json, os, re, subprocess, sys
Used by
run by Contract Guard Workflow (workflow run), run by Current Integrity Workflow (workflow run), run by Watchdog Router Workflow (workflow run)
Produces
reject_duplicate_keys, read_json, canonical, require, sha256, bytes_sha256, git, write_json, write_outputs, load_contract, app_release_url, assign_parquet
Defines here
reject_duplicate_keys, read_json, canonical, require, sha256, bytes_sha256, git, write_json, write_outputs, load_contract, app_release_url, assign_parquet, resolve_state, fetch, require_public_response, verify_public_parquet, parquet_schema, verify_local_parquet, verify_data_pointer, verify_data_release_sentinels, verify_consumer, _verify_current_and_historical_consumer, run_full_release_verifier, command_resolve
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gridatlas@203f9dc3764c05153c2b95f8ace88eb543f26c1e atman/202608291507-current-integrity.py:1-700 · blob 36274a147e9e79e2ac1582a451dede156aa76cc7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Read-only resolver, sharded verifier and watchdog probes for live Data Grid Atlas."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit
from urllib.request import Request, urlopen


SCHEMA = "data-gridatlas.current-integrity.v1"
SHARD_SCHEMA = "data-gridatlas.current-integrity-shard.v1"
GENERATION = "202608291507"
CONTRACT = "contracts/202608291507-automation.json"
HEX40 = re.compile(r"^[0-9a-f]{40}$")
HEX64 = re.compile(r"^[0-9a-f]{64}$")
ROLES = [
    "consumer",
    "full_release",
    "pointer",
    "manifest",
    "privacy",
    "provenance",
    "cors",
    "runtime",
]
FEATURE_COLUMNS = [
    ("source_id", "VARCHAR"),
    ("feature_index", "INTEGER"),
    ("feature_id", "VARCHAR"),
    ("geometry_type", "VARCHAR"),
    ("geometry_json", "VARCHAR"),
    ("properties_json", "VARCHAR"),
    ("original_feature_sha256", "VARCHAR"),
    ("projected_feature_sha256", "VARCHAR"),
    ("min_x", "DOUBLE"),
    ("min_y", "DOUBLE"),
    ("max_x", "DOUBLE"),
    ("max_y", "DOUBLE"),
]
MEMBERSHIP_COLUMNS = [
    ("layer_id", "VARCHAR"),
    ("source_id", "VARCHAR"),
    ("feature_index", "INTEGER"),
]
RETAINED_KEYS = {
    "name", "SiteName", "Site Name", "type", "street", "city", "postcode", "area_m2",
    "area_ha", "colour", "brand", "operator", "club", "capacity", "sport",
    "emission_tco2e", "datatype", "sector", "country", "tech", "raw_tech", "voltage",
    "power_kw", "connectors", "status", "mounting", "source",
}
FORBIDDEN_KEYS = {"phone", "operator:phone", "payment:phone", "owner", "owner:wikidata", "ownership"}


def reject_duplicate_keys(pairs: list[tuple[str, object]]) -> dict:
    value: dict[str, object] = {}
    for key, item in pairs:
        if key in value:
            raise ValueError(f"duplicate JSON key: {key}")
        value[key] = item
    return value


def read_json(path: Path) -> dict:
    return json.loads(
        path.read_text(encoding="utf-8"),
        object_pairs_hook=reject_duplicate_keys,
        parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)),
    )


def canonical(value: object) -> str:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)


def require(condition: bool, message: str) -> None:
    if not condition:
        raise SystemExit(message)


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def bytes_sha256(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()


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


def write_json(path: Path, value: object) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, sort_keys=True, indent=2) + "\n", encoding="utf-8")


def write_outputs(path: Path | None, values: dict[str, object]) -> None:
    if path is None:
        return
    with path.open("a", encoding="utf-8") as handle:
        for key, value in values.items():
            if isinstance(value, (dict, list)):
                value = json.dumps(value, sort_keys=True, separators=(",", ":"))
            handle.write(f"{key}={value}\n")


def load_contract(repository: Path, relative: str) -> dict:
    contract = read_json(repository / relative)
    require(contract.get("schema") == "data-gridatlas.automation-contract.v1", "automation contract schema mismatch")
    require(contract.get("generation") == GENERATION, "automation generation mismatch")
    require(contract.get("repository") == "Ventusltd/data-gridatlas", "repository contract mismatch")
    require(contract["closure"]["shards"] == 8, "integrity shard count must be eight")
    require(contract["runtime"]["maximum_parallel_shards"] == 8, "parallel shard ceiling mismatch")
    require(contract["rules"]["mutate_main"] is False, "automation must be read-only")
    return contract


def app_release_url(contract: dict, release_id: str) -> str:
    """The public directory one GridAtlas release is served from.

    GridAtlas moved its published releases under `atlas/releases/`; the
    pre-migration shape returns 404 and this verifier held it as a literal, so
    the hourly watchdog's consumer probe has failed every hour since
    2026-09-01 while being entirely correct about what it found. The prefix is
    contract data rather than a literal here so that the next move is one
    declared edit instead of a hunt through the verifier.
    """
    public = contract["public"]
    return public["app_root"] + public["app_release_prefix"] + release_id + "/"


def assign_parquet(artifacts: list[dict], shards: int) -> list[list[dict]]:
    lanes: list[list[dict]] = [[] for _ in range(shards)]
    totals = [0 for _ in range(shards)]
    for item in sorted(artifacts, key=lambda value: (-value["bytes"], value["path"])):
        lane = min(range(shards), key=lambda index: (totals[index], index))
        lanes[lane].append(item)
        totals[lane] += item["bytes"]
    for lane in lanes:
        lane.sort(key=lambda value: value["path"])
    return lanes


def resolve_state(repository: Path, contract_relative: str, expected_head: str = "", expected_pointer: str = "") -> dict:
    repository = repository.resolve()
    contract = load_contract(repository, contract_relative)
    baseline = contract["baseline"]
    head = git(repository, "rev-parse", "HEAD")
    require(HEX40.fullmatch(head) is not None, "malformed HEAD")
    if expected_head:
        require(HEX40.fullmatch(expected_head) is not None, "malformed expected HEAD")
        require(head == expected_head, f"HEAD compare-and-swap mismatch: {head}")
    subprocess.run(
        ["git", "-C", str(repository), "merge-base", "--is-ancestor", baseline["main_commit"], head],
        check=True,
    )

    pointer_paths = [repository / "state/live-set.json", repository / "releases/current.json"]
    require(all(path.is_file() and not path.is_symlink() for path in pointer_paths), "pointer file missing or symlinked")
    pointer_bytes = [path.read_bytes() for path in pointer_paths]
    require(pointer_bytes[0] == pointer_bytes[1], "pointer files are not byte-identical")
    pointer_sha = bytes_sha256(pointer_bytes[0])
    require(pointer_sha == baseline["pointer_sha256"], "stable pointer SHA-256 mismatch")
    if expected_pointer:
        require(HEX64.fullmatch(expected_pointer) is not None, "malformed expected pointer SHA-256")
        require(pointer_sha == expected_pointer, "pointer compare-and-swap mismatch")
    pointer = json.loads(pointer_bytes[0], object_pairs_hook=reject_duplicate_keys)
    require(pointer.get("schema") == "data-gridatlas.live-set.v1", "pointer schema mismatch")
    require(pointer.get("classification") == "VERIFIED_LIVE_DATA_GRIDATLAS_V9", "pointer classification mismatch")
    require((pointer.get("verification") or {}).get("promotion_eligible") is True, "pointer is not promotion eligible")
    require((pointer.get("verification") or {}).get("initial_v8_parquet_requests") == 0, "initial Parquet invariant mismatch")

    current = pointer.get("current") or {}
    consumer = pointer.get("consumer") or {}
    release_id = baseline["release_id"]
    expected_current = {
        "release_id": release_id,
        "publication_commit": baseline["release_commit"],
        "release_sha256": baseline["release_sha256"],
        "data_manifest_sha256": baseline["manifest_sha256"],
        "browser_registry_sha256": baseline["browser_registry_sha256"],
        "ledger_sha256": baseline["ledger_sha256"],
        "packaging_source_commit": baseline["packaging_source_commit"],
        "candidate_source_commit": baseline["candidate_source_commit"],
    }
    for key, value in expected_current.items():
        require(current.get(key) == value, f"pointer data binding mismatch: {key}")
    expected_consumer = {
        "release_id": contract["consumer"]["release_id"],
        "publication_commit": contract["consumer"]["publication_commit"],
        "app_pointer_commit": contract["consumer"]["pointer_commit"],
        "release_manifest_sha256": contract["consumer"]["release_manifest_sha256"],
        "build_manifest_sha256": contract["consumer"]["build_manifest_sha256"],
        "pointer_sha256": contract["consumer"]["pointer_sha256"],
    }
    for key, value in expected_consumer.items():
        require(consumer.get(key) == value, f"pointer consumer binding mismatch: {key}")

    release_root = repository / release_id
    require(release_root.is_dir() and not release_root.is_symlink(), "immutable release root missing")
    require(git(repository, "rev-parse", f"HEAD:{release_id}") == baseline["release_tree"], "immutable release tree changed")
    exact_hashes = {
        release_root / "release.json": baseline["release_sha256"],
        release_root / "data/manifest.json": baseline["manifest_sha256"],
        release_root / "browser-layer-registry.json": baseline["browser_registry_sha256"],
        release_root / "sha256sums.txt": baseline["ledger_sha256"],
    }
    for path, expected in exact_hashes.items():
        require(path.is_file() and sha256(path) == expected, f"immutable release hash mismatch: {path.name}")

    routing = baseline.get("routing_release") or {}
    routing_id = routing.get("release_id", "")
    require(routing_id == "202608291410-repd-routing", "REPD routing release identity mismatch")
    routing_root = repository / routing_id
    require(routing_root.is_dir() and not routing_root.is_symlink(), "immutable REPD routing release missing")
    require(
        git(repository, "rev-parse", f"HEAD:{routing_id}") == routing.get("release_tree"),
        "immutable REPD routing release tree changed",
    )
    routing_hashes = {
        routing_root / "projects.json": routing.get("projects_sha256"),
        routing_root / "release.json": routing.get("release_sha256"),
        routing_root / "sha256sums.txt": routing.get("ledger_sha256"),
    }
    for path, expected in routing_hashes.items():
        require(HEX64.fullmatch(str(expected)) is not None, f"malformed routing hash contract: {path.name}")
        require(path.is_file() and not path.is_symlink(), f"immutable routing file missing: {path.name}")
        require(sha256(path) == expected, f"immutable routing hash mismatch: {path.name}")
    routing_release = read_json(routing_root / "release.json")
    require(routing_release.get("schema") == "data-gridatlas.repd-routing-release.v1", "routing release schema mismatch")
    require(routing_release.get("classification") == "IMMUTABLE_REPD_ROUTING_RELEASE", "routing release classification mismatch")
    require(routing_release.get("release_id") == routing_id, "routing release ID mismatch")
    require(routing_release.get("source_commit") == routing.get("source_commit"), "routing source commit mismatch")

    manifest = read_json(release_root / "data/manifest.json")
    require(manifest.get("schema") == "data-gridatlas.v8-transplant-manifest.v1", "candidate manifest schema mismatch")
    require(manifest.get("classification") == "FULL_V8_TRANSPLANT_CANDIDATE", "candidate manifest classification mismatch")
    require(manifest.get("raw_geojson_outputs") == 0, "raw GeoJSON output invariant failed")
    closure = manifest.get("closure") or {}
    for source, target in (("layers", "layers"), ("sources", "sources"), ("features", "features"), ("layer_membership_rows", "memberships")):
        require(closure.get(source) == contract["closure"][target], f"manifest closure mismatch: {source}")
    parquet = [item for item in manifest.get("artifacts", []) if item.get("path", "").endswith(".parquet")]
    require(len(parquet) == contract["closure"]["parquet_files"], "Parquet file count mismatch")
    require(sum(item["bytes"] for item in parquet) == contract["closure"]["parquet_bytes"], "Parquet byte closure mismatch")
    require(len({item["path"] for item in parquet}) == len(parquet), "duplicate Parquet manifest path")
    for item in parquet:
        require(HEX64.fullmatch(item.get("sha256", "")) is not None, f"malformed Parquet SHA-256: {item.get('path')}")
        require(not Path(item["path"]).is_absolute() and ".." not in Path(item["path"]).parts, "unsafe Parquet path")

    lanes = assign_parquet(parquet, contract["closure"]["shards"])
    return {
        "repository": repository,
        "contract": contract,
        "head": head,
        "pointer_sha256": pointer_sha,
        "pointer": pointer,
        "release_root": release_root,
        "manifest": manifest,
        "parquet": parquet,
        "lanes": lanes,
    }


def fetch(url: str, *, byte_range: str | None = None, attempts: int = 4) -> tuple[int, dict[str, str], bytes]:
    headers = {
        "Accept-Encoding": "identity",
        "User-Agent": "data-gridatlas-202608291507-integrity",
    }
    if byte_range:
        headers["Range"] = byte_range
    error: Exception | None = None
    for attempt in range(attempts):
        try:
            request = Request(url, headers=headers)
            with urlopen(request, timeout=30) as response:
                return response.status, {key.lower(): value for key, value in response.headers.items()}, response.read()
        except (HTTPError, URLError, TimeoutError, OSError) as exc:
            error = exc
            if attempt + 1 < attempts:
                time.sleep(attempt + 1)
    raise SystemExit(f"public fetch failed after {attempts} attempts: {url}: {error!r}")


def require_public_response(status: int, headers: dict[str, str], expected_status: int, url: str) -> None:
    require(status == expected_status, f"public status mismatch: {url}:{status}")
    require(headers.get("access-control-allow-origin") == "*", f"public CORS mismatch: {url}")
    require(headers.get("content-encoding") in (None, "identity"), f"public encoding mismatch: {url}")


def verify_public_parquet(state: dict, item: dict) -> dict:
    contract = state["contract"]
    release_id = contract["baseline"]["release_id"]
    relative = item["path"]
    url = contract["public"]["data_root"] + release_id + "/data/" + quote(relative, safe="/")
    size = item["bytes"]
    status, headers, payload = fetch(url, byte_range="bytes=0-3")
    require_public_response(status, headers, 206, url)
    require(payload == b"PAR1", f"public Parquet prefix mismatch: {relative}")
    require(headers.get("content-range") == f"bytes 0-3/{size}", f"public prefix range mismatch: {relative}")
    status, headers, payload = fetch(url, byte_range=f"bytes={size - 4}-{size - 1}")
    require_public_response(status, headers, 206, url)
    require(payload == b"PAR1", f"public Parquet suffix mismatch: {relative}")
    require(headers.get("content-range") == f"bytes {size - 4}-{size - 1}/{size}", f"public suffix range mismatch: {relative}")
    return {"url": url, "prefix": True, "suffix": True, "cors": True, "identity": True}


def parquet_schema(connection, path: Path) -> list[tuple[str, str]]:
    return [(row[0], row[1]) for row in connection.execute("DESCRIBE SELECT * FROM read_parquet(?)", [str(path)]).fetchall()]


def verify_local_parquet(connection, state: dict, item: dict, scan_privacy: bool) -> dict:
    path = state["release_root"] / "data" / item["path"]
    require(path.is_file() and not path.is_symlink(), f"local Parquet missing or symlinked: {item['path']}")
    require(path.stat().st_size == item["bytes"], f"local Parquet byte mismatch: {item['path']}")
    require(sha256(path) == item["sha256"], f"local Parquet SHA-256 mismatch: {item['path']}")
    rows = connection.execute("SELECT count(*) FROM read_parquet(?)", [str(path)]).fetchone()[0]
    require(rows == item["rows"], f"local Parquet row mismatch: {item['path']}")
    codecs = {row[0] for row in connection.execute("SELECT DISTINCT compression FROM parquet_metadata(?)", [str(path)]).fetchall()}
    require(codecs == ({"ZSTD"} if rows else set()), f"local Parquet compression mismatch: {item['path']}:{codecs}")
    schema = parquet_schema(connection, path)
    if item["schema"] in {"data-gridatlas.v8-parity-features.v1", "data-gridatlas.v8-snapped-topology.v1"}:
        require(schema == FEATURE_COLUMNS, f"feature Parquet schema mismatch: {item['path']}")
    elif item["schema"] == "data-gridatlas.v8-layer-membership.v1":
        require(schema == MEMBERSHIP_COLUMNS, f"membership Parquet schema mismatch: {item['path']}")
    else:
        require(bool(schema), f"empty Parquet schema: {item['path']}")

    privacy_rows = 0
    if scan_privacy and item["schema"] in {"data-gridatlas.v8-parity-features.v1", "data-gridatlas.v8-snapped-topology.v1"}:
        cursor = connection.execute("SELECT properties_json FROM read_parquet(?)", [str(path)])
        while True:
            batch = cursor.fetchmany(5000)
            if not batch:
                break
            for (raw,) in batch:
                properties = json.loads(raw, object_pairs_hook=reject_duplicate_keys)
                require(isinstance(properties, dict) and canonical(properties) == raw, f"non-canonical properties: {item['path']}")
                keys = set(properties)
                require(keys.issubset(RETAINED_KEYS), f"property allowlist escape: {item['path']}:{sorted(keys - RETAINED_KEYS)}")
                require(keys.isdisjoint(FORBIDDEN_KEYS), f"forbidden property escaped: {item['path']}:{sorted(keys & FORBIDDEN_KEYS)}")
                privacy_rows += 1
    return {
        "path": item["path"],
        "bytes": item["bytes"],
        "rows": rows,
        "sha256": item["sha256"],
        "schema": item["schema"],
        "compression": sorted(codecs),
        "privacy_rows": privacy_rows,
    }


def verify_data_pointer(state: dict) -> dict:
    contract = state["contract"]
    expected = (state["repository"] / "state/live-set.json").read_bytes()
    urls = [
        contract["public"]["data_root"] + "state/live-set.json",
        contract["public"]["data_root"] + "releases/current.json",
    ]
    payloads = []
    for url in urls:
        status, headers, payload = fetch(url)
        require_public_response(status, headers, 200, url)
        require(payload == expected, f"public data pointer differs: {url}")
        payloads.append(payload)
    require(payloads[0] == payloads[1], "public data pointers are not identical")
    return {"urls": urls, "sha256": bytes_sha256(payloads[0]), "verified": True}


def verify_data_release_sentinels(state: dict, include_ranges: bool = True) -> dict:
    contract = state["contract"]
    baseline = contract["baseline"]
    base = contract["public"]["data_root"] + baseline["release_id"] + "/"
    checks = {
        "release.json": baseline["release_sha256"],
        "browser-layer-registry.json": baseline["browser_registry_sha256"],
        "data/manifest.json": baseline["manifest_sha256"],
        "sha256sums.txt": baseline["ledger_sha256"],
    }
    for relative, expected in checks.items():
        url = base + relative
        status, headers, payload = fetch(url)
        require_public_response(status, headers, 200, url)
        require(bytes_sha256(payload) == expected, f"public release sentinel mismatch: {relative}")
    ranges = []
    if include_ranges:
        by_path = {item["path"]: item for item in state["parquet"]}
        sentinels = [
            "partitions/uk_primary_roads.parquet",
            "partitions/repd_master_v8_oracle.parquet",
            "layer_membership.parquet",
        ]
        ranges = [verify_public_parquet(state, by_path[path]) for path in sentinels]
    return {"files": checks, "range_sentinels": ranges, "verified": True}


def verify_consumer(state: dict) -> dict:
    contract = state["contract"]
    expected = contract["consumer"]
    root = contract["public"]["app_root"]
    pointer_urls = [root + "state/live-set.json", root + "releases/current-v3.json"]
    payloads = []
    for url in pointer_urls:
        status, headers, payload = fetch(url)
        require_public_response(status, headers, 200, url)
        payloads.append(payload)
    require(payloads[0] == payloads[1], "public app pointers are not byte-identical")
    require(bytes_sha256(payloads[0]) == expected["pointer_sha256"], "public app pointer SHA-256 mismatch")
    pointer = json.loads(payloads[0], object_pairs_hook=reject_duplicate_keys)
    require(pointer.get("schema") == "gridatlas.live-set.v3", "public app pointer schema mismatch")
    require(pointer.get("classification") == "VERIFIED_LIVE_ATLAS_V9", "public app pointer classification mismatch")
    current = pointer.get("current") or {}
    exact = {
        "release_id": expected["release_id"],
        "publication_commit": expected["publication_commit"],
        "release_manifest_sha256": expected["release_manifest_sha256"],
        "build_manifest_sha256": expected["build_manifest_sha256"],
        "data_release_id": contract["baseline"]["release_id"],
        "data_release_commit": contract["baseline"]["release_commit"],
        "data_release_sha256": contract["baseline"]["release_sha256"],
    }
    for key, value in exact.items():
        require(current.get(key) == value, f"public app binding mismatch: {key}")
    query = expected["query"]
    require((current.get("query_contract") or {}).get("parameter") == query["parameter"], "app query parameter mismatch")
    require((current.get("query_contract") or {}).get("golden_value") == query["value"], "app query value mismatch")

    release = app_release_url(contract, expected["release_id"])
    release_checks = {
        "release-manifest.json": expected["release_manifest_sha256"],
        "build-manifest.json": expected["build_manifest_sha256"],
        "index.html": expected["index_sha256"],
    }
    index_payload = None
    for relative, digest in release_checks.items():
        url = release + relative
        status, headers, payload = fetch(url)
        require_public_response(status, headers, 200, url)
        require(bytes_sha256(payload) == digest, f"public app release mismatch: {relative}")
        if relative == "index.html":
            index_payload = payload
    deep_link = release + "?" + quote(query["parameter"]) + "=" + quote(query["value"])
    status, headers, payload = fetch(deep_link)
    require_public_response(status, headers, 200, deep_link)
    require(payload == index_payload, "deep-link index differs from release index")

    raw_pointer = (
        "https://raw.githubusercontent.com/" + expected["repository"] + "/" + expected["pointer_commit"] + "/state/live-set.json"
    )
    status, _, payload = fetch(raw_pointer)
    require(status == 200 and payload == payloads[0], "public app pointer differs from pinned Git commit")
    return {
        "pointer_urls": pointer_urls,
        "pointer_sha256": expected["pointer_sha256"],
        "release_id": expected["release_id"],
        "deep_link": deep_link,
        "golden_value": query["value"],
        "verified": True,
    }

_historical_verify_consumer = verify_consumer


def _verify_current_and_historical_consumer(state: dict) -> dict:
    contract = state["contract"]
    expected = contract["consumer"]
    root = contract["public"]["app_root"]
    query = expected["query"]

    # Preserve the exact historical consumer attestation at its pinned Git commit.
    historical_pointer_url = (
        "https://raw.githubusercontent.com/"
        + expected["repository"]
        + "/"
        + expected["pointer_commit"]
        + "/state/live-set.json"
    )
    status, _, historical_payload = fetch(historical_pointer_url)
    require(status == 200, "historical app pointer is unavailable")
    require(
        bytes_sha256(historical_payload) == expected["pointer_sha256"],
        "historical app pointer SHA-256 mismatch",
    )
    historical_pointer = json.loads(
        historical_payload,
        object_pairs_hook=reject_duplicate_keys,
    )
    require(historical_pointer.get("schema") == "gridatlas.live-set.v3", "historical pointer schema mismatch")
    require(historical_pointer.get("classification") == "VERIFIED_LIVE_ATLAS_V9", "historical pointer classification mismatch")
    historical_current = historical_pointer.get("current") or {}
    require(historical_current.get("release_id") == expected["release_id"], "historical release binding mismatch")

    historical_release = app_release_url(contract, expected["release_id"])
    historical_checks = {
        "release-manifest.json": expected["release_manifest_sha256"],
        "build-manifest.json": expected["build_manifest_sha256"],
        "index.html": expected["index_sha256"],
    }
    historical_index = None
    for relative, digest in historical_checks.items():
        url = historical_release + relative
        status, headers, payload = fetch(url)
        require_public_response(status, headers, 200, url)
        require(bytes_sha256(payload) == digest, f"historical app release mismatch: {relative}")
        if relative == "index.html":
            historical_index = payload
    historical_deep_link = (
        historical_release
        + "?"
        + quote(query["parameter"])
        + "="
        + quote(query["value"])
    )
    status, headers, payload = fetch(historical_deep_link)
    require_public_response(status, headers, 200, historical_deep_link)
    require(payload == historical_index, "historical deep-link index differs")

    # Follow the promoted live pointer instead of requiring it to equal an older v3 pointer.
    current_pointer_url = root + "state/live-set.json"
    status, headers, current_payload = fetch(current_pointer_url)
    require_public_response(status, headers, 200, current_pointer_url)
    current_pointer = json.loads(
        current_payload,
        object_pairs_hook=reject_duplicate_keys,
    )
    require(str(current_pointer.get("schema", "")).startswith("gridatlas.live-set."), "current pointer schema mismatch")
    require(str(current_pointer.get("classification", "")).startswith("VERIFIED_LIVE_"), "current pointer classification mismatch")
    verification = current_pointer.get("verification") or {}
    require(verification.get("promotion_eligible") is True, "current app pointer is not promotion eligible")
    require(int(verification.get("failed_gates", -1)) == 0, "current app pointer has failed gates")

    current = current_pointer.get("current") or {}
    release_id = str(current.get("release_id") or "")
    require(re.fullmatch(r"\d{12}-atlas-v9", release_id) is not None, "unsafe current app release ID")
    release_url = app_release_url(contract, release_id)
    # `live_url` is the stable composed-app route and `release_route` is the
    # immutable release directory; before the migration they were the same
    # string and this compared one against the other. Bind each to what it is,
    # so the pointer must declare the exact directory this verifier then reads.
    require(current.get("live_url") == root + contract["public"]["app_route"], "current app live URL mismatch")
    require(current.get("release_route") == urlsplit(release_url).path, "current app release route mismatch")
    receiver = current.get("deep_link_receiver") or {}
    require(receiver.get("identity_parameter") == query["parameter"], "current query parameter mismatch")
    require(receiver.get("identity_rule") == "EXACT_REPD_REF_ONLY", "current identity rule mismatch")
    require(receiver.get("automatic_search") is True, "current automatic search gate failed")
    require(receiver.get("automatic_fly_to") is True, "current automatic fly-to gate failed")

    manifests = current.get("manifests") or {}
    required_manifest_keys = {
        "release-manifest.json": "release_sha256",
        "build-manifest.json": "build_sha256",
    }
    for key in ["release_sha256", "build_sha256", "sha256sums_sha256"]:
        require(HEX64.fullmatch(str(manifests.get(key) or "")) is not None, f"malformed current manifest digest: {key}")

    ledger_url = release_url + "sha256sums.txt"
    status, ledger_headers, ledger_payload = fetch(ledger_url)
    require_public_response(status, ledger_headers, 200, ledger_url)
    require(bytes_sha256(ledger_payload) == manifests["sha256sums_sha256"], "current ledger SHA-256 mismatch")
    ledger: dict[str, str] = {}
    for number, raw in enumerate(ledger_payload.decode("utf-8").splitlines(), 1):
        if not raw.strip():
            continue
        digest, separator, relative = raw.partition("  ")
        require(separator == "  ", f"bad current ledger line: {number}")
        require(HEX64.fullmatch(digest) is not None, f"bad current ledger digest: {number}")
        require(relative and not relative.startswith("/") and ".." not in Path(relative).parts, f"unsafe current ledger path: {number}")
        ledger[relative] = digest

    current_index = None
    for relative, manifest_key in required_manifest_keys.items():
        require(ledger.get(relative) == manifests[manifest_key], f"current pointer/ledger mismatch: {relative}")
        url = release_url + relative
        status, file_headers, file_payload = fetch(url)
        require_public_response(status, file_headers, 200, url)
        require(bytes_sha256(file_payload) == manifests[manifest_key], f"current app release mismatch: {relative}")
        parsed = json.loads(file_payload, object_pairs_hook=reject_duplicate_keys)
        require(parsed.get("release_id") == release_id, f"current release identity mismatch: {relative}")

    if manifests.get("deep_link_sha256"):
        require(HEX64.fullmatch(str(manifests["deep_link_sha256"])) is not None, "malformed deep-link manifest digest")
        require(ledger.get("deep-link-receiver-manifest.json") == manifests["deep_link_sha256"], "deep-link pointer/ledger mismatch")
        deep_manifest_url = release_url + "deep-link-receiver-manifest.json"
        status, deep_headers, deep_payload = fetch(deep_manifest_url)
        require_public_response(status, deep_headers, 200, deep_manifest_url)
        require(bytes_sha256(deep_payload) == manifests["deep_link_sha256"], "current deep-link manifest mismatch")

    require(HEX64.fullmatch(str(ledger.get("index.html") or "")) is not None, "current index absent from ledger")
    index_url = release_url + "index.html"
    status, index_headers, current_index = fetch(index_url)
    require_public_response(status, index_headers, 200, index_url)
    require(bytes_sha256(current_index) == ledger["index.html"], "current index SHA-256 mismatch")

    current_deep_link = (
        release_url
        + "?"
        + quote(query["parameter"])
        + "="
        + quote(query["value"])
    )
    status, deep_headers, deep_payload = fetch(current_deep_link)
    require_public_response(status, deep_headers, 200, current_deep_link)
    require(deep_payload == current_index, "current deep-link index differs from release index")

    promotion_commit = str(current.get("promotion_commit") or "")
    require(HEX40.fullmatch(promotion_commit) is not None, "malformed current promotion commit")
    raw_current_url = (
        "https://raw.githubusercontent.com/"
        + expected["repository"]
        + "/"
        + promotion_commit
        + "/state/live-set.json"
    )
    status, _, raw_current_payload = fetch(raw_current_url)
    require(status == 200, "declared promotion pointer is unavailable")
    promotion_pointer = json.loads(
        raw_current_payload,
        object_pairs_hook=reject_duplicate_keys,
    )
    promotion_current = promotion_pointer.get("current") or {}
    require(
        promotion_current.get("release_id") == release_id,
        "declared promotion pointer release mismatch",
    )
    promotion_verification = promotion_pointer.get("verification") or {}
    require(
        promotion_verification.get("commit_lineage_attested") is True,
        "declared promotion pointer lineage is not attested",
    )
    require(
        verification.get("commit_lineage_attested") is True,
        "current pointer lineage is not attested",
    )
    lineage = verification.get("commit_lineage") or {}
    require(
        lineage.get("promotion_commit") == promotion_commit,
        "current pointer lineage promotion mismatch",
    )

    return {
        "pointer_urls": [historical_pointer_url, current_pointer_url],
        "historical_pointer_sha256": expected["pointer_sha256"],
        "historical_release_id": expected["release_id"],
        "historical_deep_link": historical_deep_link,
        "pointer_sha256": bytes_sha256(current_payload),
        "release_id": release_id,
        "deep_link": current_deep_link,
        "golden_value": query["value"],
        "identity_rule": receiver.get("identity_rule"),
        "verified": True,
    }


verify_consumer = _verify_current_and_historical_consumer

def run_full_release_verifier(state: dict, output: Path) -> dict:
    command = [
        sys.executable,
        str(state["repository"] / "atman/202608291237-verify-live-data-release.py"),
        "--repository", str(state["repository"]),
        "--release", str(state["release_root"]),
        "--source-commit", state["contract"]["baseline"]["packaging_source_commit"],
        "--output", str(output),
    ]
    subprocess.run(command, check=True)
    proof = read_json(output)
    require(proof.get("classification") == "VERIFIED_IMMUTABLE_LIVE_DATA_RELEASE", "full release verifier rejected release")
    require(proof.get("failed") == 0, "full release verifier reported failures")
    return proof


def command_resolve(args: argparse.Namespace) -> None:
    state = resolve_state(args.repository, args.contract, args.expected_head, args.expected_pointer_sha256)
    matrix = {
        "include": [
            {"lane": index, "role": ROLES[index], "declared_bytes": sum(item["bytes"] for item in lane)}
            for index, lane in enumerate(state["lanes"])
        ]
    }
    result = {
        "schema": "data-gridatlas.current-integrity-plan.v1",
        "classification": "RESOLVED_VERIFIED_LIVE_POINTER",
        "generation": GENERATION,
        "head_sha": state["head"],
        "pointer_sha256": state["pointer_sha256"],
        "release_id": state["contract"]["baseline"]["release_id"],