GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / tools/intelligence/cartridges/news-and-sector-clean

Make Cartridge and 2 more files

A Python command-line tool in the news and sector clean folder of PipelineNews covering solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

534 lines of Python from pipelinenews, in 3 files. Topic: Electricity markets and data pipelines. Section 1043 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Make Cartridge render · pipelinenews / tools/intelligence/cartridges/news-and-sector-clean/make_cartridge.py lines 1–205
  2. Make Cartridge render · pipelinenews / tools/intelligence/cartridges/no-grading/make_cartridge.py lines 1–187
  3. Make Cartridge render · pipelinenews / tools/intelligence/cartridges/phone-first-heights/make_cartridge.py lines 1–142

Make Cartridge

A Python command-line tool in the news and sector clean folder of PipelineNews covering solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

renderpipelinenews / tools/intelligence/cartridges/news-and-sector-clean/make_cartridge.py · lines 1–205 of 205 · Entry point · pattern anchor (shared by 16 files)

What it does
It lists and searches solar and the REPD register. Defines read, anchor, 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: solar, the REPD register.
Inputs & outputs
In: JSON file 202608291447-registry.json; 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`) and the anchor step (`anchor`). Generate `cartridge.json`: clean the newspaper, and the sector panel. 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/news-and-sector-clean · Python CLI
Uses
argparse, io, json, os, sys
Used by
none found
Produces
read, anchor, main
Defines here
read, anchor, 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/news-and-sector-clean/make_cartridge.py:1-205 · blob 4d74db4c8d56669bd45204d5c5e207f4c5ea1994 · 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
"""Generate cartridge.json: clean the newspaper, and the sector panel.

TWO SURFACES, ONE CAUSE
-----------------------
Both were showing whatever a collector returned, without asking whether it was
about the thing it was filed under.

THE NEWSPAPER. 136 headlines, all displayed. The payload already marked 89 as
unbound -- role DISCOVERY_ONLY, canonical_relevant false. Those rows carry an
EMPTY repd_ref, yet each was printed under a project name taken from elsewhere,
so the page said a New Jersey storage consultation was an update on Wilton
International, and that a care home award belonged to The Grange solar farm.

Two kinds of story earn a place now, and they are not the same kind. BOUND:
the register ties it to a project, and it keeps its caption. SECTOR: it is
about solar, storage, grid, an inverter, a data centre or a named capacity,
anywhere in the world -- real trade news, no caption, because no project has
been established for it. Eight stories match neither: two care homes that
collided on a project name, a ring road and a port.

THE SECTOR PANEL. Seven topics, 51 items, and the collector returned a generic
government feed for six of them:

    DATA_CENTRES              9 of 9 on topic
    GREAT_GRID_UPGRADE        1 of 6
    INVERTER_SECURITY_POLICY  2 of 12
    MV_HV_COMPONENTS          0 of 6
    WORLDWIDE_PV              0 of 6
    ENERGY_SECURITY_HORMUZ    0 of 6
    ENERGY_SECURITY_UKRAINE   0 of 6

"Biometrics and Surveillance Camera Commissioner FOI responses 2026" appears
under five different topics. So does "The economic benefits of touring and
impact of EU exit". Under INVERTERS · SECURITY sat a cleared fly-tipping site
in Kidlington, Scottish military firing times and a statement on Syria.

That is not something an item filter fixes. Six topics have no intelligence in
them, and filtering items would leave six near-empty sections still claiming to
cover a subject. Only DATA_CENTRES is shown; the panel says the rest are
withheld and why, and their rows stay in the payload so a fixed collector can
restore them without another release here.

    python make_cartridge.py --parent 202608312037-pipelinenews
"""

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"


def read(path):
    return io.open(path, encoding="utf-8", newline="").read()


def anchor(text, needle, label):
    n = text.count(needle)
    if n != 1:
        raise SystemExit("anchor %r occurs %d times, expected 1:\n%s"
                         % (label, n, needle[:200]))
    return needle


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--parent", default="202608312037-pipelinenews")
    a = ap.parse_args()

    parent = os.path.join(RELEASES, a.parent)
    idx = read(os.path.join(parent, "index.html"))
    app = read(os.path.join(parent, APP))
    registry = json.loads(read(os.path.join(parent, "data/202608291447-registry.json")))
    old_sector = registry["supplemental_assets"]["sector_intelligence"]

    ri, ra = [], []

    # ---- the newspaper --------------------------------------------------
    ra.append({
        "label": "keep project-bound and sector-relevant stories, drop the rest",
        "from": anchor(app, "    newsRows = payload.rows;", "news ingest"),
        "to": r"""    // BOUND keeps its caption; SECTOR is real trade news with no project
    // established, so it carries none. Everything else goes.
    //
    // The sector test reads the headline, which is an inference and is treated
    // as one: it decides what to SHOW, and is never used to claim a story is
    // about a project.
    const NEWS_SECTOR = /\b(solar|pv|photovolta|battery|bess|storage|ldes|grid|inverter|substation|transmission|curtail|ppa|renewab|wind|electrolys|interconnector|flexibilit|flexitricity|energy hub|energy park|power plant|megawatt|data ?centres?|datacentres?|data ?centers?)\b/i;
    const NEWS_CAPACITY = /\b\d[\d,.]*\s?(mw|mwh|gw|gwh|kw)\b/i;
    const NEWS_OFFTOPIC = /\b(care home|care centre|care award|ring road|dibden|solent gateway)\b/i;
    // Engineering and business only. Geopolitics is somebody else's page.
    const NEWS_NEUTRAL = /\b(iran|ukraine|russia|israel|gaza|war|sanction|missile|conflict)\b/i;

    const newsBound = (row) =>
      row[NEWS_FIELD.eligible] === true
      && row[NEWS_FIELD.canonical] === true
      && String(row[NEWS_FIELD.role] || "") === "PRIMARY_MATCH"
      && String(row[NEWS_FIELD.repdRef] || "").trim() !== "";

    const newsSector = (row) => {
      const headline = String(row[NEWS_FIELD.headline] || "");
      if (NEWS_OFFTOPIC.test(headline) || NEWS_NEUTRAL.test(headline)) return false;
      return NEWS_SECTOR.test(headline) || NEWS_CAPACITY.test(headline);
    };

    const allNews = payload.rows;
    newsRows = allNews.filter((row) => newsBound(row) || newsSector(row));
    runtimeEvidence.newsBound = allNews.filter(newsBound).length;
    runtimeEvidence.newsSector = newsRows.length - runtimeEvidence.newsBound;
    runtimeEvidence.newsDropped = allNews.length - newsRows.length;"""})

    ra.append({
        "label": "the meta line counts bound, sector and withheld",
        "from": anchor(
            app,
            '    document.getElementById("newsMeta").textContent = `${registry.news_counts.uk} UK · ${registry.news_counts.international} international (${registry.news_counts.us} US · ${registry.news_counts.europe} Europe · ${registry.news_counts.other} other) · ${registry.news_counts.all} headlines · immutable compact edition`;',
            "news meta"),
        "to": r"""    document.getElementById("newsMeta").textContent =
      `${runtimeEvidence.newsBound.toLocaleString("en-GB")} bound to a REPD project · `
      + `${runtimeEvidence.newsSector.toLocaleString("en-GB")} sector headlines, no project binding · `
      + `${runtimeEvidence.newsDropped.toLocaleString("en-GB")} withheld as off-topic · immutable compact edition`;"""})

    ra.append({
        "label": "no project caption without a REPD reference",
        "from": anchor(app, '  const projectName = row[NEWS_FIELD.project] || "";',
                       "project caption"),
        "to": """  // With no repd_ref there is no project this story is about, so it must not
  // carry one. This is what captioned a New Jersey storage story "Wilton
  // International, Greystones Road".
  const projectName = String(row[NEWS_FIELD.repdRef] || "").trim()
    ? (row[NEWS_FIELD.project] || "")
    : "";"""})

    for mode in ("INTERNATIONAL", "US", "EUROPE"):
        needle = '<button data-news="%s">%s</button>' % (mode, mode)
        ri.append({"label": "remove the %s filter; its stories now sit in one list" % mode,
                   "from": anchor(idx, needle, "%s button" % mode), "to": ""})

    entry = json.loads(json.dumps(old_sector))
    entry["generation"] = "{GEN}"
    entry["cartridge"] = dict(entry["cartridge"],
                              generation="{GEN}",
                              filename="{GEN}-sector-intelligence.mjs",
                              path="assets/{GEN}-sector-intelligence.mjs",
                              sha256="", bytes=0)
    entry["topics_shown"] = ["DATA_CENTRES"]
    entry["topics_withheld"] = {
        "GREAT_GRID_UPGRADE": "1 of 6 items on topic",
        "INVERTER_SECURITY_POLICY": "2 of 12 items on topic",
        "MV_HV_COMPONENTS": "0 of 6",
        "WORLDWIDE_PV": "0 of 6",
        "ENERGY_SECURITY_HORMUZ": "0 of 6, and geopolitical",
        "ENERGY_SECURITY_UKRAINE": "0 of 6, and geopolitical",
    }
    entry["why_withheld"] = (
        "The collector returned a generic government feed for six of seven "
        "topics. One item, a Biometrics Commissioner FOI response, appears "
        "under five different topics. The rows remain in the payload so a fixed "
        "collector restores the topics without another release here.")

    # A cartridge may not overwrite an existing registry key, and it should not:
    # the old entry is what the previous release attested. So the corrected
    # module is registered under its own key and the app is repointed at it.
    ra.append({
        "label": "read the sector panel from the corrected registry entry",
        "from": anchor(app, "  const entry = registry.supplemental_assets?.sector_intelligence;",
                       "sector registry lookup"),
        "to": """  const entry = registry.supplemental_assets?.sector_intelligence_clean
    || registry.supplemental_assets?.sector_intelligence;"""})

    man = {
        "key": "sector_intelligence_clean",
        "summary": ("Newspaper shows only project-bound and sector-relevant "
                    "headlines; the sector panel shows only the one topic whose "
                    "items are actually on topic."),
        "modifies_existing_dashboard": True,
        "modification_note": ("Filters the news payload at ingest, removes the "
                              "project caption for unbound stories, deletes three "
                              "geography filters, and replaces the sector "
                              "intelligence module with one that shows only "
                              "DATA_CENTRES and states what is withheld."),
        "repairs": {"index.html": ri, "app": ra},
        "hash_fields": [
            {"at": ["cartridge", "sha256"], "path": "assets/{GEN}-sector-intelligence.mjs"},
        ],
        "registry_entry": entry,
    }

    out = os.path.join(HERE, "cartridge.json")
    io.open(out, "w", encoding="utf-8", newline="").write(
        json.dumps(man, ensure_ascii=False, indent=2) + "\n")
    print("wrote cartridge.json")
    print("  index.html repairs  %d" % len(ri))
    print("  app.mjs repairs     %d" % len(ra))
    print("  sector module replaced, topics shown: DATA_CENTRES")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Make Cartridge

A Python command-line tool in the no grading folder of PipelineNews covering substations. It is built from the read step (`read`) and the anchor step (`anchor`).

renderpipelinenews / tools/intelligence/cartridges/no-grading/make_cartridge.py · lines 1–187 of 187 · Entry point · pattern anchor (shared by 16 files)

What it does
It draws substations. Defines read, anchor, 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: substations.
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
Generate `cartridge.json`: report the distance, never grade it. 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/no-grading · Python CLI
Uses
argparse, io, json, os, sys
Used by
none found
Produces
read, anchor, main
Defines here
read, anchor, 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/no-grading/make_cartridge.py:1-187 · blob ad6e4b0e4428acbe195a74ddd1ce011149ece614 · 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
"""Generate cartridge.json: report the distance, never grade it.

THE PROBLEM
-----------
GRID and SUB tinted their number by band -- STRONG green, MODERATE yellow,
DISTANT orange, REMOTE red -- and the payload carried those labels through to
the tooltip. That is a verdict on a named project's grid position, and it is
not one this page can stand behind.

A developer may build their own substation. Distance to a mapped asset says
nothing about whether a connection is obtainable, what it costs, or whether
anyone intends to use that asset at all. "REMOTE" on somebody's scheme is an
opinion wearing the clothes of a measurement, and the register it sits beside
is read by people making decisions about those schemes.

THE RULE
--------
Report the measurement and let the maths and the tools do the talking. A
distance, its method and its limits are facts. A grade is not.

WHAT CHANGES
------------
In the table: the four band colours become one neutral colour, and the
data-band attribute stops being emitted, so nothing downstream can style or
read a verdict back out of the DOM.

In the grid proximity dashboard, which the first attempt missed entirely --
the band survived in five places there. The GRID column printed the band as
its whole value, so the column said "strong" where it should say a distance.
Sorting by GRID sorted by the verdict. The readout was headed by it. The
project drawer repeated it. And the drawer announced "Target acquired", which
is targeting language about somebody's site and goes.

The distances, the voltages, the caveats and the working are untouched: this
removes a judgement, not information.

    python make_cartridge.py --parent 202608312114-pipelinenews
"""

import argparse, io, json, os, 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"
PROX = "assets/202608311610-grid-proximity.mjs"


def read(p):
    return io.open(p, encoding="utf-8", newline="").read()


def anchor(text, needle, label):
    n = text.count(needle)
    if n != 1:
        raise SystemExit("anchor %r occurs %d times, expected 1:\n%s"
                         % (label, n, needle[:200]))
    return needle


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--parent", default="202608312114-pipelinenews")
    a = ap.parse_args()
    parent = os.path.join(RELEASES, a.parent)
    idx = read(os.path.join(parent, "index.html"))
    app = read(os.path.join(parent, APP))
    prox = read(os.path.join(parent, PROX))

    ri, ra, rp = [], [], []

    # ---- the table -----------------------------------------------------
    old_css = (
        '    .action-metric[data-band="STRONG"] b { color: #6fd18a; }\n'
        '    .action-metric[data-band="MODERATE"] b { color: #d8c96a; }\n'
        '    .action-metric[data-band="DISTANT"] b { color: #d89a6a; }\n'
        '    .action-metric[data-band="REMOTE"] b { color: #b06a6a; }')
    new_css = (
        '    /* One colour for every distance. A green-to-red scale grades a named\n'
        '       project\'s grid position, and a developer may build their own\n'
        '       substation: proximity to a mapped asset is not a verdict on the\n'
        '       scheme. Report the measurement, let the tools do the talking. */\n'
        '    .action-metric b { color: #5fbdc2; }')
    ri.append({"label": "one neutral colour for every distance, no green-to-red grade",
               "from": anchor(idx, old_css, "band colours"), "to": new_css})

    # A second green-to-red set, on .grid-cell, with nothing in the release
    # emitting that class any more. Dead rules are not harmless: this one is a
    # working grading scale sitting in the stylesheet, and the next edit that
    # needs a grid cell will find it and use it.
    dead_css = (
        '    .grid-cell[data-band="STRONG"] .km { color: #6fd18a; }\n'
        '    .grid-cell[data-band="MODERATE"] .km { color: #d8c96a; }\n'
        '    .grid-cell[data-band="DISTANT"] .km { color: #d89a6a; }\n'
        '    .grid-cell[data-band="REMOTE"] .km { color: #b06a6a; }')
    ri.append({
        "label": "remove the second, unused green-to-red scale on .grid-cell",
        "from": anchor(idx, dead_css, "grid-cell band colours"),
        "to": ('    /* A second green-to-red scale lived here for .grid-cell, which\n'
               '       nothing emits any more. Removed rather than left: a dead grading\n'
               '       rule is one edit away from being a live one. */')})

    old_attr = '  const band = hit.b ? ` data-band="${escapeHtml(hit.b)}"` : "";'
    new_attr = ('  // No band attribute is emitted, so nothing downstream can style or read\n'
                '  // a verdict back out of the DOM. The distance is the whole claim.\n'
                '  const band = "";')
    ra.append({"label": "stop emitting the band attribute",
               "from": anchor(app, old_attr, "band attribute"), "to": new_attr})

    # ---- the grid proximity dashboard ----------------------------------
    # The GRID column printed the band as its entire value. It becomes the
    # measurement it was standing in front of: the nearest circuit, which is
    # what the working behind the button is about.
    rp.append({
        "label": "GRID reports the nearest circuit, not a verdict on it",
        "from": anchor(prox, """      ["_gp", "GRID", (r) => `<button class="gp-lock" type="button" data-why="${esc(r.ref)}"
        title="show the working">${esc(r.grid_probable.band.toLowerCase())}</button>`],""",
                       "grid column"),
        "to": """      // Was the band -- "strong", "remote" -- as the whole cell. A distance is
      // a measurement and a band is a verdict on somebody's scheme, so the
      // cell now shows the measurement and the working stays one click away.
      ["_gp", "GRID", (r) => `<button class="gp-lock" type="button" data-why="${esc(r.ref)}"
        title="show the working">${r.circuit ? km(r.circuit.km) : "n/a"}</button>`],"""})

    rp.append({
        "label": "sorting by GRID sorts by distance, not by verdict",
        "from": anchor(prox, '        : k === "_gp" ? BAND_RANK[r.grid_probable.band]',
                       "grid sort"),
        "to": '        : k === "_gp" ? (r.circuit ? r.circuit.km : Infinity)'})

    rp.append({
        "label": "the readout is headed by the project, not by a grade",
        "from": anchor(prox, '          box.innerHTML = `<div class="gp-readout"><h4>${esc(r.grid_probable.band)} · ${esc(r.name)}</h4>',
                       "readout heading"),
        "to": '          box.innerHTML = `<div class="gp-readout"><h4>${esc(r.name)}</h4>'})

    rp.append({
        "label": "the drawer states a distance where it stated a grade",
        "from": anchor(prox, '            <dt>GRID</dt><dd>${esc((row.grid_probable && row.grid_probable.band || "").toLowerCase())}</dd>',
                       "drawer band"),
        "to": '            <dt>NEAREST CIRCUIT</dt><dd>${row.circuit ? km(row.circuit.km) + " · " + row.circuit.kv + " kV" : "n/a"}</dd>'})

    rp.append({
        "label": "no targeting language over somebody's site",
        "from": anchor(prox, '          <h4>${t >= 1 ? "Target acquired" : "Acquiring…"}</h4>',
                       "target acquired"),
        "to": '          <h4>${t >= 1 ? "In range" : "Measuring…"}</h4>'})

    # BAND_RANK now has no reader. Leaving a dead verdict table in the source
    # invites the next edit to reach for it.
    rp.append({
        "label": "remove the rank table the verdict was sorted by",
        "from": anchor(prox, 'const BAND_RANK = { STRONG: 0, MODERATE: 1, DISTANT: 2, REMOTE: 3, UNKNOWN: 4 };',
                       "band rank"),
        "to": '/* BAND_RANK is gone with the grading it ordered. Nothing sorts by verdict. */'})

    man = {
        "key": "no_grading",
        "summary": ("Grid proximity reports distances and no longer grades them. "
                    "The green-to-red bands, the data-band attribute, the GRID "
                    "column's verdict and the targeting language are gone."),
        "modifies_existing_dashboard": True,
        "modification_note": (
            "Replaces the four band colours with one neutral colour; stops "
            "emitting data-band; makes the GRID column and its sort the nearest "
            "circuit distance; removes the band from the readout heading and the "
            "project drawer; replaces \"Target acquired\" with \"In range\"; and "
            "deletes BAND_RANK, which no longer has a reader."),
        "repairs": {
            "index.html": ri,
            "app": ra,
            "assets": [{"path": PROX, "edits": rp}],
        },
    }

    out = os.path.join(HERE, "cartridge.json")
    io.open(out, "w", encoding="utf-8", newline="").write(
        json.dumps(man, ensure_ascii=False, indent=2) + "\n")
    print("wrote cartridge.json")
    print("  index.html repairs      %d" % len(ri))
    print("  app.mjs repairs         %d" % len(ra))
    print("  grid-proximity repairs  %d" % len(rp))
    return 0


