GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / tools/intelligence

Shift and 1 more file (part 2)

A JavaScript module in the overnight folder of PipelineNews that fetches shift log.

668 lines of JavaScript and Python from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1053 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. V8 Neutral Surface render · pipelinenews / tools/intelligence/v8_neutral_surface.py lines 1–161
  2. Shift storage · pipelinenews / tools/overnight/202609012300-shift.mjs lines 1–507

V8 Neutral Surface

A Python command-line tool in the intelligence folder of PipelineNews that checks release (`check_release`). It is built from the scan step (`scan`).

renderpipelinenews / tools/intelligence/v8_neutral_surface.py · lines 1–161 of 161 · Entry point

What it does
It lists and searches its content. Defines scan, check_release, main. Uses libraries io, json, os, re, sys. 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: command-line arguments.
Downstream impact
Used directly by 1 file: Shift (pipelinenews).
What it achieves
V8 - the surface never characterises anyone's project or company.
Why it matters
Run by Shift.
Application
pipelinenews · tools/intelligence · Python CLI
Uses
PipelineNews — Intelligence (import), io, json, os, re, sys
Used by
run by Shift (script call)
Produces
scan, check_release, main
Defines here
scan, check_release, 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/v8_neutral_surface.py:1-161 · blob 651896172d192bea827e0e7ab67fa48c4d5be1ff · 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
"""V8 - the surface never characterises anyone's project or company.

THE RULE
--------
We do not say a project is bankrupt, distressed, failing, stalled or dead.
If a register says it, the register says it and we attribute it. We never say
it in our own voice, and no tile we render may assert it.

The reason is commercial and jurisdictional, not squeamish: this platform is
read by the people whose projects it describes, across several jurisdictions.
A characterisation we author is our claim, and we own the consequences of it.
A register status we quote is the register's claim, correctly attributed.

WHAT THIS CHECKS
----------------
Language WE author on a shipped surface:
  - the labels block of a payload (all public wording lives there)
  - copy hardcoded in a cartridge
  - the section text in index.html

It deliberately does NOT flag raw register values in data rows. Companies
House may publish "liquidation" as a filing type and DESNZ may publish a
status; quoting those with attribution is the correct behaviour, and banning
the words outright would stop us reporting the register at all.

Run against a built release:
    python v8_neutral_surface.py <path-to-release>
    python v8_neutral_surface.py            (checks every pipelinenews release)

Read-only. No network.
"""

import io
import json
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))
RELEASES = os.path.join(REPO, "releases")

# Characterisations of a project's or company's condition. If one of these is
# in copy we author, it is us making the claim.
BANNED = [
    "distressed", "bankrupt", "bankruptcy", "insolvent", "insolvency",
    "failing", "failed project", "collapsed", "troubled",
    "in trouble", "at risk", "zombie", "dead", "doomed", "abandoned",
    "stalled", "stalling", "struck off", "wound up", "winding up",
    "going under", "defaulted", "delinquent", "distress",
    "mothballed", "written off", "write-off", "non-viable", "unviable",
    "uncreditworthy", "financially weak", "cash-strapped",
]

# Words that are legitimate when clearly attributed to a named register, and
# a claim when they are not. Presence requires an attribution marker nearby.
ATTRIBUTABLE = ["liquidation", "administration", "receivership", "refused",
                "withdrawn", "expired", "revoked"]
ATTRIBUTION_MARKERS = ["register", "desnz", "companies house", "gazette",
                       "published", "records", "as published", "planning"]

# Advice or instruction to act. We surface evidence; we do not tell anyone to
# stop selling to a named counterparty.
DIRECTIVES = ["stop selling", "do not engage", "avoid this", "blacklist",
              "walk away", "drop this", "write them off"]


CSS_NOISE = re.compile(
    r"[a-z-]+\s*:\s*[^;\"]+;|style\s*=|border-collapse|white-space|text-align|"
    r"font-[a-z]+|margin|padding|overflow|display\s*:|width\s*:|color\s*:")


