GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / tools/intelligence/cartridges/hops-are-not-kilometres

Sector Intelligence and 2 more files

A JavaScript module in the assets folder of PipelineNews that validates asset (`validateAsset`), decodes payload (`decodePayload`) and loads payload (`loadPayload`), using SHA-256.

592 lines of Python and JavaScript from pipelinenews, in 3 files. Topic: Electricity markets and data pipelines. Section 1042 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. Make Cartridge ingest · pipelinenews / tools/intelligence/cartridges/hops-are-not-kilometres/make_cartridge.py lines 1–155
  2. Make Cartridge ingest · pipelinenews / tools/intelligence/cartridges/mapped-is-not-nearest/make_cartridge.py lines 1–161
  3. Sector Intelligence render · pipelinenews / tools/intelligence/cartridges/news-and-sector-clean/assets/{GEN}-sector-intelligence.mjs lines 1–276

Make Cartridge

A Python command-line tool in the hops are not kilometres folder of PipelineNews covering GB transmission network and substations.

ingestpipelinenews / tools/intelligence/cartridges/hops-are-not-kilometres/make_cartridge.py · lines 1–155 of 155 · Entry point · pattern anchor (shared by 16 files)

What it does
Defines read, anchor, main. Uses libraries argparse, io, json, os.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: substations.
Inputs & outputs
In: JSON file gb-transmission-network.v1.json; JSON file cartridge.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the read step (`read`) and the anchor step (`anchor`). Generate `cartridge.json`: a kilometre is not a connection. It accepts `--parent`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · tools/intelligence/cartridges/hops-are-not-kilometres · Python CLI
Uses
argparse, io, json, os
Used by
none found
Produces
read, anchor, main
Defines here
read, anchor, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/hops-are-not-kilometres/make_cartridge.py:1-155 · blob 57712a7287099ce996b9e69db087a2b565abe992 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Generate cartridge.json: a kilometre is not a connection.

The grid proximity panel's CONNECT view is headed AUTO-DRAWN CONNECTIONS and
explains, correctly, what its two lines per project are: the site to the
nearest point on the nearest circuit, and the site to the nearest mapped
substation, measured as straight lines. Every caveat it carries is right and
stays. But the view is called CONNECTIONS, its lines have a length in
kilometres, and nothing on it says that the kilometre is a different
quantity from the thing that decides whether two sites are joined at all.

On 1 September 2026 the Atlas gained electrical distance measured in
published circuits: for a declared site, how many circuits away each
neighbouring site is, on the network NESO publishes. That is not a shorter
kilometre; it is a different question. Two sites a few kilometres apart can
share no circuit. The two ends of one circuit can be a long way apart: read
on 2 September 2026 from Ventusltd/data-grid-gb
derived/gb-transmission-network.v1.json, the longest circuit NESO publishes
is PEMB41 to WALH41 at 223.195 km of route (ohl_km + cable_km), and 17 of
the 1,392 circuits publish more than 100 km of route. Those are the
published route lengths, not straight lines between the ends, and they are
the only lengths this docstring cites.

So the CONNECT caption gains one clause: a kilometre is not a connection,
and MAP is where the count of published circuits is reported. The panel
keeps reporting exactly what it reported - straight-line kilometres - and
keeps every word it already said about them.

Nothing here grades a distance and nothing here claims capacity, headroom or
availability; a circuit count says whether sites are joined on the published
network, not what could flow between them.

This cartridge changes one string in one file. It adds no payload, makes no
network call at render time, and touches no other surface.

    python tools/intelligence/cartridges/hops-are-not-kilometres/make_cartridge.py \
        --parent 202608312339-pipelinenews
