GLOBALGRID2050 / EXPLORE CODE

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

Current Integrity and 1 more file

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.

571 lines of Python from data-gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 482 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 701–1017
  2. Build Dependency Catalog storage · data-gridatlas / compiler/202608290904-build-dependency-catalog.py lines 1–254

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 701–1017 of 1017 · version 2026-08-29 15:07 (continued from section 481) · 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
command_shard, command_reduce, command_probe, changed_since_baseline, consume, verify_workflow_source, command_guard, add_common, main
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:701-1017 · 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
        "parquet_files": len(state["parquet"]),
        "parquet_bytes": sum(item["bytes"] for item in state["parquet"]),
        "matrix": matrix,
        "assignments": [
            {"lane": index, "role": ROLES[index], "bytes": sum(item["bytes"] for item in lane), "paths": [item["path"] for item in lane]}
            for index, lane in enumerate(state["lanes"])
        ],
        "rebuild_required": False,
        "main_mutated": False,
        "failed": 0,
    }
    write_json(args.output, result)
    write_outputs(args.github_output, {
        "head_sha": state["head"],
        "pointer_sha256": state["pointer_sha256"],
        "release_id": state["contract"]["baseline"]["release_id"],
        "matrix": matrix,
    })
    print(json.dumps(result, sort_keys=True))


def command_shard(args: argparse.Namespace) -> None:
    state = resolve_state(args.repository, args.contract, args.expected_head, args.expected_pointer_sha256)
    require(0 <= args.lane < len(state["lanes"]), "invalid shard lane")
    require(args.role == ROLES[args.lane], "shard role mismatch")
    import duckdb

    require(duckdb.__version__ == state["contract"]["runtime"]["duckdb"], "DuckDB runtime mismatch")
    connection = duckdb.connect(":memory:")
    connection.execute("SET threads=1")
    files = []
    try:
        for item in state["lanes"][args.lane]:
            local = verify_local_parquet(connection, state, item, scan_privacy=True)
            local["public"] = None if args.skip_public else verify_public_parquet(state, item)
            files.append(local)
    finally:
        connection.close()

    consumer = None
    full_release = None
    if args.lane == 0 and not args.skip_public:
        verify_data_pointer(state)
        verify_data_release_sentinels(state, include_ranges=False)
        consumer = verify_consumer(state)
    if args.lane == 1:
        full_release = run_full_release_verifier(state, args.output.parent / "full-release-verification.json")

    result = {
        "schema": SHARD_SCHEMA,
        "classification": "VERIFIED_CURRENT_INTEGRITY_SHARD",
        "generation": GENERATION,
        "head_sha": state["head"],
        "pointer_sha256": state["pointer_sha256"],
        "lane": args.lane,
        "role": args.role,
        "files": files,
        "file_count": len(files),
        "bytes": sum(item["bytes"] for item in files),
        "rows": sum(item["rows"] for item in files),
        "privacy_rows": sum(item["privacy_rows"] for item in files),
        "public_verified": not args.skip_public,
        "consumer": consumer,
        "full_release": full_release,
        "runtime": {"python": ".".join(map(str, sys.version_info[:3])), "duckdb": duckdb.__version__},
        "rebuild_performed": False,
        "main_mutated": False,
        "failed": 0,
    }
    write_json(args.output, result)
    print(json.dumps(result, sort_keys=True))