if __name__ == "__main__":
    sys.exit(main())

Make Cartridge

A Python command-line tool in the phone first heights folder of PipelineNews that generates `cartridge.json`: stop measuring a phone's screen with 100vh.

renderpipelinenews / tools/intelligence/cartridges/phone-first-heights/make_cartridge.py · lines 1–142 of 142 · Entry point · pattern anchor (shared by 16 files)

What it does
Defines read, anchor, 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.
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
Its name says it makes cartridge. Defines `read` and `anchor`. 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/phone-first-heights · Python CLI
Uses
argparse, io, json, os, sys
Used by
none found
Produces
read, anchor, main
Defines here
read, anchor, 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/phone-first-heights/make_cartridge.py:1-142 · blob c43bd5db848bb2d2d26d94b9740a8d96f0704536 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Generate cartridge.json: stop measuring a phone's screen with 100vh.

WHY THIS ONE FIRST
------------------
"the map feature from pipelinenews doesnt load on iphone", and then: build for
the phone first and let it scale up, because the link that reaches most readers
arrives in a WhatsApp message.

THE FAULT
---------
The desktop shell is a fixed-height flex app:

    body{display:flex;height:100vh;overflow:hidden}

and the mobile block turns it back into a document:

    @media(max-width:768px){ body{display:block;overflow:auto} }