"""

import argparse
import io
import json
import os

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
RELEASES = os.path.join(REPO, "releases")
PROX = "assets/202608311610-grid-proximity.mjs"


def read(path):
    return io.open(path, encoding="utf-8", newline="").read()


def anchor(text, needle, label):
    """A repair is an exact substitution, so the anchor must be unique.

    Asserting the count here rather than at build time means a parent whose
    text has moved fails while the cartridge is being written, with a name
    attached, instead of failing inside the builder with a diff.
    """
    n = text.count(needle)
    if n != 1:
        raise SystemExit("anchor %r occurs %d times, expected 1" % (label, n))
    return needle


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--parent", default="202608312339-pipelinenews")
    args = ap.parse_args()

    parent = os.path.join(RELEASES, args.parent)
    if not os.path.isdir(parent):
        raise SystemExit("no such release: %s" % parent)
    prox = read(os.path.join(parent, PROX))

    # The last sentence the CONNECT caption writes in its own words before it
    # hands over to the payload's substation caveat. Plain text inside a
    # template literal, no escapes.
    perpendicular = ("The circuit point is a true perpendicular onto the line, "
                     "not the nearest drawn vertex.")
    anchor(prox, perpendicular, "the CONNECT caption's perpendicular sentence")

    added = ("\n        A kilometre is not a connection: two sites a few kilometres "
             "apart can share no published circuit, and the two ends of one "
             "published circuit can be over 200 km of route apart. This panel "
             "reports straight-line kilometres only; MAP reports the count of "
             "published circuits between the declared site and its neighbours.")

    cartridge = {
        "key": "hops_are_not_kilometres",
        "summary": (
            "The grid proximity panel's CONNECT caption says that a kilometre "
            "is not a connection and that MAP reports the count of published "
            "circuits between sites. Every existing caveat is kept."
        ),
        "modifies_existing_dashboard": True,
        "modification_note": "Extends one caption in the grid proximity module. No payload, no render-time network call.",
        "repairs": {
            "assets": [
                {
                    "path": PROX,
                    "edits": [
                        {
                            "label": "the CONNECT caption separates kilometres from circuits, without dropping a caveat",
                            "from": perpendicular,
                            "to": perpendicular + added,
                        }
                    ],
                }
            ]
        },
        "registry_entry": {
            "schema": "pipelinenews.hops-are-not-kilometres.v1",
            "generation": "{GEN}",
            "usage_context": "NON_COMMERCIAL_OPEN_SOURCE",
            "usage_context_establishes_upstream_rights": False,
            "activation": "render-time; no payload",
            "additive_only": False,
            "mutates_existing_dashboard": "extends the grid proximity CONNECT caption",
            "network_at_runtime": False,
            "rule": (
                "A straight-line kilometre and a count of published circuits "
                "are different quantities and neither is a cable route, a "
                "connection length, a grade or headroom. The panel reports "
                "the kilometre and says so; the circuit count is reported "
                "where it is measured, in MAP. The only length cited is a "
                "published route length: the longest circuit in NESO's "
                "Appendix B is 223.195 km of route."
            ),
            "found_by": (
                "Reading the CONNECT view after the Atlas gained circuit-count "
                "distance on 1 September 2026. The view is titled "
                "AUTO-DRAWN CONNECTIONS, draws lines with lengths, and "
                "nowhere said that length in kilometres is not the quantity "
                "that decides whether two sites are joined. The route "
                "lengths were read from circuits[].ohl_km and cable_km in "
                "Ventusltd/data-grid-gb derived/gb-transmission-network.v1.json "
                "on 2 September 2026."
            ),
            "upstream": (
                "NESO Electricity Ten Year Statement 2025, Appendix B, via "
                "Ventusltd/data-grid-gb derived/gb-transmission-network.v1.json"
            ),
        },
    }

    out = os.path.join(HERE, "cartridge.json")
    io.open(out, "w", encoding="utf-8", newline="\n").write(
        json.dumps(cartridge, indent=2, ensure_ascii=False) + "\n")
    print("wrote %s (parent %s)" % (out, args.parent))


if __name__ == "__main__":
    main()

Make Cartridge

A Python command-line tool in the mapped is not nearest folder of PipelineNews covering substations, 33kV and 132kV.

ingestpipelinenews / tools/intelligence/cartridges/mapped-is-not-nearest/make_cartridge.py · lines 1–161 of 161 · Entry point · pattern anchor (shared by 16 files)

What it does
Defines read, anchor, main. Uses libraries argparse, io, json, os.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: substations, 33kV, 132kV.
Inputs & outputs
In: JSON file cartridge.json; command-line arguments. Voltage levels named: 132kV, 33kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the read step (`read`) and the anchor step (`anchor`). Generate `cartridge.json`: the nearest mapped substation is not the nearest substation. Its code works with 132 kV and 33 kV. It accepts `--parent`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · tools/intelligence/cartridges/mapped-is-not-nearest · Python CLI
Uses
argparse, io, json, os
Used by
none found
Produces
read, anchor, main
Defines here
read, anchor, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/mapped-is-not-nearest/make_cartridge.py:1-161 · blob 47e451f5b750c4f7b8d073b692b9915de441e462 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Generate cartridge.json: the nearest mapped substation is not the nearest substation.

The GRID + SUB strip says what it measures:

    straight-line km to the nearest mapped circuit and to the nearest
    substation at 33 kV or above

"Mapped" is doing quiet work in that sentence. The SUB figure is the distance
to the nearest point in a layer, and the layer is known to be incomplete. The
product that publishes the layer's transmission end says so itself. In
Ventusltd/data-grid-gb derived/connection-points.v3.json, read on
2 September 2026:

    counts.connection_points   886
    counts.with_location       502
    join.unlocated             384
    join.unlocated_are_published
        "a site nobody has mapped is published without coordinates rather
         than dropped"
    join.why
        "ETYS names substations and does not locate them"

So of the 886 transmission substations NESO names at 132 kV and above, the
Atlas can place 502 on the map and 384 have no coordinates at all. A project
whose true nearest substation is one of the 384 will be shown a distance to
some other, mapped, substation - a larger number than the truth, presented
with two decimal places.

The strip already carries, on hover, "Absence from a mapped layer is not
absence on the ground" (payload.caveat.coverage, from
data/202608311800-grid-distance.json in the parent release). That is the
principle; it has never been given its size. This cartridge adds the size,
with the product's own numbers, in the sentence the reader actually sees,
and keeps every existing word of the strip.

Nothing here grades a distance. Nothing here claims capacity or headroom. The
numbers are the ones published in the file named above and no others.

This cartridge changes one string in one file. It adds no payload, makes no
network call at render time, and touches no other surface.

    python tools/intelligence/cartridges/mapped-is-not-nearest/make_cartridge.py \
        --parent 202608312339-pipelinenews
"""