def command_reduce(args: argparse.Namespace) -> None:
    state = resolve_state(args.repository, args.contract, args.expected_head, args.expected_pointer_sha256)
    paths = sorted(args.attestations.rglob("shard-*.json"))
    require(len(paths) == 8, f"expected eight shard attestations, found {len(paths)}")
    shards = [read_json(path) for path in paths]
    require({item.get("lane") for item in shards} == set(range(8)), "shard lane closure mismatch")
    require({item.get("role") for item in shards} == set(ROLES), "shard role closure mismatch")
    declared = {item["path"] for item in state["parquet"]}
    observed: list[str] = []
    for shard in shards:
        require(shard.get("schema") == SHARD_SCHEMA, "shard schema mismatch")
        require(shard.get("classification") == "VERIFIED_CURRENT_INTEGRITY_SHARD", "shard classification mismatch")
        require(shard.get("head_sha") == state["head"], "shard HEAD mismatch")
        require(shard.get("pointer_sha256") == state["pointer_sha256"], "shard pointer mismatch")
        require(shard.get("failed") == 0 and shard.get("rebuild_performed") is False and shard.get("main_mutated") is False, "shard safety mismatch")
        require(shard.get("public_verified") is True, "shard public verification missing")
        observed.extend(item["path"] for item in shard["files"])
    require(len(observed) == len(set(observed)), "Parquet file verified by multiple shards")
    require(set(observed) == declared, "Parquet shard closure mismatch")
    consumer = next(item for item in shards if item["lane"] == 0).get("consumer") or {}
    release = next(item for item in shards if item["lane"] == 1).get("full_release") or {}
    require(consumer.get("verified") is True, "consumer proof missing")
    require(release.get("classification") == "VERIFIED_IMMUTABLE_LIVE_DATA_RELEASE", "full release proof missing")
    result = {
        "schema": SCHEMA,
        "classification": "VERIFIED_CURRENT_DATA_GRIDATLAS_INTEGRITY",
        "generation": GENERATION,
        "head_sha": state["head"],
        "pointer_sha256": state["pointer_sha256"],
        "release_id": state["contract"]["baseline"]["release_id"],
        "shards": 8,
        "parquet_files": len(observed),
        "parquet_bytes": sum(item["bytes"] for item in state["parquet"]),
        "parquet_rows": sum(item["rows"] for item in state["parquet"]),
        "privacy_rows": sum(item["privacy_rows"] for shard in shards for item in shard["files"]),
        "consumer_release_id": consumer["release_id"],
        "deep_link": consumer["deep_link"],
        "rebuild_required": False,
        "rebuild_performed": False,
        "main_mutated": False,
        "failed": 0,
    }
    write_json(args.output, result)
    print(json.dumps(result, sort_keys=True))


def command_probe(args: argparse.Namespace) -> None:
    state = resolve_state(args.repository, args.contract, args.expected_head, args.expected_pointer_sha256)
    if args.mode == "data-pointer":
        proof = verify_data_pointer(state)
    elif args.mode == "data-release":
        proof = verify_data_release_sentinels(state, include_ranges=True)
    elif args.mode == "consumer":
        proof = verify_consumer(state)
    else:
        raise SystemExit(f"unknown probe mode: {args.mode}")
    result = {
        "schema": "data-gridatlas.watchdog-probe.v1",
        "classification": "VERIFIED_WATCHDOG_PROBE",
        "generation": GENERATION,
        "mode": args.mode,
        "head_sha": state["head"],
        "pointer_sha256": state["pointer_sha256"],
        "proof": proof,
        "main_mutated": False,
        "failed": 0,
    }
    write_json(args.output, result)
    print(json.dumps(result, sort_keys=True))


def changed_since_baseline(repository: Path, baseline: str, include_working_tree: bool) -> dict[str, str]:
    changed: dict[str, str] = {}

    def consume(raw: str) -> None:
        for line in raw.splitlines():
            fields = line.split("\t")
            require(len(fields) == 2, f"unsupported changed-path record: {line!r}")
            status, path = fields
            require(status == "A", f"only added successor files are allowed: {status}:{path}")
            require(path not in changed, f"duplicate changed path: {path}")
            changed[path] = status

    consume(git(repository, "diff", "--name-status", f"{baseline}..HEAD"))
    if include_working_tree:
        consume(git(repository, "diff", "--name-status"))
        untracked = git(repository, "ls-files", "--others", "--exclude-standard")
        for path in untracked.splitlines():
            require(path not in changed, f"duplicate untracked path: {path}")
            changed[path] = "A"
    return changed


