GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / faraday / .github/workflows

GlobalGrid2050 Size Guard and 6 more files

A shell script in the scripts folder that reads repo size guard.

697 lines of YAML and Shell and JavaScript from faraday, galaxies-wafers, gb-electricity-ui and 2 more, in 7 files. Topic: Automation and CI. Section 1707 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. Nightshift Workflow automation · faraday / .github/workflows/nightshift.yml lines 1–107
  2. Browser Matrix Workflow automation · galaxies-wafers / .github/workflows/browser-matrix.yml lines 1–53
  3. Pages Workflow automation · gb-electricity-ui / .github/workflows/pages.yml lines 1–34
  4. Publish Gemini Bridge Workflow automation · gemini / .github/workflows/publish_gemini_bridge.yml lines 1–61
  5. GlobalGrid2050 Size Guard automation · globalgrid2050 / .github/scripts/size_guard.sh lines 1–223
  6. Inverter Flow test · globalgrid2050 / .github/tests/inverter-flow.cjs lines 1–27
  7. GlobalGrid2050 000 Freeze All Workflows to Manual Workflow automation · globalgrid2050 / .github/workflows/000_freeze_all_workflows_to_manual.yml lines 1–192

Nightshift Workflow

A GitHub Actions workflow in Faraday. Runs by hand.

automationfaraday / .github/workflows/nightshift.yml · lines 1–107 of 107 · Entry point

