GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / archive/202608261547-pipelinenews/202608260159-pipelinenews/scripts/plugins

Projects V9 5 1 and 9 more files

A JavaScript module in the plugins folder of PipelineNews that compares project updates v9, updates sort header, renders table and reads inputs for county and sort projects.

622 lines of JavaScript and Python and Shell from pipelinenews, in 10 files. Topic: Electricity markets and data pipelines. Section 981 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. Projects V9 5 1 energy-data · pipelinenews / archive/202608261547-pipelinenews/202608260159-pipelinenews/scripts/plugins/projects-v9-5-1.js lines 1–326
  2. Build Parquet storage · pipelinenews / archive/202608261547-pipelinenews/analytics_v1/scripts/build_parquet.py lines 1–90
  3. Stage Storage Contract storage · pipelinenews / archive/202608261547-pipelinenews/analytics_v1/scripts/stage-storage-contract.mjs lines 1–18
  4. SQL Views storage · pipelinenews / archive/202608261547-pipelinenews/analytics_v1/sql/views.sql lines 1–10
  5. Check Storage Contract test · pipelinenews / archive/202608261547-pipelinenews/analytics_v1/tests/check-storage-contract.mjs lines 1–14
  6. Run Parquet test · pipelinenews / archive/202608261547-pipelinenews/analytics_v1/tests/run-parquet.sh lines 1–6
  7. Run Storage Contract test · pipelinenews / archive/202608261547-pipelinenews/analytics_v1/tests/run-storage-contract.sh lines 1–6
  8. Verify Parquet test · pipelinenews / archive/202608261547-pipelinenews/analytics_v1/tests/verify_parquet.py lines 1–24
  9. Attribution Ledger transform · pipelinenews / archive/202608261547-pipelinenews/attributionv1/modules/attribution-ledger.mjs lines 1–90
  10. Discrepancy View transform · pipelinenews / archive/202608261547-pipelinenews/attributionv1/modules/discrepancy-view.mjs lines 1–38

Projects V9 5 1

A JavaScript module in the plugins folder of PipelineNews that compares project updates v9, updates sort header, renders table and reads inputs for county and sort projects.

energy-datapipelinenews / archive/202608261547-pipelinenews/202608260159-pipelinenews/scripts/plugins/projects-v9-5-1.js · lines 1–326 of 326 · version 2026-08-26 01:59 · Not reached from any entry point (candidate for review) · pattern compareProjectUpdates (shared by 20 files)

What it does
It draws the REPD register, solar, battery storage (BESS) and wind. Defines 20 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 experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. 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: Compare Atlas V8 Deep Links (pipelinenews).
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 Compare Atlas V8 Deep Links.
Application
pipelinenews · archive/202608261547-pipelinenews/202608260159-pipelinenews/scripts/plugins · 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), State (import), Project Filter V9 2 (import), Canonical Projects V9 5 1 (import), Gauges V9 2 (import), Newspaper V9 5 1 (import), GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
Used by
imported by Compare Atlas V8 Deep Links (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, 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 archive/202608261547-pipelinenews/202608260159-pipelinenews/scripts/plugins/projects-v9-5-1.js:1-326 · blob 3e74e74b855a5de611297831be88ed410cf887e5 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: duplicate_candidate
import { escapeHtml } from "../core/utils.js";
import { state } from "../core/state.js";
import {
  buildProjectSearchTextV9_2,
  projectMatchesV9_2,
  summariseProjectsV9_2,
  tokeniseSearchV9_2,
} from "../core/project-filter-v9-2.js";
import { loadCanonicalProjectsV9_5_1 } from "../data/canonical-projects-v9-5-1.js";
import {
  formatCapacityV9_2,
  formatLargestV9_2,
  setGaugeUniverseV9_2,
  updateGaugesV9_2,
} from "./gauges-v9-2.js";
import { signalForProjectV9_5_1 } from "./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 WITHHELD_OPERATOR = "OPERATOR LABEL WITHHELD";
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;

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");
  body.innerHTML = filtered.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, WITHHELD_OPERATOR].filter(Boolean).join  … [line shortened here: 2,115 characters; full line on GitHub]
  }).join("");
}

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;
  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, WITHHELD_OPERATOR, project.county, project.region, project.country, project.planning_authority, project.planning_app  … [line shortened here: 1,393 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);
  });
}

Build Parquet

A Python module in the scripts folder of PipelineNews that reads storage and audit, using SHA-256.

storagepipelinenews / archive/202608261547-pipelinenews/analytics_v1/scripts/build_parquet.py · lines 1–90 of 90 · version 2026-08-26 15:47 · Entry point