def verify_workflow_source(path: Path, contract: dict) -> dict:
    source = path.read_text(encoding="utf-8")
    require("permissions: {}" in source, f"top-level deny-all permissions missing: {path}")
    require("contents: write" not in source, f"repository-content write permission forbidden: {path}")
    require("pull_request_target:" not in source, f"pull_request_target forbidden: {path}")
    require("secrets: inherit" not in source, f"inherited secrets forbidden: {path}")
    require("workflow_dispatch:" in source, f"manual recovery trigger missing: {path}")

    use_lines = re.findall(r"(?m)^\s*uses:\s*([^\s]+)\s*$", source)
    pins = contract["action_pins"]
    for item in use_lines:
        require("@" in item, f"unversioned action: {path}:{item}")
        action, reference = item.rsplit("@", 1)
        require(action in pins, f"unapproved action: {path}:{action}")
        require(reference == pins[action] and HEX40.fullmatch(reference) is not None, f"floating or wrong action pin: {path}:{item}")
    require(source.count("uses:") == len(use_lines), f"unparsed action use: {path}")
    require(source.count("actions/checkout@") == source.count("persist-credentials: false"), f"checkout credential persistence mismatch: {path}")

    timeouts = [int(value) for value in re.findall(r"timeout-minutes:\s*(\d+)", source)]
    require(timeouts and max(timeouts) <= contract["runtime"]["maximum_job_minutes"], f"workflow timeout exceeds contract: {path}")
    require(all(value > 0 for value in timeouts), f"non-positive workflow timeout: {path}")

    name = path.name
    if name == Path(contract["workflow"]["watchdog"]).name:
        require(source.count("actions: write") == 1, "watchdog router requires exactly one actions:write job")
        require(f"cron: '{contract['workflow']['schedule_utc']}'" in source, "watchdog schedule mismatch")
        require("max-parallel: 3" in source, "watchdog public probe ceiling mismatch")
    else:
        require("actions: write" not in source, f"actions write permission forbidden outside router: {path}")
        require("schedule:" not in source, f"unexpected schedule outside watchdog: {path}")
    if name == Path(contract["workflow"]["integrity"]).name:
        require("max-parallel: 8" in source, "integrity parallel ceiling mismatch")
        require("fail-fast: false" in source, "integrity evidence lanes must not fail fast")
    if name == Path(contract["workflow"]["guard"]).name:
        require("pull_request:" in source and "push:" in source, "guard push/PR trigger mismatch")

    return {
        "path": path.as_posix(),
        "sha256": sha256(path),
        "actions": len(use_lines),
        "jobs": len(timeouts),
        "maximum_timeout_minutes": max(timeouts),
        "actions_write_grants": source.count("actions: write"),
        "contents_write_grants": source.count("contents: write"),
    }