def scan(label, text, res, allow_attributable=True):
    # CSS declarations are not prose. Remove them before looking for claims.
    low = CSS_NOISE.sub(" ", text.lower())
    for term in BANNED:
        if re.search(r"\b%s\b" % re.escape(term), low):
            snippet = low[max(0, low.index(term) - 60): low.index(term) + 60]
            res.check("%s: does not characterise with '%s'" % (label, term),
                      False, "absent", "PRESENT", "…%s…" % snippet.strip())
    for term in DIRECTIVES:
        if term in low:
            res.check("%s: gives no directive '%s'" % (label, term),
                      False, "absent", "PRESENT")
    if allow_attributable:
        for term in ATTRIBUTABLE:
            for m in re.finditer(r"\b%s\b" % re.escape(term), low):
                window = low[max(0, m.start() - 140): m.end() + 140]
                if not any(a in window for a in ATTRIBUTION_MARKERS):
                    res.check("%s: '%s' is attributed to a register" % (label, term),
                              False, "attributed", "UNATTRIBUTED",
                              "…%s…" % window.strip()[:150])


def check_release(path, res):
    name = os.path.basename(path)

    # 1. payload labels — every public string lives here
    data_dir = os.path.join(path, "data")
    if os.path.isdir(data_dir):
        for fn in sorted(os.listdir(data_dir)):
            if not fn.endswith(".json"):
                continue
            try:
                doc = json.loads(io.open(os.path.join(data_dir, fn), encoding="utf-8").read())
            except ValueError:
                continue
            labels = doc.get("labels")
            if labels:
                scan("%s/%s labels" % (name, fn), json.dumps(labels), res)

    # 2. copy hardcoded in cartridges
    assets = os.path.join(path, "assets")
    if os.path.isdir(assets):
        for fn in sorted(os.listdir(assets)):
            if not fn.endswith(".mjs"):
                continue
            src = io.open(os.path.join(assets, fn), encoding="utf-8").read()
            strings = re.findall(r'"([^"\\\n]{12,})"', src)
            strings += re.findall(r"`([^`]{12,})`", src)
            scan("%s/%s copy" % (name, fn), " ".join(strings), res)

    # 3. the section text we author in index.html
    idx = os.path.join(path, "index.html")
    if os.path.exists(idx):
        html = io.open(idx, encoding="utf-8").read()
        visible = re.sub(r"<script.*?</script>", " ", html, flags=re.S)
        visible = re.sub(r"<style.*?</style>", " ", visible, flags=re.S)
        visible = re.sub(r"<[^>]+>", " ", visible)
        # Only OUR sections are our voice. The frozen parent UI is not this
        # release's claim to answer for, and flagging it every build would
        # train everyone to ignore V8.
        ours = re.findall(r"PROJECT INTELLIGENCE.{0,1400}", visible, re.S)
        scan("%s/index.html (our section)" % name, " ".join(ours), res)


def main():
    res = Result("V8", "Neutral surface - we never characterise, the register speaks")

    targets = sys.argv[1:] or [os.path.join(RELEASES, d) for d in sorted(os.listdir(RELEASES))
                               if os.path.isdir(os.path.join(RELEASES, d))
                               and os.path.exists(os.path.join(RELEASES, d, "index.html"))]
    if not targets:
        res.check("at least one release to check", False, ">=1", 0)
        return res.report()

    for t in targets:
        check_release(t, res)

    # If nothing fired, say so positively rather than reporting an empty pass.
    if not res.checks:
        res.check("no characterisation in any shipped surface (%d releases)" % len(targets),
                  True, "clean", "clean",
                  "checked payload labels, cartridge copy and index.html body text")
    return res.report()


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

Shift

A JavaScript module in the overnight folder of PipelineNews that fetches shift log.

storagepipelinenews / tools/overnight/202609012300-shift.mjs · lines 1–507 of 507 · version 2026-09-01 23:00 · Not reached from any entry point (candidate for review) · pattern untracked (shared by 2 files)