What it does
It loads storage and audit. Defines raw, load, sha, stable_json, iso_time. Uses libraries hashlib, json, shutil, datetime, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file storage.v1.json; JSON file parquet-build.v1.json; JSON file parquet_audit.json; JSON file parquet_manifest.json; DuckDB queries.
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
It is built from the stable JSON helper (`stable_json`) and the iso time helper (`iso_time`). Its name says it builds Parquet. Defines `raw`, `load`, `sha` and 2 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · archive/202608261547-pipelinenews/analytics_v1/scripts · Python module
Uses
hashlib, json, shutil, datetime, pathlib, duckdb, pyarrow, pyarrow.parquet
Used by
none found
Produces
raw, load, sha, stable_json, iso_time
Defines here
raw, load, sha, stable_json, iso_time
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/analytics_v1/scripts/build_parquet.py:1-90 · blob d253aa236ab2f085f645a4bf1133878c086d7a0a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: experimental · users: none · canonical: production_core
#!/usr/bin/env python3
import hashlib, json, shutil
from datetime import datetime, timezone
from pathlib import Path

import duckdb
import pyarrow as pa
import pyarrow.parquet as pq

ROOT = Path(__file__).resolve().parents[2]
ANALYTICS = ROOT / "analytics_v1"
BASE_PATH = ANALYTICS / "contracts/storage.v1.json"
SPEC_PATH = ANALYTICS / "contracts/parquet-build.v1.json"
PARQUET_DIR = ANALYTICS / "parquet"
SQL_PATH = ANALYTICS / "sql/views.sql"
AUDIT_PATH = ANALYTICS / "reports/parquet_audit.json"
MANIFEST_PATH = ANALYTICS / "data/parquet_manifest.json"

def raw(path): return path.read_bytes()
def load(path): return json.loads(raw(path))
def sha(value): return hashlib.sha256(value).hexdigest()
def stable_json(value): return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def iso_time(value):
    if value is None: return None
    parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if parsed.tzinfo is None: parsed = parsed.replace(tzinfo=timezone.utc)
    return parsed.astimezone(timezone.utc)

TYPE_MAP = {"VARCHAR": pa.string(), "BIGINT": pa.int64(), "DOUBLE": pa.float64(), "TIMESTAMP": pa.timestamp("us", tz="UTC")}
base, spec = load(BASE_PATH), load(SPEC_PATH)
if sha(raw(BASE_PATH)) != spec["base_contract"]["sha256"]: raise SystemExit("base contract hash mismatch")
if duckdb.__version__ != spec["runtime"]["duckdb"] or pa.__version__ != spec["runtime"]["pyarrow"]: raise SystemExit("runtime version mismatch")

products = {}
for item in base["inputs"]:
    path = ROOT / item["path"]
    if sha(raw(path)) != item["sha256"]: raise SystemExit(f"input hash mismatch: {item['path']}")
    products[item["release"]] = load(path)

staging = ANALYTICS / ".parquet-staging"
if staging.exists(): shutil.rmtree(staging)
staging.mkdir(parents=True)
table_audits, view_lines = [], []

for table in base["tables"]:
    source_rows = products[table["release"]][table["array_path"]]
    fields = [pa.field(name, TYPE_MAP[kind], nullable=nullable) for name, kind, nullable in table["columns"]]
    schema = pa.schema(fields, metadata={b"pipelinenews.table_id": table["table_id"].encode(), b"pipelinenews.grain": table["grain"].encode()})
    projected = []
    for source in source_rows:
        row = {}
        for name, kind, _nullable in table["columns"]:
            value = stable_json(source) if name == "payload_json" else source.get(name)
            row[name] = iso_time(value) if kind == "TIMESTAMP" else value
        projected.append(row)
    arrow = pa.Table.from_pylist(projected, schema=schema)
    path = staging / f"{table['table_id']}.parquet"
    pq.write_table(arrow, path, compression="zstd", use_dictionary=False, write_statistics=True, version="2.6", data_page_version="1.0", row_group_size=65536)
    readback = pq.read_table(path)
    if not readback.schema.equals(schema, check_metadata=True): raise SystemExit(f"schema mismatch: {table['table_id']}")
    rows = readback.to_pylist(); keys = ["\u001f".join(str(row[key]) for key in table["key"]) for row in rows]
    null_keys = sum(any(row[key] is None or row[key] == "" for key in table["key"]) for row in rows)
    duplicates = len(rows) - len(set(keys))
    if len(rows) != table["expected_rows"] or duplicates or null_keys: raise SystemExit(f"key law failed: {table['table_id']}")
    metadata = pq.ParquetFile(path).metadata
    codecs = sorted({metadata.row_group(r).column(c).compression for r in range(metadata.num_row_groups) for c in range(metadata.num_columns)})
    if codecs != ["ZSTD"]: raise SystemExit(f"compression mismatch: {table['table_id']}")
    table_audits.append({"table_id":table["table_id"],"source_rows":len(source_rows),"parquet_rows":len(rows),"distinct_declared_keys":len(set(keys)),"duplicate_key_groups":duplicates,"required_null_key_rows":null_keys,"schema":str(schema),"schema_match":True,"compression":codecs,"bytes":path.stat().st_size,"sha256":sha(raw(path))})
    order = " ORDER BY source_display_order, reason_decision_id" if table["table_id"] == "newsv5_reason_decisions" else ""
    view_lines.append(f"CREATE OR REPLACE VIEW v_{table['table_id']} AS SELECT * FROM read_parquet('{table['table_id']}.parquet'){order};")

