GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / releases/javascript

JavaScript Projects V8 Foundation and 1 more file

A JavaScript module in PipelineNews that compares project updates v9 (`compareProjectUpdatesV9_5_1`), updates sort header (`updateSortHeader`), renders table (`renderTable`) and reads inputs for county and sort projects, using EPSG:27700 and SHA-256.

574 lines of JavaScript from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1030 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. JavaScript Projects V8 Foundation energy-data · pipelinenews / releases/javascript/202608262141-projects-v8-foundation.js lines 1–351
  2. JavaScript Sector Intelligence render · pipelinenews / releases/javascript/202609010719-sector-intelligence.js lines 1–223

JavaScript Projects V8 Foundation

A JavaScript module in PipelineNews that compares project updates v9 (`compareProjectUpdatesV9_5_1`), updates sort header (`updateSortHeader`), renders table (`renderTable`) and reads inputs for county and sort projects, using EPSG:27700 and SHA-256.

energy-datapipelinenews / releases/javascript/202608262141-projects-v8-foundation.js · lines 1–351 of 351 · version 2026-08-26 21:41 · pattern compareProjectUpdates (shared by 20 files)

What it does
It draws the REPD register, solar, battery storage (BESS) and wind. Defines 21 functions or classes, including atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1, updateSortHeader. Side effects: changes the web page (DOM).
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: the REPD register, solar, battery storage (BESS), wind.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: JavaScript App V8 Foundation (pipelinenews). Reached from 1 other entry point, including V8 Candidate (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202608262141-v8-candidate.html).
What it achieves
It compares project updates v9 (`compareProjectUpdatesV9_5_1`), updates sort header (`updateSortHeader`) and renders table (`renderTable`). Its `downloadCsv` function gives CSV download or refusal from active table owner, filtered register rows and official detail partitions (VEDIC: export filtered projects). It responds to click events.
Why it matters
Imported by JavaScript App V8 Foundation.
Application
pipelinenews · releases/javascript · JavaScript module
VEDIC
EXPORT FILTERED PROJECTS (GG2050-VEDIC-000060): Pipeline News · Renewable project register. active_table_owner, filtered_register_rows, official_detail_partitions → csv_download_or_refusal
Uses
Testcode — Pipeline (import), JavaScript State (import), Project Filter V9 2 (import), JavaScript Canonical Projects V9 5 1 (import), Gauges V9 2 (import), JavaScript Newspaper V9 5 1 (import), GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
Used by
imported by JavaScript App V8 Foundation (import)
Produces
atlasUrlV9_5_1, compareProjectUpdatesV9_5_1, loadProjectsV9_5_1, refreshProjectsV9_5_1, bindProjectControlsV9_5_1
Defines here
atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1, updateSortHeader, relationshipSummary, renderTable, updateWindowControls, updateResultSummary, syncFilterUrl, apply, populateCounties, setButtonState, hydrateFiltersFromUrl, csvCell, downloadCsv, clearFilters, copyProjectId, loadProjectsV9_5_1, refreshProjectsV9_5_1, bindProjectControlsV9_5_1
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202608262141-projects-v8-foundation.js:1-351 · blob 9a961c3d8e39725bc3ba488e8f2900be5de0eb93 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { escapeHtml } from "./202608261927-utils.js";
import { state } from "./202608261927-state.js";
import {
  buildProjectSearchTextV9_2,
  projectMatchesV9_2,
  summariseProjectsV9_2,
  tokeniseSearchV9_2,
} from "./202608261927-filters.js";
import { loadCanonicalProjectsV9_5_1 } from "./202608261927-canonical-projects-v9-5-1.js";
import {
  formatCapacityV9_2,
  formatLargestV9_2,
  setGaugeUniverseV9_2,
  updateGaugesV9_2,
} from "./202608261927-gauges.js";
import { signalForProjectV9_5_1 } from "./202608261927-newspaper-v9-5-1.js";

