GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / solar-electrical-topology-analysis-engine-text-based / scripts

Local Authority Bridge and 2 more files

A Python command-line tool in the scripts folder of Solar Electrical Topology Analysis Engine Text Based that makes handler, creates server and builds parser, covering reference inverter block.

560 lines of Python from solar-electrical-topology-analysis-engine-text-based, in 3 files. Topic: Solar and storage design. Section 204 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. Check Line Lengths ingest · solar-electrical-topology-analysis-engine-text-based / scripts/check_line_lengths.py lines 1–70
  2. Check Microbuild Plan ingest · solar-electrical-topology-analysis-engine-text-based / scripts/check_microbuild_plan.py lines 1–225
  3. Local Authority Bridge other · solar-electrical-topology-analysis-engine-text-based / scripts/local_authority_bridge.py lines 1–265

Check Line Lengths

A Python command-line tool in the scripts folder of Solar Electrical Topology Analysis Engine Text Based that works with active files (`active_files`). It is built from the violations step (`violations`).

ingestsolar-electrical-topology-analysis-engine-text-based / scripts/check_line_lengths.py · lines 1–70 of 70 · Entry point

What it does
It loads data. Defines active_files, violations, main. Uses libraries __future__, pathlib, sys. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Fail when active topology source lines exceed the reviewable limit.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
solar-electrical-topology-analysis-engine-text-based · scripts · Python CLI
Uses
__future__, pathlib, sys
Used by
none found
Produces
active_files, violations, main
Defines here
active_files, violations, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 scripts/check_line_lengths.py:1-70 · blob 47671ead86b31605dda5ccce95b423dbd85f2c94 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Fail when active topology source lines exceed the reviewable limit."""

from __future__ import annotations

from pathlib import Path
import sys


LIMIT = 100
ROOT = Path(__file__).resolve().parents[1]
PATTERNS = (
    "src/solar_topology/**/*.py",
    "scripts/**/*.py",
    "tests/**/*.py",
    "tests/**/*.js",
    "v8-leapfrog/*.js",
    "v8-leapfrog/*.html",
    "v8-leapfrog/*.css",
    ".github/workflows/*.yml",
    ".github/workflows/*.yaml",
    "pyproject.toml",
)


def active_files() -> tuple[Path, ...]:
    files: set[Path] = set()
    for pattern in PATTERNS:
        files.update(
            path
            for path in ROOT.glob(pattern)
            if path.is_file()
        )
    return tuple(sorted(files))


def violations(path: Path) -> list[tuple[int, int]]:
    result = []
    for number, line in enumerate(
        path.read_text(encoding="utf-8").splitlines(),
        start=1,
    ):
        width = len(line.expandtabs(4))
        if width > LIMIT:
            result.append((number, width))
    return result


def main() -> int:
    failures: list[str] = []
    for path in active_files():
        for number, width in violations(path):
            relative = path.relative_to(ROOT).as_posix()
            failures.append(f"{relative}:{number}: {width} > {LIMIT}")

    if failures:
        print("Line-length failures:")
        for failure in failures:
            print(f"  {failure}")
        return 1

    print(
        f"Line-length check passed for {len(active_files())} active files "
        f"at <= {LIMIT} characters."
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Check Microbuild Plan

A Python command-line tool in the scripts folder of Solar Electrical Topology Analysis Engine Text Based that validates evidence (`validate_evidence`), using SHA-256. It loads plan (`load_plan`) and validates plan (`validate_plan`).

ingestsolar-electrical-topology-analysis-engine-text-based / scripts/check_microbuild_plan.py · lines 1–225 of 225 · Entry point · pattern require (shared by 53 files)

What it does
It loads data. Defines 6 functions or classes, including PlanValidationError, require, load_plan, validate_evidence, validate_plan. Uses libraries __future__, argparse, json, pathlib, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file microbuild-plan.json; command-line arguments.
Downstream impact
Used directly by 10 files: Advance Microbuild (solar-electrical-topology-analysis-engine-text-based); Microbuild Evidence (solar-electrical-topology-analysis-engine-text-based); Run Microbuild (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Advancement (solar-electrical-topology-analysis-engine-text-based); and 6 more. Reached from 1 other entry point, including Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Validate the ordered twenty-step microbuild programme. It accepts `--path` and `--check`.
Why it matters
Imported by Advance Microbuild, Microbuild Evidence and Run Microbuild. Run by Microbuild Worker Workflow. Checked by 6 tests, including Test Microbuild Advancement.
Application
solar-electrical-topology-analysis-engine-text-based · scripts · Python CLI
Uses
__future__, argparse, json, pathlib, re, typing
Used by
imported by Advance Microbuild (import), imported by Microbuild Evidence (import), imported by Run Microbuild (import), imported by Test Microbuild Advancement (import), imported by Test Microbuild Evidence (import), imported by Test Microbuild Plan (import), imported by Test Microbuild Runner (import), run by Test Microbuild Workflow (script call), and 2 more
Produces
PlanValidationError, require, load_plan, validate_evidence, validate_plan, main
Defines here
PlanValidationError, require, load_plan, validate_evidence, validate_plan, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 scripts/check_microbuild_plan.py:1-225 · blob 050d11a0bb9b5bb760aa857e6adc6a88b0a0ece0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Validate the ordered twenty-step microbuild programme."""