import argparse
import io
import json
import os

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
RELEASES = os.path.join(REPO, "releases")
APP = "assets/202608291447-app.mjs"


def read(path):
    return io.open(path, encoding="utf-8", newline="").read()


def anchor(text, needle, label):
    """A repair is an exact substitution, so the anchor must be unique.

    Asserting the count here rather than at build time means a parent whose
    text has moved fails while the cartridge is being written, with a name
    attached, instead of failing inside the builder with a diff.
    """
    n = text.count(needle)
    if n != 1:
        raise SystemExit("anchor %r occurs %d times, expected 1" % (label, n))
    return needle


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--parent", default="202608312339-pipelinenews")
    args = ap.parse_args()

    parent = os.path.join(RELEASES, args.parent)
    if not os.path.isdir(parent):
        raise SystemExit("no such release: %s" % parent)
    app = read(os.path.join(parent, APP))

    # The literal source bytes, including the · escape as it is written
    # in the file rather than the middle dot it denotes. This clause sits in
    # the middle of the strip, so the cartridges that extend its tail (the
    # refusal) and its count (the "within 2 km" clause) anchor elsewhere and
    # can be applied in any order with this one.
    scope = "to the nearest substation at 33 kV or above \\u00b7 "
    anchor(app, scope, "the GRID + SUB strip's statement of what it measures")

    added = ("nearest mapped is not nearest: of the 886 transmission "
             "substations NESO names at 132 kV and above, the Atlas locates "
             "502 and publishes the other 384 without coordinates rather "
             "than dropping them, so the nearest mapped substation may not "
             "be the nearest substation \\u00b7 ")

    cartridge = {
        "key": "mapped_is_not_nearest",
        "summary": (
            "The GRID + SUB strip states the size of the gap in the mapped "
            "layer: 886 transmission substations named by NESO, 502 located, "
            "384 published without coordinates. The nearest mapped "
            "substation may not be the nearest substation."
        ),
        "modifies_existing_dashboard": True,
        "modification_note": "Extends one strip caption. No payload, no render-time network call.",
        "repairs": {
            "app": [
                {
                    "label": "the strip gives the coverage limit its size, without dropping a caveat",
                    "from": scope,
                    "to": scope + added,
                }
            ]
        },
        "registry_entry": {
            "schema": "pipelinenews.mapped-is-not-nearest.v1",
            "generation": "{GEN}",
            "usage_context": "NON_COMMERCIAL_OPEN_SOURCE",
            "usage_context_establishes_upstream_rights": False,
            "activation": "render-time; no payload",
            "additive_only": False,
            "mutates_existing_dashboard": "extends the GRID + SUB strip caption",
            "network_at_runtime": False,
            "rule": (
                "A distance to the nearest mapped feature is a distance to a "
                "layer, not to the network. Where the layer's own publisher "
                "states its coverage, the strip states it too, in the "
                "publisher's numbers: 886 named, 502 located, 384 without "
                "coordinates. Absence from a mapped layer is not absence on "
                "the ground, and the existing caveats stay verbatim. No "
                "grade, no headroom, no capacity is implied."
            ),
            "found_by": (
                "Reading counts and join in Ventusltd/data-grid-gb "
                "derived/connection-points.v3.json on 2 September 2026 "
                "beside the strip in the parent release. The strip said "
                "'nearest mapped' and the hover said 'absence from a mapped "
                "layer is not absence on the ground'; neither said how much "
                "of the transmission network the layer fails to place, and "
                "the publisher had already counted it."
            ),
            "upstream": (
                "NESO Electricity Ten Year Statement 2025, Appendix B, joined "
                "to OpenStreetMap-derived substation geometry via "
                "Ventusltd/data-grid-gb derived/connection-points.v3.json "
                "(counts.connection_points 886, counts.with_location 502, "
                "join.unlocated 384)"
            ),
        },
    }

    out = os.path.join(HERE, "cartridge.json")
    io.open(out, "w", encoding="utf-8", newline="\n").write(
        json.dumps(cartridge, indent=2, ensure_ascii=False) + "\n")
    print("wrote %s (parent %s)" % (out, args.parent))