What it does
It runs solar, cables and transformers. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain terms in the code: solar, cables, transformers.
Inputs & outputs
In: JSON file job.json. Out: JSON file job.json; commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “night shift - networks solved twice”; runs Topo (`bench/topo.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
faraday · .github/workflows · workflow
Uses
Topo (workflow run)
Used by
none found
Produces
none declared
Defines here
night shift - networks solved twice
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 .github/workflows/nightshift.yml:1-107 · blob 610e8a7f99fc2ed0e62f2fb9178315c702168331 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
name: night shift - networks solved twice
# The same seeded networks as bench/topo.py on the home machine, asked in four different ways (more solar, a weak grid, long cables,
# smaller transformers), on GitHub's runners. Every case is solved in Python and again in the JavaScript the Kuiper runs; a job FAILS
# if any case differs. Row by row shards are not kept (any shard can be rebuilt from its seeds); the merged summary and the most
# telling cases are committed to bench/results/runners/.
on:
  workflow_dispatch:
    inputs:
      seeds_per_job: { description: 'seeds per job (x18 cases)', default: '3000000' }
      first_shard: { description: 'first shard number of chunk 0 (2,000 seeds a shard)', default: '30000' }
permissions:
  contents: write
jobs:
  solve:
    runs-on: ubuntu-latest
    timeout-minutes: 300
    strategy:
      fail-fast: false
      max-parallel: 12          # never all 20 of the account's slots: Pages deploys are jobs too and queued for hours behind this on 20 Sept
      matrix:
        variant: [1, 2, 3, 4]
        chunk: [0, 1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: '3.12' }
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - name: self test
        run: python bench/topo.py --selftest
      - name: solve twice
        env:
          TOPO_VARIANT: ${{ matrix.variant }}
          TOPO_OUT: ${{ github.workspace }}/out
        run: |
          SEEDS=${{ github.event.inputs.seeds_per_job }}
          export TOPO_START_SHARD=$(( ${{ github.event.inputs.first_shard }} + ${{ matrix.chunk }} * (SEEDS / 2000) ))
          python bench/topo.py --seeds $SEEDS --workers 4 | tee out.txt
          grep -q "DIFFERED 0," out.txt
          grep -q "could not run 0" out.txt
      - name: merge this job
        run: |
          python - <<'EOF'
          import glob, json, heapq, os
          tot = {}; tops = {}
          for f in glob.glob('out/shards/*.json'):
              d = json.load(open(f))
              for k, v in d.items():
                  if isinstance(v, (int, float)) and k not in ('shard', 'seconds'): tot[k] = tot.get(k, 0) + v
              for k, v in d['check'].items():
                  if isinstance(v, (int, float)): tot['check_' + k] = tot.get('check_' + k, 0) + v
              for k, v in d['by_shape'].items():
                  s = tot.setdefault('by_shape', {}).setdefault(k, [0, 0]); s[0] += v[0]; s[1] += v[1]
              for kind, items in d['tops'].items():
                  h = tops.setdefault(kind, [])
                  for it in map(tuple, items):
                      if len(h) < 200: heapq.heappush(h, it)
                      elif it > h[0]: heapq.heapreplace(h, it)
          tot['variant'] = int(os.environ['V']); tot['chunk'] = int(os.environ['C'])
          json.dump({'summary': tot, 'tops': {k: sorted(v, reverse=True) for k, v in tops.items()}}, open('job.json', 'w'))
          print(json.dumps(tot)[:600])
          EOF
        env: { V: '${{ matrix.variant }}', C: '${{ matrix.chunk }}' }
      - uses: actions/upload-artifact@v4
        with: { name: 'job-v${{ matrix.variant }}-c${{ matrix.chunk }}', path: job.json }
  record:
    needs: solve
    if: always()
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/download-artifact@v4
        with: { path: jobs }
      - name: one record for the run
        run: |
          python - <<'EOF'
          import glob, json, heapq, os, time
          by_variant = {}; tops = {}
          for f in sorted(glob.glob('jobs/*/job.json')):
              d = json.load(open(f)); s = d['summary']; v = str(s['variant'])
              t = by_variant.setdefault(v, {})
              for k, val in s.items():
                  if isinstance(val, (int, float)) and k not in ('variant', 'chunk'): t[k] = t.get(k, 0) + val
              for shape, pair in s.get('by_shape', {}).items():
                  p = t.setdefault('by_shape', {}).setdefault(shape, [0, 0]); p[0] += pair[0]; p[1] += pair[1]
              for kind, items in d['tops'].items():
                  h = tops.setdefault(v + ' | ' + kind, [])
                  for it in map(tuple, items):
                      if len(h) < 200: heapq.heappush(h, it)
                      elif it > h[0]: heapq.heapreplace(h, it)
          os.makedirs('bench/results/runners', exist_ok=True)
          out = {'schema': 'faraday.runners.v1', 'run': os.environ['RUN'], 'written_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
                 'variants': {'1': 'half as much solar again', '2': 'a connection of half the fault level', '3': 'every cable three times as long', '4': 'every transformer one size down'},
                 'jobs_recorded': len(glob.glob('jobs/*/job.json')), 'by_variant': by_variant,
                 'columns': ['score', 'seed', 'case', 'p_kw', 'vmax_pu', 'vmin_pu', 'worst_tx_pct', 'flags'], 'tops': {k: sorted(v, reverse=True) for k, v in tops.items()}}
          json.dump(out, open('bench/results/runners/run-%s.json' % os.environ['RUN'], 'w'), separators=(',', ':'))
          print(json.dumps(by_variant)[:1500])
          EOF
        env: { RUN: '${{ github.run_id }}' }
      - name: commit the record
        run: |
          git config user.name "faraday night shift"
          git config user.email "actions@users.noreply.github.com"
          git add bench/results/runners
          git diff --cached --quiet || git commit -m "night shift on the runners: run ${{ github.run_id }}, networks solved twice in four different ways"
          git pull --rebase
          git push

Browser Matrix Workflow

A GitHub Actions workflow in Galaxies Wafers. Runs by hand.

automationgalaxies-wafers / .github/workflows/browser-matrix.yml · lines 1–53 of 53 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV.
Inputs & outputs
Voltage levels named: 400kV.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Twenty GitHub-hosted browser jobs against the served Pages site: the ten iterations, each at phone and desktop size.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
galaxies-wafers · .github/workflows · workflow
Uses
Judge Check (workflow run), Smoke (workflow run), Galaxies Wafers — Index Page (estate URL)
Used by
none found
Produces
none declared
Defines here
browser-matrix
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 .github/workflows/browser-matrix.yml:1-53 · blob d7eb7770ab4691958ed310a7b9d58f2b4a18091a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
# Twenty GitHub-hosted browser jobs against the served Pages site: the ten
# iterations, each at phone and desktop size. Runs after every Pages build and on
# demand. Read-only token, pinned actions, no secrets, ten-minute cap per job.
name: browser-matrix
on:
  page_build:
  workflow_dispatch:
permissions:
  contents: read
concurrency:
  group: browser-matrix
  cancel-in-progress: true
jobs:
  smoke:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    strategy:
      fail-fast: false
      matrix:
        page:
          - iterations/01-route-alpha/
          - iterations/02-tunnels/
          - iterations/03-code-particle/
          - iterations/04-400kv-engine/
          - iterations/05-periodic-table/
          - iterations/06-stars-as-engines/?layers=crossname,grid-engine-shell,spider,module-Gg
          - iterations/07-code-card/?layers=grid-engine-shell,learned,module-Ga
          - iterations/08-space-and-time/?t=342795&layers=module-Ga,module-Vn
          - iterations/09-deeplink-receiver/?layers=module-Ps,module-Gn,module-x126
          - iterations/10-ground-bridge/
        size: [phone, desktop]
    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
      - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0
        with:
          node-version: 20
      - name: verdict fixtures
        run: node proof/browser/judge.check.mjs
      - name: install puppeteer
        run: npm i --no-save --no-audit --no-fund puppeteer@23.11.1
      - name: smoke
        env:
          PAGE: ${{ matrix.page }}
          SIZE: ${{ matrix.size }}
          BASE: https://ventusltd.github.io/galaxies-wafers/
        run: node proof/browser/smoke.mjs
      - name: receipt
        if: always()
        uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0
        with:
          name: smoke-${{ strategy.job-index }}-${{ matrix.size }}
          path: smoke-result.json
          retention-days: 14

Pages Workflow

A GitHub Actions workflow in GB Electricity UI that builds and publishes the site. Runs on push and by hand.

automationgb-electricity-ui / .github/workflows/pages.yml · lines 1–34 of 34 · Entry point

What it does
It builds and publishes its content. Side effects: starts processes.
Inputs & outputs
Out: GitHub Pages deployment.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Deploy static Pages”; publishes to GitHub Pages.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gb-electricity-ui · .github/workflows · workflow
Uses
none found
Used by
none found
Produces
none declared
Defines here
Deploy static Pages
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gb-electricity-ui@f29f8b8e9a6317e7041ff0469645237a273de8a3 .github/workflows/pages.yml:1-34 · blob beeabe931359284361f32d03e97cb5c1f2d37d6a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: Deploy static Pages

on:
  workflow_dispatch:
  push:
    branches: [main]

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: pages
  cancel-in-progress: false

jobs:
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Configure Pages
        uses: actions/configure-pages@v5
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: .
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

Publish Gemini Bridge Workflow

A GitHub Actions workflow that builds and publishes the site. Runs on push, on a schedule and by hand.

automationgemini / .github/workflows/publish_gemini_bridge.yml · lines 1–61 of 61 · Entry point

What it does
It builds and publishes its content. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'gemini'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: GitHub Pages deployment; commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Runs Gemini Build Manifest (`scripts/build_manifest.py`); publishes to GitHub Pages.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gemini · .github/workflows · workflow
Uses
Gemini Build Manifest (workflow run), Test Manifest (workflow run)
Used by
none found
Produces
none declared
Defines here
Publish Gemini bridge
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gemini@bf5d9f7de72c07ce57ec64864ac5181cc46c8381 .github/workflows/publish_gemini_bridge.yml:1-61 · blob 8ee86c049a9cb87207088e8805d5a828161ddf7a · GitHub at these lines
State
achieves: comment · context: auto · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
name: Publish Gemini bridge
on:
  push:
    branches: [main]
  workflow_dispatch:
  schedule:
    - cron: '0 6 * * *'
concurrency:
  group: gemini-bridge-pages
  cancel-in-progress: false
permissions:
  contents: read
jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
          fetch-depth: 0
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - name: Build and verify reproducibility
        shell: bash
        run: |
          set -euo pipefail
          export BRIDGE_SOURCE_SHA="$(git log -1 --format=%H -- context handoff scripts/build_manifest.py scripts/ui ui)"
          export BRIDGE_SOURCE_DATE="$(git show -s --format=%cI "$BRIDGE_SOURCE_SHA")"
          python scripts/build_manifest.py
          find docs -type f -print0 | sort -z | xargs -0 sha256sum > /tmp/first.sha
          python scripts/build_manifest.py
          sha256sum --check /tmp/first.sha
          python -m unittest discover -s tests -v
      - name: Persist generated output
        run: |
          git config user.name 'github-actions[bot]'
          git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
          git add docs
          if ! git diff --cached --quiet; then
            git commit -m 'Publish deterministic Gemini context'
            git push origin HEAD:main
          fi
      - uses: actions/upload-pages-artifact@v3
        with:
          path: docs
  deploy:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - uses: actions/configure-pages@v5
      - uses: actions/deploy-pages@v4
        id: deployment

GlobalGrid2050 Size Guard

A shell script in the scripts folder that reads repo size guard.

automationglobalgrid2050 / .github/scripts/size_guard.sh · lines 1–223 of 223 · Entry point

What it does
It loads repo size guard. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file REPO_SIZE_GUARD_LATEST.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repo Guard Workflow (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by GlobalGrid2050 Repo Guard Workflow.
Application
globalgrid2050 · .github/scripts · shell script
Uses
none found
Used by
run by GlobalGrid2050 Repo Guard Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 .github/scripts/size_guard.sh:1-223 · blob d6cd7063704c832d68e037f85d0acc57f2d3dcd8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env bash
set -euo pipefail

WARN_MIB="${DATASCIENCE_WARN_FILE_MB:-5}"
FAIL_MIB="${DATASCIENCE_FAIL_FILE_MB:-25}"
HARD_MIB="${DATASCIENCE_HARD_FILE_MB:-100}"
ENFORCE="${DATASCIENCE_ENFORCE_SIZE_GUARD:-true}"
SCAN_SCOPE="${DATASCIENCE_SIZE_GUARD_SCOPE:-changed}"
BASE_REF="${DATASCIENCE_BASE_REF:-origin/main}"
REPORT_DIR="data_science_protocol/audit_reports"
JSON_DIR="${REPORT_DIR}/json"

mkdir -p "${REPORT_DIR}" "${JSON_DIR}"

python3 - <<'PY'
import json
import os
import subprocess
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path.cwd()

warn_mib = float(os.environ.get("DATASCIENCE_WARN_FILE_MB", "5"))
fail_mib = float(os.environ.get("DATASCIENCE_FAIL_FILE_MB", "25"))
hard_mib = float(os.environ.get("DATASCIENCE_HARD_FILE_MB", "100"))
enforce = os.environ.get("DATASCIENCE_ENFORCE_SIZE_GUARD", "true").lower() in {"1", "true", "yes"}
scan_scope = os.environ.get("DATASCIENCE_SIZE_GUARD_SCOPE", "changed").lower()
base_ref = os.environ.get("DATASCIENCE_BASE_REF", "origin/main")

stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
report_dir = ROOT / "data_science_protocol" / "audit_reports"
json_dir = report_dir / "json"
report_md = report_dir / f"repo_size_guard_{stamp}.md"
report_json = json_dir / f"repo_size_guard_{stamp}.json"
latest_md = report_dir / "REPO_SIZE_GUARD_LATEST.md"
latest_json = json_dir / "REPO_SIZE_GUARD_LATEST.json"

excluded_parts = {
    ".git", ".venv", "venv", "env", "node_modules", "__pycache__",
    ".mypy_cache", ".pytest_cache", ".ipynb_checkpoints"
}

review_extensions = {
    ".csv", ".json", ".geojson", ".topojson", ".parquet", ".zip",
    ".sqlite", ".db", ".html", ".js", ".css", ".py", ".md", ".yml",
    ".yaml", ".txt"
}

def run(cmd):
    return subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True)

def git(args):
    result = run(["git", *args])
    return result.stdout.strip() if result.returncode == 0 else ""

def mib(size_bytes):
    return round(size_bytes / 1024 / 1024, 3)

def skip(path):
    try:
        parts = path.relative_to(ROOT).parts
    except ValueError:
        return True
    return any(part in excluded_parts for part in parts)

def candidate_paths():
    if scan_scope == "all":
        return sorted([p for p in ROOT.rglob("*") if p.is_file() and not skip(p)])

    changed = set()
    diff_cmds = [
        ["git", "diff", "--name-only", "--diff-filter=ACMRT", f"{base_ref}...HEAD"],
        ["git", "diff", "--name-only", "--diff-filter=ACMRT", "HEAD~1..HEAD"],
    ]
    for cmd in diff_cmds:
        result = run(cmd)
        if result.returncode == 0 and result.stdout.strip():
            changed.update(line.strip() for line in result.stdout.splitlines() if line.strip())
            break

    local = run(["git", "diff", "--name-only", "--diff-filter=ACMRT"])
    if local.returncode == 0:
        changed.update(line.strip() for line in local.stdout.splitlines() if line.strip())

    staged = run(["git", "diff", "--cached", "--name-only", "--diff-filter=ACMRT"])
    if staged.returncode == 0:
        changed.update(line.strip() for line in staged.stdout.splitlines() if line.strip())

    paths = []
    for rel in sorted(changed):
        p = ROOT / rel
        if p.exists() and p.is_file() and not skip(p):
            paths.append(p)
    return paths

def classify(path, size_bytes):
    rel = path.relative_to(ROOT).as_posix().lower()
    suffix = path.suffix.lower()

    if size_bytes >= hard_mib * 1024 * 1024:
        risk = "hard limit risk"
    elif size_bytes >= fail_mib * 1024 * 1024:
        risk = "fail"
    elif size_bytes >= warn_mib * 1024 * 1024:
        risk = "warn"
    else:
        risk = "pass"

    if suffix in {".geojson", ".topojson"}:
        kind = "gis geometry"
    elif rel.startswith("data/raw") or "raw" in rel or "dump" in rel or "archive_full" in rel:
        kind = "raw or transient candidate"
    elif rel.startswith("data/"):
        kind = "data"
    elif rel.startswith("data_science_protocol/"):
        kind = "audit or protocol"
    elif rel.startswith(".github/"):
        kind = "workflow or guardrail"
    else:
        kind = "repository file"

    return risk, kind

files = []
for path in candidate_paths():
    size = path.stat().st_size
    suffix = path.suffix.lower()
    if suffix not in review_extensions and size < warn_mib * 1024 * 1024:
        continue
    risk, kind = classify(path, size)
    if risk != "pass" or kind in {"gis geometry", "raw or transient candidate"}:
        files.append({
            "path": path.relative_to(ROOT).as_posix(),
            "sizeBytes": size,
            "sizeMiB": mib(size),
            "risk": risk,
            "kind": kind,
        })

files = sorted(files, key=lambda item: item["sizeBytes"], reverse=True)
warn_files = [f for f in files if f["risk"] == "warn"]
fail_files = [f for f in files if f["risk"] in {"fail", "hard limit risk"}]
hard_files = [f for f in files if f["risk"] == "hard limit risk"]

payload = {
    "reportTitle": "GlobalGrid2050 Repository Size Guard",
    "schemaVersion": "1.2.0",
    "generatedUTC": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "repository": os.environ.get("GITHUB_REPOSITORY", "Ventusltd/globalgrid2050"),
    "branch": git(["branch", "--show-current"]),
    "gitHead": git(["rev-parse", "--short", "HEAD"]),
    "mode": "enforce" if enforce else "audit only",
    "scanScope": scan_scope,
    "baseRef": base_ref,
    "thresholdsMiB": {"warn": warn_mib, "fail": fail_mib, "hard": hard_mib},
    "warnCount": len(warn_files),
    "failCount": len(fail_files),
    "hardLimitRiskCount": len(hard_files),
    "files": files,
}

executive = (
    f"Repository size guard ran in {payload['mode']} mode with {scan_scope} scan scope. "
    f"Warn threshold {warn_mib} MiB. Fail threshold {fail_mib} MiB. Hard threshold {hard_mib} MiB. "
    f"Found {len(warn_files)} warning files and {len(fail_files)} fail threshold files."
)
if scan_scope == "changed":
    executive += " Legacy large files are not blocking this run unless they were changed or added."
if enforce and fail_files:
    executive += " Build failed because changed or scanned files breached the fail threshold."

lines = [
    "# GlobalGrid2050 Repository Size Guard",
    "",
    f"Generated UTC: `{payload['generatedUTC']}`",
    f"Repository: `{payload['repository']}`",
    f"Branch: `{payload['branch'] or 'unknown'}`",
    f"Git head: `{payload['gitHead'] or 'unknown'}`",
    f"Mode: `{payload['mode']}`",
    f"Scan scope: `{scan_scope}`",
    f"Base ref: `{base_ref}`",
    "",
    "## Executive summary",
    "",
    executive,
    "",
    "## Files requiring review",
    "",
]

if files:
    lines += ["| Path | MiB | Risk | Kind |", "| --- | --- | --- | --- |"]
    for item in files[:200]:
        lines.append(f"| {item['path']} | {item['sizeMiB']} | {item['risk']} | {item['kind']} |")
else:
    lines.append("No files above watch threshold or matching raw or GIS review patterns in this scan scope.")

lines += [
    "",
    "## Governance note",
    "",
    "Use changed scope for push and pull request enforcement. Use all scope for manual audit runs.",
]

report_dir.mkdir(parents=True, exist_ok=True)
json_dir.mkdir(parents=True, exist_ok=True)

report_text = "\n".join(lines) + "\n"
json_text = json.dumps(payload, indent=2) + "\n"

report_md.write_text(report_text, encoding="utf-8")
latest_md.write_text(report_text, encoding="utf-8")
report_json.write_text(json_text, encoding="utf-8")
latest_json.write_text(json_text, encoding="utf-8")

print(executive)
print(f"Wrote {report_md.relative_to(ROOT)}")
print(f"Wrote {report_json.relative_to(ROOT)}")

if enforce and fail_files:
    raise SystemExit(2)
PY

Inverter Flow

A JavaScript module in the tests folder of GlobalGrid2050.

testglobalgrid2050 / .github/tests/inverter-flow.cjs · lines 1–27 of 27 · Entry point · pattern frame (shared by 66 files)

What it does
It tests its inputs. Defines frame. Uses libraries node:fs, node:path, node:http, node:assert/strict. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'inverter'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
Out: JSON file results.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Inverter Flow Check Workflow (globalgrid2050).
What it achieves
Defines `frame`. It writes `inverter-flow-evidence/results.json`.
Why it matters
Run by GlobalGrid2050 Inverter Flow Check Workflow.
Application
globalgrid2050 · .github/tests · JavaScript module
Uses
node:fs, node:path, node:http, node:assert/strict
Used by
run by GlobalGrid2050 Inverter Flow Check Workflow (workflow run)
Produces
frame
Defines here
frame
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 .github/tests/inverter-flow.cjs:1-27 · blob 4be2ba50cb0074e20395c774ae80b4cb52774c22 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
const fs=require('node:fs'),path=require('node:path'),http=require('node:http'),assert=require('node:assert/strict');
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');
const root=path.resolve(__dirname,'../..');
const server=http.createServer((req,res)=>{const file=path.resolve(root,'.'+decodeURIComponent(req.url.split('?')[0]));if(!file.startsWith(root+path.sep)||!fs.existsSync(file)||!fs.statSync(file).isFile()){res.writeHead(404).end();return;}res.setHeader('Content-Type',/\.(mjs|js)$/.test(file)?'text/javascript':file.endsWith('.css')?'text/css':file.endsWith('.json')?'application/json':'text/html');r  … [line shortened here: 433 characters; full line on GitHub]
(async()=>{let browser;try{
 if(process.platform==='win32')throw Error('Run browser checks on hosted Linux');
 await new Promise(r=>server.listen(0,'127.0.0.1',r));browser=await chromium.launch();
 const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
 await page.goto('http://127.0.0.1:'+server.address().port+'/ventus/wiring/inverter-48.html');
 await page.waitForFunction(()=>window.__inverter48?.ready&&__inverter48.flowStats.homePaths===48,{},{timeout:60000});
 const initial=await page.evaluate(()=>({strings:__inverter48.model.strings.filter(s=>s.connected).length,homes:__inverter48.model.homes.length,stats:__inverter48.flowStats,walks:__inverter48.nativeWalks.length}));
 assert.equal(initial.strings,24);assert.equal(initial.homes,48);assert.equal(initial.walks,24);assert.equal(initial.stats.strings,24);
 const frame=()=>page.evaluate(()=>document.querySelector('#engine').contentDocument.querySelector('#inverter-flow').toDataURL());
 const a=await frame();await page.waitForTimeout(250);assert.notEqual(await frame(),a,'Flow overlay must actually change pixels');
 await page.locator('#flow-scope').click();await page.waitForFunction(()=>__inverter48.flowStats.homePaths===2);assert.equal(await page.evaluate(()=>__inverter48.flowStats.strings),1);
 await page.locator('#menu').click();await page.locator('#string').selectOption('S02');await page.waitForFunction(()=>__inverter48.selected==='S02');
 await page.locator('#flow').click();await page.waitForFunction(()=>__inverter48.flowStats.homePaths===0);const paused=await frame();await page.waitForTimeout(200);assert.equal(await frame(),paused);
 await page.locator('#flow').click();await page.locator('#flow-scope').click();await page.waitForFunction(()=>__inverter48.flowStats.homePaths===48);
 await page.locator('#menu').click();await page.locator('#hud-toggle').click();await page.locator('#length-string').selectOption('S02');await page.locator('#length-plus').fill('0');await page.locator('#length-plus').dispatchEvent('change');
 await page.waitForFunction(()=>__inverter48.flowStats.homePaths===46);assert.equal(await page.evaluate(()=>__inverter48.nativeWalks.find(s=>s.stringId==='S02').open),true);
 await page.locator('#length-reset').click();await page.waitForFunction(()=>__inverter48.flowStats.homePaths===48);await page.locator('#hud-close').click();
 assert.equal(await page.evaluate(()=>getComputedStyle(document.documentElement).colorScheme),'dark');assert.deepEqual(errors,[]);
 fs.mkdirSync('inverter-flow-evidence',{recursive:true});await page.screenshot({path:'inverter-flow-evidence/overview.png'});
 await page.locator('#menu').click();await page.locator('#focus').click();await page.locator('#menu').click();await page.waitForTimeout(200);await page.screenshot({path:'inverter-flow-evidence/string-detail.png'});
 await page.setViewportSize({width:390,height:844});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));assert.deepEqual(errors,[]);
 const report={status:'pass',initial,checks:['24 closed circuits and 48 animated home conductors','changing flow pixels','single-string inspection','pause/resume','short cable stops only its circuit','reset restores 48 conductors','dark theme','mobile overflow','no runtime errors']};fs.writeFileSync('inverter-flow-evidence/results.json',JSON.stringify(report,null,2));console.log(JSON.stringify(rep  … [line shortened here: 406 characters; full line on GitHub]
 }catch(e){console.error(e);process.exitCode=1;}finally{if(browser)await browser.close();server.close();}})();

GlobalGrid2050 000 Freeze All Workflows to Manual Workflow

A GitHub Actions workflow. Runs by hand.

automationglobalgrid2050 / .github/workflows/000_freeze_all_workflows_to_manual.yml · lines 1–192 of 192 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file FREEZE_ALL_WORKFLOWS_TO_MANUAL_LATEST.json. Out: commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · .github/workflows · workflow
Uses
none found
Used by
none found
Produces
none declared
Defines here
Freeze all workflows to manual dispatch
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 .github/workflows/000_freeze_all_workflows_to_manual.yml:1-192 · blob 725803df7618a67da68809603170b6d06bafaf0c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: production_core
name: Freeze all workflows to manual dispatch

on:
  workflow_dispatch:
permissions:
  contents: write

concurrency:
  group: freeze-all-workflows-to-manual
  cancel-in-progress: false

jobs:
  freeze-workflows:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GRIDBOT_PAT || github.token }}

      - name: Rewrite root workflows to manual dispatch only
        shell: bash
        run: |
          python - <<'PY'
          from pathlib import Path
          import datetime as dt
          import json
          import re

          workflow_root = Path('.github/workflows')
          report_dir = Path('data_science_protocol/audit_reports')
          report_json_dir = report_dir / 'json'
          report_dir.mkdir(parents=True, exist_ok=True)
          report_json_dir.mkdir(parents=True, exist_ok=True)

          def is_on_line(line: str) -> bool:
              return re.match(r"^(on|'on'|\"on\")\s*:", line) is not None

          def find_on_block(lines: list[str]) -> tuple[int | None, int | None]:
              start = None
              for index, line in enumerate(lines):
                  if is_on_line(line):
                      start = index
                      break
              if start is None:
                  return None, None
              end = start + 1
              while end < len(lines):
                  line = lines[end]
                  if line.strip() == '' or line.startswith('#'):
                      end += 1
                      continue
                  if not line.startswith((' ', '\t')):
                      break
                  end += 1
              return start, end

          def preserved_dispatch_block(block: list[str]) -> list[str]:
              for index in range(1, len(block)):
                  line = block[index]
                  if re.match(r"^\s{2}workflow_dispatch\s*:", line):
                      end = index + 1
                      while end < len(block):
                          candidate = block[end]
                          if candidate.strip() == '':
                              end += 1
                              continue
                          indent = len(candidate) - len(candidate.lstrip(' '))
                          if indent <= 2:
                              break
                          end += 1
                      preserved = block[index:end]
                      while preserved and preserved[-1].strip() == '':
                          preserved.pop()
                      return ['on:'] + preserved
              return ['on:', '  workflow_dispatch:']

          def freeze_text(text: str) -> tuple[str, bool, dict]:
              has_final_newline = text.endswith('\n')
              lines = text.splitlines()
              start, end = find_on_block(lines)
              if start is None or end is None:
                  return text, False, {'hadOnBlock': False, 'reason': 'no top level on block found'}
              before_block = lines[start:end]
              after_block = preserved_dispatch_block(before_block)
              new_lines = lines[:start] + after_block + lines[end:]
              new_text = '\n'.join(new_lines)
              if has_final_newline:
                  new_text += '\n'
              changed = new_text != text
              before_joined = '\n'.join(before_block)
              after_joined = '\n'.join(after_block)
              return new_text, changed, {
                  'hadOnBlock': True,
                  'changed': changed,
                  'beforeOnBlock': before_joined,
                  'afterOnBlock': after_joined,
                  'hadSchedule': 'schedule:' in before_joined,
                  'hadPush': 'push:' in before_joined,
                  'hadPullRequest': 'pull_request' in before_joined,
                  'hadWorkflowRun': 'workflow_run' in before_joined,
                  'manualDispatchPreserved': 'workflow_dispatch:' in after_joined,
                  'automaticTriggerRemainingInOnBlock': any(token in after_joined for token in ['schedule:', 'push:', 'pull_request', 'workflow_run', 'repository_dispatch', 'release:', 'page_build'])
              }

          changed_files = []
          inspected_files = []
          notes = []

          for path in sorted(workflow_root.glob('*.y*ml')):
              text = path.read_text(encoding='utf-8')
              new_text, changed, detail = freeze_text(text)
              inspected_files.append({'path': path.as_posix(), **detail})
              if changed:
                  path.write_text(new_text, encoding='utf-8')
                  changed_files.append(path.as_posix())

          for nested in sorted(Path('.').glob('*/.github/workflows/*.y*ml')):
              notes.append(f'Nested workflow copy noted but not active at repository root: {nested.as_posix()}')

          now = dt.datetime.now(dt.timezone.utc)
          stamp = now.strftime('%Y%m%dT%H%M%SZ')
          payload = {
              'reportTitle': 'Freeze all root workflows to manual dispatch',
              'generatedUTC': now.isoformat().replace('+00:00', 'Z'),
              'scope': 'Root .github/workflows only',
              'inspectedCount': len(inspected_files),
              'changedCount': len(changed_files),
              'changedFiles': changed_files,
              'inspectedFiles': inspected_files,
              'notes': notes,
              'pass': all(item.get('manualDispatchPreserved', False) and not item.get('automaticTriggerRemainingInOnBlock', True) for item in inspected_files if item.get('hadOnBlock')),
              'executiveSummary': 'All root GitHub Actions workflows are converted to manual workflow_dispatch only, stopping scheduled and push based automatic repository growth while preserving the workflow files for later repo splitting.',
              'rollbackMethod': 'Revert this freeze commit or restore individual workflow trigger blocks from Git history.'
          }

          md_lines = [
              '# Freeze all root workflows to manual dispatch',
              '',
              f"Generated UTC: `{payload['generatedUTC']}`",
              f"Scope: `{payload['scope']}`",
              f"Inspected workflows: `{payload['inspectedCount']}`",
              f"Changed workflows: `{payload['changedCount']}`",
              f"Pass: `{payload['pass']}`",
              '',
              '## Executive summary',
              '',
              payload['executiveSummary'],
              '',
              '## Changed files',
              '',
          ]
          md_lines.extend(f'- `{item}`' for item in changed_files)
          if not changed_files:
              md_lines.append('- None')
          md_lines.extend(['', '## Nested workflow copies noted', ''])
          md_lines.extend(f'- `{item}`' for item in notes)
          if not notes:
              md_lines.append('- None')
          md_lines.extend(['', '## Rollback', '', payload['rollbackMethod'], ''])

          report_latest = report_dir / 'FREEZE_ALL_WORKFLOWS_TO_MANUAL_LATEST.md'
          report_stamp = report_dir / f'FREEZE_ALL_WORKFLOWS_TO_MANUAL_{stamp}.md'
          json_latest = report_json_dir / 'FREEZE_ALL_WORKFLOWS_TO_MANUAL_LATEST.json'
          json_stamp = report_json_dir / f'FREEZE_ALL_WORKFLOWS_TO_MANUAL_{stamp}.json'
          text = '\n'.join(md_lines)
          report_latest.write_text(text, encoding='utf-8')
          report_stamp.write_text(text, encoding='utf-8')
          json_text = json.dumps(payload, indent=2, ensure_ascii=False) + '\n'
          json_latest.write_text(json_text, encoding='utf-8')
          json_stamp.write_text(json_text, encoding='utf-8')
          print(json.dumps({'pass': payload['pass'], 'changedCount': payload['changedCount']}, indent=2))
          if not payload['pass']:
              raise SystemExit(1)
          PY

      - name: Commit freeze
        shell: bash
        run: |
          git config user.name "Gridbot"
          git config user.email "gridbot@users.noreply.github.com"
          git add .github/workflows
          git add data_science_protocol/audit_reports/FREEZE_ALL_WORKFLOWS_TO_MANUAL_*.md
          git add data_science_protocol/audit_reports/json/FREEZE_ALL_WORKFLOWS_TO_MANUAL_*.json
          if git diff --cached --quiet; then
            echo "No freeze changes to commit."
          else
            git commit -m "chore: freeze workflows to manual dispatch only [skip ci]"
            git push origin HEAD:main
          fi