from __future__ import annotations

import argparse
import json
from pathlib import Path
import re
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_PLAN_PATH = ROOT / "microbuild-plan.json"
SCHEMA_VERSION = "globalgrid2050.solar-dc.microbuild-plan.v1"
PROGRAMME_ID = "twenty-step-autopilot-20260801"
ALLOWED_STATES = {"planned", "active", "passed", "blocked"}
CURRENT_STATES = {"active", "blocked"}
STEP_ID = re.compile(r"^MB-(0[1-9]|1[0-9]|20)$")
TEST_ID = re.compile(r"^[a-z][a-z0-9_]*$")
SHA40 = re.compile(r"^[0-9a-f]{40}$")
SHA256 = re.compile(r"^sha256:[0-9a-f]{64}$")
EVIDENCE_FIELDS = {
    "step_id",
    "manifest_revision",
    "tested_commit",
    "test_id",
    "result",
    "workflow_run_id",
    "artifact_id",
    "evidence_hash",
}


class PlanValidationError(ValueError):
    """The machine-readable programme violates its sequencing contract."""


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


def load_plan(path: Path = DEFAULT_PLAN_PATH) -> dict[str, Any]:
    payload = json.loads(path.read_text(encoding="utf-8"))
    require(isinstance(payload, dict), "microbuild plan must contain one JSON object")
    return payload


def validate_evidence(
    evidence: object,
    *,
    step_id: str,
    test_id: str,
    manifest_revision: int,
) -> None:
    require(isinstance(evidence, dict), f"{step_id} passed evidence must be an object")
    assert isinstance(evidence, dict)
    require(set(evidence) == EVIDENCE_FIELDS, f"{step_id} evidence fields changed")
    require(evidence["step_id"] == step_id, f"{step_id} evidence step mismatch")
    require(evidence["test_id"] == test_id, f"{step_id} evidence test mismatch")
    require(evidence["result"] == "pass", f"{step_id} evidence must record pass")
    require(
        isinstance(evidence["manifest_revision"], int)
        and 1 <= evidence["manifest_revision"] <= manifest_revision,
        f"{step_id} evidence manifest revision is invalid",
    )
    require(
        isinstance(evidence["tested_commit"], str)
        and SHA40.fullmatch(evidence["tested_commit"]) is not None,
        f"{step_id} tested commit is invalid",
    )
    for field in ("workflow_run_id", "artifact_id"):
        require(
            isinstance(evidence[field], int) and evidence[field] > 0,
            f"{step_id} evidence {field} must be positive",
        )
    require(
        isinstance(evidence["evidence_hash"], str)
        and SHA256.fullmatch(evidence["evidence_hash"]) is not None,
        f"{step_id} evidence hash is invalid",
    )