if __name__ == "__main__":
    main()

Sector Intelligence

A JavaScript module in the assets folder of PipelineNews that validates asset (`validateAsset`), decodes payload (`decodePayload`) and loads payload (`loadPayload`), using SHA-256.

Set aside from the main view: 97% of its lines are the same as pipelinenews_intelligence/202608312244/assets/202608312109-sector-intelligence.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Sector Intelligence; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9693 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 pipelinenews_intelligence/202608312244/assets/202608312109-sector-intelligence.mjs:1-275 2a730933cb5f29a0fb65015fb6438ccd8ecaf309
  • sha256 a51dd792a15d71ec15b35cbc995110df04aa67d235aab3182580baac65787961
  • target sha256 19ba45f057bfedca5f6bffea0ea4435a1b7aa7219d485dd80319a8f80c9349d7
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderpipelinenews / tools/intelligence/cartridges/news-and-sector-clean/assets/{GEN}-sector-intelligence.mjs · lines 1–276 of 276 · Not reached from any entry point (candidate for review) · pattern topicIsShown (shared by 2 files)

What it does
It draws its content. Defines 10 functions or classes, including topicIsShown, element, installStyles, sha256Hex, validateAsset. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: DuckDB queries.
What it achieves
It validates asset (`validateAsset`), decodes payload (`decodePayload`) and loads payload (`loadPayload`). The module is a new cartridge over an older immutable payload. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence/cartridges/news-and-sector-clean/assets · JavaScript module
Uses
none found
Used by
none found
Produces
SECTOR_INTELLIGENCE_CARTRIDGE_CONTRACT, mountSectorIntelligence
Defines here
topicIsShown, element, installStyles, sha256Hex, validateAsset, decodePayload, loadPayload, renderRows, mountSectorIntelligence, select
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/news-and-sector-clean/assets/{GEN}-sector-intelligence.mjs:1-276 · blob a1f37a28e7162785d670df4afde578f98ecf6e94 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// The module is a new cartridge over an older immutable payload. Keep those
// identities separate: the registry attests this module's build generation,
// while PAYLOAD_GENERATION attests the frozen data it reads.
const GENERATION = "{GEN}";
const PAYLOAD_GENERATION = "202608272130";
const PAYLOAD_SCHEMA = "pipelinenews.sector-intelligence-browser.v3";
const USAGE_CONTEXT = "NON_COMMERCIAL_OPEN_SOURCE";
const TOPICS = Object.freeze([
  Object.freeze({ code: "DATA_CENTRES", label: "DATA CENTRES", rank: 1 }),
  Object.freeze({ code: "INVERTER_SECURITY_POLICY", label: "INVERTERS · SECURITY", rank: 2 }),
  Object.freeze({ code: "ENERGY_SECURITY_HORMUZ", label: "STRAIT OF HORMUZ", rank: 3 }),
  Object.freeze({ code: "ENERGY_SECURITY_UKRAINE", label: "UKRAINE", rank: 4 }),
  Object.freeze({ code: "GREAT_GRID_UPGRADE", label: "GREAT GRID UPGRADE", rank: 5 }),
  Object.freeze({ code: "WORLDWIDE_PV", label: "WORLDWIDE PV", rank: 6 }),
  Object.freeze({ code: "MV_HV_COMPONENTS", label: "MV/HV COMPONENTS", rank: 7 }),
]);
// Which topics may be shown.
//
// The collector was asked for seven subjects and returned a generic GOV.UK feed
// for six of them. Counted on the shipped payload, 51 items:
//
//   DATA_CENTRES              9 of 9 on topic
//   GREAT_GRID_UPGRADE        1 of 6   (five are retail sales, waste sites, FOI)
//   INVERTER_SECURITY_POLICY  2 of 12  (a cleared fly-tip, firing times, Syria)
//   MV_HV_COMPONENTS          0 of 6
//   WORLDWIDE_PV              0 of 6
//   ENERGY_SECURITY_HORMUZ    0 of 6
//   ENERGY_SECURITY_UKRAINE   0 of 6
//
// "Biometrics and Surveillance Camera Commissioner FOI responses 2026" and
// "The economic benefits of touring and impact of EU exit" each appear under
// FIVE different topics, which is the collector falling back to the same feed
// every time it found nothing.
//
// That is not a filter problem. Six of these topics have no intelligence in
// them, and an item-level filter would leave six near-empty sections still
// claiming to cover a subject. Only the topic that works is shown, and the page
// says the others are withheld and why. The rows stay in the payload so the
// collector can be fixed and the topics restored without another release here.
//
// The two geopolitical topics would not return even if they were populated.
// This page is for engineering and business; a named flashpoint is neither, it
// dates badly, and it carries a keyword profile that has nothing to do with
// whether a substation has headroom.
const SHOWN_TOPICS = Object.freeze(new Set(["DATA_CENTRES"]));
const NEVER_SHOWN_TOPICS = Object.freeze(new Set([
  "ENERGY_SECURITY_HORMUZ",
  "ENERGY_SECURITY_UKRAINE",
]));

