In this section
- Sector Render Proof interaction · pipelinenews / tools/intelligence/sector_render_proof.mjs lines 1–114
- Serve storage · pipelinenews / tools/intelligence/serve.mjs lines 1–93
- Surface Truth Proof ingest · pipelinenews / tools/intelligence/surface_truth_proof.mjs lines 1–49
- V6 Deep Link Cartridge other · pipelinenews / tools/intelligence/v6_deep_link_cartridge.py lines 1–145
- V7 Additive Only render · pipelinenews / tools/intelligence/v7_additive_only.py lines 1–167
Sector Render Proof
A JavaScript module in the intelligence folder of PipelineNews. It is built from the check step (`check`).
interactionpipelinenews / tools/intelligence/sector_render_proof.mjs · lines 1–114 of 114 · Entry point
- What it does
- It loads data. Defines El, check. 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
- Mount the registered Sector Intelligence cartridge against its real payload.
- 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, check
- Defines here
- El, 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 tools/intelligence/sector_render_proof.mjs:1-114 · blob f204881958c63dcc0135828acaabd6e1638252b7 · 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 node
/**
* Mount the registered Sector Intelligence cartridge against its real payload.
*
* This is deliberately registry-driven: a later timestamp can inherit an
* older immutable module and payload. A release directory's timestamp is not
* the identity of every asset inside it.
*/
import { readFile } from "node:fs/promises";
import { join, resolve } 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 sector_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?.sector_intelligence_clean
|| registry.supplemental_assets?.sector_intelligence;
if (!entry?.cartridge?.path || !entry?.payload?.path) {
throw new Error("sector-intelligence registry entry is missing");
}
class El {
constructor(tag) {
this.tagName = String(tag).toUpperCase();
this.children = [];
this.attributes = {};
this.dataset = {};
this.style = {};
this.className = "";
this.textContent = "";
this.hidden = false;
this._listeners = {};
}
setAttribute(name, value) { this.attributes[name] = String(value); }
getAttribute(name) { return this.attributes[name]; }
appendChild(child) { this.children.push(child); return child; }
append(...children) { this.children.push(...children); }
replaceChildren(...children) { this.children = children; }
addEventListener(type, listener) { (this._listeners[type] ||= []).push(listener); }
collectText() { return [this.textContent, ...this.children.map((child) => child.collectText())].join(" "); }
}
globalThis.HTMLElement = El;
globalThis.document = {
head: new El("head"),
createElement: (tag) => new El(tag),
createTextNode: (text) => Object.assign(new El("#text"), { textContent: String(text) }),
querySelector: () => null,
};
const payloadBytes = await readFile(join(root, entry.payload.path));
let fetchCalls = 0;
globalThis.fetch = async (url) => {
fetchCalls += 1;
if (String(url) !== entry.payload.path) throw new Error(`unexpected fetch ${url}`);
const arrayBuffer = payloadBytes.buffer.slice(
payloadBytes.byteOffset,
payloadBytes.byteOffset + payloadBytes.byteLength,
);
return { ok: true, status: 200, arrayBuffer: async () => arrayBuffer };
};
const moduleUrl = "file://" + join(root, entry.cartridge.path).replace(/\\/g, "/");
const mod = await import(moduleUrl);
const contract = mod.SECTOR_INTELLIGENCE_CARTRIDGE_CONTRACT;
const host = new El("div");
const result = mod.mountSectorIntelligence({
host,
payloadAsset: { ...entry.payload, url: entry.payload.path },
});
const checks = [];
const check = (name, pass, detail = "") => checks.push({ name, pass: Boolean(pass), detail });
check("module contract matches registry generation",
contract.generation === entry.generation,
`${contract.generation} vs ${entry.generation}`);
check("mount requests no payload", result.payloadRequests === 0, `requests=${result.payloadRequests}`);
check("mount performs no fetch", fetchCalls === 0, `fetches=${fetchCalls}`);
check("only one evidenced topic is exposed", result.buttons.size === 1, `tabs=${result.buttons.size}`);
check("the exposed topic is DATA_CENTRES", result.buttons.has("DATA_CENTRES"));
check("withheld topics are absent from the controls",
![...result.buttons].some(([code]) => code !== "DATA_CENTRES"));
await result.select("DATA_CENTRES");
check("first selection fetches exactly once", fetchCalls === 1, `fetches=${fetchCalls}`);
check("nine evidenced rows render", result.list.children.length === 9,
`rows=${result.list.children.length}`);
check("status reports successful landed readback",
result.status.dataset.sectorStatus === "OK" && /9 rows/.test(result.status.textContent),
result.status.textContent);
check("rendered cards contain data-centre evidence",
/data centre/i.test(result.list.collectText()));
await result.select("DATA_CENTRES");
check("repeat selection does not refetch", fetchCalls === 1, `fetches=${fetchCalls}`);
let failures = 0;
for (const item of checks) {
if (!item.pass) failures += 1;
console.log(` ${item.pass ? "PASS" : "FAIL"} ${item.name}`
+ `${!item.pass && item.detail ? ` -> ${item.detail}` : ""}`);
}
console.log(`\n ${checks.length} checks, ${failures} failed`);
process.exit(failures ? 1 : 0);Serve
A JavaScript module in the intelligence folder of PipelineNews.
storagepipelinenews / tools/intelligence/serve.mjs · lines 1–93 of 93 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Uses libraries node:http, node:fs/promises, node:path, node:url. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- 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.
- What it achieves
- Minimal static server for reviewing a PipelineNews release locally.
- Why it matters
- No other file in the estate was found to import it.
- Application
- pipelinenews · tools/intelligence · JavaScript module
- Uses
- node:http, node:fs/promises, node:path, node:url
- 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 tools/intelligence/serve.mjs:1-93 · blob 954a27bafff5de47aa9161ad4a517166be15c8d1 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* Minimal static server for reviewing a pipelinenews release locally.
*
* node serve.mjs serve the newest release
* node serve.mjs 202608311314-pipelinenews
* node serve.mjs <release> 9000 on a specific port
*
* The app is an ES module that fetches six relative paths, so it cannot run
* from file:// - the browser blocks module loading and fetch on that scheme.
* It needs an HTTP origin, which is all this provides.
*
* Localhost only, read-only, no dependencies, no network access outbound.
* Stop it with Ctrl+C. Nothing is written to disk.
*/
import { createServer } from "node:http";
import { readFile, stat, readdir } from "node:fs/promises";
import { join, extname, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
const HERE = resolve(fileURLToPath(import.meta.url), "..");
const RELEASES = resolve(HERE, "..", "..", "releases");
const TYPES = {
".html": "text/html; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".css": "text/css; charset=utf-8",
".parquet": "application/octet-stream",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
};
const args = process.argv.slice(2);
const port = Number(args.find((a) => /^\d+$/.test(a))) || 8787;
let release = args.find((a) => !/^\d+$/.test(a));
if (!release) {
const dirs = (await readdir(RELEASES, { withFileTypes: true }))
.filter((d) => d.isDirectory() && /^\d{12}-pipelinenews$/.test(d.name))
.map((d) => d.name)
.sort();
release = dirs[dirs.length - 1];
if (!release) {
console.error("no release directories found in", RELEASES);
process.exit(1);
}
}
const root = join(RELEASES, release);
try {
await stat(join(root, "index.html"));
} catch {
console.error("not a release (no index.html):", root);
process.exit(1);
}
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://localhost");
let rel = decodeURIComponent(url.pathname);
if (rel === "/") rel = "/index.html";
// Path traversal guard: the resolved target must stay under root.
const target = resolve(join(root, rel));
if (target !== root && !target.startsWith(root + sep)) {
res.writeHead(403).end("forbidden");
console.log(`403 ${rel}`);
return;
}
const body = await readFile(target);
res.writeHead(200, {
"content-type": TYPES[extname(target).toLowerCase()] || "application/octet-stream",
"cache-control": "no-store",
});
res.end(body);
console.log(`200 ${rel} (${body.length} bytes)`);
} catch (error) {
res.writeHead(error.code === "ENOENT" ? 404 : 500).end(String(error.code || error));
console.log(`${error.code === "ENOENT" ? 404 : 500} ${req.url}`);
}
});
server.listen(port, "127.0.0.1", () => {
console.log(`\n serving ${release}`);
console.log(` from ${root}`);
console.log(`\n OPEN: http://localhost:${port}/\n`);
console.log(" Ctrl+C to stop. Watch this log: every fetch the app makes appears here,");
console.log(" so a 404 tells you immediately which asset is missing.\n");
});Surface Truth Proof
A JavaScript module in the intelligence folder of PipelineNews that verifies that the shipped UI exposes only the retained, truthful surfaces.
ingestpipelinenews / tools/intelligence/surface_truth_proof.mjs · lines 1–49 of 49 · Entry point
- What it does
- It loads data. Uses libraries node:fs/promises, node:path. 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
- Used directly by 1 file: PipelineNews Build Intelligence Release 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 Build Intelligence Release Workflow.
- Application
- pipelinenews · tools/intelligence · JavaScript module
- Uses
- node:fs/promises, node:path
- Used by
- run by PipelineNews Build Intelligence Release 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/surface_truth_proof.mjs:1-49 · blob bcf90c391b4bc4f6ae67829906be06792054c592 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/** Verify that the shipped UI exposes only the retained, truthful surfaces. */
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
const releaseId = process.argv[2];
if (!releaseId) {
console.error("usage: node surface_truth_proof.mjs <release-id>");
process.exit(2);
}
const root = resolve("releases", releaseId);
const [index, app, sector, proximity] = await Promise.all([
readFile(resolve(root, "index.html"), "utf8"),
readFile(resolve(root, "assets/202608291447-app.mjs"), "utf8"),
readFile(resolve(root, "assets/202608312109-sector-intelligence.mjs"), "utf8"),
readFile(resolve(root, "assets/202608311610-grid-proximity.mjs"), "utf8"),
]);
const checks = [
["masthead reports 132 shown and four withheld",
/132 SHOWN/.test(index) && /4 WITHHELD/.test(index)],
["stale 136-headline copy is absent",
!/136 HEADLINES|136-headline/.test(index + sector)],
["Relationship Evidence launcher is absent",
!/federatedRelationshipOpen|RELATIONSHIP EVIDENCE/.test(index)],
["Project Intelligence launcher is absent",
!/projectIntelOpen|PROJECT INTELLIGENCE/.test(index)],
["withdrawn panels are not bound during boot",
!/^\s*bindFederatedRelationships\(\);\s*$/mu.test(app)
&& !/^\s*bindProjectIntelligence\(\);\s*$/mu.test(app)],
["Sector launcher reports one evidenced topic",
/WAIT · one evidenced topic/.test(app)],
["release meta names evidenced sector intelligence",
/Live News \+ evidenced sector intelligence \+ Atlas V9/.test(app)],
["connection-quality verdict is absent",
!/best-connected|target acquired/i.test(proximity)
&& !/data-band=/i.test(index + app + proximity)],
];
let failures = 0;
for (const [label, pass] of checks) {
if (!pass) failures += 1;
console.log(` ${pass ? "PASS" : "FAIL"} ${label}`);
}
console.log(`\n ${checks.length} checks, ${failures} failed`);
process.exit(failures ? 1 : 0);V6 Deep Link Cartridge
A Python command-line tool in the intelligence folder of PipelineNews.
otherpipelinenews / tools/intelligence/v6_deep_link_cartridge.py · lines 1–145 of 145 · Entry point
- What it does
- It lists and searches its content. Defines main. Uses libraries io, os, re, sys. Side effects: 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.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- V6 - static checks on the atlas deep-link cartridge.
- 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
- PipelineNews — Intelligence (import), io, os, re, sys
- Used by
- none found
- Produces
- main
- Defines here
- 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/v6_deep_link_cartridge.py:1-145 · blob 2744d62920f3a26e82535c95a9f92d720a8e4d6d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""V6 - static checks on the atlas deep-link cartridge.
SCOPE, STATED HONESTLY
----------------------
There is no JavaScript runtime on this machine, so the cartridge's own
selfTest() has NOT been executed. This verifier reads the module as text and
checks the properties that can be established without running it.
That is genuinely weaker. It proves the broken shapes are gone and the
contract is coherent; it does NOT prove the emitted URL is correct at runtime.
BEFORE PROMOTING, RUN: node -e "import('./202608311304-atlas-pointer-deep-link.mjs')
.then(m => console.log(m.selfTest()))"
and require ok === true. V6 is a gate, not a substitute for that.
Read-only. No network.
"""
import io
import os
import re
import sys
from common import Result
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(HERE))
CARTRIDGE = os.environ.get("CARTRIDGE_MJS", "")
# The seven parameters the known-good legacy link carries.
REQUIRED_PARAMS = ["repd_ref", "project", "technology", "capacity_mw",
"latitude", "longitude", "zoom"]
# The exact shape that 404s. It must not appear anywhere in the successor.
BROKEN_PATH = "/gridatlas/202608300453-atlas-v9/"
BROKEN_TEMPLATE = "/gridatlas/${GRIDATLAS_RECEIVER.release_id}/"
def main():
res = Result("V6", "Atlas deep-link cartridge - static checks (runtime test NOT run)")
if not os.path.exists(CARTRIDGE):
res.check("cartridge exists", False, "present", "absent", CARTRIDGE)
return res.report()
src = io.open(CARTRIDGE, encoding="utf-8").read()
# 1. The broken path must be gone from the emitted contract. It may still
# appear inside the header comment that explains the fix, so the check
# is scoped to the code below the comment block.
code = src.split("*/", 1)[-1]
res.equals("broken 404 path absent from cartridge code", 0, code.count(BROKEN_PATH),
"the pinned release path that 404s")
res.equals("broken hardcoded pathname template absent", 0, src.count(BROKEN_TEMPLATE),
"the predecessor's invariant asserted the broken shape and pinned it in place")
# 2. The invariant must validate against the receiver's own declared
# pathname rather than a hardcoded template.
res.check("route invariant compares against RECEIVER.pathname",
"receiverUrl.pathname === RECEIVER.pathname" in src,
"RECEIVER.pathname", "found" if "RECEIVER.pathname" in src else "missing")
# 3. Every declared target must be internally consistent: the pathname it
# declares must actually be the pathname of the base_url it declares.
# Scoped to the ATLAS_TARGETS block only - scanning the whole file also
# matches the unrelated `eligibility: Object.freeze({...})` literal.
m_block = re.search(r'const ATLAS_TARGETS = Object\.freeze\(\{(.*?)\n\}\);', src, re.S)
res.check("ATLAS_TARGETS block is present", bool(m_block))
targets = re.findall(r'(\w+):\s*Object\.freeze\(\{(.*?)\n \}\)',
m_block.group(1) if m_block else "", re.S)
res.check("at least two receiver targets are declared",
len(targets) >= 2, ">= 2", len(targets))
for name, body in targets:
m_base = re.search(r'base_url:\s*\n?\s*"([^"]+)"', body)
m_path = re.search(r'pathname:\s*"([^"]+)"', body)
if not (m_base and m_path):
res.check("[%s] declares base_url and pathname" % name, False,
"both", "missing one")
continue
base, path = m_base.group(1), m_path.group(1)
# Derive the path from the URL without a URL parser: everything from
# the third slash onward.
derived = "/" + base.split("://", 1)[1].split("/", 1)[1]
res.equals("[%s] declared pathname matches its base_url" % name, derived, path)
res.check("[%s] base_url is HTTPS" % name, base.startswith("https://"),
"https://", base[:8])
res.check("[%s] base_url ends in a slash" % name, base.endswith("/"),
"trailing slash", base[-1])
# 4. ACTIVE_TARGET must name a target that actually exists.
m_active = re.search(r'const ACTIVE_TARGET = "(\w+)"', src)
res.check("ACTIVE_TARGET is declared", bool(m_active), "declared",
m_active.group(1) if m_active else "absent")
if m_active:
names = [t[0] for t in targets]
res.check("ACTIVE_TARGET names a declared receiver",
m_active.group(1) in names, names, m_active.group(1))
# 5. The payload. This is the regression that started all of it.
m_order = re.search(r'QUERY_PARAMETER_ORDER = Object\.freeze\(\[(.*?)\]\)', src, re.S)
res.check("QUERY_PARAMETER_ORDER is declared", bool(m_order))
if m_order:
declared = re.findall(r'"(\w+)"', m_order.group(1))
res.equals("all seven payload parameters are declared",
REQUIRED_PARAMS, declared,
"matches the known-good legacy link")
for param in REQUIRED_PARAMS:
res.check("searchParams sets '%s'" % param,
('searchParams.set("%s"' % param) in src,
"set", "found" if ('searchParams.set("%s"' % param) in src else "MISSING")
# 6. The eligibility gate must survive. It is what guarantees that
# latitude and longitude exist whenever a link is emitted at all.
res.check("eligibility gate still requires geometry_status valid",
'field: "geometry_status"' in src and 'equals: "valid"' in src)
res.check("identity is still numeric-only",
'/^\\d+$/u.test(repdRef)' in src, "numeric guard", "present"
if '/^\\d+$/u.test(repdRef)' in src else "MISSING")
res.check("EXACT_PROJECT_REPD_REF match semantics unchanged",
'inbound_match_semantics: "EXACT_PROJECT_REPD_REF"' in src)
# 7. Coordinates must be emitted as a pair, never half.
res.check("latitude and longitude are gated on both being present",
"latitude !== null && longitude !== null" in src,
"paired guard", "present" if "latitude !== null && longitude !== null" in src
else "MISSING")
# 8. The cartridge must not be promotable by accident.
res.check("cartridge declares deployment: not-authorised",
'deployment: "not-authorised"' in src)
# 9. A runtime self-test must at least EXIST, so the stronger gate is
# available to whoever has a JS runtime.
res.check("runtime selfTest() is exported for the promotion gate",
"export function selfTest()" in src)
res.check("RUNTIME SELF-TEST HAS NOT BEEN EXECUTED (no JS runtime here)",
True, "acknowledged", "acknowledged",
"run node before promoting; V6 alone is not sufficient")
return res.report()
if __name__ == "__main__":
sys.exit(main())V7 Additive Only
A Python command-line tool in the intelligence folder of PipelineNews that uses SHA-256.
renderpipelinenews / tools/intelligence/v7_additive_only.py · lines 1–167 of 167 · Entry point
- What it does
- It fetches data. Defines main. Uses libraries io, os, re, sys, json. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- 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.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- V7 - the project-intelligence cartridge must be ADDITIVE ONLY.
- 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
- PipelineNews — Intelligence (import), io, os, re, sys, json
- Used by
- none found
- Produces
- main
- Defines here
- 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/v7_additive_only.py:1-167 · blob fa694e4dfc20c493702f6193d4399e3f6d3783ab · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""V7 - the project-intelligence cartridge must be ADDITIVE ONLY.
Why this exists
---------------
The design freeze 202608311304 has one rule: the existing dashboard is not
modified. New features live inside their own cartridge host and nowhere else.
That rule is easy to state and easy to break by accident - one
document.querySelector outside the host, one stray style injection, one
listener on window, and the cartridge is reaching into the frozen design.
This verifier reads the cartridge as text and fails if it can reach anything
outside the host element it was handed.
SCOPE: static. There is no JavaScript runtime on this machine, so the cartridge
has not been executed. These checks prove it does not CONTAIN the means to
touch the rest of the page; they do not prove it renders correctly.
Read-only. No network.
"""
import io
import os
import re
import sys
from common import Result
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(HERE))
CARTRIDGE = os.environ.get("PANEL_MJS", "")
REGISTRY = os.environ.get("REGISTRY_ENTRY", "")
# Anything that reaches outside the host element it was handed.
ESCAPE_HATCHES = [
("document.querySelector", "selects arbitrary elements on the page"),
("document.querySelectorAll", "selects arbitrary elements on the page"),
("document.getElementById", "selects an element outside the host"),
("document.body", "reaches the page body"),
("document.head", "reaches the document head"),
("document.write", "rewrites the document"),
("window.addEventListener", "listens on the window"),
("document.addEventListener", "listens on the document"),
("localStorage", "persists state outside the page"),
("sessionStorage", "persists state outside the page"),
("insertAdjacentHTML", "can inject outside the host"),
("document.styleSheets", "mutates existing styles"),
("<style", "injects a stylesheet"),
("classList.add(\"active\")", None), # placeholder, refined below
]
# Contract flags that must be present and true.
REQUIRED_TRUE = ["additive_only", "asserts_no_personal_data", "derived_values_are_inferred"]
REQUIRED_FALSE = ["mutates_existing_dom", "eligible_for_news_signal",
"corroboration_adapters_built"]
def main():
res = Result("V7", "Project-intelligence cartridge - additive only (static)")
if not os.path.exists(CARTRIDGE):
res.check("cartridge exists", False, "present", "absent", CARTRIDGE)
return res.report()
src = io.open(CARTRIDGE, encoding="utf-8").read()
# Strip block comments so the doc header explaining the rules does not
# trip the checks that enforce them.
code = re.sub(r"/\*.*?\*/", "", src, flags=re.S)
code = re.sub(r"^\s*//.*$", "", code, flags=re.M)
# 1. No escape hatch out of the host.
for token, why in ESCAPE_HATCHES:
if why is None:
continue
res.equals("does not use %s (%s)" % (token, why), 0, code.count(token))
# 2. The only DOM entry point is the host it was handed.
res.check("mount signature takes a host",
"export function mountProjectIntelligence({ host, payloadAsset })" in code,
"host parameter", "present")
res.check("host type is asserted before use",
"host instanceof HTMLElement" in code)
res.check("appends only to the host",
code.count("host.appendChild") > 0 and "appendChild" in code)
# createElement is fine - it builds detached nodes. Every one of them must
# end up under the host, which is what the appendChild check above covers.
res.check("builds detached nodes with createElement",
"document.createElement" in code,
"createElement", "present",
"detached construction is the additive-safe way to build DOM")
# 3. Contract flags.
for flag in REQUIRED_TRUE:
res.check("contract declares %s: true" % flag,
re.search(r"%s:\s*true" % flag, code) is not None)
for flag in REQUIRED_FALSE:
res.check("contract declares %s: false" % flag,
re.search(r"%s:\s*false" % flag, code) is not None)
res.check("contract declares project_bindings: 0",
re.search(r"project_bindings:\s*0", code) is not None)
res.check("contract declares deployment: not-authorised",
'deployment: "not-authorised"' in code)
res.check("contract declares one_signal_policy WITHHOLD",
'one_signal_policy: "WITHHOLD"' in code)
# 4. Lazy payload. The loader asserts payloadRequests === 0 at mount, so
# the cartridge must not fetch until the user selects a tab.
mount_body = code.split("export function mountProjectIntelligence", 1)[-1]
before_select = mount_body.split("async function select", 1)[0]
res.equals("no fetch before a tab is selected", 0, before_select.count("fetch("))
res.check("returns payloadRequests for the loader to assert",
"payloadRequests" in mount_body and "projectBindings: 0" in mount_body)
res.check("guards against requesting the index more than once",
'invariant(payloadRequests === 1' in code)
# 5. Privacy and corroboration boundaries are asserted at runtime, not
# merely declared.
res.check("asserts the payload's no_personal_data flag at load",
"data.law?.no_personal_data === true" in code)
res.check("asserts corroboration is still unbuilt before display",
"data.law?.corroboration_adapters_built === false" in code)
res.check("asserts the payload schema",
'data.schema === "pipelinenews.v9.project-intelligence.v1"' in code)
# 6. Public wording must come from the payload, never be hardcoded.
res.check("band names are read from the payload labels block",
"data.labels.band[" in code or "labels.band" in code)
res.check("caveats are read from the payload labels block",
"labels.caveat" in code)
res.check("provenance is read from the payload labels block",
"labels.provenance" in code)
# 7. Uses only classes already in the frozen stylesheet. A new class name
# would mean a CSS change, which this freeze does not permit.
allowed = {"news-tools", "card", "btn", "gauges", "meta", "section-title", "active"}
used = set(re.findall(r'el\("[a-z]+",\s*"([a-z- ]+)"', code))
used |= set(re.findall(r'classList\.toggle\("([a-z-]+)"', code))
unknown = sorted({c for group in used for c in group.split() if c not in allowed})
res.equals("introduces no new CSS class", [], unknown,
"a new class would require a stylesheet change; the freeze forbids it")
# 8. Registry entry agrees with the cartridge.
if os.path.exists(REGISTRY):
import json
entry = json.load(io.open(REGISTRY, encoding="utf-8"))
pi = entry["supplemental_assets"]["project_intelligence"]
res.equals("registry generation matches the cartridge",
"202608311304", pi["generation"])
res.equals("registry declares zero project bindings", 0, pi["project_bindings"])
res.equals("registry declares additive_only", True, pi["additive_only"])
res.check("registry names the cartridge's real export",
pi["cartridge"]["export"] == "mountProjectIntelligence")
res.check("registry payload carries a sha256",
len(pi["payload"].get("sha256", "")) == 64)
else:
res.check("registry entry exists", False, "present", "absent", REGISTRY)
res.check("RUNTIME NOT EXECUTED (no JS runtime here)", True,
"acknowledged", "acknowledged",
"open the page and click through all five tabs before promoting")
return res.report()
if __name__ == "__main__":
sys.exit(main())