It overrides display and overflow. It never overrides HEIGHT. So on a phone the
body is still exactly 100vh tall.

On iOS, 100vh is the viewport with the browser chrome HIDDEN -- Safari's own
definition, unchanged since it shipped. While the toolbar is showing, which is
most of the time and always when you first arrive from a link, 100vh is taller
than what you can see. A fixed-height scrolling body inside a shorter window is
the whole family of iOS complaints at once: the last rows sit under the
toolbar, the page scrolls in two places that disagree, and rubber-banding
fights the inner scroller.

.paper is the same mistake at 65vh, and .tablewrap at 65vh.

THE FIX
-------
On a phone the body should be a document, not a fixed-height application: let
it grow and let the browser scroll it. min-height:100svh keeps the full-screen
feel -- svh is the SMALL viewport, the one that is correct while the toolbar is
showing, so it never promises more room than exists.

For the panels that genuinely want a viewport fraction, dvh: the DYNAMIC
viewport, which tracks the toolbar as it hides and shows.

Both are already the house style: orientation.css uses dvh in seven places.
This brings the frozen shell into line with the repair that was made around it.

Every declaration is written twice, vh then the modern unit, so a browser that
does not know dvh keeps exactly today's behaviour.

    python make_cartridge.py --parent 202608312145-pipelinenews