function topicIsShown(code) {
  return SHOWN_TOPICS.has(code) && !NEVER_SHOWN_TOPICS.has(code);
}

const EXPECTED_FIELDS = Object.freeze([
  "topic_code", "topic_display_rank", "intelligence_item_id", "item_kind", "title", "summary", "canonical_url",
  "source_published_at", "observed_at", "staleness_state", "status", "evidence_class", "source_id",
  "source_licence_id", "source_terms_url", "redistribution_rights", "attribution", "owner_repository",
  "owner_generation", "owner_record_id", "generic_article_id", "value_min", "value_max", "unit", "binding_label",
  "project_binding_count", "eligible_for_news_signal",
]);
const FORBIDDEN_FIELDS = Object.freeze([
  "repd_ref", "gg_project_id", "project", "technology", "capacity_mw", "operator", "county", "related_context_repd_ref",
]);

export const SECTOR_INTELLIGENCE_CARTRIDGE_CONTRACT = Object.freeze({
  schema: "pipelinenews.sector-intelligence-cartridge.v3",
  generation: GENERATION,
  usage_context: USAGE_CONTEXT,
  usage_context_establishes_upstream_rights: false,
  activation: "dynamic-import-on-user-open; payload-fetch-on-first-topic-selection",
  topics: TOPICS,
  payload_schema: PAYLOAD_SCHEMA,
  startup_module_requests: 0,
  startup_payload_requests: 0,
  maximum_payload_requests: 1,
  maximum_rows_per_topic: 24,
  generic_news_rows_mutated: false,
  project_bindings: 0,
  eligible_for_news_signal: false,
  atman_runtime_dependency: false,
  deployment: "not-authorised",
});

