In this section
- Build Payload render · pipelinenews / tools/intelligence/cartridges/wider-fleet/build_payload.py lines 1–259
- Make Cartridge render · pipelinenews / tools/intelligence/cartridges/withdraw-nonanswers/make_cartridge.py lines 1–189
- PipelineNews — Intelligence ingest · pipelinenews / tools/intelligence/common.py lines 1–176
- Reconcile Provisional storage · pipelinenews / tools/intelligence/reconcile-provisional.mjs lines 1–41
Build Payload
A Python command-line tool in the wider fleet folder of PipelineNews that reads wider fleet, the Renewable Energy Planning Database (REPD) register, postcodes and wind.
renderpipelinenews / tools/intelligence/cartridges/wider-fleet/build_payload.py · lines 1–259 of 259 · Entry point · pattern report (shared by 21 files)
- What it does
- It loads wider fleet, the REPD register, postcodes and wind. Defines 7 functions or classes, including norm, megawatts, load_csv_index, resolve, build. Uses libraries argparse, csv, io, json, os. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- 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, postcodes, wind.
- Inputs & outputs
- In: JSON file wider-fleet.json; command-line arguments. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It loads CSV index (`load_csv_index`) and is built from the norm step (`norm`) and the megawatts step (`megawatts`). Build the WIDER FLEET payload: every REPD technology type the Pipeline News spine does not carry, with its REPD reference. It accepts `--register`, `--repd-csv` and `--out`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- pipelinenews · tools/intelligence/cartridges/wider-fleet · Python CLI
- Uses
- argparse, csv, io, json, os, re, sys, collections
- Used by
- none found
- Produces
- norm, megawatts, load_csv_index, resolve, build, report, main
- Defines here
- norm, megawatts, load_csv_index, resolve, build, report, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/wider-fleet/build_payload.py:1-259 · blob 916ed86fdf10f82f0f754d35e63f38466a37c2a6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
Build the WIDER FLEET payload: every REPD technology type the Pipeline News
spine does not carry, with its REPD reference.
WHY THE REFERENCE MATTERS
-------------------------
GridAtlas resolves an arrival by REPD ref and nothing else
(identity_rule: EXACT_REPD_REF_ONLY). A MAP link without one lands with
status ABSENT, and the place-search cartridge returns before its flyTo --
so the card opens, the substation measurement runs off the link's own
coordinates, and the camera never moves. The project is on screen only if
you happen to already be looking at it. Watched live on 2026-09-02 for
Rainham Phase II: correct card, correct 1.426 km measurement, camera still
at [-3.5, 54.0].
The first cut of this payload came from repd_master.json, whose properties
are name, operator, tech, raw_tech, status, capacity and mounting -- no
reference of any kind, because repd_updaterv8.py never reads one from the
REPD CSV. So the ref is joined back on here, from the same CSV that
produced the register.
THE JOIN, AND WHY IT IS NOT A REBUILD
-------------------------------------
The register keeps its own geodesy and its own classification: the CSV
carries OSGB36 eastings and northings, and reprojecting them here would be
a second implementation of both. Only identity and locality are taken from
the CSV, matched onto rows the register already produced:
1. site name + technology type + installed capacity (unique)
2. site name + technology type, capacity ignored (when 1 found none)
3. ... narrowed by operator (when several)
4. ... then by development status (when still several)
Tier 2 exists because the register and the CSV disagree on capacity for 120
of these rows; a decimal place is not an identity. It still requires the
site name AND the technology type to match, and still requires the result
to be unique.
Anything still ambiguous, or absent from the CSV, gets no reference. It is
left null and the MAP link for that row carries no ref, exactly as before.
A guessed identity is worse than a missing one: it would point the Atlas at
a different project and every measurement on the card would be about the
wrong site.
TOWN is deliberately not populated. There is no town column in the REPD;
the field the spine calls "town" is the planning authority, and putting an
authority under a TOWN heading would be a quiet lie.
Usage:
python build_payload.py --register dist/repd_master.json \
--repd-csv repd.csv --out site/
Outputs:
<out>/wider-fleet.json the register cut, one row per project
<out>/wider-fleet-report.txt what was carried and what was not
"""
import argparse
import csv
import io
import json
import os
import re
import sys
from collections import Counter, defaultdict
# The four REPD technology types the pipeline spine already carries. Anything
# outside this set is this payload's scope. Named in the REPD's own vocabulary
# so the boundary is checkable against the source, not against a nickname.
SPINE_TYPES = {
"Solar Photovoltaics",
"Battery",
"Wind Onshore",
"Wind Offshore",
}
def norm(value):
return re.sub(r"\s+", " ", (value or "").strip()).lower()
def megawatts(value):
try:
return round(float(value), 3)
except (TypeError, ValueError):
return None
def load_csv_index(path):
"""Index the REPD extract by name+technology+capacity, and by name+technology.
The capacity-free index is not a loosening. The register's capacity and the
CSV's disagree on 120 of these rows -- the register carries a rounded or a
later figure -- and without a second index every one of them lost its
identity to a decimal place.
"""
with_capacity = defaultdict(list)
without_capacity = defaultdict(list)
with io.open(path, encoding="utf-8-sig", errors="replace") as handle:
for row in csv.DictReader(handle):
if not (row.get("Ref ID") or "").strip():
continue
name = norm(row.get("Site Name"))
technology = norm(row.get("Technology Type"))
with_capacity[(name, technology,
megawatts(row.get("Installed Capacity (MWelec)")))].append(row)
without_capacity[(name, technology)].append(row)
return with_capacity, without_capacity
def resolve(index, props):
"""Return (csv_row, how) or (None, why-not). Never guesses."""
with_capacity, without_capacity = index
name = norm(props.get("name"))
technology = norm(props.get("raw_tech"))
candidates = with_capacity.get((name, technology, megawatts(props.get("capacity"))), [])
if not candidates:
# Same site, same technology, one row: the capacity is the only thing
# that disagreed, and a decimal place is not an identity.
loose = without_capacity.get((name, technology), [])
if len(loose) == 1:
return loose[0], "name+technology, capacity differs"
if not loose:
return None, "absent"
candidates = loose
if len(candidates) == 1:
return candidates[0], "name+technology+capacity"
by_operator = [r for r in candidates
if norm(r.get("Operator (or Applicant)")) == norm(props.get("operator"))]
if len(by_operator) == 1:
return by_operator[0], "narrowed by operator"
pool = by_operator or candidates
by_status = [r for r in pool
if norm(r.get("Development Status (short)")) == norm(props.get("status"))]
if len(by_status) == 1:
return by_status[0], "narrowed by status"
return None, "ambiguous"
def build(register_path, csv_path):
with open(register_path, encoding="utf-8") as handle:
document = json.load(handle)
features = document.get("features", document)
index = load_csv_index(csv_path) if csv_path else None
rows, how, skipped = [], Counter(), 0
for feature in features:
props = feature.get("properties") or {}
raw = (props.get("raw_tech") or "Unknown").strip()
if raw in SPINE_TYPES:
continue
coordinates = (feature.get("geometry") or {}).get("coordinates") or []
if len(coordinates) < 2:
skipped += 1
continue
match, reason = (resolve(index, props) if index else (None, "no csv supplied"))
how[reason] += 1
row = {
"n": props.get("name") or "",
"o": props.get("operator") or "",
"t": props.get("tech") or "other",
"rt": raw,
"s": props.get("status") or "",
"c": megawatts(props.get("capacity")) or 0.0,
"ll": [round(float(coordinates[0]), 5), round(float(coordinates[1]), 5)],
}
if match:
row["ref"] = (match.get("Ref ID") or "").strip()
county = (match.get("County") or "").strip()
postcode = (match.get("Post Code") or "").strip()
if county:
row["cty"] = county
if postcode:
row["pc"] = postcode
rows.append(row)
rows.sort(key=lambda r: -r["c"])
return rows, how, skipped
def report(rows, how, skipped):
counts, power = Counter(), defaultdict(float)
for row in rows:
counts[row["rt"]] += 1
power[row["rt"]] += row["c"]
referenced = sum(1 for r in rows if r.get("ref"))
lines = ["WIDER FLEET BUILD", "",
"%-42s %6s %13s %s" % ("REPD TECHNOLOGY TYPE", "N", "MW", "WITH REF")]
for name, count in counts.most_common():
with_ref = sum(1 for r in rows if r["rt"] == name and r.get("ref"))
lines.append("%-42s %6d %13s %d" % (name, count, format(power[name], ",.1f"), with_ref))
lines += ["", "identity resolution against the REPD extract"]
for reason, count in how.most_common():
lines.append(" %-34s %d" % (reason, count))
lines += [
"",
"tabs (REPD technology types) : %d" % len(counts),
"projects : %d" % len(rows),
"capacity : %.2f GW" % (sum(r["c"] for r in rows) / 1000),
"with a REPD reference : %d of %d (%.1f%%)"
% (referenced, len(rows), 100.0 * referenced / max(1, len(rows))),
"without one, MAP unresolved : %d" % (len(rows) - referenced),
"with county : %d" % sum(1 for r in rows if r.get("cty")),
"with postcode : %d" % sum(1 for r in rows if r.get("pc")),
"dropped, no coordinates : %d" % skipped,
"spine types excluded : %s" % ", ".join(sorted(SPINE_TYPES)),
]
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--register", required=True,
help="repd_master.json produced by repd_updaterv8.py")
parser.add_argument("--repd-csv", required=True,
help="the DESNZ REPD extract the register was built from")
parser.add_argument("--out", required=True, help="output directory")
parser.add_argument("--min-types", type=int, default=15,
help="fail the build below this many technology types")
parser.add_argument("--min-referenced", type=float, default=90.0,
help="fail the build below this %% of rows carrying a REPD ref")
args = parser.parse_args()
rows, how, skipped = build(args.register, args.repd_csv)
if not rows:
sys.exit("no wider-fleet rows: register empty, or every type is in the spine")
types = len({row["rt"] for row in rows})
if types < args.min_types:
sys.exit("only %d technology types, expected at least %d -- "
"the register or the spine boundary has moved" % (types, args.min_types))
referenced = 100.0 * sum(1 for r in rows if r.get("ref")) / len(rows)
if referenced < args.min_referenced:
sys.exit("only %.1f%% of rows carry a REPD reference, expected at least %.1f%% -- "
"the CSV and the register have drifted apart"
% (referenced, args.min_referenced))
os.makedirs(args.out, exist_ok=True)
with open(os.path.join(args.out, "wider-fleet.json"), "w", encoding="utf-8") as handle:
json.dump(rows, handle, separators=(",", ":"))
text = report(rows, how, skipped)
with open(os.path.join(args.out, "wider-fleet-report.txt"), "w", encoding="utf-8") as handle:
handle.write(text + "\n")
print(text)
if __name__ == "__main__":
main()Make Cartridge
A Python command-line tool in the withdraw nonanswers folder of PipelineNews that works with line containing (`line_containing`), covering the Renewable Energy Planning Database (REPD) register.
renderpipelinenews / tools/intelligence/cartridges/withdraw-nonanswers/make_cartridge.py · lines 1–189 of 189 · Entry point · pattern section (shared by 12 files)
- What it does
- Defines read, once, section, line_containing, main. Uses libraries argparse, io, json, os, sys. Side effects: changes the web page (DOM); starts processes.
- 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.
- Inputs & outputs
- In: JSON file cartridge.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the read step (`read`), the once step (`once`) and the section step (`section`). Withdraw two intelligence panels that answer no defensible user question. Its code works with 1 MW. It accepts `--parent`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- pipelinenews · tools/intelligence/cartridges/withdraw-nonanswers · Python CLI
- Uses
- argparse, io, json, os, sys
- Used by
- none found
- Produces
- read, once, section, line_containing, main
- Defines here
- read, once, section, line_containing, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/withdraw-nonanswers/make_cartridge.py:1-189 · blob a9ac75cf8af48eb360d1f0e3fba2f413dad3793d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Withdraw two intelligence panels that answer no defensible user question.
Relationship Evidence contains three ABSTAIN/NO-join rows. Project Intelligence
mixes window position, planning state, construction state and missing-data
states under "where to look first". Neither helps a user decide anything, and
both were explicitly rejected in the live UI review.
The immutable assets remain registered for provenance. This cartridge removes
their launch surfaces and boot bindings, corrects the 132/136 headline copy,
and makes the one retained Sector topic explicit.
"""
import argparse
import io
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
RELEASES = os.path.join(REPO, "releases")
APP = "assets/202608291447-app.mjs"
SECTOR = "assets/202608312109-sector-intelligence.mjs"
def read(path):
# release_builder normalises the copied release to the LF bytes GitHub
# Pages serves before it applies repairs. Generate anchors against those
# bytes, not against a Windows checkout's CRLF working copy.
return io.open(path, encoding="utf-8", newline="").read().replace("\r\n", "\n")
def once(text, needle, label):
count = text.count(needle)
if count != 1:
raise SystemExit("anchor %r occurs %d times, expected 1" % (label, count))
return needle
def section(text, labelled_by):
start_marker = (
' <section class="meta sector-intelligence-launch" '
'aria-labelledby="%s">' % labelled_by)
start = text.find(start_marker)
if start < 0:
raise SystemExit("section %s not found" % labelled_by)
end_marker = "\n </section>"
end = text.find(end_marker, start)
if end < 0:
raise SystemExit("section %s has no close" % labelled_by)
return text[start:end + len(end_marker)]
def line_containing(text, needle, label):
matches = [line for line in text.splitlines() if needle in line]
if len(matches) != 1:
raise SystemExit("line %r occurs %d times, expected 1" % (label, len(matches)))
return matches[0]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--parent", default="202608312212-pipelinenews")
args = parser.parse_args()
parent = os.path.join(RELEASES, args.parent)
index = read(os.path.join(parent, "index.html"))
app = read(os.path.join(parent, APP))
sector = read(os.path.join(parent, SECTOR))
status_line = line_containing(index, '136 HEADLINES', "static headline total")
release_meta_line = line_containing(
app,
'document.getElementById("releaseMeta").textContent =',
"runtime release meta")
manifest = {
"key": "withdraw_nonanswers",
"summary": (
"Withdraws Relationship and Project Intelligence non-answers and "
"makes the visible news and Sector counts truthful."),
"modifies_existing_dashboard": True,
"modification_note": (
"Removes two rejected launch surfaces and their boot bindings; "
"reports 132 shown headlines, four withheld, and one evidenced "
"Sector topic without claiming the old payload was deleted."),
"registry_repairs": [
{
"key": "relationship_governance_status",
"set": {
"ui_state": "WITHDRAWN",
"ui_withdrawal_reason": (
"Three rows all abstain and assert no join; retained as "
"provenance, not exposed as product intelligence."),
},
},
{
"key": "project_intelligence",
"set": {
"ui_state": "WITHDRAWN",
"ui_withdrawal_reason": (
"The projection mixes incompatible lifecycle and "
"missing-data taxonomies; retained for audit only."),
},
},
],
"repairs": {
"index.html": [
{
"label": "masthead reports the edition actually shown",
"from": status_line,
"to": (' <div class="status">● 132 SHOWN · 47 PROJECT-BOUND '
'· 85 SECTOR · 4 WITHHELD · FULL ≥1 MW</div>'),
},
{
"label": "sector copy no longer repeats the stale 136 total",
"from": once(
index,
"The generic 136-headline newspaper remains separate and unchanged.",
"sector stale headline total"),
"to": "The filtered news edition remains separate and cannot create project identity.",
},
{
"label": "withdraw relationship abstention ledger from the product UI",
"from": section(index, "federatedRelationshipHeading"),
"to": "",
},
{
"label": "withdraw project-intelligence mixed taxonomy from the product UI",
"from": section(index, "projectIntelHeading"),
"to": "",
},
],
"app": [
{
"label": "sector launcher reports one evidenced topic",
"from": once(
app,
'meta.textContent = "WAIT · seven topics · choose one to request the compact Parquet-derived payload";',
"seven-topic sector meta"),
"to": ('meta.textContent = "WAIT · one evidenced topic · choose it to request '
'the compact Parquet-derived payload";'),
},
{
"label": "do not bind the withdrawn relationship non-answer",
"from": once(app, " bindFederatedRelationships();", "relationship boot binding"),
"to": " // Relationship abstention ledger withdrawn from the product UI.",
},
{
"label": "do not bind the withdrawn project mixed taxonomy",
"from": once(app, " bindProjectIntelligence();", "project-intelligence boot binding"),
"to": " // Project mixed-taxonomy panel withdrawn from the product UI.",
},
{
"label": "release meta names only the retained visible surfaces",
"from": release_meta_line,
"to": (' document.getElementById("releaseMeta").textContent = '
'`Live News + evidenced sector intelligence + Atlas V9 deep-link successor '
'· 132 shown headlines · 4 withheld off-topic · ${rows.length.toLocaleString("en-GB")} '
'canonical projects · ${registry.performance.maximum_physical_project_rows} physical rows '
'· TIMESTAMPED RELEASE · POINTER-CONTROLLED`;'),
},
],
"assets": [
{
"path": SECTOR,
"edits": [
{
"label": "sector module describes the filtered edition",
"from": once(
sector,
"Sector context is separate from the 136-headline newspaper and cannot create or alter REPD project identity.",
"sector module stale headline total"),
"to": "Sector context is separate from the filtered news edition and cannot create or alter REPD project identity.",
}
],
}
],
},
}
output = os.path.join(HERE, "cartridge.json")
io.open(output, "w", encoding="utf-8", newline="").write(
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
print("wrote cartridge.json: two panels withdrawn; counts and Sector copy repaired")
return 0
if __name__ == "__main__":
sys.exit(main())PipelineNews — Intelligence
A Python module in the tools folder that loads manifest (`load_manifest`) and partitions (`load_partitions`) and loads records (`load_records`).
ingestpipelinenews / tools/intelligence/common.py · lines 1–176 of 176 · pattern load_partitions (shared by 2 files)
- What it does
- It loads data. Defines 13 functions or classes, including Result, __init__, check, equals, failed. Uses libraries io, json, os, sys, glob. Side effects: reads or writes files; starts processes.
- 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: JSON file 202608261927-build-manifest-v9-1.json.
- Downstream impact
- Used directly by 3 files: V6 Deep Link Cartridge (pipelinenews); V7 Additive Only (pipelinenews); V8 Neutral Surface (pipelinenews).
- What it achieves
- It is built from the result class (`Result`), the check step (`check`) and the equals step (`equals`). Shared helpers for the VERIFIERS suite.
- Why it matters
- Imported by V6 Deep Link Cartridge, V7 Additive Only and V8 Neutral Surface.
- Application
- pipelinenews · tools/intelligence · Python module
- Uses
- io, json, os, sys, glob
- Used by
- imported by V6 Deep Link Cartridge (import), imported by V7 Additive Only (import), imported by V8 Neutral Surface (import)
- Produces
- Result, require, load_manifest, load_partitions, load_records, load_spine, load_fixture
- Defines here
- Result, __init__, check, equals, failed, ok, report, require, load_manifest, load_partitions, load_records, load_spine, load_fixture
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/common.py:1-176 · blob 0d70b825e857ba70d4132f4ebf18ebe03746c041 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Shared helpers for the VERIFIERS suite.
Pure stdlib. No network. No third-party imports. Read-only: nothing in here
writes to any repository. Every verifier imports from this module so that a
path change is made once.
"""
import io
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
BUILD_PLAN = os.path.dirname(HERE)
GRIDATLAS = os.path.dirname(BUILD_PLAN)
GITHUB = os.path.dirname(GRIDATLAS)
EVIDENCE = os.path.join(BUILD_PLAN, "PROJECT-STUDIES", "_evidence")
FIXTURES = os.path.join(HERE, "fixtures")
MANIFEST = os.path.join(
GITHUB, "pipelinenews", "data", "manifests",
"202608261927-build-manifest-v9-1.json")
# The AUTHORITATIVE source: 16 partition files, 480-500 records each.
# Verifiers read these, never a derived artefact, so that a defect in the
# extraction chain shows up as a difference rather than being baked in.
PARTITION_DIR = os.path.join(GITHUB, "pipelinenews", "data", "projects")
PARTITION_GLOB = "202608261927-project-partition-v9-1-*.json"
# Derived artefacts, verified AGAINST the authoritative source above.
RECORDS = os.path.join(EVIDENCE, "records-clean.txt")
SPINE = os.path.join(EVIDENCE, "spine-v3.tsv")
GRIDATLAS_REFS = os.path.join(EVIDENCE, "gridatlas-refs.txt")
# Keys the partition envelope carries around the record array. The last
# record on each line of the derived records-clean.txt is followed by these,
# which is why a strict json.loads on that file fails on exactly 16 lines.
PARTITION_ENVELOPE_KEYS = ("record_count", "release", "schema", "partition")
# Spine TSV column order, as emitted by the extraction chain.
SPINE_COLS = [
"repd_ref", "capacity_mw", "technology", "status", "lifecycle", "name",
"operator", "lpa", "county", "region", "country", "lon", "lat",
"geometry_status", "submitted", "granted", "refused", "expected_op",
"under_construction", "operational", "withdrawn",
]
class Result(object):
"""Accumulates PASS/FAIL checks for one verifier."""
def __init__(self, verifier, title):
self.verifier = verifier
self.title = title
self.checks = []
def check(self, name, ok, expected=None, actual=None, detail=None):
self.checks.append({
"name": name, "ok": bool(ok),
"expected": expected, "actual": actual, "detail": detail,
})
return bool(ok)
def equals(self, name, expected, actual, detail=None):
return self.check(name, expected == actual, expected, actual, detail)
@property
def failed(self):
return [c for c in self.checks if not c["ok"]]
@property
def ok(self):
return not self.failed
def report(self):
head = "%s %s" % (self.verifier, self.title)
print(head)
print("-" * max(len(head), 64))
for c in self.checks:
mark = "PASS" if c["ok"] else "FAIL"
line = " [%s] %s" % (mark, c["name"])
if not c["ok"] or c["expected"] is not None:
line += "\n expected: %r\n actual: %r" % (
c["expected"], c["actual"])
if c["detail"]:
line += "\n %s" % c["detail"]
print(line)
print(" %d checks, %d failed\n" % (len(self.checks), len(self.failed)))
return 0 if self.ok else 1
def require(path, what):
if not os.path.exists(path):
sys.stderr.write("MISSING %s: %s\n" % (what, path))
sys.exit(2)
return path
def load_manifest():
with io.open(require(MANIFEST, "build manifest"), encoding="utf-8") as fh:
return json.load(fh)
def load_partitions():
"""Parse the 16 authoritative partition files.
Returns (records, partitions) where partitions carries each file's
declared record_count, so the envelope can be checked against its contents.
"""
import glob
paths = sorted(glob.glob(os.path.join(PARTITION_DIR, PARTITION_GLOB)))
if not paths:
sys.stderr.write("MISSING partitions: %s\n"
% os.path.join(PARTITION_DIR, PARTITION_GLOB))
sys.exit(2)
records, partitions = [], []
for path in paths:
with io.open(path, encoding="utf-8") as fh:
doc = json.load(fh)
rows = doc.get("projects") or []
records.extend(rows)
partitions.append({
"file": os.path.basename(path),
"declared": doc.get("record_count"),
"actual": len(rows),
"release": doc.get("release"),
"schema": doc.get("schema"),
})
return records, partitions
def load_records():
"""Records from the derived records-clean.txt, one per line.
Uses raw_decode rather than json.loads: the last record on each partition
is followed by the partition envelope (record_count / release / schema),
which is trailing content, not a truncated record. Returns
(records, bad_lines, trailers) so a caller can assert that the only
trailing content is the expected envelope and that there are exactly as
many trailers as partitions.
"""
decoder = json.JSONDecoder()
records, bad, trailers = [], [], []
with io.open(require(RECORDS, "clean records"), encoding="utf-8") as fh:
for n, line in enumerate(fh, 1):
line = line.strip()
if not line:
continue
try:
obj, end = decoder.raw_decode(line)
except ValueError as exc:
bad.append((n, str(exc), line[:80]))
continue
records.append(obj)
rest = line[end:].strip()
if rest:
trailers.append((n, rest))
return records, bad, trailers
def load_spine():
rows = []
with io.open(require(SPINE, "spine tsv"), encoding="utf-8") as fh:
for line in fh:
line = line.rstrip("\n")
if not line:
continue
rows.append(line.split("\t"))
return rows
def load_fixture(name):
path = require(os.path.join(FIXTURES, name), "fixture")
with io.open(path, encoding="utf-8") as fh:
return json.load(fh)Reconcile Provisional
A JavaScript module in the intelligence folder of PipelineNews that reads project register, using SHA-256.
storagepipelinenews / tools/intelligence/reconcile-provisional.mjs · lines 1–41 of 41 · Entry point
- What it does
- It loads project register. Uses libraries node:fs, node:crypto. Side effects: reads or writes files; starts processes.
- 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: JSON file project-register.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: Register Quarter Test (pipelinenews); PipelineNews BBC RSS Discovery Workflow (pipelinenews).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by PipelineNews BBC RSS Discovery Workflow. Checked by Register Quarter Test.
- Application
- pipelinenews · tools/intelligence · JavaScript module
- Uses
- Provisional Identity (import), Register Source (import), Register Delta (import), node:fs, node:crypto
- Used by
- run by Register Quarter Test (script call), run by PipelineNews BBC RSS Discovery Workflow (workflow run)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/reconcile-provisional.mjs:1-41 · blob aaa6b0bc786c1df91788c632141a9e38c292b568 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {readFileSync,writeFileSync,existsSync,renameSync} from 'node:fs';
import {createHash} from 'node:crypto';
import {reconcileProvisional} from '../../cartridges/provisional-identity.mjs';
import {resolveRegister,decodeProjects,validatePayload,listReleases} from './register-source.mjs';
import {computeDelta,operatorAliases} from './register-delta.mjs';
const registerPath='data/provisional/project-register.json';
if(!existsSync(registerPath)){console.log('No provisional register');process.exit(0);}
// usage: node tools/intelligence/reconcile-provisional.mjs [<projects payload path> | --release <id>]
// Default: the newest release's REGISTERED projects asset (registry assets.projects,
// digest-checked). The old default searched the release folder for
// "*-v8-fast-projects.json", which picks the inherited Q2 payload in a release whose
// register was replaced (202611132345 carries both; its registry names the Q3 one).
const args=process.argv.slice(2);
let source,official,delta=null;
if(args[0] && args[0]!=='--release'){
const path=args[0],bytes=readFileSync(path),data=JSON.parse(bytes);
validatePayload(data);
source={path,sha256:createHash('sha256').update(bytes).digest('hex')};
official=decodeProjects(data);
}else{
const next=resolveRegister('.',{release:args[0]==='--release'?args[1]:undefined});
source={path:next.path,sha256:next.sha256};
official=decodeProjects(next.payload);
// Previous distinct register, for operator renames and the safety gate.
for(const release of listReleases('.').filter(id=>id<next.release).reverse()){
let previous;try{previous=resolveRegister('.',{release});}catch{continue;}
if(previous.sha256===next.sha256)continue;
delta=computeDelta(decodeProjects(previous.payload),official,{previous,next});break;
}
if(delta?.gate.status==='HOLD'){
console.log(JSON.stringify({source,gate:delta.gate,action:'register unchanged; new quarter held for review'}));
process.exit(0);
}
}
const register=JSON.parse(readFileSync(registerPath));
const result={...register,projects:reconcileProvisional(register.projects,official,source,{operatorAliases:delta?operatorAliases(delta):new Map()})};
const body=JSON.stringify(result,null,2)+'\n';
if(body!==readFileSync(registerPath,'utf8').replaceAll('\r\n','\n')){
const temporary=registerPath+'.tmp';writeFileSync(temporary,body);renameSync(temporary,registerPath);
}
console.log(JSON.stringify({source,gate:delta?.gate.status??'NOT_EVALUATED',delta:delta?.counts??null,pending:result.projects.filter(p=>!p.official_repd_ref).length,matched:result.projects.filter(p=>p.official_repd_ref).length}));