GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / data-grid-gb / tests

Build V8 Transplant Candidate Workflow and 2 more files

A GitHub Actions workflow in Data GridAtlas. Runs on push and by hand.

686 lines of YAML and Python from data-grid-gb, data-gridatlas, in 3 files. Topic: Automation and CI. Section 1701 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. Test Lanes test · data-grid-gb / tests/test_lanes.py lines 1–167
  2. Bootstrap Verify Data GridAtlas Workflow automation · data-gridatlas / .github/workflows/202608290904-bootstrap-verify-data-gridatlas.yml lines 1–140
  3. Build V8 Transplant Candidate Workflow automation · data-gridatlas / .github/workflows/202608291015-build-v8-transplant-candidate.yml lines 1–379

Test Lanes

A test in the tests folder of Data Grid GB that checks Reproduce and Lanes, using SHA-256. It makes lane root (`make_lane_root`) and sets up (`setUp`).

testdata-grid-gb / tests/test_lanes.py · lines 1–167 of 167 · Entry point · pattern quiet (shared by 2 files)

What it does
It tests its inputs. Defines 17 functions or classes, including make_lane_root, quiet, LaneTests, setUp, tearDown. Uses libraries __future__, contextlib, hashlib, io, json. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file result.json; JSON file lanes.json; command-line arguments. Out: JSON file result.json; JSON file lanes.json; JSON file stray.json; JSON file sources.json.
Downstream impact
Used directly by 1 file: Test Assets Workflow (data-grid-gb).
What it achieves
Tests for the vendored-lane machinery (assetpipe.lanes, `pipelines/run_lanes.py`, the lane part of `reproduce.py`). It writes `out/result.json`.
Why it matters
Checked by Test Assets Workflow.
Application
data-grid-gb · tests · test
Uses
Reproduce (import), Lanes (import), Data Grid GB — Assetpipe (import), Run Lanes (script call), __future__, contextlib, hashlib, io, json, shutil, subprocess, sys
Used by
run by Test Assets Workflow (workflow run)
Produces
make_lane_root, quiet, LaneTests, VendoredLaneTests
Defines here
make_lane_root, quiet, LaneTests, setUp, tearDown, build, test_build_pin_and_check, test_tampered_or_unpinned_file_is_caught, test_unverified_lane_outputs_fail_strict_check_only, test_closed_lane_may_not_be_vendored, test_blocked_fetch_is_recorded_as_failure_not_zero, test_pinned_input_with_wrong_bytes_is_refused, test_reproduce_rebuilds_lanes_and_catches_nondeterminism, VendoredLaneTests, test_lane_selftests_pass, test_every_lane_is_open_or_explicitly_unverified, test_fetch_never_runs_in_tests_or_verify
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 tests/test_lanes.py:1-167 · blob ab6badfec04589be5c4b084a44928d229390dee9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
"""Tests for the vendored-lane machinery (assetpipe.lanes, pipelines/run_lanes.py, the lane part of reproduce.py)."""
from __future__ import annotations

import contextlib
import hashlib
import io
import json
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

import reproduce  # noqa: E402
from assetpipe import lanes  # noqa: E402

BUILD = '''import json, os, sys
src = open("raw/in.txt", encoding="utf-8").read().split()
os.makedirs("out", exist_ok=True)
extra = {"noise": os.getpid()} if os.environ.get("LANE_NOISE") else {}
with open("out/result.json", "w", encoding="utf-8", newline="\\n") as fh:
    json.dump({"words": sorted(src), "retrieved": sys.argv[1] if len(sys.argv) > 1 else None, **extra}, fh, sort_keys=True)
'''
FETCH_BLOCKED = 'import sys\nprint("Tunnel connection failed: 403 Forbidden")\nsys.exit(2)\n'


def make_lane_root(tmp: Path, *, open_value="yes", env=None) -> Path:
    for domain in ("datacentres", "conventional"):
        (tmp / domain / "lanes").mkdir(parents=True)
        doc = {"schema": lanes.LANES_SCHEMA, "domain": domain, "lanes": []}
        if domain == "datacentres":
            ldir = tmp / domain / "lanes" / "fake-lane"
            (ldir / "raw").mkdir(parents=True)
            (ldir / "raw" / "in.txt").write_text("b a c", encoding="utf-8")
            (ldir / "build.py").write_text(BUILD, encoding="utf-8")
            (ldir / "fetch.py").write_text(FETCH_BLOCKED, encoding="utf-8")
            doc["lanes"].append({"id": "fake-lane", "lane": "TEST", "open": open_value, "licence": "OGL-3.0",
                                 "licence_url": "https://example.org/ogl", "fetch": [["fetch.py"]],
                                 "build": [["build.py", "{retrieved}"]], "outputs": ["out/result.json"],
                                 "env": env or {}})
        (tmp / domain / "lanes" / "lanes.json").write_text(json.dumps(doc), encoding="utf-8")
    return tmp