What it does
It fetches shift log. Defines 18 functions or classes, including utcNow, slash, run, git, gitAt. Uses libraries node:fs, node:path, node:child_process, node:url. Side effects: reads or writes files; makes network requests; 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 current.json; JSON file shift-log.json; JSON file b.json; JSON file release-manifest.json; command-line arguments.
What it achieves
It is built from the utc now helper (`utcNow`), the slash step (`slash`) and the run step (`run`). The Pipeline News night shift.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/overnight · JavaScript module
Uses
Release Builder (script call), Homepage Reachability (script call), V8 Neutral Surface (script call), Proof (script call), Verify Atlas Deep Link Contract (script call), node:fs, node:path, node:child_process, node:url
Used by
none found
Produces
utcNow, slash, run, git, gitAt, status, untracked, PYTHON, record, flag, opt, stage
Defines here
utcNow, slash, run, git, gitAt, status, untracked, PYTHON, record, flag, opt, stage, undo, fail, isDebris, complete, targetOf, walk
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/overnight/202609012300-shift.mjs:1-507 · blob 12313d8b745f3a77b1fd250f9bae69469761bd3c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * The Pipeline News night shift.
 *
 * One queued step per invocation: built on this laptop by the repository's
 * own Python builder, proven here, published to both surfaces, pushed to
 * GitHub, and verified against the live bytes.
 *
 * WHY THIS IS NOT A COPY OF THE GRIDATLAS RUNNER
 * ----------------------------------------------
 * The two applications ship differently and pretending otherwise would
 * produce a runner that reports success against the wrong bytes.
 *
 *   GridAtlas cuts a COMPOSITION: a pointer file names hashed cartridges,
 *   and "live" is `atlas/current.json` on GitHub Pages.
 *
 *   Pipeline News builds an immutable RELEASE DIRECTORY by copying its
 *   parent and applying one cartridge (`tools/intelligence/release_builder.py`,
 *   pure stdlib, no network, no git). "Live" is a snapshot of that
 *   directory published at globalgrid2050.com/pipelinenews_intelligence/
 *   <generation>/, which lives in a DIFFERENT repository - the
 *   globalgrid2050 checkout beside this one. Nothing in this repository
 *   publishes that host, which is why ten releases built on 31 August sit
 *   in `releases/` with `"deployment": "not-authorised"` and no pointer
 *   naming them.
 *
 * TWO THINGS THIS RUNNER MUST DO THAT THE OTHER DOES NOT
 * ------------------------------------------------------
 * 1. Author `atman/<generation>-public-browser-readback.mjs`. The Pages
 *    workflow at `.github/workflows/202608301214-pages-v2.yml` does
 *    `test -f "$verifier"` and FAILS the deploy when it is missing. Only
 *    four such files exist, none for any generation after 30 August. A
 *    release without one is a release that cannot deploy, so the runner
 *    writes it as part of the cut rather than leaving it to be discovered.
 *
 * 2. Publish the snapshot into the globalgrid2050 checkout and push there
 *    too. The homepage `index.html` is NOT touched: it is governed by a
 *    numbered-snapshot ritual and a byte-exact sentinel contract, and a
 *    previous session rewrote more of it than was asked and had the work
 *    rejected. The directory publish makes the URL live; naming it on the
 *    homepage is a separate, deliberate act.
 *
 *   node tools/overnight/202609012300-shift.mjs            # next pending step
 *   node tools/overnight/202609012300-shift.mjs --dry      # build and prove only
 *   node tools/overnight/202609012300-shift.mjs --step <path>
 */
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
import { fileURLToPath } from 'node:url';
import { isReachable } from '../publication/202609020042-homepage-reachability.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const GG = path.resolve(ROOT, '..', 'globalgrid2050');
const STEPS = path.join(HERE, 'steps');
const LOG = path.join(HERE, 'shift-log.json');

const LIVE_BASE = 'https://globalgrid2050.com/pipelinenews_intelligence';

/* The session that cuts is the session that should be credited. This was a
   hardcoded id, so every cut made from anywhere else was signed by a session
   that had not made it - including 202609020552, cut after that session was
   archived. Read from the environment, and say so when it is not set rather
   than naming someone. */
const SESSION_URL = process.env.CLAUDE_SESSION_URL
  || 'unrecorded (set CLAUDE_SESSION_URL)';

const utcNow = () => new Date().toISOString().replace(/[-:T]/g, '').slice(0, 12);
const slash = (p) => String(p).split('\\').join('/');

function run(cmd, args, { cwd = ROOT, allowFail = false, quiet = false } = {}) {
  const r = spawnSync(cmd, args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, shell: false });
  const out = (r.stdout || '') + (r.stderr || '');
  if (!quiet) process.stdout.write(out.length > 6000 ? out.slice(-6000) : out);
  if (r.status !== 0 && !allowFail) throw new Error(`${cmd} ${args.join(' ')} exited ${r.status}`);
  return { status: r.status, out };
}
const git = (...args) => run('git', args, { quiet: true }).out.trim();
const gitAt = (cwd, ...args) => run('git', args, { cwd, quiet: true }).out.trim();
const status = () => run('git', ['status', '--porcelain'], { quiet: true }).out.split('\n').filter(Boolean);
const untracked = () => git('ls-files', '--others', '--exclude-standard').split('\n').filter(Boolean).map(slash);