def validate_plan(plan: dict[str, Any], *, root: Path = ROOT) -> dict[str, object]:
    required_top = {
        "schema_version",
        "programme_id",
        "manifest_revision",
        "quantum_spawn",
        "restore_point",
        "active_step",
        "next_step",
        "steps",
    }
    require(set(plan) == required_top, "microbuild plan top-level fields changed")
    require(plan["schema_version"] == SCHEMA_VERSION, "wrong microbuild schema version")
    require(plan["programme_id"] == PROGRAMME_ID, "wrong microbuild programme id")
    require(
        isinstance(plan["manifest_revision"], int) and plan["manifest_revision"] > 0,
        "manifest revision must be a positive integer",
    )
    require(
        isinstance(plan["quantum_spawn"], str)
        and (root / plan["quantum_spawn"]).is_file(),
        "Quantum Spawn path does not exist",
    )
    require(
        isinstance(plan["restore_point"], str) and bool(plan["restore_point"].strip()),
        "restore point must be present",
    )

    steps = plan["steps"]
    require(isinstance(steps, list), "steps must be a list")
    require(len(steps) == 20, "microbuild plan must contain exactly twenty steps")

    expected_ids = [f"MB-{ordinal:02d}" for ordinal in range(1, 21)]
    current_indexes: list[int] = []
    test_ids: list[str] = []
    passed_count = 0

    for index, raw_step in enumerate(steps):
        require(isinstance(raw_step, dict), f"step {index + 1} must be an object")
        step = raw_step
        required_step = {
            "id",
            "ordinal",
            "phase",
            "title",
            "status",
            "test_id",
            "evidence",
        }
        require(set(step) == required_step, f"{expected_ids[index]} fields changed")
        require(step["id"] == expected_ids[index], f"step id order failed at {index + 1}")
        require(STEP_ID.fullmatch(step["id"]) is not None, f"invalid step id {step['id']}")
        require(step["ordinal"] == index + 1, f"{step['id']} ordinal mismatch")
        require(step["phase"] == ("A" if index < 10 else "B"), f"{step['id']} phase mismatch")
        require(isinstance(step["title"], str) and bool(step["title"].strip()), f"{step['id']} title missing")
        require(step["status"] in ALLOWED_STATES, f"{step['id']} status invalid")
        require(
            isinstance(step["test_id"], str)
            and TEST_ID.fullmatch(step["test_id"]) is not None,
            f"{step['id']} test id invalid",
        )
        test_ids.append(step["test_id"])

        if step["status"] in CURRENT_STATES:
            current_indexes.append(index)
        if step["status"] == "passed":
            passed_count += 1
            validate_evidence(
                step["evidence"],
                step_id=step["id"],
                test_id=step["test_id"],
                manifest_revision=plan["manifest_revision"],
            )
        else:
            require(step["evidence"] is None, f"{step['id']} may not have evidence before pass")

    require(len(set(test_ids)) == 20, "every step must have one unique test id")
    require(len(current_indexes) <= 1, "at most one active or blocked step is permitted")

    if not current_indexes:
        require(passed_count == 20, "a programme without an active step must be fully passed")
        require(plan["active_step"] is None, "completed programme active_step must be null")
        require(plan["next_step"] is None, "completed programme next_step must be null")
        return {
            "pass": True,
            "programme_status": "completed",
            "programme_id": plan["programme_id"],
            "manifest_revision": plan["manifest_revision"],
            "active_step": None,
            "active_status": None,
            "active_test_id": None,
            "next_step": None,
            "passed_steps": 20,
            "planned_steps": 0,
            "total_steps": 20,
        }

    current_index = current_indexes[0]
    current = steps[current_index]
    require(plan["active_step"] == current["id"], "active_step pointer mismatch")

    for index, step in enumerate(steps):
        if index < current_index:
            require(step["status"] == "passed", f"{step['id']} before current step must be passed")
        elif index > current_index:
            require(step["status"] == "planned", f"{step['id']} after current step must be planned")

    expected_next = expected_ids[current_index + 1] if current_index < 19 else None
    require(plan["next_step"] == expected_next, "next_step pointer mismatch")
    require(passed_count == current_index, "passed-step count does not match current position")

    return {
        "pass": True,
        "programme_status": "active" if current["status"] == "active" else "blocked",
        "programme_id": plan["programme_id"],
        "manifest_revision": plan["manifest_revision"],
        "active_step": plan["active_step"],
        "active_status": current["status"],
        "active_test_id": current["test_id"],
        "next_step": plan["next_step"],
        "passed_steps": passed_count,
        "planned_steps": 19 - current_index,
        "total_steps": 20,
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--path", type=Path, default=DEFAULT_PLAN_PATH)
    parser.add_argument("--check", action="store_true")
    args = parser.parse_args()
    try:
        summary = validate_plan(load_plan(args.path))
    except (OSError, json.JSONDecodeError, PlanValidationError) as exc:
        raise SystemExit(f"microbuild plan invalid: {exc}") from exc
    print(json.dumps(summary, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Local Authority Bridge

A Python command-line tool in the scripts folder of Solar Electrical Topology Analysis Engine Text Based that makes handler, creates server and builds parser, covering reference inverter block.

othersolar-electrical-topology-analysis-engine-text-based / scripts/local_authority_bridge.py · lines 1–265 of 265 · Entry point · pattern build_parser (shared by 5 files)

What it does
Defines 14 functions or classes, including authority_response_bytes, _json_bytes, _content_type, make_handler, AuthorityBridgeHandler. Uses libraries __future__, argparse, http, http.server, json. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file reference-inverter-block.json; command-line arguments.
Downstream impact
Used directly by 3 files: Run Authority Slice (solar-electrical-topology-analysis-engine-text-based); Test End to End Authority Slice (solar-electrical-topology-analysis-engine-text-based); Test Local Authority Bridge (solar-electrical-topology-analysis-engine-text-based). Reached from 6 other entry points, including Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based); Microbuild Worker Workflow (solar-electrical-topology-analysis-engine-text-based); Run Microbuild (solar-electrical-topology-analysis-engine-text-based).
What it achieves
It makes handler (`make_handler`), creates server (`create_server`) and builds parser (`build_parser`). Serve the Python-owned authority response and existing Studio locally. It accepts `--host`, `--port` and `--strategy`.
Why it matters
Imported by Run Authority Slice. Checked by 2 tests, including Test End to End Authority Slice.
Application
solar-electrical-topology-analysis-engine-text-based · scripts · Python CLI
Uses
Build Authority Bundle (import), __future__, argparse, http, http.server, json, mimetypes, pathlib, typing
Used by
imported by Run Authority Slice (import), imported by Test End to End Authority Slice (import), imported by Test Local Authority Bridge (import)
Produces
authority_response_bytes, make_handler, create_server, build_parser, main
Defines here
authority_response_bytes, _json_bytes, _content_type, make_handler, AuthorityBridgeHandler, log_message, do_HEAD, do_GET, _send, _redirect, _handle, create_server, build_parser, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 scripts/local_authority_bridge.py:1-265 · blob 0a1dcfdcaba5b1bf00268cdefcab3149cc5ecdd5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Serve the Python-owned authority response and existing Studio locally."""

from __future__ import annotations

import argparse
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import mimetypes
from pathlib import Path
from typing import Final
from urllib.parse import urlsplit

try:
    from scripts.build_authority_bundle import authority_response_json
except ModuleNotFoundError:  # Direct execution from the scripts directory.
    from build_authority_bundle import authority_response_json


ROOT: Final = Path(__file__).resolve().parents[1]
LOCAL_AUTHORITY_BRIDGE_VERSION: Final = (
    "globalgrid2050.solar-dc.local-authority-bridge.v1"
)
DEFAULT_HOST: Final = "127.0.0.1"
DEFAULT_PORT: Final = 8765
HEALTH_ROUTE: Final = "/health"
STUDIO_ROUTE: Final = "/v10-development/authority/index.html"
AUTHORITY_BUNDLE_ROUTE: Final = (
    "/authority-bundles/reference-inverter-block.json"
)

STATIC_ROUTES: Final[dict[str, Path]] = {
    STUDIO_ROUTE: ROOT / "v10-development" / "authority" / "index.html",
    "/v10-development/authority/authority-view.js": (
        ROOT / "v10-development" / "authority" / "authority-view.js"
    ),
    "/v10-development/authority/authority-evidence.js": (
        ROOT / "v10-development" / "authority" / "authority-evidence.js"
    ),
    "/v10-development/topology-studio.html": (
        ROOT / "v10-development" / "topology-studio.html"
    ),
}


def authority_response_bytes(strategy: str = "leapfrog") -> bytes:
    """Return the exact newline-terminated response served by the bridge."""

    return (authority_response_json(strategy) + "\n").encode("utf-8")


def _json_bytes(payload: object) -> bytes:
    return (
        json.dumps(payload, sort_keys=True, separators=(",", ":")) + "\n"
    ).encode("utf-8")


def _content_type(path: Path) -> str:
    guessed, _ = mimetypes.guess_type(path.name)
    if guessed is None:
        return "application/octet-stream"
    if guessed.startswith("text/") or guessed in {
        "application/javascript",
        "application/json",
    }:
        return f"{guessed}; charset=utf-8"
    return guessed


def make_handler(
    *,
    strategy: str = "leapfrog",
    root: Path = ROOT,
) -> type[BaseHTTPRequestHandler]:
    """Create a request handler bound to one strategy and repository root."""

    static_routes = {
        route: root / path.relative_to(ROOT)
        for route, path in STATIC_ROUTES.items()
    }

    class AuthorityBridgeHandler(BaseHTTPRequestHandler):
        server_version = "GlobalGrid2050AuthorityBridge/1"

        def log_message(self, format: str, *args: object) -> None:
            return

        def do_HEAD(self) -> None:  # noqa: N802 - required HTTP handler name
            self._handle(send_body=False)

        def do_GET(self) -> None:  # noqa: N802 - required HTTP handler name
            self._handle(send_body=True)

        def _send(
            self,
            status: HTTPStatus,
            body: bytes,
            *,
            content_type: str,
            send_body: bool,
            extra_headers: dict[str, str] | None = None,
        ) -> None:
            self.send_response(status)
            self.send_header("Content-Type", content_type)
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Cache-Control", "no-store")
            self.send_header("X-Content-Type-Options", "nosniff")
            self.send_header("Access-Control-Allow-Origin", "*")
            for name, value in (extra_headers or {}).items():
                self.send_header(name, value)
            self.end_headers()
            if send_body:
                self.wfile.write(body)

        def _redirect(self, location: str, *, send_body: bool) -> None:
            body = _json_bytes({"location": location})
            self._send(
                HTTPStatus.FOUND,
                body,
                content_type="application/json; charset=utf-8",
                send_body=send_body,
                extra_headers={"Location": location},
            )

        def _handle(self, *, send_body: bool) -> None:
            route = urlsplit(self.path).path

            if route in {"/", "/v10-development/authority/"}:
                self._redirect(STUDIO_ROUTE, send_body=send_body)
                return

            if route == HEALTH_ROUTE:
                body = _json_bytes(
                    {
                        "bridge_version": LOCAL_AUTHORITY_BRIDGE_VERSION,
                        "strategy": strategy,
                        "studio_route": STUDIO_ROUTE,
                        "authority_bundle_route": AUTHORITY_BUNDLE_ROUTE,
                        "status": "ready",
                    }
                )
                self._send(
                    HTTPStatus.OK,
                    body,
                    content_type="application/json; charset=utf-8",
                    send_body=send_body,
                )
                return

            if route == AUTHORITY_BUNDLE_ROUTE:
                body = authority_response_bytes(strategy)
                payload = json.loads(body)
                self._send(
                    HTTPStatus.OK,
                    body,
                    content_type="application/json; charset=utf-8",
                    send_body=send_body,
                    extra_headers={
                        "X-Authority-Response-Hash": str(payload["response_hash"]),
                        "X-Authority-Strategy": strategy,
                    },
                )
                return

            static_path = static_routes.get(route)
            if static_path is not None and static_path.is_file():
                body = static_path.read_bytes()
                self._send(
                    HTTPStatus.OK,
                    body,
                    content_type=_content_type(static_path),
                    send_body=send_body,
                )
                return

            body = _json_bytes({"error": "not_found", "path": route})
            self._send(
                HTTPStatus.NOT_FOUND,
                body,
                content_type="application/json; charset=utf-8",
                send_body=send_body,
            )

    return AuthorityBridgeHandler


def create_server(
    *,
    host: str = DEFAULT_HOST,
    port: int = DEFAULT_PORT,
    strategy: str = "leapfrog",
    root: Path = ROOT,
) -> ThreadingHTTPServer:
    """Create, but do not start, a local authority bridge server."""

    if strategy not in {"leapfrog", "sequential"}:
        raise ValueError(f"unsupported authority strategy: {strategy}")
    if not 0 <= port <= 65535:
        raise ValueError("port must be between 0 and 65535")
    return ThreadingHTTPServer(
        (host, port),
        make_handler(strategy=strategy, root=root),
    )


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Serve the authoritative reference inverter block locally.",
    )
    parser.add_argument("--host", default=DEFAULT_HOST)
    parser.add_argument("--port", type=int, default=DEFAULT_PORT)
    parser.add_argument(
        "--strategy",
        choices=("leapfrog", "sequential"),
        default="leapfrog",
    )
    parser.add_argument(
        "--once",
        action="store_true",
        help="Handle one request and exit.",
    )
    parser.add_argument(
        "--version",
        action="version",
        version=LOCAL_AUTHORITY_BRIDGE_VERSION,
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    server = create_server(
        host=args.host,
        port=args.port,
        strategy=args.strategy,
    )
    try:
        host, port = server.server_address[:2]
        print(
            json.dumps(
                {
                    "bridge_version": LOCAL_AUTHORITY_BRIDGE_VERSION,
                    "host": host,
                    "port": port,
                    "strategy": args.strategy,
                    "studio_url": f"http://{host}:{port}{STUDIO_ROUTE}",
                },
                sort_keys=True,
            ),
            flush=True,
        )
        if args.once:
            server.handle_request()
        else:
            server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())