def quiet(fn, *args, **kwargs):
    with contextlib.redirect_stdout(io.StringIO()) as out:
        result = fn(*args, **kwargs)
    return result, out.getvalue()


class LaneTests(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp(prefix="lanes-test-"))

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def build(self, root):
        lane = lanes.load_lanes("datacentres", root)["lanes"][0]
        ldir = lanes.lanes_dir("datacentres", root) / lane["id"]
        codes = lanes.run_commands(ldir, lane, lane["build"], today="2026-10-29", retrieved="unspecified",
                                   log=lambda *_: None)
        lanes.write_manifest("datacentres", root)
        lanes.write_manifest("conventional", root)
        return codes

    def test_build_pin_and_check(self):
        root = make_lane_root(self.tmp)
        self.assertEqual(self.build(root), [0])
        self.assertEqual(lanes.check_manifest("datacentres", root), [])
        out = root / "datacentres/lanes/fake-lane/out/result.json"
        self.assertEqual(json.loads(out.read_text())["words"], ["a", "b", "c"])

    def test_tampered_or_unpinned_file_is_caught(self):
        root = make_lane_root(self.tmp)
        self.build(root)
        out = root / "datacentres/lanes/fake-lane/out/result.json"
        out.write_text("{}", encoding="utf-8")
        self.assertTrue(any("does not match" in p for p in lanes.check_manifest("datacentres", root)))
        self.build(root)
        (root / "datacentres/lanes/fake-lane/out/stray.json").write_text("{}", encoding="utf-8")
        self.assertTrue(any("without a pin" in p for p in lanes.check_manifest("datacentres", root)))

    def test_unverified_lane_outputs_fail_strict_check_only(self):
        root = make_lane_root(self.tmp, open_value="unverified")
        self.build(root)
        self.assertTrue(lanes.check_manifest("datacentres", root, strict_open=True))
        self.assertEqual(lanes.check_manifest("datacentres", root, strict_open=False), [])
        self.assertEqual(lanes.allowed({"open": "unverified"}, False)[0], False)
        self.assertEqual(lanes.allowed({"open": "unverified"}, True)[0], True)
        self.assertEqual(lanes.allowed({"open": "no"}, True)[0], False)

    def test_closed_lane_may_not_be_vendored(self):
        root = make_lane_root(self.tmp, open_value="no")
        lanes.write_manifest("datacentres", root)
        self.assertTrue(any("not fully open" in p for p in lanes.check_manifest("datacentres", root)))

    def test_blocked_fetch_is_recorded_as_failure_not_zero(self):
        root = make_lane_root(self.tmp)
        lane = lanes.load_lanes("datacentres", root)["lanes"][0]
        ldir = lanes.lanes_dir("datacentres", root) / "fake-lane"
        codes = lanes.run_commands(ldir, lane, lane["fetch"], today="2026-10-29", retrieved="x", log=lambda *_: None)
        self.assertEqual(codes, [2])
        manifest = lanes.write_manifest("datacentres", root, fetches={
            "fake-lane": {"date": "2026-10-29", "codes": codes, "ok": False}})
        self.assertFalse(manifest["lanes"]["fake-lane"]["last_fetch"]["ok"])
        self.assertEqual(lanes.retrieved_for(manifest, "fake-lane"), "unspecified")

    def test_pinned_input_with_wrong_bytes_is_refused(self):
        root = make_lane_root(self.tmp)
        lane = {"id": "x", "inputs": [{"file": "inputs/a.bin", "url": "https://example.org/a",
                                        "sha256": hashlib.sha256(b"right").hexdigest(), "commit": False}]}
        ldir = root / "x"
        with self.assertRaises(lanes.LaneError):
            lanes.fetch_inputs(ldir, lane, opener=lambda url: b"wrong", log=lambda *_: None)
        lanes.fetch_inputs(ldir, lane, opener=lambda url: b"right", log=lambda *_: None)
        self.assertTrue(lanes.inputs_present(ldir, lane))
        self.assertEqual(lanes.tracked_files(ldir, lane), {}, "an uncommitted input is never pinned as a file")

    def test_reproduce_rebuilds_lanes_and_catches_nondeterminism(self):
        root = make_lane_root(self.tmp)
        self.build(root)
        for domain in ("datacentres", "conventional"):
            (root / domain / "sources.json").write_text(json.dumps(
                {"schema": "gb-asset-source-registry.v1", "domain": domain, "sources": []}), encoding="utf-8")
        mismatches = []
        lanes_result = reproduce.check_lanes(root, "datacentres", mismatches)
        self.assertEqual(mismatches, [])
        self.assertEqual(lanes_result["fake-lane"]["rebuilt"], "identical")
        noisy = make_lane_root(Path(tempfile.mkdtemp(prefix="lanes-noisy-")), env={})
        try:
            self.build(noisy)
            lanes_json = noisy / "datacentres/lanes/lanes.json"
            doc = json.loads(lanes_json.read_text())
            doc["lanes"][0]["env"] = {"LANE_NOISE": "/1"}  # absolute values pass through unchanged
            lanes_json.write_text(json.dumps(doc), encoding="utf-8")
            mismatches = []
            result = reproduce.check_lanes(noisy, "datacentres", mismatches)
            self.assertEqual(result["fake-lane"]["rebuilt"], "DIFFERENT")
            self.assertTrue(mismatches)
        finally:
            shutil.rmtree(noisy, ignore_errors=True)