sql = "-- Generated deterministic DuckDB views; execute with analytics_v1/parquet as working directory.\n" + "\n".join(view_lines) + "\n"
(ANALYTICS / "sql").mkdir(exist_ok=True)
SQL_PATH.write_text(sql, encoding="utf-8")
connection = duckdb.connect(":memory:")
for table in base["tables"]:
    path = (staging / f"{table['table_id']}.parquet").as_posix().replace("'", "''")
    connection.execute(f"CREATE VIEW v_{table['table_id']} AS SELECT * FROM read_parquet('{path}')")
    if connection.execute(f"SELECT count(*) FROM v_{table['table_id']}").fetchone()[0] != table["expected_rows"]: raise SystemExit(f"DuckDB view mismatch: {table['table_id']}")
connection.close()

if PARQUET_DIR.exists(): shutil.rmtree(PARQUET_DIR)
staging.rename(PARQUET_DIR)
audit = {"schema":"pipelinenews.parquet-audit.v1","status":"PASS","generated_at":base["generated_at"],"runtime":{"python":"3.11","duckdb":duckdb.__version__,"pyarrow":pa.__version__},"counts":{"tables":len(table_audits),"source_rows":sum(x["source_rows"] for x in table_audits),"parquet_rows":sum(x["parquet_rows"] for x in table_audits),"duplicate_key_groups":sum(x["duplicate_key_groups"] for x in   … [line shortened here: 795 characters; full line on GitHub]
AUDIT_PATH.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8")
artifacts = [{"path":f"analytics_v1/parquet/{p.name}","sha256":sha(raw(p)),"bytes":p.stat().st_size} for p in sorted(PARQUET_DIR.glob("*.parquet"))]
artifacts += [{"path":"analytics_v1/sql/views.sql","sha256":sha(raw(SQL_PATH)),"bytes":SQL_PATH.stat().st_size},{"path":"analytics_v1/reports/parquet_audit.json","sha256":sha(raw(AUDIT_PATH)),"bytes":AUDIT_PATH.stat().st_size}]
manifest = {"schema":"pipelinenews.parquet-release-manifest.v1","status":"CANDIDATE","generated_at":base["generated_at"],"base_contract_sha256":sha(raw(BASE_PATH)),"build_spec_sha256":sha(raw(SPEC_PATH)),"inputs":base["inputs"],"artifacts":artifacts,"checks":audit["counts"],"database_artifact":None,"database_policy":"DuckDB views are recreated from immutable Parquet; no database file is committed.  … [line shortened here: 402 characters; full line on GitHub]
MANIFEST_PATH.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
print(f"PASS Parquet build: {audit['counts']['tables']} tables / {audit['counts']['parquet_rows']} rows / zstd / DuckDB readback")

Stage Storage Contract

A JavaScript module in the scripts folder of PipelineNews that reads cross version reconciliation, dependency audit and staging, using SHA-256.

storagepipelinenews / archive/202608261547-pipelinenews/analytics_v1/scripts/stage-storage-contract.mjs · lines 1–18 of 18 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review)

What it does
It loads cross version reconciliation, dependency audit and staging. Defines sha256, check. Uses libraries node:crypto, node:fs/promises, node:child_process. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file storage.v1.json; JSON file cross_version_reconciliation.json; JSON file dependency_audit.json; DuckDB queries. Out: JSON file cross_version_reconciliation.json; JSON file dependency_audit.json; JSON file staging_manifest.json.
What it achieves
Defines `sha256` and `check`. It writes `../data/cross_version_reconciliation.json`.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/analytics_v1/scripts · JavaScript module
Uses
node:crypto, node:fs/promises, node:child_process
Used by
none found
Produces
sha256, check
Defines here
sha256, check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/analytics_v1/scripts/stage-storage-contract.mjs:1-18 · blob fd5bdcded63c22124b5feaba74de48aa438077c0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: experimental · users: none · canonical: unreached_review
import {createHash} from "node:crypto";
import {mkdir, readFile, writeFile} from "node:fs/promises";
import {spawnSync} from "node:child_process";
const root=new URL("../../",import.meta.url), contractPath=new URL("../contracts/storage.v1.json",import.meta.url);
const sha256=(v)=>createHash("sha256").update(v).digest("hex"), contractBytes=await readFile(contractPath), contract=JSON.parse(contractBytes);
const inputBytes=new Map();
for(const input of contract.inputs){const b=await readFile(new URL(input.path,root)); if(sha256(b)!==input.sha256) throw new Error(`input hash mismatch: ${input.path}`); inputBytes.set(input.release,b);}
const products=new Map([...inputBytes].map(([release,b])=>[release,JSON.parse(b)]));
const rows=contract.tables.map((table)=>{const data=products.get(table.release)[table.array_path]; const keys=data.map(row=>table.key.map(k=>row[k]).join("\u001f")); return {release_id:table.release,table_id:table.table_id,domain:table.domain,namespace:table.namespace,grain:table.grain,key:table.key,source_path:contract.inputs.find(x=>x.release===table.release).path,source_sha256:contract.inputs.f  … [line shortened here: 751 characters; full line on GitHub]
for(const row of rows){const expected=contract.tables.find(x=>x.table_id===row.table_id).expected_rows;if(row.total_rows!==expected||row.total_rows!==row.distinct_declared_keys||row.duplicate_key_groups||row.required_null_key_rows) throw new Error(`key law failed: ${row.table_id}`);}
const check=(args)=>{const r=spawnSync(args[0],args.slice(1),{encoding:"utf8"});return {available:r.status===0,version:r.status===0?r.stdout.trim()||r.stderr.trim():null};};
const dependencyAudit={schema:"pipelinenews.analytical-dependency-audit.v1",status:"BLOCKED",audited_at:contract.generated_at,checks:{duckdb_cli:check(["duckdb","--version"]),python_duckdb:check(["python3","-c","import duckdb; print(duckdb.__version__)"]),pyarrow:check(["python3","-c","import pyarrow; print(pyarrow.__version__)"])},blocker:"No installed DuckDB CLI, Python duckdb module or PyArrow   … [line shortened here: 586 characters; full line on GitHub]
const ledger={schema:"pipelinenews.cross-version-reconciliation.v1",status:"STAGED_CONTRACT_ONLY",generated_at:contract.generated_at,grain:contract.reconciliation_law.grain,primary_key:contract.reconciliation_law.key,counts:{tables:rows.length,rows:rows.reduce((n,x)=>n+x.total_rows,0),duplicate_key_groups:rows.reduce((n,x)=>n+x.duplicate_key_groups,0),required_null_key_rows:rows.reduce((n,x)=>n+x.  … [line shortened here: 750 characters; full line on GitHub]
const ledgerBytes=Buffer.from(`${JSON.stringify(ledger,null,2)}\n`),auditBytes=Buffer.from(`${JSON.stringify(dependencyAudit,null,2)}\n`);
const manifest={schema:"pipelinenews.analytical-staging-manifest.v1",status:"BLOCKED_DEPENDENCIES",generated_at:contract.generated_at,inputs:[...contract.inputs,{path:"analytics_v1/contracts/storage.v1.json",sha256:sha256(contractBytes)}],artifacts:[{path:"analytics_v1/data/cross_version_reconciliation.json",sha256:sha256(ledgerBytes),rows:rows.length},{path:"analytics_v1/reports/dependency_audit.  … [line shortened here: 695 characters; full line on GitHub]
await Promise.all([mkdir(new URL("../data/",import.meta.url),{recursive:true}),mkdir(new URL("../reports/",import.meta.url),{recursive:true})]);
await Promise.all([writeFile(new URL("../data/cross_version_reconciliation.json",import.meta.url),ledgerBytes),writeFile(new URL("../reports/dependency_audit.json",import.meta.url),auditBytes),writeFile(new URL("../data/staging_manifest.json",import.meta.url),`${JSON.stringify(manifest,null,2)}\n`)]);
console.log(`STAGED Movement 5: ${rows.length} tables / ${ledger.counts.rows} source rows; Parquet BLOCKED_DEPENDENCIES`);

SQL Views

An SQL query in PipelineNews that reads newsv2 event assertions, newsv3 organisation labels, newsv3 project operator roles and newsv3 transaction role decisions.

storagepipelinenews / archive/202608261547-pipelinenews/analytics_v1/sql/views.sql · lines 1–10 of 10 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review)

What it does
It loads newsv2 event assertions, newsv3 organisation labels, newsv3 project operator roles and newsv3 transaction role decisions. Side effects: uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: Parquet file newsv2_event_assertions.parquet; Parquet file newsv3_organisation_labels.parquet; Parquet file newsv3_project_operator_roles.parquet; Parquet file newsv3_transaction_role_decisions.parquet; Parquet file newsv4_source_health.parquet; Parquet file newsv5_reason_decisions.parquet; Parquet file newsv6_dc_sources.parquet; Parquet file newsv6_dc_observations.parquet.
What it achieves
It reads `newsv2_event_assertions.parquet`.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/analytics_v1/sql · SQL query
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/analytics_v1/sql/views.sql:1-10 · blob a4204824c0b25df6c7013fe3ccf038f1dfba9c52 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: storage · domain stage: experimental · users: none · canonical: unreached_review
-- Generated deterministic DuckDB views; execute with analytics_v1/parquet as working directory.
CREATE OR REPLACE VIEW v_newsv2_event_assertions AS SELECT * FROM read_parquet('newsv2_event_assertions.parquet');
CREATE OR REPLACE VIEW v_newsv3_organisation_labels AS SELECT * FROM read_parquet('newsv3_organisation_labels.parquet');
CREATE OR REPLACE VIEW v_newsv3_project_operator_roles AS SELECT * FROM read_parquet('newsv3_project_operator_roles.parquet');
CREATE OR REPLACE VIEW v_newsv3_transaction_role_decisions AS SELECT * FROM read_parquet('newsv3_transaction_role_decisions.parquet');
CREATE OR REPLACE VIEW v_newsv4_source_health AS SELECT * FROM read_parquet('newsv4_source_health.parquet');
CREATE OR REPLACE VIEW v_newsv5_reason_decisions AS SELECT * FROM read_parquet('newsv5_reason_decisions.parquet') ORDER BY source_display_order, reason_decision_id;
CREATE OR REPLACE VIEW v_newsv6_dc_sources AS SELECT * FROM read_parquet('newsv6_dc_sources.parquet');
CREATE OR REPLACE VIEW v_newsv6_dc_observations AS SELECT * FROM read_parquet('newsv6_dc_observations.parquet');
CREATE OR REPLACE VIEW v_newsv6_dc_link_decisions AS SELECT * FROM read_parquet('newsv6_dc_link_decisions.parquet');

Check Storage Contract

A JavaScript module in the tests folder of PipelineNews that tests cross version reconciliation, dependency audit and staging, using SHA-256.

testpipelinenews / archive/202608261547-pipelinenews/analytics_v1/tests/check-storage-contract.mjs · lines 1–14 of 14 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review)

What it does
It tests cross version reconciliation, dependency audit and staging. Defines read. Uses libraries node:assert/strict, node:crypto, node:fs/promises. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file storage.v1.json; JSON file cross_version_reconciliation.json; JSON file dependency_audit.json; JSON file staging_manifest.json.
What it achieves
Its name says it checks storage contract. Defines `read`. It reads `../contracts/storage.v1.json`.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/analytics_v1/tests · JavaScript module
Uses
node:assert/strict, node:crypto, node:fs/promises
Used by
none found
Produces
read
Defines here
read
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/analytics_v1/tests/check-storage-contract.mjs:1-14 · blob f06e96a1b5f640a5d2321a50cd9999047a0dc5bb · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
import assert from "node:assert/strict";
import {createHash} from "node:crypto";
import {readFile} from "node:fs/promises";
const read=async p=>readFile(new URL(p,import.meta.url)),sha256=v=>createHash("sha256").update(v).digest("hex");
const [contractBytes,ledgerBytes,auditBytes,manifestBytes]=await Promise.all([read("../contracts/storage.v1.json"),read("../data/cross_version_reconciliation.json"),read("../reports/dependency_audit.json"),read("../data/staging_manifest.json")]);
const contract=JSON.parse(contractBytes),ledger=JSON.parse(ledgerBytes),audit=JSON.parse(auditBytes),manifest=JSON.parse(manifestBytes);
assert.equal(contract.status,"BLOCKED_DEPENDENCIES"); assert.equal(contract.physical_law.write_state,"NOT_WRITTEN"); assert.equal(contract.tables.length,9);
assert.deepEqual(ledger.counts,{tables:9,rows:208,duplicate_key_groups:0,required_null_key_rows:0,renewable_tables:5,data_centre_tables:3,cross_domain_identity_links:0});
assert.equal(new Set(ledger.tables.map(x=>`${x.release_id}\u001f${x.table_id}`)).size,9); assert.ok(ledger.tables.every(x=>x.total_rows===x.distinct_declared_keys&&x.parquet_path===null));
assert.equal(ledger.domain_boundary.identity_bridge_decision,"ABSTAIN_NO_AUTHORISED_BRIDGE"); assert.equal(contract.reconciliation_law.renewable_to_data_centre_identity_links_allowed,false);
assert.ok(contract.tables.every(t=>t.columns.some(c=>c[0]==="payload_json"&&c[1]==="VARCHAR"&&c[2]===false))); assert.ok(contract.tables.every(t=>t.key.length>0&&t.expected_rows>0));
assert.equal(audit.status,"BLOCKED"); assert.ok(Object.values(audit.checks).every(x=>x.available===false)); assert.equal(manifest.parquet_artifacts.length,0); assert.equal(manifest.duckdb_artifacts.length,0);
assert.equal(manifest.artifacts[0].sha256,sha256(ledgerBytes)); assert.equal(manifest.artifacts[1].sha256,sha256(auditBytes));
console.log("PASS staged Movement 5 contract: 9 table laws / 208 rows reconciled; real Parquet correctly BLOCKED");

Run Parquet

A shell script in the tests folder of PipelineNews.

testpipelinenews / archive/202608261547-pipelinenews/analytics_v1/tests/run-parquet.sh · lines 1–6 of 6 · version 2026-08-26 15:47 · Entry point

What it does
It tests its inputs. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
It is itself an entry point (shell script); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · archive/202608261547-pipelinenews/analytics_v1/tests · shell script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/analytics_v1/tests/run-parquet.sh:1-6 · blob afb68919b129ddc7b5c8cd171ea2747404878dca · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: production_core
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/../.."
python3 analytics_v1/scripts/build_parquet.py
python3 analytics_v1/tests/verify_parquet.py
bash newsv6/tests/run_newsv6.sh

Run Storage Contract

A shell script in the tests folder of PipelineNews.

testpipelinenews / archive/202608261547-pipelinenews/analytics_v1/tests/run-storage-contract.sh · lines 1–6 of 6 · version 2026-08-26 15:47 · Entry point

What it does
It tests its inputs. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
It is itself an entry point (shell script); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · archive/202608261547-pipelinenews/analytics_v1/tests · shell script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/analytics_v1/tests/run-storage-contract.sh:1-6 · blob 4e4c748373e11f10c1858d37cb6e90878ed293c2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: production_core
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/../.."
node analytics_v1/scripts/stage-storage-contract.mjs
node analytics_v1/tests/check-storage-contract.mjs
bash newsv6/tests/run_newsv6.sh

Verify Parquet

A Python module in the tests folder of PipelineNews that tests storage and audit, using SHA-256.

testpipelinenews / archive/202608261547-pipelinenews/analytics_v1/tests/verify_parquet.py · lines 1–24 of 24 · version 2026-08-26 15:47 · Entry point

What it does
It tests storage and audit. Uses libraries hashlib, json, pathlib, duckdb, pyarrow.parquet. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file storage.v1.json; JSON file parquet-build.v1.json; JSON file parquet_audit.json; JSON file parquet_manifest.json; DuckDB queries.
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
Its name says it verifies Parquet.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · archive/202608261547-pipelinenews/analytics_v1/tests · Python module
Uses
hashlib, json, pathlib, duckdb, pyarrow.parquet
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/analytics_v1/tests/verify_parquet.py:1-24 · blob 85cab0f8047269b7f07df5461565f707dd671490 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: experimental · users: none · canonical: production_core
#!/usr/bin/env python3
import hashlib, json
from pathlib import Path
import duckdb, pyarrow.parquet as pq

ROOT=Path(__file__).resolve().parents[2]; A=ROOT/"analytics_v1"
load=lambda p: json.loads(p.read_bytes()); sha=lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
contract=load(A/"contracts/storage.v1.json"); spec=load(A/"contracts/parquet-build.v1.json"); audit=load(A/"reports/parquet_audit.json"); manifest=load(A/"data/parquet_manifest.json")
assert audit["status"]=="PASS" and manifest["status"]=="CANDIDATE"
assert audit["counts"]=={"tables":9,"source_rows":208,"parquet_rows":208,"duplicate_key_groups":0,"required_null_key_rows":0,"schema_mismatches":0,"duckdb_view_mismatches":0,"cross_domain_identity_links":0}
assert manifest["base_contract_sha256"]==sha(A/"contracts/storage.v1.json") and manifest["build_spec_sha256"]==sha(A/"contracts/parquet-build.v1.json")
assert len(list((A/"parquet").glob("*.parquet")))==9 and manifest["database_artifact"] is None
artifact_map={x["path"]:x for x in manifest["artifacts"]}
con=duckdb.connect(":memory:")
for table in contract["tables"]:
    path=A/"parquet"/f"{table['table_id']}.parquet"; rel=f"analytics_v1/parquet/{path.name}"
    assert artifact_map[rel]["sha256"]==sha(path)
    arrow=pq.read_table(path); assert arrow.num_rows==table["expected_rows"]
    keys=["\u001f".join(str(row[key]) for key in table["key"]) for row in arrow.to_pylist()]
    assert len(keys)==len(set(keys)) and all("None" not in key for key in keys)
    assert con.execute(f"SELECT count(*) FROM read_parquet('{path.as_posix()}')").fetchone()[0]==table["expected_rows"]
assert contract["reconciliation_law"]["renewable_to_data_centre_identity_links_allowed"] is False
assert audit["domain_boundary"]["identity_bridge_decision"]=="ABSTAIN_NO_AUTHORISED_BRIDGE"
print("PASS independent Parquet verifier: 9 tables / 208 rows / schemas, keys, hashes and DuckDB reads")

Attribution Ledger

A JavaScript module in PipelineNews that appends attributions (`appendAttributions`) and builds charge fixture proof (`buildChargeFixtureProof`), using SHA-256. It normalises attribution (`normaliseAttribution`), appends attributions (`appendAttributions`) and builds charge fixture proof (`buildChargeFixtureProof`).

transformpipelinenews / archive/202608261547-pipelinenews/attributionv1/modules/attribution-ledger.mjs · lines 1–90 of 90 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review)

What it does
It calculates its inputs. Defines 6 functions or classes, including sha256, assertNoPersonKeys, normaliseAttribution, appendAttributions, attributionsFromRegisteredCharge. Uses libraries node:crypto.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 4 files: Discrepancy View (pipelinenews); Register Ingest (pipelinenews); Build Charge Fixture Proof (pipelinenews); Check Batch5 Attribution (pipelinenews).
What it achieves
Defines `sha256`, `assertNoPersonKeys`, `normaliseAttribution` and 3 more.
Why it matters
Imported by Discrepancy View, Register Ingest and Build Charge Fixture Proof. Checked by Check Batch5 Attribution.
Application
pipelinenews · archive/202608261547-pipelinenews/attributionv1/modules · JavaScript module
Uses
node:crypto
Used by
imported by Discrepancy View (import), imported by Register Ingest (import), imported by Build Charge Fixture Proof (import), imported by Check Batch5 Attribution (import)
Produces
normaliseAttribution, appendAttributions, attributionsFromRegisteredCharge, buildChargeFixtureProof
Defines here
sha256, assertNoPersonKeys, normaliseAttribution, appendAttributions, attributionsFromRegisteredCharge, buildChargeFixtureProof
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/attributionv1/modules/attribution-ledger.mjs:1-90 · blob d49c16d6959c0149db1ea576d32d722b6cff5b29 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
import { createHash } from "node:crypto";

const allowedRoles = new Set(["DEVELOPER", "OWNER", "EPC", "PRINCIPAL_CONTRACTOR", "ICP", "OM_PROVIDER", "LENDER", "TECHNICAL_ADVISER"]);
const allowedStatuses = new Set(["CONFIRMED", "REPORTED", "ABSTAIN"]);
const forbiddenKeys = /(^|_)(person|individual|officer|name_of_person)($|_)/iu;
const sha256 = (value) => createHash("sha256").update(value).digest("hex");

function assertNoPersonKeys(value, path = "row") {
  if (!value || typeof value !== "object") return;
  for (const [key, child] of Object.entries(value)) {
    if (forbiddenKeys.test(key)) throw new Error(`person-keyed field forbidden at ${path}.${key}`);
    assertNoPersonKeys(child, `${path}.${key}`);
  }
}

export function normaliseAttribution(input) {
  assertNoPersonKeys(input);
  if (!String(input.repd_ref ?? "").match(/^\d+$/u)) throw new Error("numeric repd_ref required");
  const expectedProjectId = `GG2050-REPD-${input.repd_ref}`;
  if (input.gg_project_id !== expectedProjectId) throw new Error("canonical project ID mismatch");
  if (!allowedRoles.has(input.role)) throw new Error(`unsupported role: ${input.role}`);
  if (!allowedStatuses.has(input.claim_status)) throw new Error(`unsupported claim status: ${input.claim_status}`);
  if (!String(input.organisation ?? "").trim()) throw new Error("organisation required");
  const url = new URL(input.evidence_url);
  if (url.protocol !== "https:") throw new Error("evidence URL must use HTTPS");
  const credibility = Number(input.credibility);
  if (!(credibility > 0 && credibility <= 1)) throw new Error("credibility must be in (0, 1]");
  if (input.claim_status === "CONFIRMED" && credibility < 0.7) throw new Error("CONFIRMED requires tier-one or tier-two evidence");
  const identity = `${expectedProjectId}\n${input.role}\n${String(input.organisation).trim()}\n${url.toString()}\n${input.observed_at}`;
  return {
    attribution_id: `PN-ATTR-${sha256(identity).slice(0, 20).toUpperCase()}`,
    repd_ref: String(input.repd_ref),
    gg_project_id: expectedProjectId,
    role: input.role,
    organisation: String(input.organisation).trim(),
    company_number: input.company_number ? String(input.company_number) : null,
    effective_from: input.effective_from ?? null,
    effective_to: input.effective_to ?? null,
    evidence_url: url.toString(),
    evidence_domain: url.hostname.toLowerCase(),
    evidence_kind: input.evidence_kind,
    credibility,
    observed_at: input.observed_at,
    claim_status: input.claim_status
  };
}

export function appendAttributions(existing, incoming) {
  const rows = [...existing, ...incoming].map(normaliseAttribution);
  const byId = new Map();
  for (const row of rows) if (!byId.has(row.attribution_id)) byId.set(row.attribution_id, row);
  return [...byId.values()].sort((left, right) => left.gg_project_id.localeCompare(right.gg_project_id, "en", { numeric: true }) || left.role.localeCompare(right.role) || left.observed_at.localeCompare(right.observed_at) || left.attribution_id.localeCompare(right.attribution_id));
}

export function attributionsFromRegisteredCharge(project, charge) {
  if (charge.source_domain !== "find-and-update.company-information.service.gov.uk") throw new Error("registered-charge source must be the official company register");
  if (!Array.isArray(charge.persons_entitled) || !charge.persons_entitled.length) return [];
  return charge.persons_entitled.map((organisation) => normaliseAttribution({
    repd_ref: project.repd_ref,
    gg_project_id: project.gg_project_id,
    role: "LENDER",
    organisation,
    company_number: charge.company_number,
    effective_from: charge.created_on,
    effective_to: null,
    evidence_url: charge.evidence_url,
    evidence_kind: "REGISTERED_CHARGE_NAMED_SECURED_PARTY",
    credibility: 1,
    observed_at: charge.observed_at,
    claim_status: "CONFIRMED"
  }));
}

export function buildChargeFixtureProof(fixture) {
  if (fixture.schema !== "pipelinenews.attribution-charge-fixture.v1" || fixture.fixture_only !== true) throw new Error("fixture marker required");
  const roles = attributionsFromRegisteredCharge(fixture.project, fixture.charge);
  return {
    schema: "pipelinenews.attribution-charge-fixture-proof.v1",
    fixture_only: true,
    counts: { roles: roles.length, confirmed: roles.filter((row) => row.claim_status === "CONFIRMED").length },
    roles,
    interpretation: {
      named_secured_party_confirmed: true,
      registered_charge_date_confirmed: true,
      financial_close_inferred_from_charge_alone: false
    }
  };
}

export { allowedRoles, allowedStatuses };

Discrepancy View

A JavaScript module in PipelineNews that builds discrepancy fixture proof (`buildDiscrepancyFixtureProof`). It builds discrepancy fixture proof (`buildDiscrepancyFixtureProof`).

transformpipelinenews / archive/202608261547-pipelinenews/attributionv1/modules/discrepancy-view.mjs · lines 1–38 of 38 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review) · pattern count (shared by 27 files)

What it does
It calculates its inputs. Defines buildDiscrepancyView, buildDiscrepancyFixtureProof, count.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: Build Discrepancy Fixture Proof (pipelinenews); Check Batch7 Product (pipelinenews).
What it achieves
Defines `buildDiscrepancyView`, `buildDiscrepancyFixtureProof` and `count`.
Why it matters
Imported by Build Discrepancy Fixture Proof. Checked by Check Batch7 Product.
Application
pipelinenews · archive/202608261547-pipelinenews/attributionv1/modules · JavaScript module
Uses
Attribution Ledger (import)
Used by
imported by Build Discrepancy Fixture Proof (import), imported by Check Batch7 Product (import)
Produces
buildDiscrepancyView, buildDiscrepancyFixtureProof
Defines here
buildDiscrepancyView, buildDiscrepancyFixtureProof, count
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/attributionv1/modules/discrepancy-view.mjs:1-38 · blob 86773f03b3d16b8937690840fe03d09a3a9ede58 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
import { appendAttributions } from "./attribution-ledger.mjs";

export function buildDiscrepancyView(rawRoles, projects) {
  const roles = appendAttributions([], rawRoles);
  const projectById = new Map(projects.map((project) => [project.gg_project_id, project]));
  const confirmed = roles.filter((row) => row.claim_status === "CONFIRMED");
  return roles.filter((row) => row.claim_status === "REPORTED").map((reported) => {
    const comparable = confirmed.filter((row) => row.gg_project_id === reported.gg_project_id && row.role === reported.role);
    const consistent = comparable.some((row) => row.organisation === reported.organisation);
    const status = !comparable.length ? "NO_CONFIRMED_RECORD" : consistent ? "CONSISTENT" : "CONFLICTS_WITH_CONFIRMED";
    const project = projectById.get(reported.gg_project_id);
    return {
      discrepancy_id: `${reported.attribution_id}-VIEW`,
      gg_project_id: reported.gg_project_id,
      project_name: project?.name ?? null,
      role: reported.role,
      reported_organisation: reported.organisation,
      reported_source: reported.evidence_url,
      reported_at: reported.observed_at,
      confirmed_records: comparable.map((row) => ({ organisation: row.organisation, evidence_url: row.evidence_url, observed_at: row.observed_at })),
      project_state_at_claim: project?.lifecycle ?? "UNKNOWN",
      status
    };
  }).sort((left, right) => left.gg_project_id.localeCompare(right.gg_project_id, "en", { numeric: true }) || left.role.localeCompare(right.role) || left.reported_organisation.localeCompare(right.reported_organisation));
}

export function buildDiscrepancyFixtureProof(fixture) {
  if (fixture.schema !== "pipelinenews.attribution-discrepancy-fixture.v1" || fixture.fixture_only !== true) throw new Error("fixture marker required");
  const rows = buildDiscrepancyView(fixture.roles, fixture.projects);
  const count = (status) => rows.filter((row) => row.status === status).length;
  return {
    schema: "pipelinenews.attribution-discrepancy-fixture-proof.v1",
    fixture_only: true,
    counts: { rows: rows.length, consistent: count("CONSISTENT"), conflicts_with_confirmed: count("CONFLICTS_WITH_CONFIRMED"), no_confirmed_record: count("NO_CONFIRMED_RECORD") },
    rows,
    publication_law: { descriptive_status_only: true, allegation_or_person_assessment: false, source_links_retained: true }
  };
}