const mounted = new WeakMap();

function element(tag, attributes = {}, text = null) {
  const node = document.createElement(tag);
  for (const [name, value] of Object.entries(attributes)) {
    if (name === "class") node.className = value;
    else node.setAttribute(name, String(value));
  }
  if (text !== null) node.textContent = String(text);
  return node;
}

function installStyles() {
  if (document.querySelector(`style[data-sector-generation="${GENERATION}"]`)) return;
  const style = document.createElement("style");
  style.dataset.sectorGeneration = GENERATION;
  style.textContent = `
    .sector-shell{border:1px solid #3e4650;background:#0d1117;color:#f0f4f8;margin:12px 0;padding:12px;min-width:0}
    .sector-head{display:flex;flex-wrap:wrap;gap:10px;justify-content:space-between;align-items:flex-start}
    .sector-head h2{color:#00ffff;font:700 17px/1.2 monospace;margin:0}
    .sector-head p{color:#b9c2cb;font:11px/1.45 monospace;margin:5px 0 0;max-width:900px}
    .sector-tabs{display:flex;gap:6px;overflow-x:auto;overscroll-behavior:contain;padding:12px 0}
    .sector-tabs button{background:#171d24;border:1px solid #65717c;color:#fff;cursor:pointer;flex:none;font:700 10px/1.2 monospace;min-height:44px;padding:8px 12px}
    .sector-tabs button[aria-selected="true"]{background:#00343b;border-color:#00ffff;color:#00ffff}
    .sector-list{display:grid;gap:8px;grid-template-columns:repeat(auto-fit,minmax(270px,1fr));min-width:0}
    .sector-card{background:#141a20;border:1px solid #343f49;min-width:0;padding:10px}
    .sector-card>a{align-items:center;color:#ffeb3b;display:inline-flex;font:700 12px/1.4 monospace;min-height:44px;overflow-wrap:anywhere;text-decoration:none}
    .sector-card>a:focus-visible,.sector-card>a:hover{text-decoration:underline}
    .sector-card p{color:#b8c0c8;font:10px/1.45 monospace;margin:6px 0;overflow-wrap:anywhere}
    .sector-card .sector-binding{border:1px solid #56616d;color:#00ff88;display:inline-block;font-weight:700;padding:4px 7px}
    .sector-message{border:1px dashed #52606d;color:#adb7c2;font:11px/1.45 monospace;padding:18px}
    @media (max-width:768px),((orientation:landscape) and (max-height:500px)){
      .sector-shell{padding:8px}.sector-list{grid-template-columns:1fr}.sector-card>a{min-height:44px}
    }
  `;
  document.head.appendChild(style);
}

async function sha256Hex(bytes) {
  const digest = await crypto.subtle.digest("SHA-256", bytes);
  return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
}

function validateAsset(asset) {
  if (!asset || typeof asset !== "object") throw new Error("sector payload asset is missing");
  if (!/^data\/202608272130-sector-intelligence\.json$/u.test(asset.url)) throw new Error("sector payload URL changed");
  if (!Number.isSafeInteger(asset.bytes) || asset.bytes <= 0) throw new Error("sector payload byte count is invalid");
  if (!/^[a-f0-9]{64}$/u.test(asset.sha256)) throw new Error("sector payload digest is invalid");
}