"""

import argparse, io, json, os, 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")
CSS = "assets/202608270055-v8-fast.css"


def read(p):
    return io.open(p, encoding="utf-8", newline="").read()


def anchor(text, needle, label):
    n = text.count(needle)
    if n != 1:
        raise SystemExit("anchor %r occurs %d times, expected 1:\n%s"
                         % (label, n, needle[:160]))
    return needle


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--parent", default="202608312145-pipelinenews")
    a = ap.parse_args()
    css = read(os.path.join(RELEASES, a.parent, CSS))

    edits = []

    # 1. The desktop shell keeps its fixed height; only the unit is modernised.
    edits.append({
        "label": "the desktop shell measures the viewport that is actually visible",
        "from": anchor(css, "body{display:flex;height:100vh;overflow:hidden;font-size:13px}",
                       "body"),
        "to": ("body{display:flex;height:100vh;height:100dvh;overflow:hidden;"
               "font-size:13px}")})

    # 2. On a phone, be a document. This is the fault.
    edits.append({
        "label": "on a phone the body grows instead of being pinned to 100vh",
        "from": anchor(css, "@media(max-width:768px){body{display:block;overflow:auto}",
                       "mobile body"),
        "to": ("@media(max-width:768px){body{display:block;overflow:auto;"
               "height:auto;min-height:100vh;min-height:100svh}")})

    # 3. The newspaper pane.
    edits.append({
        "label": "the newspaper pane tracks the toolbar instead of ignoring it",
        "from": anchor(css, ".paper{height:min(68vh,760px);min-height:520px;"
                            "overflow:auto;overscroll-behavior:contain}", "paper"),
        "to": (".paper{height:min(68vh,760px);height:min(68dvh,760px);"
               "min-height:520px;overflow:auto;overscroll-behavior:contain}")})

    edits.append({
        "label": "and on a phone too",
        "from": anchor(css, ".paper{height:65vh;min-height:480px}", "mobile paper"),
        "to": ".paper{height:65vh;height:65dvh;min-height:480px}"})

    # 4. The table pane.
    edits.append({
        "label": "the table pane likewise",
        "from": anchor(css, ".tablewrap{background:var(--panel);border:1px solid "
                            "var(--soft);overflow:auto;max-height:65vh}", "tablewrap"),
        "to": (".tablewrap{background:var(--panel);border:1px solid var(--soft);"
               "overflow:auto;max-height:65vh;max-height:65dvh}")})

    man = {
        "key": "phone_first_heights",
        "summary": ("The body is no longer pinned to 100vh on a phone, and the "
                    "panes that want a viewport fraction use dvh, which tracks "
                    "the browser toolbar."),
        "modifies_existing_dashboard": True,
        "modification_note": (
            "The mobile block overrode display and overflow but not height, so a "
            "phone kept a body exactly 100vh tall -- and on iOS 100vh is the "
            "viewport with the chrome hidden, which is taller than what you can "
            "see whenever the toolbar is showing. The body now grows, with "
            "min-height:100svh for the full-screen feel; .paper and .tablewrap "
            "use dvh. Every declaration is written vh-then-modern, so a browser "
            "without dvh keeps today's behaviour exactly."),
        "repairs": {"assets": [{"path": CSS, "edits": edits}]},
    }

    out = os.path.join(HERE, "cartridge.json")
    io.open(out, "w", encoding="utf-8", newline="").write(
        json.dumps(man, ensure_ascii=False, indent=2) + "\n")
    print("wrote cartridge.json")
    print("  css repairs  %d" % len(edits))
    return 0


if __name__ == "__main__":
    sys.exit(main())