const LABELS = Object.freeze({
  solar: "Solar",
  bess: "Battery Storage",
  wind_onshore: "Onshore Wind",
  wind_offshore: "Offshore Wind",
});
const COLOURS = Object.freeze({ solar: "#ffff00", bess: "#ffae00", wind_onshore: "#00ffff", wind_offshore: "#0066ff" });
const UNITS = Object.freeze({ solar: "MWp", bess: "MW", wind_onshore: "MW", wind_offshore: "MW" });
const ALLOWED_TECHNOLOGIES = new Set(["all", "solar", "bess", "wind_onshore", "wind_offshore"]);
const ALLOWED_STATUSES = new Set(["All", "Operational", "Under Construction", "Awaiting Construction", "Application Submitted"]);
const ALLOWED_SORTS = new Set(["capacity_desc", "updated_desc", "updated_asc"]);

let all = [];
let filtered = [];
let metadata = null;
let release = null;
let searchIndex = new Map();
let technology = "all";
let status = "All";
let county = "All";
let query = "";
let sortMode = "capacity_desc";
let controlsBound = false;
const WINDOW_SIZE=50;
let windowStart=0;

export function atlasUrlV9_5_1(project) {
  if (project.geometry_status !== "valid") return "";
  const url = new URL("https://globalgrid2050.com/repd_grid_atlasv8/");
  url.searchParams.set("repd_ref", project.repd_ref);
  url.searchParams.set("project", project.name);
  url.searchParams.set("technology", project.technology);
  url.searchParams.set("capacity_mw", project.capacity_mw);
  url.searchParams.set("latitude", project.latitude);
  url.searchParams.set("longitude", project.longitude);
  url.searchParams.set("zoom", "12");
  return url.href;
}

function displayDate(value) {
  if (!value) return "not supplied by REPD";
  const [year, month, day] = String(value).split("-");
  return year && month && day ? `${day}/${month}/${year}` : String(value);
}

function repdUpdatedTimestamp(project) {
  if (!project.repd_record_updated) return null;
  const value = Date.parse(`${project.repd_record_updated}T00:00:00Z`);
  return Number.isFinite(value) ? value : null;
}

export function compareProjectUpdatesV9_5_1(left, right, direction = "desc") {
  const leftTime = repdUpdatedTimestamp(left);
  const rightTime = repdUpdatedTimestamp(right);
  if (leftTime === null && rightTime === null) return 0;
  if (leftTime === null) return 1;
  if (rightTime === null) return -1;
  return direction === "asc" ? leftTime - rightTime : rightTime - leftTime;
}

function updateSortHeader() {
  const header = document.getElementById("repdUpdatedHeader");
  const button = document.getElementById("sortUpdated");
  const indicator = document.getElementById("updatedSortIndicator");
  if (!header || !button || !indicator) return;
  if (sortMode === "updated_desc") {
    header.setAttribute("aria-sort", "descending");
    indicator.textContent = "▼";
    button.setAttribute("aria-label", "REPD updated date sorted newest first; click for oldest first");
    button.title = "Newest first — click for oldest first";
    return;
  }
  if (sortMode === "updated_asc") {
    header.setAttribute("aria-sort", "ascending");
    indicator.textContent = "▲";
    button.setAttribute("aria-label", "REPD updated date sorted oldest first; click for newest first");
    button.title = "Oldest first — click for newest first";
    return;
  }
  header.setAttribute("aria-sort", "none");
  indicator.textContent = "↕";
  button.setAttribute("aria-label", "Sort by REPD updated date, newest first");
  button.title = "Click for newest first";
}

function relationshipSummary(project) {
  const development = Array.isArray(project.development_repd_refs) ? project.development_repd_refs.length : 0;
  const direct = Array.isArray(project.direct_related_repd_refs) ? project.direct_related_repd_refs.length : 0;
  const siblings = Array.isArray(project.planning_sibling_repd_refs) ? project.planning_sibling_repd_refs.length : 0;
  return `${development} development · ${direct} direct · ${siblings} planning sibling record(s)`;
}