function decodePayload(payload) {
  if (payload.schema !== PAYLOAD_SCHEMA || payload.generation !== PAYLOAD_GENERATION) throw new Error("sector payload identity mismatch");
  if (payload.usage_context !== USAGE_CONTEXT || payload.usage_context_establishes_upstream_rights !== false) {
    throw new Error("sector usage/right separation mismatch");
  }
  if (payload.derived_only_from_landed_parquet_duckdb_readback !== true) throw new Error("sector payload lacks landed-Parquet lineage");
  if (payload.project_bindings !== 0 || payload.eligible_for_news_signal !== false || payload.generic_news_rows_mutated !== false) {
    throw new Error("sector payload crossed the generic-news or project-binding boundary");
  }
  if (JSON.stringify(payload.fields) !== JSON.stringify(EXPECTED_FIELDS)) throw new Error("sector payload field contract changed");
  for (const field of FORBIDDEN_FIELDS) if (payload.fields.includes(field)) throw new Error(`query identity field entered sector payload: ${field}`);
  if (!Array.isArray(payload.rows)) throw new Error("sector payload rows are missing");
  const rows = payload.rows.map((values) => {
    if (!Array.isArray(values) || values.length !== EXPECTED_FIELDS.length) throw new Error("sector payload row width changed");
    const row = Object.fromEntries(EXPECTED_FIELDS.map((field, index) => [field, values[index]]));
    if (!/^GG2050-SECTOR-ITEM-[A-F0-9]{20}$/u.test(row.intelligence_item_id)) throw new Error("sector item identity changed");
    if (row.project_binding_count !== 0 || row.eligible_for_news_signal !== false) throw new Error("sector item attempted a project signal");
    if (!TOPICS.some(({ code, rank }) => code === row.topic_code && rank === row.topic_display_rank)) throw new Error("sector topic changed");
    for (const field of ["source_licence_id", "source_terms_url", "redistribution_rights", "attribution"]) {
      if (!row[field]) throw new Error(`source-specific rights field is empty: ${field}`);
    }
    const expectedLabel = row.generic_article_id
      ? "SECTOR CONTEXT ONLY — QUERY PROJECT IDENTITY REMOVED"
      : "SECTOR CONTEXT ONLY — NOT A PROJECT BINDING";
    if (row.binding_label !== expectedLabel) throw new Error("sector context label changed");
    return Object.freeze(row);
  });
  if (new Set(rows.map(({ intelligence_item_id, topic_code }) => `${intelligence_item_id}\u001f${topic_code}`)).size !== rows.length) {
    throw new Error("sector browser key collision");
  }
  for (const topic of TOPICS.filter(({ code }) => topicIsShown(code))) {
    if (rows.filter(({ topic_code }) => topic_code === topic.code).length > payload.maximum_rows_per_topic) {
      throw new Error("sector browser topic row limit exceeded");
    }
  }
  return Object.freeze(rows);
}

async function loadPayload(asset) {
  validateAsset(asset);
  const response = await fetch(asset.url, { cache: "force-cache", credentials: "same-origin" });
  if (!response.ok) throw new Error(`sector payload request failed: ${response.status}`);
  const bytes = await response.arrayBuffer();
  if (bytes.byteLength !== asset.bytes) throw new Error("sector payload byte count mismatch");
  if (await sha256Hex(bytes) !== asset.sha256) throw new Error("sector payload digest mismatch");
  return decodePayload(JSON.parse(new TextDecoder().decode(bytes)));
}

function renderRows(container, rows) {
  container.replaceChildren();
  if (!rows.length) {
    container.appendChild(element("div", { class: "sector-message" }, "No retained source metadata is available for this topic."));
    return;
  }
  for (const row of rows) {
    const card = element("article", { class: "sector-card", "data-sector-item-id": row.intelligence_item_id });
    const title = element("a", { href: row.canonical_url, target: "_blank", rel: "noopener noreferrer" }, row.title);
    const rights = element("p");
    const terms = element("a", { href: row.source_terms_url, target: "_blank", rel: "noopener noreferrer" }, row.source_licence_id);
    rights.append(document.createTextNode(`${row.attribution} · ${row.redistribution_rights} · `), terms);
    card.append(title);
    if (row.summary) card.appendChild(element("p", {}, row.summary));
    if (row.item_kind === "CONTEXT_METRIC") {
      const range = row.value_min === row.value_max ? `${row.value_min}` : `${row.value_min}–${row.value_max}`;
      card.appendChild(element("p", {}, `PINNED OWNER CONTEXT METRIC · ${range} ${row.unit}`));
    }
    card.append(
      rights,
      element("p", {}, `${row.evidence_class} · ${String(row.source_published_at || row.observed_at).slice(0, 10)} · ${row.staleness_state}`),
      element("p", { class: "sector-binding" }, row.binding_label),
    );
    container.appendChild(card);
  }
}