def command_guard(args: argparse.Namespace) -> None:
    state = resolve_state(args.repository, args.contract, args.expected_head, args.expected_pointer_sha256)
    contract = state["contract"]
    repository = state["repository"]
    expected_files = set(contract["first_checkpoint_files"])
    changed = changed_since_baseline(repository, contract["baseline"]["main_commit"], args.include_working_tree)
    require(set(changed) == expected_files, f"automation source boundary mismatch: expected={sorted(expected_files)} actual={sorted(changed)}")

    for relative in sorted(expected_files):
        path = repository / relative
        require(path.is_file() and not path.is_symlink(), f"automation successor missing or symlinked: {relative}")
    workflow_paths = sorted((repository / ".github/workflows").glob("202608291507-*.yml"))
    expected_workflows = {
        repository / contract["workflow"]["watchdog"],
        repository / contract["workflow"]["integrity"],
        repository / contract["workflow"]["guard"],
    }
    require(set(workflow_paths) == expected_workflows, "automation workflow file closure mismatch")
    workflows = []
    for path in workflow_paths:
        proof = verify_workflow_source(path, contract)
        proof["path"] = path.relative_to(repository).as_posix()
        workflows.append(proof)

    forbidden_suffixes = {".geojson", ".csv", ".tsv", ".xlsx", ".duckdb", ".zip", ".tar", ".gz"}
    tracked = git(repository, "ls-files").splitlines()
    if args.include_working_tree:
        tracked += git(repository, "ls-files", "--others", "--exclude-standard").splitlines()
    release_prefix = contract["baseline"]["release_id"] + "/"
    escaped = [path for path in tracked if Path(path).suffix.lower() in forbidden_suffixes and not path.startswith(release_prefix)]
    require(not escaped, f"forbidden analytical output outside immutable release: {escaped}")

    result = {
        "schema": "data-gridatlas.automation-contract-guard.v1",
        "classification": "VERIFIED_READ_ONLY_AUTOMATION_CONTRACT",
        "generation": GENERATION,
        "head_sha": state["head"],
        "baseline_commit": contract["baseline"]["main_commit"],
        "pointer_sha256": state["pointer_sha256"],
        "release_tree": git(repository, "rev-parse", f"HEAD:{contract['baseline']['release_id']}"),
        "successor_files": sorted(expected_files),
        "changed_files": changed,
        "workflows": workflows,
        "maximum_job_minutes": contract["runtime"]["maximum_job_minutes"],
        "contents_write_grants": sum(item["contents_write_grants"] for item in workflows),
        "actions_write_grants": sum(item["actions_write_grants"] for item in workflows),
        "immutable_release_mutated": False,
        "pointer_mutated": False,
        "main_mutated_by_guard": False,
        "failed": 0,
    }
    write_json(args.output, result)
    print(json.dumps(result, sort_keys=True))


def add_common(parser: argparse.ArgumentParser) -> None:
    parser.add_argument("--repository", type=Path, required=True)
    parser.add_argument("--contract", default=CONTRACT)
    parser.add_argument("--expected-head", default="")
    parser.add_argument("--expected-pointer-sha256", default="")


def main() -> None:
    parser = argparse.ArgumentParser()
    commands = parser.add_subparsers(dest="command", required=True)

    resolve = commands.add_parser("resolve")
    add_common(resolve)
    resolve.add_argument("--output", type=Path, required=True)
    resolve.add_argument("--github-output", type=Path)
    resolve.set_defaults(handler=command_resolve)

    shard = commands.add_parser("shard")
    add_common(shard)
    shard.add_argument("--lane", type=int, required=True)
    shard.add_argument("--role", required=True, choices=ROLES)
    shard.add_argument("--skip-public", action="store_true")
    shard.add_argument("--output", type=Path, required=True)
    shard.set_defaults(handler=command_shard)

    reduce = commands.add_parser("reduce")
    add_common(reduce)
    reduce.add_argument("--attestations", type=Path, required=True)
    reduce.add_argument("--output", type=Path, required=True)
    reduce.set_defaults(handler=command_reduce)

    probe = commands.add_parser("probe")
    add_common(probe)
    probe.add_argument("--mode", choices=["data-pointer", "data-release", "consumer"], required=True)
    probe.add_argument("--output", type=Path, required=True)
    probe.set_defaults(handler=command_probe)

    guard = commands.add_parser("guard")
    add_common(guard)
    guard.add_argument("--include-working-tree", action="store_true")
    guard.add_argument("--output", type=Path, required=True)
    guard.set_defaults(handler=command_guard)

    args = parser.parse_args()
    args.handler(args)


if __name__ == "__main__":
    main()

Build Dependency Catalog

A Python command-line tool in the compiler folder of Data GridAtlas that reads GridAtlas bootstrap, dependency ledger, quarantine and GridAtlas consumer, using SHA-256.

