In this section
- Release Builder automation · pipelinenews / tools/intelligence/release_builder.py lines 701–1084
- Release Hash Guard automation · pipelinenews / tools/intelligence/release_hash_guard.py lines 1–74
- Render Proof interaction · pipelinenews / tools/intelligence/render_proof.mjs lines 1–140
Release Builder
A Python command-line tool in the intelligence folder of PipelineNews that reads cartridge and the Renewable Energy Planning Database (REPD) register, using SHA-256.
automationpipelinenews / tools/intelligence/release_builder.py · lines 701–1084 of 1084 (continued from section 1050) · Entry point · pattern refresh_sha256_sidecars (shared by 2 files)
- What it does
- It loads cartridge and the REPD register. Defines 27 functions or classes, including utc_stamp, sha256_file, sha256_published, published_bytes, published_size. Uses libraries argparse, atexit, contextlib, datetime, hashlib. 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. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file 202608291447-registry.json; JSON file build-manifest.json; JSON file cartridge.json; JSON file release-manifest.json; command-line arguments.
- Downstream impact
- Used directly by 6 files: Shift (pipelinenews); Build 30x Ledger (pipelinenews); Run Pages Candidate Gate (pipelinenews); PipelineNews Build Intelligence Release Workflow (pipelinenews); and 2 more. Reached from 1 other entry point, including PipelineNews Pages Routing Candidate Workflow (pipelinenews).
- What it achieves
- It normalises lf (`normalise_to_lf`), refreshes sha256 sidecars (`refresh_sha256_sidecars`) and refreshes build manifest (`refresh_build_manifest`). PipelineNews release builder — one timestamp, one discovery cartridge. It accepts `--list`, `--from` and `--cartridge`.
- Why it matters
- Run by 6 workflows and scripts, including Shift, Build 30x Ledger and Run Pages Candidate Gate.
- Application
- pipelinenews · tools/intelligence · Python CLI
- Uses
- argparse, atexit, contextlib, datetime, hashlib, io, json, os
- Used by
- run by Shift (script call), run by Build 30x Ledger (script call), run by Run Pages Candidate Gate (script call), run by PipelineNews Build Intelligence Release Workflow (workflow run), run by PipelineNews Map Corpus Contract Workflow (workflow run), run by PipelineNews Pages Workflow (workflow run)
- Produces
- utc_stamp, sha256_file, sha256_published, published_bytes, published_size, read, write, walk, normalise_to_lf, refresh_sha256_sidecars, refresh_build_manifest, apply_once
- Defines here
- sub, cmd_check, 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/release_builder.py:701-1084 · blob 205733aac1f4b07778836fb2cefa43b4ac3c7226 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
stamped["{GEN}"] = gen
def sub(text):
for k, v in stamped.items():
text = text.replace(k, v)
return text
# ---- 1. copy the cartridge's own files -------------------------------
print(" new files")
added = []
for sub_dir in ("assets", "data"):
src_dir = os.path.join(pkg, sub_dir)
if not os.path.isdir(src_dir):
continue
for name in sorted(os.listdir(src_dir)):
dest_name = sub(name)
src_file = os.path.join(src_dir, name)
dst_file = os.path.join(target, sub_dir, dest_name)
# {GEN} must be substituted in CONTENT as well as in filenames.
# The cartridge declares its own generation, and app.mjs asserts
# cartridge.CONTRACT.generation === entry.generation before it will
# mount. Leaving the placeholder in the body ships a panel that
# throws on open and shows "unavailable" — caught by render_proof.
if os.path.splitext(name)[1].lower() in TEXT_EXT:
body = io.open(src_file, encoding="utf-8", newline="").read()
transformed = False
if "{GEN}" in body:
body = sub(body)
transformed = True
# Compose the target switch with generation substitution.
# The old early `continue` made --atlas-target unreachable for
# any module that also contained {GEN}; a manifest could claim
# "ported" while its executable still emitted legacy URLs.
if (atlas_target and name.endswith('.mjs')
and 'const ACTIVE_TARGET' in body):
body = re.sub(r'const ACTIVE_TARGET = "\w+"',
'const ACTIVE_TARGET = "%s"' % atlas_target,
body)
transformed = True
print(' (atlas target set to %s)' % atlas_target)
if transformed:
write(dst_file, body)
added.append("%s/%s" % (sub_dir, dest_name))
print(" %s (text build inputs applied)" % added[-1])
continue
shutil.copyfile(src_file, dst_file)
added.append("%s/%s" % (sub_dir, dest_name))
print(" %s" % added[-1])
# The parent tree was normalised at line 290, but the cartridge's own files
# arrive AFTER that, straight from a working copy that Windows checks out
# with CRLF. They then get hashed as they lie, so sha256sums.txt and the
# registry attest CRLF bytes while GitHub Pages serves the LF ones git
# stored. Measured on a clean build of 202608312036: the pointer asset's
# recorded digest was 2c0eb0e0 and its published digest 9923acba.
#
# The browser hashes what the server sends, so the release must attest that.
# Normalising again here, before any digest is taken, is the whole fix.
normalise_to_lf(target)
# ---- 2. index.html : the UI section, plus any declared repairs --------
print("\n index.html")
idx = read(os.path.join(target, "index.html"))
for rep in man.get("repairs", {}).get("index.html", []):
idx = apply_once(idx, sub(rep["from"]), sub(rep["to"]), rep["label"],
rep.get("expect", 1))
if man.get("section"):
idx = apply_once(idx, ANALYTICS_ANCHOR, sub(man["section"]) + ANALYTICS_ANCHOR,
"UI section for %s" % key)
idx = apply_once(idx, "<title>", "<title>", "title tag present", idx.count("<title>"))
write(os.path.join(target, "index.html"), idx)
# ---- 3. app.mjs : loader, plus any declared repairs -------------------
print("\n %s" % APP)
app = read(os.path.join(target, APP))
for rep in man.get("repairs", {}).get("app", []):
app = apply_once(app, sub(rep["from"]), sub(rep["to"]), rep["label"],
rep.get("expect", 1))
if man.get("loader"):
app = apply_once(app, "async function boot() {",
sub(man["loader"]) + "async function boot() {",
"loader for %s" % key)
app = apply_once(app, BOOT_BIND_ANCHOR,
"%s\n %s" % (BOOT_BIND_ANCHOR, sub(man["bind_call"])),
"bind call in boot()")
write(os.path.join(target, APP), app)
# ---- 3b. any other shipped asset -------------------------------------
# index.html and app.mjs were the only files a cartridge could repair, so a
# fault living in a supplemental module -- the grid proximity dashboard,
# say -- could not be corrected by a cartridge at all. It is the same
# operation on a different path, and the path is declared and checked
# rather than free: it must stay inside the release directory.
for rep in man.get("repairs", {}).get("assets", []):
rel = rep["path"]
full = os.path.normpath(os.path.join(target, rel))
if not full.startswith(os.path.normpath(target) + os.sep):
raise SystemExit("asset repair escaped the release: %s" % rel)
if not os.path.exists(full):
raise SystemExit("asset repair target missing: %s" % rel)
print("\n %s" % rel)
text = read(full)
for one in rep["edits"]:
text = apply_once(text, sub(one["from"]), sub(one["to"]),
one["label"], one.get("expect", 1))
write(full, text)
# ---- 4. registry -----------------------------------------------------
print("\n %s" % REGISTRY)
reg_path = os.path.join(target, REGISTRY)
reg = json.loads(read(reg_path))
# A cartridge that only repairs shipped files registers nothing: there is no
# new asset to attest. Requiring an entry forced such a cartridge to invent
# one, which would put a fictitious asset in the registry to satisfy the
# builder. The repairs are recorded in the build manifest either way.
if "registry_entry" in man:
entry = json.loads(sub(json.dumps(man["registry_entry"])))
for ref in man.get("hash_fields", []):
node, rel_path = entry, sub(ref["path"])
for step in ref["at"][:-1]:
node = node[step]
abs_path = os.path.join(target, rel_path)
node[ref["at"][-1]] = sha256_file(abs_path)
node["bytes"] = os.path.getsize(abs_path)
if key in reg.get("supplemental_assets", {}):
raise SystemExit("registry already carries %s" % key)
reg.setdefault("supplemental_assets", {})[key] = entry
else:
print(" no registry entry: this cartridge only repairs shipped files")
core_replaced = None
if "registry_core" in man:
core_replaced = apply_registry_core(target, reg, man["registry_core"], sub)
# A registered asset may be retained for provenance while its launcher is
# withdrawn from a later release. Record that state explicitly; otherwise
# the verifier cannot distinguish a deliberate withdrawal from a broken
# host or missing boot binding. Registry repairs are restricted to this
# small UI-state vocabulary and cannot rewrite asset identity or digests.
#
# The vocabulary started at withdrawal alone, and that was too narrow the
# first time a cartridge changed the SHAPE of a surface instead of removing
# it. wider-fleet-dropdown replaced twenty appended tabs with one select;
# the registry entry it inherited went on saying
# "tabs_in_product_technology_row": true and "appends twenty buttons to
# #tech", and neither could be corrected. A published attestation that
# describes a control the release does not draw is worse than no
# attestation, because it is the file a reader checks the UI against.
# These fields are descriptive only: none of them names a path, a digest,
# a byte count, a generation or a schema, so the identity guarantee this
# restriction exists to protect is untouched.
allowed_registry_repairs = {
"ui_state", "ui_withdrawal_reason",
"control_in_product_technology_row", "deep_linkable", "mutation_scope",
"presentation", "tabs_in_product_technology_row",
}
for repair in man.get("registry_repairs", []):
other_key = repair.get("key")
other = (reg.get("supplemental_assets") or {}).get(other_key)
if not isinstance(other, dict):
raise SystemExit("registry repair target missing: %s" % other_key)
updates = repair.get("set") or {}
forbidden = sorted(set(updates) - allowed_registry_repairs)
if forbidden:
raise SystemExit("registry repair fields forbidden for %s: %s"
% (other_key, forbidden))
for field, value in updates.items():
other[field] = value
print(" %s UI state -> %s" % (other_key, other.get("ui_state", "unchanged")))
# Every INHERITED cartridge entry still carries the parent's digest, and
# the parent's digest was taken from a Windows working copy holding CRLF.
# normalise_to_lf has since rewritten those files to the LF bytes that
# actually ship, so the inherited digests now describe bytes no one will
# ever receive. Measured on 202608311610: the registry claims
# grid-proximity.mjs is 34,239 bytes (3265e118...), the file on the server
# is 33,541 (8703fce7...). The build manifest is already re-derived after
# normalisation for exactly this reason; the registry never was.
print(" re-deriving inherited digests after LF normalisation")
for other_key, other in sorted((reg.get("supplemental_assets") or {}).items()):
for kind in ("cartridge", "payload"):
node = other.get(kind)
if not isinstance(node, dict) or "path" not in node:
continue
abs_path = os.path.join(target, node["path"])
if not os.path.exists(abs_path):
continue
digest, size = sha256_published(abs_path), published_size(abs_path)
if node.get("sha256") != digest or node.get("bytes") != size:
print(" %s.%s %s -> %s" % (other_key, kind,
str(node.get("sha256"))[:12], digest[:12]))
node["sha256"], node["bytes"] = digest, size
# record_count is the same kind of claim as sha256 and bytes: a statement
# about the file at `path`. It was not re-derived, so a cartridge that ships
# a longer payload under an inherited filename left the registry announcing
# the old count for the new file - the registry describing a file no one will
# ever receive, which is the exact defect the block above exists to fix.
# Derived, never repaired: `record_count` is deliberately absent from
# allowed_registry_repairs, because a count a cartridge can assert is a count
# that can disagree with the payload.
if kind == "payload" and "record_count" in node:
# An unparseable payload is a worse problem than a stale count, and
# swallowing it would leave the registry asserting the inherited number
# over a file nobody can read - neither a failure nor a correction.
try:
doc = json.loads(read(abs_path))
except ValueError as exc:
raise SystemExit("payload will not parse, so its record_count cannot "
"be derived: %s (%s)" % (node["path"], exc))
counted = None
if isinstance(doc, dict):
# Exactly one list-of-records, named or not. Taking the FIRST such
# list in dict order would count whichever key the JSON happens to
# put first, so a payload carrying both `rows` and `sources` would
# produce a confidently wrong number rather than no number. Ambiguity
# must fail loudly, not resolve itself by insertion order.
candidates = [k for k, v in doc.items()
if isinstance(v, list) and v and isinstance(v[0], dict)]
if len(candidates) > 1:
raise SystemExit(
"cannot derive record_count for %s: %d candidate row lists "
"(%s). Name the field rather than trusting key order."
% (node["path"], len(candidates), ", ".join(sorted(candidates))))
counted = (len(doc[candidates[0]]) if candidates
else doc.get("record_count"))
elif isinstance(doc, list):
counted = len(doc)
if isinstance(counted, int) and node.get("record_count") != counted:
print(" %s.%s record_count %s -> %s"
% (other_key, kind, node.get("record_count"), counted))
node["record_count"] = counted
write(reg_path, json.dumps(reg, indent=2, ensure_ascii=False) + "\n")
print(" supplemental_assets.%s" % key)
# ---- 5. manifests ----------------------------------------------------
print("\n manifests")
rel = json.loads(read(os.path.join(target, "release-manifest.json")))
rel.update({
"schema": "pipelinenews.additive-cartridge-release.v1",
"generation": gen,
"release_id": release_id,
"parent_release_id": parent_id,
"classification": ("DASHBOARD_MODIFYING_CARTRIDGE"
if man.get("modifies_existing_dashboard")
else "ADDITIVE_DISCOVERY_CARTRIDGE"),
"cartridge_added": key,
"cartridges_present": sorted(reg["supplemental_assets"].keys()),
# Hard-coding False was true while every cartridge was a self-contained
# panel. A cartridge that patches the table renderer is not additive,
# and a manifest that says it is would be the one place a reader goes
# to find out. The cartridge declares it; the manifest records it.
"existing_dashboard_modified": bool(man.get("modifies_existing_dashboard")),
"existing_dashboard_modification": man.get("modification_note") or None,
"generation_source": "read from UTC clock at build time, never chosen",
"rollback": "build again with --from an earlier release; nothing is edited in place",
"immutable_after_publication": True,
"deployment": "not-authorised",
"runtime_verified": False,
})
if atlas_target:
rel["atlas_target"] = atlas_target
if core_replaced:
rel["registry_core_replaced"] = core_replaced
write(os.path.join(target, "release-manifest.json"),
json.dumps(rel, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
print(" release-manifest.json")
refresh_sha256_sidecars(target)
refresh_build_manifest(target, release_id)
files = [f for f in walk(target) if f != "sha256sums.txt"]
write(os.path.join(target, "sha256sums.txt"),
"".join("%s %s\n" % (sha256_published(os.path.join(target, f)), f) for f in files))
print(" sha256sums.txt (%d files)" % len(files))
# ---- 6. the parent must be untouched ---------------------------------
after = {p: sha256_file(os.path.join(parent, p)) for p in walk(parent)}
if after != before:
raise SystemExit("FAIL: the parent release changed. That must never happen.")
print("\n %s unchanged (%d files, byte-for-byte)" % (parent_id, len(after)))
# ---- 7. the release must pass its own check ---------------------------
# `--check` existed from the beginning and nothing ran it. Six releases
# shipped with a digest that does not describe their own bytes, and each of
# them would have been caught here, at the one moment when the answer is
# still "build it again" rather than "it is immutable now".
#
# A failure leaves build_ok False, so the atexit handler above discards the
# partial release. That is deliberate: a release that cannot verify itself
# must not exist, because --list will offer it as a parent and every later
# build will inherit whatever was wrong with it.
print("\n ---- proving the release against itself ----\n")
if cmd_check(release_id) != 0:
raise SystemExit("FAIL: %s does not pass its own --check. Nothing shipped."
% release_id)
build_ok["done"] = True
print("\nBuilt %s" % release_id)
print(" unhappy with it? python release_builder.py --from %s --cartridge <other>"
% parent_id)
return 0
# --------------------------------------------------------------------- check
def cmd_check(release_id):
target = os.path.join(RELEASES, release_id)
if not os.path.isdir(target):
raise SystemExit("no such release: %s" % target)
print("Checking %s\n" % release_id)
ok = True
listed = {}
for line in io.open(os.path.join(target, "sha256sums.txt"), encoding="utf-8"):
digest, name = line.rstrip("\n").split(" ", 1)
listed[name] = digest
actual = {f for f in walk(target) if f != "sha256sums.txt"}
bad = [n for n, d in listed.items()
if n in actual and sha256_published(os.path.join(target, n)) != d]
for label, items in (("unlisted files", sorted(actual - set(listed))),
("listed but absent", sorted(set(listed) - actual)),
("digest mismatch", bad)):
print(" [%s] %-20s %s" % ("PASS" if not items else "FAIL", label,
"none" if not items else items[:4]))
ok &= not items
reg = json.loads(read(os.path.join(target, REGISTRY)))
ok &= check_registry_core(target, reg)
idx = read(os.path.join(target, "index.html"))
app = read(os.path.join(target, APP))
for key, entry in sorted((reg.get("supplemental_assets") or {}).items()):
for kind in ("cartridge", "payload"):
node = entry.get(kind)
if not node or "path" not in node:
continue
p = os.path.join(target, node["path"])
good = os.path.exists(p) and sha256_published(p) == node.get("sha256")
print(" [%s] %s.%s digest" % ("PASS" if good else "FAIL", key, kind))
ok &= good
withdrawn = entry.get("ui_state") == "WITHDRAWN"
host = entry.get("host_id")
if host:
present = ('id="%s"' % host) in idx
good = (not present) if withdrawn else present
expectation = "absent after withdrawal" if withdrawn else "present in UI"
print(" [%s] %s host %s" % ("PASS" if good else "FAIL", key, expectation))
ok &= good
bind = entry.get("bind_call")
if bind:
wired = bind in app
good = (not wired) if withdrawn else wired
expectation = "absent after withdrawal" if withdrawn else "wired in boot()"
print(" [%s] %s loader %s" % ("PASS" if good else "FAIL", key, expectation))
ok &= good
print()
return 0 if ok else 1
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--list", action="store_true", help="show rollback points and cartridges")
ap.add_argument("--from", dest="parent", help="parent release id to build from")
ap.add_argument("--cartridge", help="cartridge package name under cartridges/")
ap.add_argument("--gen", help="12-digit generation (default: current UTC minute)")
ap.add_argument("--atlas-target", choices=["legacy", "ported"],
help="record which atlas this release points at")
ap.add_argument("--check", help="verify an existing release")
ap.add_argument("--applicable", metavar="PARENT",
help="report which cartridges can actually be built onto PARENT")
a = ap.parse_args()
if a.list:
return cmd_list()
if a.check:
return cmd_check(a.check)
if a.applicable:
return cmd_applicable(a.applicable)
if a.parent and a.cartridge:
return cmd_build(a.parent, a.cartridge, a.gen or utc_stamp(), a.atlas_target)
ap.print_help()
return 1
if __name__ == "__main__":
sys.exit(main())Release Hash Guard
A Python command-line tool in the intelligence folder of PipelineNews that uses SHA-256. It is built from the digest step (`digest`) and the tree step (`tree`).
automationpipelinenews / tools/intelligence/release_hash_guard.py · lines 1–74 of 74 · Entry point · pattern digest (shared by 56 files)
- What it does
- It loads data. Defines digest, tree, main. Uses libraries argparse, hashlib, os, sys. 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: command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- No truncation of previous work: every existing release byte must survive. It accepts `--repo`, `--snapshot` and `--verify`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- pipelinenews · tools/intelligence · Python CLI
- Uses
- argparse, hashlib, os, sys
- Used by
- none found
- Produces
- digest, tree, main
- Defines here
- digest, tree, 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/release_hash_guard.py:1-74 · blob a06d8fab36750f42e713eab031ce437352f1ce27 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""No truncation of previous work: every existing release byte must survive.
python release_hash_guard.py --snapshot before.sha256
... build a release ...
python release_hash_guard.py --verify before.sha256 --allow-new 202611132345-pipelinenews
--snapshot writes `sha256 path` for every file under releases/. --verify
recomputes them and fails if any recorded file changed or disappeared, or if
a file appeared anywhere other than inside the --allow-new release folders.
Stdlib only, read-only on releases/.
"""
import argparse
import hashlib
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(HERE))
def digest(path):
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def tree(root):
out = {}
base = os.path.join(root, "releases")
for d, _dirs, names in os.walk(base):
for n in names:
full = os.path.join(d, n)
out[os.path.relpath(full, root).replace(os.sep, "/")] = digest(full)
return out
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument("--repo", default=REPO)
g = ap.add_mutually_exclusive_group(required=True)
g.add_argument("--snapshot")
g.add_argument("--verify")
ap.add_argument("--allow-new", action="append", default=[])
a = ap.parse_args(argv)
now = tree(a.repo)
if a.snapshot:
with open(a.snapshot, "w", encoding="utf-8", newline="\n") as fh:
for path in sorted(now):
fh.write("%s %s\n" % (now[path], path))
print("snapshot: %d files" % len(now))
return 0
before = {}
with open(a.verify, encoding="utf-8") as fh:
for line in fh:
d, p = line.rstrip("\n").split(" ", 1)
before[p] = d
allowed = tuple("releases/%s/" % r for r in a.allow_new)
changed = sorted(p for p in before if p in now and now[p] != before[p])
missing = sorted(p for p in before if p not in now)
added = sorted(p for p in now if p not in before)
stray = [p for p in added if not p.startswith(allowed)]
for label, items in (("changed", changed), ("missing", missing), ("unexpected new", stray)):
print(" [%s] %-15s %s" % ("PASS" if not items else "FAIL", label,
"none" if not items else items[:5]))
print(" %d recorded files verified, %d new files inside %s"
% (len(before) - len(changed) - len(missing), len(added) - len(stray), list(a.allow_new) or "-"))
return 1 if (changed or missing or stray) else 0
if __name__ == "__main__":
sys.exit(main())Render Proof
A JavaScript module in the intelligence folder of PipelineNews that renders proof for the project-intelligence cartridge.
interactionpipelinenews / tools/intelligence/render_proof.mjs · lines 1–140 of 140 · Entry point
- What it does
- It loads data. Defines El, ok. Uses libraries node:fs/promises, node:path, node:url. 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.
- Inputs & outputs
- In: JSON file 202608291447-registry.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: PipelineNews Build Intelligence Release Workflow (pipelinenews).
- What it achieves
- Its name says it renders proof.
- Why it matters
- Run by PipelineNews Build Intelligence Release Workflow.
- Application
- pipelinenews · tools/intelligence · JavaScript module
- Uses
- node:fs/promises, node:path, node:url
- Used by
- run by PipelineNews Build Intelligence Release Workflow (workflow run)
- Produces
- El, ok
- Defines here
- El, ok
- 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/render_proof.mjs:1-140 · blob f0cd94c887a6bfaacc958b6928137071688f4e51 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
* Render proof for the project-intelligence cartridge.
*
* node render_proof.mjs <release-id>
*
* The cartridge has never been exercised. This mounts it against a minimal DOM
* and the real payload, then opens every tab and asserts each produced markup
* containing figures that match the data.
*
* It is NOT a browser. It does not prove layout, CSS, or that a human can read
* the result. It proves the code runs, the loader contract holds, the payload
* parses, and every tab renders real numbers rather than throwing.
*
* No network. Reads the release directory only.
*/
import { readFile } from "node:fs/promises";
import { join, resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const HERE = resolve(fileURLToPath(import.meta.url), "..");
const RELEASES = resolve(HERE, "..", "..", "releases");
const releaseId = process.argv[2];
if (!releaseId) {
console.error("usage: node render_proof.mjs <release-id>");
process.exit(2);
}
const root = join(RELEASES, releaseId);
const registry = JSON.parse(await readFile(join(root, "data", "202608291447-registry.json"), "utf8"));
const entry = registry.supplemental_assets?.project_intelligence;
if (!entry?.cartridge?.path || !entry?.payload?.path) {
throw new Error("project-intelligence registry entry is missing");
}
const gen = entry.generation;
// ---- minimal DOM ---------------------------------------------------------
class El {
constructor(tag) {
this.tagName = String(tag).toUpperCase();
this.children = [];
this.attributes = {};
this.style = { cssText: "" };
this.dataset = {};
this._html = "";
this._text = "";
this.classList = {
_s: new Set(),
add: (c) => this.classList._s.add(c),
remove: (c) => this.classList._s.delete(c),
toggle: (c, on) => (on ? this.classList._s.add(c) : this.classList._s.delete(c)),
contains: (c) => this.classList._s.has(c),
};
this._listeners = {};
}
set className(v) { for (const c of String(v).split(/\s+/)) if (c) this.classList._s.add(c); }
get className() { return [...this.classList._s].join(" "); }
set innerHTML(v) { this._html = String(v); this.children = []; }
get innerHTML() { return this._html; }
set textContent(v) { this._text = String(v); }
get textContent() { return this._text; }
setAttribute(k, v) { this.attributes[k] = String(v); }
getAttribute(k) { return this.attributes[k]; }
appendChild(c) { this.children.push(c); return c; }
addEventListener(t, fn) { (this._listeners[t] ||= []).push(fn); }
click() { for (const fn of this._listeners.click || []) fn({}); }
/** Everything this node and its descendants rendered. */
collect() {
return this._html + this._text + this.children.map((c) => c.collect()).join("");
}
}
globalThis.HTMLElement = El;
globalThis.document = { createElement: (t) => new El(t) };
// ---- the real payload, served through the cartridge's own fetch path ------
const payloadPath = join(root, entry.payload.path);
const payloadText = await readFile(payloadPath, "utf8");
let fetchCalls = 0;
globalThis.fetch = async (url) => {
fetchCalls += 1;
if (!String(url).includes("project-intelligence")) throw new Error("unexpected fetch " + url);
return { ok: true, status: 200, json: async () => JSON.parse(payloadText) };
};
// ---- mount ---------------------------------------------------------------
const mod = await import("file://" + join(root, entry.cartridge.path).replace(/\\/g, "/"));
const contract = mod.PROJECT_INTELLIGENCE_CARTRIDGE_CONTRACT;
const host = new El("div");
const checks = [];
const ok = (name, pass, detail) => checks.push({ name, pass: Boolean(pass), detail });
ok("contract generation matches registry", contract.generation === gen, `${contract.generation} vs ${gen}`);
ok("contract declares additive_only", contract.additive_only === true);
ok("contract declares mutates_existing_dom false", contract.mutates_existing_dom === false);
const result = mod.mountProjectIntelligence({
host,
payloadAsset: { url: entry.payload.path },
});
ok("mount requests NO payload", result.payloadRequests === 0, `payloadRequests=${result.payloadRequests}`);
ok("mount creates no bindings", result.projectBindings === 0);
ok("no fetch happened at mount", fetchCalls === 0, `fetchCalls=${fetchCalls}`);
ok("host received children", host.children.length > 0, `${host.children.length} nodes`);
// The tab buttons live in the first child (the news-tools strip).
const tools = host.children[0];
const buttons = tools.children;
ok("five tabs rendered", buttons.length === 5, `${buttons.length} buttons: ${buttons.map((b) => b._html).join(", ")}`);
// ---- open every tab ------------------------------------------------------
const payload = JSON.parse(payloadText);
const expected = String(payload.record_count.toLocaleString("en-GB"));
for (const btn of buttons) {
const label = btn._html;
const before = fetchCalls;
btn.click();
await new Promise((r) => setTimeout(r, 0));
await new Promise((r) => setTimeout(r, 0));
const html = host.collect();
ok(`tab ${label}: rendered markup`, html.length > 400, `${html.length} chars`);
ok(`tab ${label}: contains a bar or a table`, /class="bar"|<table|<div style=/.test(html));
ok(`tab ${label}: no undefined/NaN leaked`, !/undefined|NaN/.test(html),
(html.match(/.{0,40}(undefined|NaN).{0,40}/) || [])[0]);
if (label === "OVERVIEW") {
ok("OVERVIEW shows the real record count", html.includes(expected), `expected ${expected}`);
}
if (before === 0) ok("payload fetched exactly once, on first tab", fetchCalls === 1, `fetchCalls=${fetchCalls}`);
}
ok("payload never re-fetched across all five tabs", fetchCalls === 1, `fetchCalls=${fetchCalls}`);
// ---- report --------------------------------------------------------------
let failed = 0;
for (const c of checks) {
if (!c.pass) failed += 1;
console.log(` ${c.pass ? "PASS" : "FAIL"} ${c.name}${c.detail && !c.pass ? ` -> ${c.detail}` : ""}`);
}
console.log(`\n ${checks.length} checks, ${failed} failed`);
process.exit(failed ? 1 : 0);