export function mountSectorIntelligence({ host, payloadAsset }) {
  if (!(host instanceof HTMLElement)) throw new Error("sector intelligence host is missing");
  if (mounted.has(host)) return mounted.get(host);
  validateAsset(payloadAsset);
  installStyles();
  const shell = element("section", { class: "sector-shell", "aria-label": "Sector intelligence" });
  const header = element("div", { class: "sector-head" });
  const heading = element("div");
  heading.append(
    element("h2", {}, "SOURCE-AND-EVIDENCE SECTOR INTELLIGENCE"),
    element("p", {}, "Ventus Ltd application context: non-commercial open source. Upstream rights remain source-specific and are shown on every item."),
    element("p", {}, "Sector context is separate from the filtered news edition and cannot create or alter REPD project identity."),
  );
  const status = element("p", { "data-sector-status": "WAIT" }, "WAIT · choose one topic; no payload has been requested.");
  header.append(heading, status);
  const tabs = element("div", { class: "sector-tabs", role: "tablist", "aria-label": "Sector topics" });
  const list = element("div", { class: "sector-list", role: "tabpanel" });
  list.appendChild(element("div", { class: "sector-message" }, "Choose a topic to load one compact DuckDB/Parquet-derived cartridge."));
  const buttons = new Map();
  let payloadPromise = null;
  let payloadRequests = 0;
  async function select(topic) {
    for (const [code, button] of buttons) button.setAttribute("aria-selected", String(code === topic));
    status.dataset.sectorStatus = "LOAD";
    status.textContent = `LOAD · ${topic}`;
    list.replaceChildren(element("div", { class: "sector-message" }, "Loading bounded sector metadata…"));
    try {
      if (!payloadPromise) {
        payloadRequests += 1;
        if (payloadRequests > 1) throw new Error("sector payload request budget exceeded");
        payloadPromise = loadPayload(payloadAsset);
      }
      const allRows = await payloadPromise;
      const rows = allRows.filter((row) => row.topic_code === topic);
      renderRows(list, rows);
      status.dataset.sectorStatus = rows.length ? "OK" : "EMPTY";
      status.textContent = `${rows.length ? "OK" : "EMPTY"} · ${rows.length} rows · landed ZSTD Parquet readback`;
    } catch (error) {
      status.dataset.sectorStatus = "FAIL";
      status.textContent = "FAIL · sector topic unavailable; core newspaper and project register are unchanged.";
      list.replaceChildren(element("div", { class: "sector-message" }, "Sector intelligence failed closed."));
      throw error;
    }
  }
  // Only the topics that carry real content get a tab. The rest stay in the
  // payload and out of the interface.
  for (const topic of TOPICS.filter(({ code }) => topicIsShown(code))) {
    const button = element("button", { type: "button", role: "tab", "aria-selected": "false", "data-sector-topic": topic.code }, topic.label);
    button.addEventListener("click", () => select(topic.code).catch((error) => console.error("sector intelligence", error)));
    buttons.set(topic.code, button);
    tabs.appendChild(button);
  }
  const withheld = TOPICS.filter(({ code }) => !topicIsShown(code));
  if (withheld.length) {
    shell.append(element("div", { class: "sector-message" },
      `${withheld.length} topics withheld: the upstream collector returned a generic `
      + `government feed rather than results on those subjects, so they carried no `
      + `sector intelligence. Their rows remain in the payload.`));
  }
  shell.append(header, tabs, list);
  host.replaceChildren(shell);
  host.hidden = false;
  host.dataset.sectorIntelligenceState = "ready";
  const result = Object.freeze({ shell, tabs, list, status, buttons, select, get payloadRequests() { return payloadRequests; } });
  mounted.set(host, result);
  return result;
}