function renderTable() {
  const body = document.getElementById("tbody");
  const windowRows=filtered.slice(windowStart,windowStart+WINDOW_SIZE);
  body.innerHTML = windowRows.map((project) => {
    const label = LABELS[project.technology];
    const unit = UNITS[project.technology];
    const location = [project.county, project.region].filter(Boolean).join(" · ");
    const signal = signalForProjectV9_5_1(project);
    const news = new URL("https://www.google.com/search");
    news.searchParams.set("q", `${project.name} ${label} UK`);
    news.searchParams.set("tbm", "nws");
    const atlas = atlasUrlV9_5_1(project);
    const mapAction = atlas
      ? `<a class="action-link atlaslink" target="_blank" rel="noopener" href="${escapeHtml(atlas)}">MAP ↗</a>`
      : '<span class="action-disabled" title="REPD geometry is unavailable; the record remains searchable and exportable">NO MAP</span>';
    const planning = project.planning_application_reference || "not supplied by REPD";
    const authority = project.planning_authority || "not supplied by REPD";
    const developmentId = project.gg_development_id || "not assigned";
    const updated = displayDate(project.repd_record_updated);
    return `<tr id="repd-${escapeHtml(project.repd_ref)}" data-repd-updated="${escapeHtml(project.repd_record_updated || "")}"><td class="site">${escapeHtml(project.name)}<div class="project-meta">REPD ${escapeHtml(project.repd_ref)} · ${escapeHtml(project.gg_project_id)} · UPDATED ${escapeHtml(updated)}</div><div class="mobile-extra">${escapeHtml([location, project.operator].filter(Boolean).join(  … [line shortened here: 2,120 characters; full line on GitHub]
  }).join("");
  updateWindowControls();
}

function updateWindowControls(){
  let panel=document.getElementById("projectWindowControls");
  if(!panel){
    panel=document.createElement("div");
    panel.id="projectWindowControls";
    panel.className="project-window-controls";
    panel.innerHTML='<button type="button" data-window="previous">PREVIOUS 50</button><span data-window-range></span><button type="button" data-window="next">NEXT 50</button>';
    document.querySelector(".tablewrap").after(panel);
    panel.addEventListener("click",(event)=>{
      const action=event.target.closest("[data-window]")?.dataset.window;
      if(action==="previous")windowStart=Math.max(0,windowStart-WINDOW_SIZE);
      if(action==="next")windowStart=Math.min(Math.floor(Math.max(0,filtered.length-1)/WINDOW_SIZE)*WINDOW_SIZE,windowStart+WINDOW_SIZE);
      if(action)renderTable();
    });
  }
  const end=Math.min(filtered.length,windowStart+WINDOW_SIZE);
  panel.querySelector("[data-window-range]").textContent=filtered.length?String(windowStart+1)+"–"+String(end)+" of "+filtered.length.toLocaleString("en-GB"):"0 records";
  panel.querySelector('[data-window="previous"]').disabled=windowStart===0;
  panel.querySelector('[data-window="next"]').disabled=end>=filtered.length;
}

function updateResultSummary() {
  const summary = summariseProjectsV9_2(filtered);
  const element = document.getElementById("resultsMeta");
  element.textContent = `${summary.count.toLocaleString("en-GB")} of ${all.length.toLocaleString("en-GB")} records · ${formatCapacityV9_2(summary.capacity_mw)} MW · largest ${formatLargestV9_2(summary.largest_mw)} MW`;
  element.classList.toggle("is-filtered", summary.count !== all.length);
  element.dataset.filteredCount = String(summary.count);
  element.dataset.totalCount = String(all.length);
}

function syncFilterUrl() {
  const url = new URL(window.location.href);
  for (const parameter of ["technology", "status", "county", "q", "sort"]) url.searchParams.delete(parameter);
  if (technology !== "all") url.searchParams.set("technology", technology);
  if (status !== "All") url.searchParams.set("status", status);
  if (county !== "All") url.searchParams.set("county", county);
  if (query) url.searchParams.set("q", query);
  if (sortMode !== "capacity_desc") url.searchParams.set("sort", sortMode);
  history.replaceState(null, "", url);
}

function apply({ syncUrl = true } = {}) {
  const tokens = tokeniseSearchV9_2(query);
  filtered = all.filter((project) => projectMatchesV9_2(project, {
    technology,
    status,
    county,
    tokens,
  }, searchIndex.get(project.repd_ref)));
  if (sortMode === "updated_desc") filtered.sort((left, right) => compareProjectUpdatesV9_5_1(left, right, "desc"));
  if (sortMode === "updated_asc") filtered.sort((left, right) => compareProjectUpdatesV9_5_1(left, right, "asc"));
  state.filtered = filtered;
  windowStart=0;
  updateGaugesV9_2(filtered);
  renderTable();
  updateResultSummary();
  updateSortHeader();
  if (syncUrl) syncFilterUrl();
}

function populateCounties() {
  const select = document.getElementById("county");
  select.replaceChildren(new Option("🌍 ALL COUNTIES", "All"));
  [...new Set(all.map((project) => project.county).filter(Boolean))]
    .sort((left, right) => left.localeCompare(right, "en-GB"))
    .forEach((value) => select.add(new Option(`📍 ${value}`, value)));
}

function setButtonState(container, dataKey, selected) {
  document.querySelectorAll(`${container} .btn`).forEach((button) => {
    const active = button.dataset[dataKey] === selected;
    button.classList.toggle("active", active);
    button.setAttribute("aria-pressed", String(active));
  });
}

function hydrateFiltersFromUrl() {
  const parameters = new URLSearchParams(window.location.search);
  const requestedTechnology = parameters.get("technology") || "all";
  const requestedStatus = parameters.get("status") || "All";
  const requestedCounty = parameters.get("county") || "All";
  const requestedSort = parameters.get("sort") || "capacity_desc";
  technology = ALLOWED_TECHNOLOGIES.has(requestedTechnology) ? requestedTechnology : "all";
  status = ALLOWED_STATUSES.has(requestedStatus) ? requestedStatus : "All";
  county = [...document.getElementById("county").options].some((option) => option.value === requestedCounty)
    ? requestedCounty
    : "All";
  query = parameters.get("q") || "";
  sortMode = ALLOWED_SORTS.has(requestedSort) ? requestedSort : "capacity_desc";
  setButtonState("#tech", "technology", technology);
  setButtonState("#status", "officialStatus", status);
  document.getElementById("county").value = county;
  document.getElementById("search").value = query;
  document.getElementById("sortProjects").value = sortMode;
}

function csvCell(value) {
  let text = value === null || value === undefined ? "" : String(value);
  if (/^(?:[=+\-@]|\s+[=+\-@]|\t|\r|\n)/u.test(text)) text = `'${text}`;
  return `"${text.replaceAll('"', '""')}"`;
}

function downloadCsv(event) {
  event.preventDefault();
  const headers = ["Site Name", "REPD Ref", "GlobalGrid Project ID", "GlobalGrid Development ID", "Identity Status", "Identity Confidence", "Technology", "Official REPD Technology", "Official REPD Capacity", "Capacity Unit", "Official REPD Status", "Derived Lifecycle", "Operator or Applicant", "County", "Region", "Country", "Planning Authority", "Planning Application Reference", "REPD Record Updat  … [line shortened here: 1,130 characters; full line on GitHub]
  const rows = filtered.map((project) => {
    const signal = signalForProjectV9_5_1(project);
    return [project.name, project.repd_ref, project.gg_project_id, project.gg_development_id, project.identity_status, project.identity_confidence, LABELS[project.technology], project.repd_technology, project.capacity_mw, UNITS[project.technology], project.status, project.lifecycle, project.operator, project.county, project.region, project.country, project.planning_authority, project.planning_appl  … [line shortened here: 1,392 characters; full line on GitHub]
  });
  const content = `\ufeff${[headers, ...rows].map((row) => row.map(csvCell).join(",")).join("\r\n")}`;
  const url = URL.createObjectURL(new Blob([content], { type: "text/csv;charset=utf-8" }));
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = `globalgrid2050_uk_renewables_pipeline_v9_5_1_${new Date().toISOString().slice(0, 10)}.csv`;
  anchor.click();
  URL.revokeObjectURL(url);
  document.getElementById("exportMeta").textContent = `${filtered.length.toLocaleString("en-GB")} filtered records exported`;
}

function clearFilters(event) {
  event.preventDefault();
  technology = "all";
  status = "All";
  county = "All";
  query = "";
  sortMode = "capacity_desc";
  setButtonState("#tech", "technology", technology);
  setButtonState("#status", "officialStatus", status);
  document.getElementById("county").value = county;
  document.getElementById("search").value = "";
  document.getElementById("sortProjects").value = sortMode;
  apply();
}

async function copyProjectId(button) {
  const value = button.dataset.copyId;
  try {
    await navigator.clipboard.writeText(value);
  } catch {
    const field = document.createElement("textarea");
    field.value = value;
    field.setAttribute("readonly", "");
    field.style.position = "fixed";
    field.style.opacity = "0";
    document.body.appendChild(field);
    field.select();
    document.execCommand("copy");
    field.remove();
  }
  const original = button.textContent;
  button.textContent = "COPIED";
  button.classList.add("copied");
  setTimeout(() => {
    button.textContent = original;
    button.classList.remove("copied");
  }, 1200);
}

export async function loadProjectsV9_5_1() {
  try {
    const model = await loadCanonicalProjectsV9_5_1();
    all = [...model.projects];
    filtered = all;
    metadata = model.metadata;
    release = model.release;
    searchIndex = new Map(all.map((project) => [project.repd_ref, buildProjectSearchTextV9_2(project)]));
    state.all = all;
    state.filtered = filtered;
    state.canonicalModel = model;
    setGaugeUniverseV9_2(all);
    populateCounties();
    hydrateFiltersFromUrl();
    apply({ syncUrl: false });
    document.getElementById("releaseMeta").textContent = `V9.5.1 interface · V${release.data_parent.release} canonical data spine · all ${all.length.toLocaleString("en-GB")} qualifying records loaded`;
  } catch (error) {
    console.error(error);
    document.getElementById("tbody").innerHTML = '<tr><td colspan="11" style="text-align:center;color:#ff6666">Canonical Q2 REPD data unavailable. V9.5.1 has failed closed.</td></tr>';
    document.getElementById("resultsMeta").textContent = "canonical data unavailable";
  }
}

export function refreshProjectsV9_5_1() {
  if (metadata) renderTable();
}

export function bindProjectControlsV9_5_1() {
  if (controlsBound) return;
  controlsBound = true;
  document.querySelectorAll("#tech .btn").forEach((button) => {
    button.onclick = () => {
      technology = button.dataset.technology;
      setButtonState("#tech", "technology", technology);
      apply();
    };
  });
  document.querySelectorAll("#status .btn").forEach((button) => {
    button.onclick = () => {
      status = button.dataset.officialStatus;
      setButtonState("#status", "officialStatus", status);
      apply();
    };
  });
  document.getElementById("county").onchange = (event) => { county = event.target.value; apply(); };
  document.getElementById("sortProjects").onchange = (event) => { sortMode = event.target.value; apply(); };
  document.getElementById("sortUpdated").onclick = () => {
    sortMode = sortMode === "updated_desc" ? "updated_asc" : "updated_desc";
    document.getElementById("sortProjects").value = sortMode;
    apply();
  };
  document.getElementById("search").oninput = (event) => { query = event.target.value.trim(); apply(); };
  document.getElementById("export").onclick = downloadCsv;
  document.getElementById("exportInline").onclick = downloadCsv;
  document.getElementById("clearFilters").onclick = clearFilters;
  document.getElementById("tbody").addEventListener("click", (event) => {
    const button = event.target.closest(".copy-id");
    if (button) copyProjectId(button);
  });
}

JavaScript Sector Intelligence

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

renderpipelinenews / releases/javascript/202609010719-sector-intelligence.js · lines 1–223 of 223 · version 2026-09-01 07:19 · Not reached from any entry point (candidate for review) · pattern mountSectorIntelligence (shared by 4 files)

What it does
It draws its content. Defines 9 functions or classes, including element, installStyles, sha256Hex, validateAsset, decodePayload. 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
Defines `element`, `installStyles`, `sha256Hex` and 6 more. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · releases/javascript · JavaScript module
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
SECTOR_INTELLIGENCE_CARTRIDGE_CONTRACT, mountSectorIntelligence
Defines here
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 releases/javascript/202609010719-sector-intelligence.js:1-223 · blob e850939eec58f56ac22a1a0b378423b2f7e368a9 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
const GENERATION = "202609010719";
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: "GREAT_GRID_UPGRADE", label: "GREAT GRID UPGRADE", rank: 3 }),
  Object.freeze({ code: "WORLDWIDE_PV", label: "WORLDWIDE PV", rank: 4 }),
  Object.freeze({ code: "MV_HV_COMPONENTS", label: "MV/HV COMPONENTS", rank: 5 }),
]);
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\/202609010719-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 !== 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) {
    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 136-headline newspaper 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(({ topic_code }) => 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;
    }
  }
  for (const topic of TOPICS) {
    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);
  }
  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;
}