/* python3 on CI, python on this laptop; resolved once and recorded. */
const PYTHON = (() => {
  for (const candidate of ['python', 'python3']) {
    const r = spawnSync(candidate, ['--version'], { encoding: 'utf8', shell: false });
    if (r.status === 0) return candidate;
  }
  throw new Error('no python interpreter found');
})();

const log = fs.existsSync(LOG) ? JSON.parse(fs.readFileSync(LOG, 'utf8'))
  : { schema: 'pipelinenews.shift-log.v1', runs: [] };
function record(entry) {
  log.runs.push(entry);
  fs.writeFileSync(LOG, JSON.stringify(log, null, 2) + '\n');
}

/* ── choose the step ─────────────────────────────────────────────────── */
const flag = (name) => process.argv.includes(name);
const opt = (name) => {
  const i = process.argv.indexOf(name);
  return i > 0 ? process.argv[i + 1] : null;
};

/* A step is finished when its release is published to BOTH repositories.
   'live' additionally means the public host was seen serving it, which it
   may not be for some time - that host rebuilds on its own schedule and
   nothing here can make it hurry. Treating 'published' as unfinished made
   the queue re-pick a step whose release was already built, committed,
   pushed and snapshotted, which would have cut a second release for one
   change. */
const FINISHED = new Set(['live', 'published']);
const done = new Set(log.runs.filter(r => FINISHED.has(r.outcome)).map(r => r.step));
let stepPath = opt('--step');
if (!stepPath) {
  if (!fs.existsSync(STEPS)) { console.log('no steps directory'); process.exit(0); }
  const pending = fs.readdirSync(STEPS).filter(f => f.endsWith('.mjs')).sort().filter(f => !done.has(f));
  if (!pending.length) { console.log('no pending step'); process.exit(0); }
  stepPath = path.join(STEPS, pending[0]);
}
const stepFile = path.basename(stepPath);
const step = (await import(pathToFileURL(path.resolve(stepPath)).href)).default;
for (const key of ['id', 'cartridge', 'scope', 'note']) {
  if (!step[key]) { console.error(`step ${stepFile} lacks ${key}`); process.exit(2); }
}

const dry = flag('--dry');
const startedAt = new Date().toISOString();
console.log(`\n\x1b[1mPN shift step ${step.id}\x1b[0m  (${stepFile})  ${startedAt}${dry ? '  [dry]' : ''}`);

const entry = { step: stepFile, id: step.id, cartridge: step.cartridge,
  started_at: startedAt, dry, python: PYTHON, stages: [] };
const stage = (name, detail) => {
  entry.stages.push({ name, at: new Date().toISOString(), ...detail });
  console.log(`  \x1b[36m${name}\x1b[0m ${detail ? JSON.stringify(detail).slice(0, 240) : ''}`);
};

let untrackedBefore = null;
function undo() {
  if (untrackedBefore === null) return;
  run('git', ['checkout', '--', '.'], { allowFail: true, quiet: true });
  const before = new Set(untrackedBefore);
  for (const p of untracked()) {
    if (!before.has(p)) fs.rmSync(path.join(ROOT, p), { force: true, recursive: true });
  }
}
function fail(reason, extra = {}) {
  entry.outcome = 'failed'; entry.reason = reason;
  entry.finished_at = new Date().toISOString();
  Object.assign(entry, extra);
  console.log(`\n\x1b[31mFAILED: ${reason}\x1b[0m`);
  undo();
  record(entry);
  process.exit(1);
}

/* ── preconditions ───────────────────────────────────────────────────── */
const brings = new Set((step.brings || []).map(slash));
/* The repo carries a long-standing set of untracked candidate artefacts
   from the older v8-fast lineage. They are not this shift's business and
   they are not cleaned - they are simply not counted as a dirty tree. */