storagedata-gridatlas / compiler/202608290904-build-dependency-catalog.py · lines 1–254 of 254 · version 2026-08-29 09:04 · Entry point · pattern write_parquet (shared by 7 files)

What it does
It loads GridAtlas bootstrap, dependency ledger, quarantine and GridAtlas consumer. Defines 8 functions or classes, including load, digest, contract_digest, insert_rows, write_parquet. Uses libraries argparse, hashlib, json, pathlib, duckdb. Side effects: reads or writes files; 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 202608290904-data-gridatlas-bootstrap.json; JSON file 202608290904-v8-file-ledger.json; JSON file 202608290904-v8-dependency-ledger.json; JSON file 202608290904-v8-quarantine.json; JSON file 202608290904-gridatlas-consumer.json; Parquet file files.parquet; Parquet file layers.parquet; Parquet file quarantine.parquet.
Downstream impact
Used directly by 1 file: Bootstrap Verify Data GridAtlas Workflow (data-gridatlas).
What it achieves
It inserts rows (`insert_rows`) and writes Parquet (`write_parquet`). Build the inventory-only Atlas V9 dependency catalogue. It accepts `--repository` and `--output`.
Why it matters
Run by Bootstrap Verify Data GridAtlas Workflow.
Application
data-gridatlas · compiler · Python CLI
Uses
argparse, hashlib, json, pathlib, duckdb
Used by
run by Bootstrap Verify Data GridAtlas Workflow (workflow run)
Produces
load, digest, contract_digest, insert_rows, write_parquet, quarantine_rows, main
Defines here
load, digest, contract_digest, insert_rows, write_parquet, quarantine_rows, main, VARCHAR
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 compiler/202608290904-build-dependency-catalog.py:1-254 · blob 3d879f875138c17752145560224590ca08c484ae · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Build the inventory-only Atlas V9 dependency catalogue."""

import argparse
import hashlib
import json
from pathlib import Path

import duckdb


GENERATION = "202608290904"
BOOTSTRAP = Path("contracts/202608290904-data-gridatlas-bootstrap.json")
FILES = Path("contracts/202608290904-v8-file-ledger.json")
LAYERS = Path("contracts/202608290904-v8-dependency-ledger.json")
QUARANTINE = Path("contracts/202608290904-v8-quarantine.json")
CONSUMER = Path("contracts/202608290904-gridatlas-consumer.json")


def load(path: Path):
    return json.loads(path.read_text(encoding="utf-8"))


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


def contract_digest(path: Path):
    return {"path": str(path), "bytes": path.stat().st_size, "sha256": digest(path)}


def insert_rows(connection, table, columns, rows):
    placeholders = ",".join("?" for _ in columns)
    connection.executemany(
        f"INSERT INTO {table} ({','.join(columns)}) VALUES ({placeholders})",
        [tuple(row[column] for column in columns) for row in rows],
    )


def write_parquet(connection, query, path: Path):
    escaped = str(path).replace("'", "''")
    connection.execute(
        f"COPY ({query}) TO '{escaped}' "
        "(FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 100000)"
    )


def quarantine_rows(contract):
    rows = []
    for item in contract["classes"]:
        rows.append(
            {
                "kind": "class",
                "item_id": item["id"],
                "path_or_value": item["id"],
                "disposition": item["disposition"],
                "reason": item["reason"],
                "details_json": json.dumps(item, sort_keys=True, separators=(",", ":")),
            }
        )
    for path in contract["unwired_atlas_data"]:
        rows.append(
            {
                "kind": "unwired_atlas_data",
                "item_id": path,
                "path_or_value": f"repd_grid_atlasv8/data/{path}",
                "disposition": "QUARANTINE_UNTIL_PROVEN",
                "reason": "Present in the V8 data directory but absent from the 60-layer runtime configuration.",
                "details_json": "{}",
            }
        )
    for path in contract["root_absolute_dependencies"]:
        rows.append(
            {
                "kind": "root_absolute_dependency",
                "item_id": path,
                "path_or_value": path,
                "disposition": "QUARANTINE_ROOT_ABSOLUTE",
                "reason": "Runtime path crosses the Atlas subtree boundary and is not an approved V9 source.",
                "details_json": "{}",
            }
        )
    for item in contract["known_defects"]:
        rows.append(
            {
                "kind": "known_defect",
                "item_id": item["id"],
                "path_or_value": item.get("configured_path", item["id"]),
                "disposition": item["disposition"],
                "reason": item.get("reason", item["id"]),
                "details_json": json.dumps(item, sort_keys=True, separators=(",", ":")),
            }
        )
    deep_link = contract["deep_link_dependency"]
    rows.append(
        {
            "kind": "deep_link_dependency",
            "item_id": "v8_pipeline_v9",
            "path_or_value": deep_link["path"],
            "disposition": deep_link["disposition"],
            "reason": "Hard-coded V8 deep-link dependency, separate from the 40 configured layer URLs.",
            "details_json": json.dumps(deep_link, sort_keys=True, separators=(",", ":")),
        }
    )
    for value in contract["external_runtime"]:
        rows.append(
            {
                "kind": "external_runtime",
                "item_id": hashlib.sha256(value.encode()).hexdigest()[:16],
                "path_or_value": value,
                "disposition": "APPLICATION_REVIEW",
                "reason": "Application runtime dependency; not data-repository payload.",
                "details_json": "{}",
            }
        )
    return sorted(rows, key=lambda row: (row["kind"], row["item_id"]))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--repository", default=".")
    parser.add_argument("--output", required=True)
    args = parser.parse_args()

    repository = Path(args.repository).resolve()
    output = Path(args.output).resolve()
    output.mkdir(parents=True, exist_ok=True)

    paths = [repository / item for item in (BOOTSTRAP, FILES, LAYERS, QUARANTINE, CONSUMER)]
    bootstrap, file_contract, layer_contract, quarantine_contract, consumer = map(load, paths)

    if bootstrap["generation"] != GENERATION or bootstrap["classification"] != "INVENTORY_ONLY":
        raise RuntimeError("bootstrap contract identity mismatch")
    if file_contract["summary"] != {"files": 104, "bytes": 39541206}:
        raise RuntimeError("V8 file ledger closure mismatch")
    summary = layer_contract["summary"]
    expected = {
        "groups": 11,
        "layer_entries": 60,
        "unique_configured_urls": 40,
        "preload_layer_entries": 12,
        "unique_preload_sources": 11,
    }
    if any(summary.get(key) != value for key, value in expected.items()):
        raise RuntimeError(f"V8 layer ledger closure mismatch: {summary}")
    if consumer["accepted_release"]["floating_raw_urls"] is not False:
        raise RuntimeError("consumer permits floating raw URLs")

    file_rows = []
    disposition = {
        ".github": "DO_NOT_COPY",
        "scripts": "REFERENCE_ONLY",
        "root": "DO_NOT_COPY",
        "data": "QUARANTINE_UNTIL_PROVEN",
    }
    for row in file_contract["rows"]:
        file_rows.append({**row, "disposition": disposition[row["class"]]})

    layer_rows = layer_contract["rows"]
    q_rows = quarantine_rows(quarantine_contract)

    connection = duckdb.connect()
    connection.execute("PRAGMA threads=1")
    connection.execute("SET preserve_insertion_order=true")
    connection.execute(
        """CREATE TABLE files(
        path VARCHAR NOT NULL, bytes UBIGINT NOT NULL, git_blob_sha1 VARCHAR NOT NULL,
        class VARCHAR NOT NULL, disposition VARCHAR NOT NULL)"""
    )
    file_columns = ["path", "bytes", "git_blob_sha1", "class", "disposition"]
    insert_rows(connection, "files", file_columns, file_rows)

    connection.execute(
        """CREATE TABLE layers(
        group_name VARCHAR NOT NULL, layer_id VARCHAR NOT NULL, label VARCHAR NOT NULL,
        configured_url VARCHAR NOT NULL, resolved_path VARCHAR NOT NULL,
        git_blob_sha1 VARCHAR NOT NULL, bytes UBIGINT NOT NULL, sha256 VARCHAR NOT NULL,
        expected_geometry VARCHAR NOT NULL, preload BOOLEAN NOT NULL, minzoom DOUBLE,
        selected_features UBIGINT NOT NULL, source_authority_state VARCHAR NOT NULL,
        licence_state VARCHAR NOT NULL, refresh_class VARCHAR NOT NULL,
        disposition VARCHAR NOT NULL, publishable BOOLEAN NOT NULL)"""
    )
    layer_columns = [
        "group_name", "layer_id", "label", "configured_url", "resolved_path",
        "git_blob_sha1", "bytes", "sha256", "expected_geometry", "preload",
        "minzoom", "selected_features", "source_authority_state", "licence_state",
        "refresh_class", "disposition", "publishable",
    ]
    normalized_layers = [
        {**row, "group_name": row["group"]} for row in layer_rows
    ]
    insert_rows(connection, "layers", layer_columns, normalized_layers)

    connection.execute(
        """CREATE TABLE quarantine(
        kind VARCHAR NOT NULL, item_id VARCHAR NOT NULL, path_or_value VARCHAR NOT NULL,
        disposition VARCHAR NOT NULL, reason VARCHAR NOT NULL, details_json VARCHAR NOT NULL)"""
    )
    q_columns = ["kind", "item_id", "path_or_value", "disposition", "reason", "details_json"]
    insert_rows(connection, "quarantine", q_columns, q_rows)

    files_path = output / "files.parquet"
    layers_path = output / "layers.parquet"
    quarantine_path = output / "quarantine.parquet"
    write_parquet(connection, "SELECT * FROM files ORDER BY path", files_path)
    write_parquet(connection, "SELECT * FROM layers ORDER BY group_name, layer_id", layers_path)
    write_parquet(connection, "SELECT * FROM quarantine ORDER BY kind, item_id", quarantine_path)

    for table, path, rows in (
        ("files", files_path, len(file_rows)),
        ("layers", layers_path, len(layer_rows)),
        ("quarantine", quarantine_path, len(q_rows)),
    ):
        escaped = str(path).replace("'", "''")
        readback = connection.execute(f"SELECT count(*) FROM read_parquet('{escaped}')").fetchone()[0]
        if readback != rows:
            raise RuntimeError(f"{table} typed readback mismatch: {readback} != {rows}")
    connection.close()

    artifacts = []
    for path, schema, rows in (
        (files_path, "data-gridatlas.files.v1", len(file_rows)),
        (layers_path, "data-gridatlas.layers.v1", len(layer_rows)),
        (quarantine_path, "data-gridatlas.quarantine.v1", len(q_rows)),
    ):
        artifacts.append(
            {"path": path.name, "bytes": path.stat().st_size, "sha256": digest(path), "schema": schema, "rows": rows}
        )

    manifest = {
        "schema": "data-gridatlas.bootstrap-manifest.v1",
        "generation": GENERATION,
        "classification": "BOOTSTRAP_CANDIDATE",
        "v8_oracle": bootstrap["v8_oracle"],
        "contracts": [contract_digest(path.relative_to(repository)) for path in paths],
        "runtime": {"python": "3.12", "duckdb": duckdb.__version__, "threads": 1, "parquet_compression": "ZSTD"},
        "artifacts": artifacts,
        "release": False,
        "current_pointer": False,
        "raw_payloads_copied": 0,
        "v8_untouched": True,
    }
    (output / "manifest.json").write_text(
        json.dumps(manifest, sort_keys=True, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps({"classification": manifest["classification"], "artifacts": artifacts}, sort_keys=True))


if __name__ == "__main__":
    main()