class VendoredLaneTests(unittest.TestCase):
    def test_lane_selftests_pass(self):
        proc = subprocess.run([sys.executable, str(ROOT / "pipelines/run_lanes.py"), "selftest"],
                              capture_output=True, text=True, timeout=600)
        self.assertEqual(proc.returncode, 0, proc.stdout[-3000:] + proc.stderr[-3000:])

    def test_every_lane_is_open_or_explicitly_unverified(self):
        for domain in ("datacentres", "conventional"):
            for lane in lanes.load_lanes(domain)["lanes"]:
                self.assertIn(lane["open"], ("yes", "unverified"), lane["id"])
                self.assertTrue(lane.get("licence") and lane.get("licence_url", "").startswith("https://"), lane["id"])

    def test_fetch_never_runs_in_tests_or_verify(self):
        text = (ROOT / ".github/workflows/test-assets.yml").read_text(encoding="utf-8")
        self.assertNotIn("run_lanes.py fetch", text)


if __name__ == "__main__":
    unittest.main()

Bootstrap Verify Data GridAtlas Workflow

A GitHub Actions workflow. Runs on push and by hand.

automationdata-gridatlas / .github/workflows/202608290904-bootstrap-verify-data-gridatlas.yml · lines 1–140 of 140 · version 2026-08-29 09:04 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path 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-gridatlas-consumer.json; JSON file 202608290904-v8-dependency-ledger.json; JSON file 202608290904-v8-file-ledger.json; JSON file 202608290904-v8-quarantine.json; JSON file bootstrap-verification.json; DuckDB queries.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Runs Verify Bootstrap (`atman/202608290904-verify-bootstrap.py`) and Build Dependency Catalog (`compiler/202608290904-build-dependency-catalog.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-gridatlas · .github/workflows · workflow
Uses
Verify Bootstrap (workflow run), Build Dependency Catalog (workflow run)
Used by
none found
Produces
none declared
Defines here
202608290904 Bootstrap verify data-gridatlas
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 .github/workflows/202608290904-bootstrap-verify-data-gridatlas.yml:1-140 · blob e9fb6dea9f6fee7926ff025bd136650125dbbdfe · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
name: 202608290904 Bootstrap verify data-gridatlas

on:
  push:
    branches: [main]
    paths:
      - '.github/workflows/202608290904-bootstrap-verify-data-gridatlas.yml'
      - 'contracts/202608290904-data-gridatlas-bootstrap.json'
      - 'contracts/202608290904-gridatlas-consumer.json'
      - 'contracts/202608290904-v8-dependency-ledger.json'
      - 'contracts/202608290904-v8-file-ledger.json'
      - 'contracts/202608290904-v8-quarantine.json'
      - 'compiler/202608290904-build-dependency-catalog.py'
      - 'atman/202608290904-verify-bootstrap.py'
  workflow_dispatch:
    inputs:
      expected_source_sha:
        description: Exact source commit to verify
        required: true
        type: string

permissions:
  contents: read

concurrency:
  group: data-gridatlas-bootstrap
  cancel-in-progress: false

jobs:
  bootstrap_verify:
    name: Double-build and verify dependency catalogue
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - name: Checkout exact source
        uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
        with:
          ref: ${{ inputs.expected_source_sha || github.sha }}
          fetch-depth: 2

      - name: Enforce compare-and-swap source boundary
        env:
          EXPECTED_SOURCE_SHA: ${{ inputs.expected_source_sha || github.sha }}
        run: |
          git fetch --no-tags --depth=1 origin main:refs/remotes/origin/main
          test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"
          test "$(git rev-parse origin/main)" = "$EXPECTED_SOURCE_SHA"
          test -z "$(git status --porcelain --untracked-files=all)"

      - name: Configure pinned Python
        uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
        with:
          python-version: '3.12'

      - name: Install locked analytical engine
        run: python -m pip install --disable-pip-version-check -r requirements.lock

      - name: Verify inventory-only source boundary
        run: |
          mkdir -p work
          python atman/202608290904-verify-bootstrap.py \
            --repository . \
            --output work/source-boundary.json

      - name: Fetch pinned V8 tree metadata without payload blobs
        run: |
          git init work/v8-oracle
          git -C work/v8-oracle remote add origin https://github.com/Ventusltd/globalgrid2050.git
          git -C work/v8-oracle -c protocol.version=2 fetch \
            --filter=blob:none --no-tags --depth=1 origin \
            f2f343a92ee972cc74ed23b4b99d8a22896791ad
          test "$(git -C work/v8-oracle rev-parse FETCH_HEAD)" = "f2f343a92ee972cc74ed23b4b99d8a22896791ad"
          test "$(git -C work/v8-oracle rev-parse 'FETCH_HEAD^{tree}')" = "2a8ecce66fdb06fbeac1d58443b2d67ba17aedb9"
          {
            git -C work/v8-oracle ls-tree -r FETCH_HEAD repd_grid_atlasv8
            git -C work/v8-oracle ls-tree FETCH_HEAD -- \
              uk_metros_trams.geojson \
              uk_mainline_railways.geojson \
              uk_motorways.geojson \
              uk_trunk_roads.geojson \
              uk_primary_roads.geojson \
              heavy_emitters_uk.json \
              dist/repd_master.json
          } > work/v8-tree.txt

      - name: Verify exact pinned V8 path and blob closure
        run: |
          python atman/202608290904-verify-bootstrap.py \
            --repository . \
            --oracle-tree work/v8-tree.txt \
            --output work/oracle-verification.json

      - name: Deterministic clean catalogue builds A and B
        run: |
          python compiler/202608290904-build-dependency-catalog.py --repository . --output build-a
          python compiler/202608290904-build-dependency-catalog.py --repository . --output build-b
          (cd build-a && find . -type f -print0 | sort -z | xargs -0 sha256sum) > work/build-a.sha256
          (cd build-b && find . -type f -print0 | sort -z | xargs -0 sha256sum) > work/build-b.sha256
          diff --unified work/build-a.sha256 work/build-b.sha256

      - name: Independent DuckDB typed and quarantine verification
        id: atman
        continue-on-error: true
        run: |
          python atman/202608290904-verify-bootstrap.py \
            --repository . \
            --oracle-tree work/v8-tree.txt \
            --catalog build-a \
            --output work/bootstrap-verification.json

      - name: Upload exact bootstrap evidence
        if: always()
        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
        with:
          name: data-gridatlas-202608290904-bootstrap-candidate
          path: |
            build-a/
            work/build-a.sha256
            work/build-b.sha256
            work/source-boundary.json
            work/oracle-verification.json
            work/bootstrap-verification.json
            work/v8-tree.txt
          if-no-files-found: warn
          retention-days: 30
          compression-level: 0

      - name: Enforce verified bootstrap candidate classification
        if: always()
        env:
          ATMAN_OUTCOME: ${{ steps.atman.outcome }}
        run: |
          python - <<'PY'
          import json
          from pathlib import Path
          proof = json.loads(Path('work/bootstrap-verification.json').read_text(encoding='utf-8'))
          if proof.get('classification') != 'VERIFIED_BOOTSTRAP_CANDIDATE' or proof.get('failed') != 0:
              raise SystemExit(f"bootstrap candidate rejected: {proof}")
          PY
          test "$ATMAN_OUTCOME" = "success"

Build V8 Transplant Candidate Workflow

A GitHub Actions workflow in Data GridAtlas. Runs on push and by hand.

automationdata-gridatlas / .github/workflows/202608291015-build-v8-transplant-candidate.yml · lines 1–379 of 379 · version 2026-08-29 10:15 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: reads or writes files; 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 202608290904-v8-dependency-ledger.json; JSON file 202608290904-v8-file-ledger.json; JSON file 202608290904-v8-quarantine.json; JSON file 202608291015-repository-boundary.json; JSON file 202608291015-v8-layer-config.json; JSON file 202608291015-v8-runtime-dependencies.json; JSON file 202608291015-v8-transplant-plan.json; JSON file 202608291015-v8-transplant-parquet.json. Out: JSON file phase-evidence-index.json.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Runs Verify V8 Transplant (`atman/202608291015-verify-v8-transplant.py`) and Build V8 Transplant (`compiler/202608291015-build-v8-transplant.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-gridatlas · .github/workflows · workflow
Uses
Verify V8 Transplant (workflow run), Build V8 Transplant (workflow run)
Used by
none found
Produces
none declared
Defines here
202608291015 Build full V8 transplant candidate
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 .github/workflows/202608291015-build-v8-transplant-candidate.yml:1-379 · blob 460a7129ea31be7fb44727e1b474a6f88fb02150 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
name: 202608291015 Build full V8 transplant candidate

on:
  push:
    branches: [main]
    paths:
      - '.github/workflows/202608291015-build-v8-transplant-candidate.yml'
      - '.gitignore'
      - 'README.md'
      - 'requirements.lock'
      - 'atman/202608291015-verify-v8-transplant.py'
      - 'compiler/202608291015-build-v8-transplant.py'
      - 'contracts/202608290904-v8-dependency-ledger.json'
      - 'contracts/202608290904-v8-file-ledger.json'
      - 'contracts/202608290904-v8-quarantine.json'
      - 'contracts/202608291015-repository-boundary.json'
      - 'contracts/202608291015-v8-layer-config.json'
      - 'contracts/202608291015-v8-runtime-dependencies.json'
      - 'contracts/202608291015-v8-transplant-plan.json'
      - 'schemas/202608291015-v8-transplant-parquet.json'
  workflow_dispatch:
    inputs:
      expected_source_sha:
        description: Exact source commit to verify and build
        required: true
        type: string

permissions:
  contents: read

concurrency:
  group: data-gridatlas-v8-transplant-202608291015
  cancel-in-progress: false

jobs:
  source_boundary:
    name: Verify exact source and transplant contract
    runs-on: ubuntu-24.04
    timeout-minutes: 10
    steps:
      - name: Checkout exact source
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          ref: ${{ inputs.expected_source_sha || github.sha }}
          fetch-depth: 2
          persist-credentials: false

      - name: Enforce compare-and-swap source boundary
        env:
          EXPECTED_SOURCE_SHA: ${{ inputs.expected_source_sha || github.sha }}
          EXECUTED_WORKFLOW_SHA: ${{ github.workflow_sha }}
        run: |
          test "$GITHUB_REF" = 'refs/heads/main'
          test "$EXECUTED_WORKFLOW_SHA" = "$EXPECTED_SOURCE_SHA"
          git fetch --no-tags --depth=1 origin main:refs/remotes/origin/main
          test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"
          test "$(git rev-parse origin/main)" = "$EXPECTED_SOURCE_SHA"
          test -z "$(git status --porcelain --untracked-files=all)"

      - name: Configure pinned Python
        uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97
        with:
          python-version: '3.12.13'

      - name: Install locked analytical engine
        run: python -m pip install --disable-pip-version-check --require-hashes -r requirements.lock

      - name: Verify full source contract
        run: |
          mkdir -p work
          python atman/202608291015-verify-v8-transplant.py \
            --repository . \
            --output work/source-verification.json

  build_phase:
    name: Double-build ${{ matrix.phase }}
    needs: source_boundary
    runs-on: ubuntu-24.04
    timeout-minutes: 25
    strategy:
      fail-fast: false
      matrix:
        phase:
          - p1_foundation
          - p2_lazy_context
          - p3_official_rebuild
          - p4_rail_global
          - p4_motorways
          - p4_trunk_roads
          - p4_primary_roads
          - quarantine
    steps:
      - name: Checkout exact source
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          ref: ${{ inputs.expected_source_sha || github.sha }}
          fetch-depth: 2
          persist-credentials: false

      - name: Reassert exact main source
        env:
          EXPECTED_SOURCE_SHA: ${{ inputs.expected_source_sha || github.sha }}
          EXECUTED_WORKFLOW_SHA: ${{ github.workflow_sha }}
        run: |
          test "$GITHUB_REF" = 'refs/heads/main'
          test "$EXECUTED_WORKFLOW_SHA" = "$EXPECTED_SOURCE_SHA"
          git fetch --no-tags --depth=1 origin main:refs/remotes/origin/main
          test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"
          test "$(git rev-parse origin/main)" = "$EXPECTED_SOURCE_SHA"

      - name: Configure pinned Python
        uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97
        with:
          python-version: '3.12.13'

      - name: Install locked analytical engine
        run: python -m pip install --disable-pip-version-check --require-hashes -r requirements.lock

      - name: Bind exact hosted runtime image
        id: runtime
        run: |
          test "$(python -c 'import platform; print(platform.python_version())')" = '3.12.13'
          test -n "$ImageOS"
          test -n "$ImageVersion"
          printf '%s\n' "$ImageOS" "$ImageVersion" 'python-3.12.13' 'duckdb-1.3.2' \
            | sha256sum | awk '{print "fingerprint=" $1}' >> "$GITHUB_OUTPUT"

      - name: Restore exact content-addressed phase cache
        id: phase_cache
        uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9
        with:
          path: |
            build-cache/${{ matrix.phase }}
            build-evidence/${{ matrix.phase }}
          key: v8-transplant-202608291015-py31213-ubuntu24-${{ steps.runtime.outputs.fingerprint }}-${{ matrix.phase }}-${{ hashFiles('.github/workflows/202608291015-build-v8-transplant-candidate.yml', 'contracts/202608291015-v8-transplant-plan.json', 'contracts/202608291015-v8-layer-config.json', 'contracts/202608291015-v8-runtime-dependencies.json', 'contracts/202608291015-repository-boundary.js  … [line shortened here: 716 characters; full line on GitHub]

      - name: Fetch only exact pinned phase inputs
        run: |
          python compiler/202608291015-build-v8-transplant.py \
            --repository . \
            --phase "${{ matrix.phase }}" \
            --source-root work/v8-input \
            --fetch-only

      - name: Deterministic phase builds A and B
        if: steps.phase_cache.outputs.cache-hit != 'true'
        run: |
          python compiler/202608291015-build-v8-transplant.py \
            --repository . --phase "${{ matrix.phase }}" \
            --source-root work/v8-input --output "build-cache/${{ matrix.phase }}"
          python compiler/202608291015-build-v8-transplant.py \
            --repository . --phase "${{ matrix.phase }}" \
            --source-root work/v8-input --output "build-b/${{ matrix.phase }}"
          mkdir -p "build-evidence/${{ matrix.phase }}"
          (cd "build-cache/${{ matrix.phase }}" && find . -type f -print0 | sort -z | xargs -0 sha256sum) > "build-evidence/${{ matrix.phase }}/build-a.sha256"
          (cd "build-b/${{ matrix.phase }}" && find . -type f -print0 | sort -z | xargs -0 sha256sum) > "build-evidence/${{ matrix.phase }}/build-b.sha256"
          diff --unified "build-evidence/${{ matrix.phase }}/build-a.sha256" "build-evidence/${{ matrix.phase }}/build-b.sha256"

      - name: Independently verify phase cache or fresh build
        run: |
          mkdir -p work
          test -s "build-evidence/${{ matrix.phase }}/build-a.sha256"
          test -s "build-evidence/${{ matrix.phase }}/build-b.sha256"
          diff --unified "build-evidence/${{ matrix.phase }}/build-a.sha256" "build-evidence/${{ matrix.phase }}/build-b.sha256"
          (cd "build-cache/${{ matrix.phase }}" && find . -type f -print0 | sort -z | xargs -0 sha256sum) > "work/${{ matrix.phase }}-current.sha256"
          diff --unified "build-evidence/${{ matrix.phase }}/build-a.sha256" "work/${{ matrix.phase }}-current.sha256"
          python atman/202608291015-verify-v8-transplant.py \
            --repository . \
            --phase-output "build-cache/${{ matrix.phase }}" \
            --source-root work/v8-input \
            --output "work/${{ matrix.phase }}-verification.json"

      - name: Upload exact verified phase
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
        with:
          name: v8-transplant-202608291015-payload-phase-${{ matrix.phase }}
          path: build-cache/${{ matrix.phase }}/
          if-no-files-found: error
          retention-days: 7
          compression-level: 0

      - name: Upload retained A/B and independent phase proof
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
        with:
          name: v8-transplant-202608291015-proof-phase-${{ matrix.phase }}
          path: |
            build-evidence/${{ matrix.phase }}/
            work/${{ matrix.phase }}-verification.json
            work/${{ matrix.phase }}-current.sha256
          if-no-files-found: error
          retention-days: 30
          compression-level: 0

  merge_verify:
    name: Merge and independently verify full V8 candidate
    needs: build_phase
    runs-on: ubuntu-24.04
    timeout-minutes: 25
    steps:
      - name: Checkout exact source
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          ref: ${{ inputs.expected_source_sha || github.sha }}
          fetch-depth: 2
          persist-credentials: false

      - name: Reassert exact main source
        env:
          EXPECTED_SOURCE_SHA: ${{ inputs.expected_source_sha || github.sha }}
          EXECUTED_WORKFLOW_SHA: ${{ github.workflow_sha }}
        run: |
          test "$GITHUB_REF" = 'refs/heads/main'
          test "$EXECUTED_WORKFLOW_SHA" = "$EXPECTED_SOURCE_SHA"
          git fetch --no-tags --depth=1 origin main:refs/remotes/origin/main
          test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"
          test "$(git rev-parse origin/main)" = "$EXPECTED_SOURCE_SHA"

      - name: Configure pinned Python
        uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97
        with:
          python-version: '3.12.13'

      - name: Install locked analytical engine
        run: python -m pip install --disable-pip-version-check --require-hashes -r requirements.lock

      - name: Download all eight verified phase artifacts
        uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131
        with:
          pattern: v8-transplant-202608291015-payload-phase-*
          path: work/phase-artifacts
          merge-multiple: true

      - name: Download all retained phase proofs
        uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131
        with:
          pattern: v8-transplant-202608291015-proof-phase-*
          path: work/phase-proofs
          merge-multiple: true

      - name: Verify retained phase proof closure
        run: |
          python - <<'PY'
          import hashlib
          import json
          import subprocess
          from pathlib import Path

          phases = {
              'p1_foundation', 'p2_lazy_context', 'p3_official_rebuild', 'p4_rail_global',
              'p4_motorways', 'p4_trunk_roads', 'p4_primary_roads', 'quarantine',
          }
          root = Path('work/phase-proofs')
          source_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
          proofs = {}
          evidence = []
          for path in sorted(item for item in root.rglob('*') if item.is_file()):
              payload = path.read_bytes()
              evidence.append({'path': path.relative_to(root).as_posix(), 'bytes': len(payload), 'sha256': hashlib.sha256(payload).hexdigest()})
              if path.name.endswith('-verification.json'):
                  phase = path.name.removesuffix('-verification.json')
                  proof = json.loads(payload)
                  if proof.get('classification') != 'VERIFIED_V8_TRANSPLANT_PHASE' or proof.get('failed') != 0:
                      raise SystemExit(f'rejected phase proof: {path}')
                  if proof.get('repository_source_commit') != source_commit:
                      raise SystemExit(f'stale phase proof: {path}')
                  proofs[phase] = proof
          if set(proofs) != phases:
              raise SystemExit(f'phase proof closure mismatch: {sorted(proofs)}')
          for phase in phases:
              a = next(root.rglob(f'{phase}/build-a.sha256'))
              b = next(root.rglob(f'{phase}/build-b.sha256'))
              current = next(root.rglob(f'{phase}-current.sha256'))
              if not (a.read_bytes() == b.read_bytes() == current.read_bytes()):
                  raise SystemExit(f'non-deterministic retained proof: {phase}')
              for line in a.read_text(encoding='utf-8').splitlines():
                  expected_hash, relative = line.split(maxsplit=1)
                  relative = relative.lstrip('*')
                  if relative.startswith('./'):
                      relative = relative[2:]
                  target = Path('work/phase-artifacts') / relative
                  if not target.is_file() or hashlib.sha256(target.read_bytes()).hexdigest() != expected_hash:
                      raise SystemExit(f'phase payload/checksum mismatch: {phase}:{relative}')
          Path('work/phase-evidence-index.json').write_text(
              json.dumps({'schema': 'data-gridatlas.phase-evidence-index.v1', 'generation': '202608291015', 'files': evidence}, sort_keys=True, indent=2) + '\n',
              encoding='utf-8',
          )
          PY

      - name: Deterministically merge full candidate
        run: |
          python compiler/202608291015-build-v8-transplant.py \
            --repository . \
            --merge-input work/phase-artifacts \
            --output candidate

      - name: Independent full closure verification
        id: atman
        continue-on-error: true
        run: |
          mkdir -p work
          set -o pipefail
          python atman/202608291015-verify-v8-transplant.py \
            --repository . \
            --candidate candidate \
            --phase-input work/phase-artifacts \
            --output work/full-candidate-verification.json \
            2>&1 | tee work/full-candidate-verification.log

      - name: Final compare-and-swap boundary
        id: final_cas
        continue-on-error: true
        env:
          EXPECTED_SOURCE_SHA: ${{ inputs.expected_source_sha || github.sha }}
          EXECUTED_WORKFLOW_SHA: ${{ github.workflow_sha }}
        run: |
          test "$GITHUB_REF" = 'refs/heads/main'
          test "$EXECUTED_WORKFLOW_SHA" = "$EXPECTED_SOURCE_SHA"
          git fetch --no-tags --depth=1 origin main:refs/remotes/origin/main
          test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"
          test "$(git rev-parse origin/main)" = "$EXPECTED_SOURCE_SHA"

      - name: Upload full V8 transplant candidate and proof
        if: steps.atman.outcome == 'success' && steps.final_cas.outcome == 'success'
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
        with:
          name: data-gridatlas-202608291015-verified-candidate-${{ inputs.expected_source_sha || github.sha }}-run-${{ github.run_id }}-attempt-${{ github.run_attempt }}
          path: |
            candidate/
            work/full-candidate-verification.json
            work/full-candidate-verification.log
            work/phase-evidence-index.json
            work/phase-proofs/
          if-no-files-found: error
          retention-days: 30
          compression-level: 0

      - name: Upload explicitly rejected evidence only
        if: always() && (steps.atman.outcome != 'success' || steps.final_cas.outcome != 'success')
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
        with:
          name: REJECTED-data-gridatlas-202608291015-${{ inputs.expected_source_sha || github.sha }}-run-${{ github.run_id }}-attempt-${{ github.run_attempt }}
          path: |
            work/full-candidate-verification.json
            work/full-candidate-verification.log
            work/phase-evidence-index.json
            work/phase-proofs/
          if-no-files-found: warn
          retention-days: 30
          compression-level: 0

      - name: Post-upload compare-and-swap receipt
        id: post_upload_cas
        if: steps.atman.outcome == 'success' && steps.final_cas.outcome == 'success'
        env:
          EXPECTED_SOURCE_SHA: ${{ inputs.expected_source_sha || github.sha }}
          EXECUTED_WORKFLOW_SHA: ${{ github.workflow_sha }}
        run: |
          test "$EXECUTED_WORKFLOW_SHA" = "$EXPECTED_SOURCE_SHA"
          git fetch --no-tags --depth=1 origin main:refs/remotes/origin/main
          test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"
          test "$(git rev-parse origin/main)" = "$EXPECTED_SOURCE_SHA"

      - name: Enforce full candidate classification
        if: always()
        env:
          ATMAN_OUTCOME: ${{ steps.atman.outcome }}
          FINAL_CAS_OUTCOME: ${{ steps.final_cas.outcome }}
          POST_UPLOAD_CAS_OUTCOME: ${{ steps.post_upload_cas.outcome }}
        run: |
          python - <<'PY'
          import json
          from pathlib import Path
          proof = json.loads(Path('work/full-candidate-verification.json').read_text(encoding='utf-8'))
          if proof.get('classification') != 'VERIFIED_FULL_V8_TRANSPLANT_CANDIDATE' or proof.get('failed') != 0:
              raise SystemExit(f"full V8 transplant candidate rejected: {proof}")
          PY
          test "$ATMAN_OUTCOME" = "success"
          test "$FINAL_CAS_OUTCOME" = "success"
          test "$POST_UPLOAD_CAS_OUTCOME" = "success"