const IGNORABLE = [
  'tools/overnight/', 'docs/coordination/',
  'releases/data/', 'releases/javascript/', 'releases/202609010145-',
  'build/202609010145-'
];
/* Python writes __pycache__ wherever it imports from, including inside
   tools/intelligence the moment the cartridge generator runs. It is build
   debris the repository does not track and this shift did not ask for, and
   it appeared between the precondition and the commit. */
const isDebris = (p) => p.includes('__pycache__/');
const dirty = status();
const dirtyElsewhere = dirty.filter((l) => {
  const p = slash(l.slice(3));
  if (IGNORABLE.some(prefix => p.startsWith(prefix)) || isDebris(p)) return false;
  if (!l.startsWith('??')) return true;
  if (brings.has(p)) return false;
  /* git collapses a wholly-untracked directory to the directory itself, so
     a step that brings `<dir>/a.py` and `<dir>/b.json` is reported as the
     single entry `<dir>/`. Matching only the file paths turned the first
     Pipeline News cut red for a tree that was exactly as the step declared
     it. A directory is allowed only when the step brings something inside
     it - a directory nothing was declared for is still dirty. */
  if (p.endsWith('/') && [...brings].some(b => b.startsWith(p))) return false;
  return true;
});
if (dirtyElsewhere.length && !dry) {
  fail('working tree not clean before the step', { dirty: dirtyElsewhere.slice(0, 20) });
}

if (!fs.existsSync(GG)) {
  fail('the globalgrid2050 checkout is not beside this repository; nothing can be published live', { expected: GG });
}

run('git', ['fetch', 'origin', '--quiet'], { quiet: true, allowFail: true });
const head = git('rev-parse', 'HEAD');
const originMain = git('rev-parse', 'origin/main');
if (head !== originMain) {
  const base = git('merge-base', 'HEAD', 'origin/main');
  if (base === head) {
    run('git', ['merge', '--ff-only', 'origin/main'], { quiet: true });
    stage('fast-forwarded to origin/main', { to: originMain.slice(0, 7) });
  } else if (base !== originMain) {
    fail('origin/main has diverged from this checkout; a human merges, not the night shift',
      { head, origin_main: originMain });
  }
}

/* ── the parent release ──────────────────────────────────────────────── */
/* A parent must be a COMPLETE release, not merely a directory whose name
   matches. A failed build leaves empty directories behind - git does not
   report an empty directory, so the undo never sees one to remove - and the
   next run picked that husk as its parent and died inside the cartridge
   generator with a FileNotFoundError. Requiring the release manifest and the
   runtime asset turns that into a clear refusal, and the husk is swept. */
const RELEASE_DIR = path.join(ROOT, 'releases');
const APP_ASSET = path.join('assets', '202608291447-app.mjs');
const complete = (id) => fs.existsSync(path.join(RELEASE_DIR, id, 'release-manifest.json'))
  && fs.existsSync(path.join(RELEASE_DIR, id, APP_ASSET));

const named = fs.readdirSync(RELEASE_DIR).filter(f => /^\d{12}-pipelinenews$/.test(f)).sort();
const husks = named.filter(id => !complete(id));
for (const id of husks) {
  fs.rmSync(path.join(RELEASE_DIR, id), { recursive: true, force: true });
  stage('swept an incomplete release directory', { id });
}
const releases = named.filter(complete);
if (!releases.length) fail('no complete parent release found', { named, husks });

/* The parent must be in the SAME LANE.
   ------------------------------------------------------------------------
   The release chain is linear and shared, and Codex now publishes into it
   too: 202609020010 is a Codex-lane release with atlas_target "codex",
   importing 202609020010-codex-atlas-lab-deep-link.mjs so that MAP opens
   their isolated Atlas lab. Taking "the newest release" as parent made
   that the base of the live line, and the next release would have
   inherited it - the public Pipeline News MAP would have pointed at the
   Codex lab. The deep-link gate caught it, which is the only reason this
   is a note rather than an incident.

   So the parent is the newest release whose declared atlas_target matches
   the one this step builds for. A lane picks up where its own lane left
   off; neither agent's chain is broken and neither silently adopts the
   other's receiver. */
const wantedTarget = step.atlasTarget || 'ported';
const targetOf = (id) => {
  try {
    return JSON.parse(fs.readFileSync(
      path.join(RELEASE_DIR, id, 'release-manifest.json'), 'utf8')).atlas_target || null;
  } catch { return null; }
};
const inLane = releases.filter(id => targetOf(id) === wantedTarget);
const otherLane = releases.filter(id => targetOf(id) && targetOf(id) !== wantedTarget);
if (!inLane.length) {
  fail(`no complete release in the ${wantedTarget} lane to build on`,
    { releases: releases.slice(-5), other_lane: otherLane.slice(-5) });
}
const parent = step.parent || inLane[inLane.length - 1];
if (!complete(parent)) fail('the named parent release is incomplete', { parent });
if (targetOf(parent) !== wantedTarget) {
  fail('the named parent is in another lane', { parent, its_target: targetOf(parent), wantedTarget });
}
stage('parent release', {
  parent, lane: wantedTarget, in_lane: inLane.length,
  skipped_other_lane: otherLane.length, swept: husks.length
});

/* ── the step prepares its cartridge ─────────────────────────────────── */
untrackedBefore = untracked();
if (typeof step.prepare === 'function') {
  try {
    await step.prepare({ root: ROOT, parent, run, python: PYTHON,
      read: (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8'),
      write: (rel, text) => {
        fs.mkdirSync(path.dirname(path.join(ROOT, rel)), { recursive: true });
        fs.writeFileSync(path.join(ROOT, rel), text);
      } });
  } catch (error) { fail(`prepare: ${error.message}`); }
  stage('cartridge prepared', { cartridge: step.cartridge });
}

/* the tooling and the cartridge source are committed BEFORE the build, so
   the release commit contains the release and nothing else - the Pages
   workflow selects a release only when exactly one changed */
if (!dry && status().length) {
  /* Only this step's own files. `git add tools/intelligence` would sweep up
     whatever else is being written in that tree - and tonight there are
     parallel agents authoring cartridges in it. A runner that commits work
     it did not produce makes its own receipt untrue. */
  run('git', ['add', 'tools/overnight', ...brings], { allowFail: true, quiet: true });
  const r = run('git', ['commit', '-q', '-m',
    `${utcNow()}: overnight - step ${step.id} authored`], { allowFail: true, quiet: true });
  if (r.status === 0) stage('tooling committed', { commit: git('rev-parse', '--short', 'HEAD') });
}

/* ── build ───────────────────────────────────────────────────────────── */
if (dry) {
  entry.outcome = 'dry'; entry.finished_at = new Date().toISOString(); record(entry);
  console.log('\n--dry: prepared and checked; no release built.');
  process.exit(0);
}

const generation = utcNow();
if (generation <= parent.slice(0, 12)) {
  fail('the clock has not advanced past the parent generation', { generation, parent });
}
const buildArgs = ['tools/intelligence/release_builder.py',
  '--from', parent, '--cartridge', step.cartridge, '--gen', generation];
if (step.atlasTarget) buildArgs.push('--atlas-target', step.atlasTarget);
{
  const r = run(PYTHON, buildArgs, { allowFail: true });
  if (r.status !== 0) fail('the release builder refused the build', { output: r.out.slice(-3000) });
}
const releaseId = `${generation}-pipelinenews`;
const releaseDir = path.join(ROOT, 'releases', releaseId);
if (!fs.existsSync(releaseDir)) fail('the builder reported success and wrote no release', { releaseId });
stage('built', { releaseId, parent });

/* ── the readback verifier the Pages workflow demands ────────────────── */
const readback = `atman/${generation}-public-browser-readback.mjs`;
if (!fs.existsSync(path.join(ROOT, readback))) {
  const template = fs.readdirSync(path.join(ROOT, 'atman'))
    .filter(f => /^\d{12}-public-browser-readback\.mjs$/.test(f)).sort().pop();
  if (!template) fail('no readback verifier exists to model the new one on');
  const text = fs.readFileSync(path.join(ROOT, 'atman', template), 'utf8');
  const stamped = text.split(template.slice(0, 12)).join(generation);
  fs.writeFileSync(path.join(ROOT, readback), stamped);
  stage('readback verifier authored', { readback, modelled_on: template });
}

/* ── gates ───────────────────────────────────────────────────────────── */
const gates = [
  ['builder check', [PYTHON, ['tools/intelligence/release_builder.py', '--check', releaseId]]],
  ['neutral surface', [PYTHON, ['tools/intelligence/v8_neutral_surface.py', `releases/${releaseId}`]]],
  ['atlas deep-link cartridge', [process.execPath, ['tools/intelligence/cartridges/atlas-live-handoff/proof.mjs', releaseId]]],
  ['deep-link contract vs GridAtlas', [process.execPath,
    ['tools/intelligence/202609012300-verify-atlas-deep-link-contract.mjs',
      '--gridatlas', path.resolve(ROOT, '..', 'gridatlas')]]],
];
for (const extra of step.gates || []) gates.push(extra);

for (const [name, [cmd, args]] of gates) {
  const target = args[0];
  if (!fs.existsSync(path.join(ROOT, target))) {
    /* a skip is not a pass */
    fail(`gate absent: ${name} (${target})`);
  }
  const r = run(cmd, args, { allowFail: true });
  const tally = r.out.match(/(\d+)\/(\d+) checks passed/);
  stage(`gate ${name}`, { status: r.status, tally: tally ? `${tally[1]}/${tally[2]}` : undefined });
  if (r.status !== 0) fail(`gate red: ${name}`, { output: r.out.slice(-2500) });
}

/* the parent must be untouched, byte for byte - immutability is the whole
   architecture, and the builder asserts it, but so does this */
{
  const r = run('git', ['diff', '--quiet', '--', `releases/${parent}`], { allowFail: true, quiet: true });
  if (r.status !== 0) fail('the build modified its own parent release');
  stage('parent untouched', { parent });
}

/* ── commit the release alone, then push ─────────────────────────────── */
run('git', ['add', `releases/${releaseId}`, readback], { quiet: true });
run('git', ['commit', '-q', '-m',
  `${generation}: ${step.scope}\n\n${step.note}\n\n` +
  `Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>\n` +
  `Claude-Session: ${SESSION_URL}`], { quiet: true });
const commit = git('rev-parse', 'HEAD');
untrackedBefore = null;
stage('committed', { commit: commit.slice(0, 7), generation });

{
  const r = run('git', ['push', 'origin', 'HEAD:main'], { allowFail: true, quiet: true });
  if (r.status !== 0) {
    entry.outcome = 'committed-not-pushed'; entry.reason = r.out.slice(-800);
    entry.finished_at = new Date().toISOString(); record(entry);
    console.log(`\n\x1b[31mpush refused\x1b[0m`);
    process.exit(1);
  }
  stage('pushed', { remote: 'origin/main' });
}

/* ── publish the snapshot to the public host ─────────────────────────── */
const snapshot = path.join(GG, 'pipelinenews_intelligence', generation);
if (fs.existsSync(snapshot)) fail('a snapshot for this generation already exists', { snapshot });
fs.cpSync(releaseDir, snapshot, { recursive: true });
stage('snapshot copied', { to: slash(path.relative(GG, snapshot)) });

/* the snapshot must be the release, byte for byte */
{
  const walk = (dir, base = '') => fs.readdirSync(dir, { withFileTypes: true }).flatMap(d =>
    d.isDirectory() ? walk(path.join(dir, d.name), `${base}${d.name}/`) : [`${base}${d.name}`]);
  const a = walk(releaseDir).sort();
  const b = walk(snapshot).sort();
  if (a.join('\n') !== b.join('\n')) fail('the snapshot does not contain the same files as the release');
  for (const rel of a) {
    if (!fs.readFileSync(path.join(releaseDir, rel)).equals(fs.readFileSync(path.join(snapshot, rel)))) {
      fail(`the snapshot differs from the release at ${rel}`);
    }
  }
  stage('snapshot verified byte-identical', { files: a.length });
}

gitAt(GG, 'add', path.join('pipelinenews_intelligence', generation));
run('git', ['commit', '-q', '-m',
  `${generation}: publish Pipeline News ${releaseId}\n\n${step.note}\n\n` +
  `The homepage index.html is deliberately NOT edited here: it is governed\n` +
  `by a numbered-snapshot ritual and a byte-exact sentinel contract, and\n` +
  `naming a release on it is a separate deliberate act.\n\n` +
  `Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>\n` +
  `Claude-Session: ${SESSION_URL}`],
  { cwd: GG, quiet: true, allowFail: true });
{
  const r = run('git', ['push', 'origin', 'HEAD:main'], { cwd: GG, allowFail: true, quiet: true });
  if (r.status !== 0) fail('the snapshot was committed and could not be pushed', { output: r.out.slice(-800) });
  stage('snapshot pushed', { repo: 'globalgrid2050' });
}

/* ── the live bytes ──────────────────────────────────────────────────── */
const liveUrl = `${LIVE_BASE}/${generation}/`;
let live = null;
/* WHAT THE LOOP SAW, NOT JUST THAT IT GAVE UP. A run that cannot reach the
   host at all and a host that is genuinely slow to rebuild both end this loop
   with live === null, and they are not the same fact. Recording the last
   status and the last transport error keeps 'published' from being read as
   'the host was slow' when the truth was that this runner never got out of its
   own network - which is exactly what happened on 202609020552, where every
   attempt came back 403 from an egress proxy refusing CONNECT and none of them
   was globalgrid2050.com answering anything. */
const observed = { attempts: 0, last_status: null, last_error: null, statuses: {} };
const deadline = Date.now() + 15 * 60 * 1000;
while (Date.now() < deadline) {
  observed.attempts += 1;
  try {
    const res = await fetch(liveUrl, { cache: 'no-store' });
    observed.last_status = res.status;
    observed.statuses[res.status] = (observed.statuses[res.status] || 0) + 1;
    if (res.ok) {
      const html = await res.text();
      live = { url: liveUrl, status: res.status, bytes: html.length,
        names_its_generation: html.includes(generation) };
      if (live.names_its_generation) break;
    }
    process.stdout.write(`  waiting for ${liveUrl} (${res.status})\r`);
  } catch (error) {
    observed.last_error = error.message;
    process.stdout.write(`  live check: ${error.message}\r`);
  }
  await new Promise(r => setTimeout(r, 20000));
}

entry.generation = generation;
entry.release_id = releaseId;
entry.commit = commit;
entry.live = live;

/* SERVED IS NOT REACHABLE. index.html is the only route a reader has to a
   published snapshot, and this runner deliberately does not edit it - naming a
   release there is a separate, deliberate act. Both facts held for 202609012326
   and 202609020025: byte-identical, pushed, served with HTTP 200, and linked
   from nothing, so the newest version a reader could reach stayed three behind.
   Recorded here so that state can never again read as a finished cut. */
{
  const reach = isReachable(generation, { globalgrid: GG });
  entry.homepage = reach.available
    ? { named: reach.named, is_newest_named: reach.is_newest_named,
        served_but_reachable_from_nothing: reach.unreachable }
    : { skipped: reach.reason };
}
entry.finished_at = new Date().toISOString();

if (!live) {
  /* Published, and not yet served. Both repositories have it and the
     snapshot was verified byte-identical to the release; the public host
     rebuilds on its own schedule. Recorded as exactly that - not claimed
     as live, and not treated as a failure of the cut, because nothing
     about the cut failed. */
  entry.outcome = 'published';
  entry.reason = 'published to both repositories and verified byte-identical; '
    + 'the runner did not observe the public host serving it within 15 minutes. '
    + 'Not claimed as live. See live_observed for WHAT was seen - a status that '
    + 'never came from the host is not evidence about the host.';
  entry.live_url = liveUrl;
  entry.live_observed = observed;
  record(entry);
  console.log(`\n\x1b[33m${releaseId} published; ${liveUrl} not serving yet\x1b[0m`);
  process.exit(0);
}
if (!live.names_its_generation) {
  entry.outcome = 'live-but-not-its-own-generation';
  entry.reason = 'the served page does not name the generation it claims to be';
  record(entry);
  process.exit(1);
}

entry.outcome = 'live';
record(entry);
run('git', ['add', slash(path.relative(ROOT, LOG))], { quiet: true, allowFail: true });
run('git', ['commit', '-q', '-m', `${utcNow()}: overnight - ${releaseId} verified live`], { allowFail: true, quiet: true });
run('git', ['push', 'origin', 'HEAD:main'], { allowFail: true, quiet: true });
console.log(`\n\x1b[32m${releaseId} is live at ${liveUrl}\x1b[0m`);
if (entry.homepage && entry.homepage.named === false) {
  console.log(`\x1b[33mand reachable from nothing: globalgrid2050.com/index.html does not name ${generation}.`
    + ` Serving it is not publishing it - name it there deliberately.\x1b[0m`);
}