GLOBALGRID2050 / EXPLORE CODE

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

Generate PipelineNews V8 Atman and 1 more file

A JavaScript module that draws performance audit, 11kV, the Renewable Energy Planning Database (REPD) register and substations.

549 lines of JavaScript from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1000 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. Generate PipelineNews V8 Atman render · pipelinenews / atman/202608262042-generate-pipelinenews-v8-atman.mjs lines 1–303
  2. Performance Audit render · pipelinenews / atman/202608262120-performance-audit.mjs lines 1–246

Generate PipelineNews V8 Atman

A JavaScript module that draws performance audit, 11kV, the Renewable Energy Planning Database (REPD) register and substations.

renderpipelinenews / atman/202608262042-generate-pipelinenews-v8-atman.mjs · lines 1–303 of 303 · version 2026-08-26 20:42 · Entry point · pattern ratio (shared by 8 files)

What it does
It draws performance audit, 11kV, the REPD register and substations. Defines mobile, n, ratio. Uses libraries node:fs, node:path, node:assert/strict. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path 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: 11kV, the REPD register, substations, 400kV.
Inputs & outputs
In: JSON file performance-audit.json; DuckDB queries. Voltage levels named: 400kV, 11kV.
Downstream impact
Used directly by 1 file: PipelineNews Atman V8 Architecture Report Workflow (pipelinenews).
What it achieves
Its name says it generates PipelineNews atman. Defines `mobile` and `ratio`. Its code works with 11 kV and 400 kV. It writes `atman-report-path.txt`.
Why it matters
Run by PipelineNews Atman V8 Architecture Report Workflow.
Application
pipelinenews · atman · JavaScript module
Uses
node:fs, node:path, node:assert/strict
Used by
run by PipelineNews Atman V8 Architecture Report Workflow (workflow run)
Produces
mobile, n, ratio
Defines here
mobile, n, ratio
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 atman/202608262042-generate-pipelinenews-v8-atman.mjs:1-303 · blob 2d11dcecbdea735afb118698d1b4937e57ba14f4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from "node:fs";
import path from "node:path";
import assert from "node:assert/strict";

const auditPath = process.env.AUDIT_JSON || "audit-input/performance-audit.json";
const stamp = process.env.REPORT_STAMP;
const auditRun = process.env.AUDIT_RUN_ID;
const repository = process.env.GITHUB_REPOSITORY || "Ventusltd/pipelinenews";
const dispatchSha = process.env.GITHUB_SHA || "unknown";
assert.match(stamp || "", /^\d{12}$/, "REPORT_STAMP must be YYYYMMDDHHMM");
assert.match(auditRun || "", /^\d+$/, "AUDIT_RUN_ID required");

const audit = JSON.parse(fs.readFileSync(auditPath, "utf8"));
const atlasEngine = fs.readFileSync("atman-input/atlas-v8-engine.js", "utf8");
const atlasIndex = fs.readFileSync("atman-input/atlas-v8-index.html", "utf8");
const pipelineProjects = fs.readFileSync("ui/javascript/202608261804-projects-v9-5-1.js", "utf8");
const pipelineLoader = fs.readFileSync("ui/javascript/202608261752-canonical-projects-v9-1.js", "utf8");

for (const [label, source, needle] of [
  ["Pipeline full-table rendering", pipelineProjects, 'body.innerHTML = filtered.map'],
  ["Pipeline concurrent partition loading", pipelineLoader, 'Promise.all(payload.project_partitions.map'],
  ["Atlas bounded fetch queue", atlasEngine, 'new FetchQueue(4)'],
  ["Atlas URL promise cache", atlasEngine, 'urlCache[url]'],
  ["Atlas activation hydration", atlasEngine, 'hydrateLayer(layerId)'],
  ["Atlas empty source registration", atlasEngine, "FeatureCollection', features: []"],
  ["Atlas UKPN 11kV declaration", atlasIndex, 'id: "11kv"'],
  ["Atlas UKPN zoom gate", atlasIndex, 'minzoom: 13.5'],
]) assert.ok(source.includes(needle), `missing expected evidence: ${label}`);

const by = new Map(audit.summary.map(r => [`${r.target}|${r.profile}`, r]));
const mobile = id => {
  const row = by.get(`${id}|mobile`);
  assert.ok(row, `missing mobile audit row: ${id}`);
  return row;
};
const mod = mobile("pipelinenews-modular");
const v961 = mobile("globalgrid-v9.6.1");
const v5 = mobile("globalgrid-v5");
const original = mobile("globalgrid-original");
assert.equal(mod.tableRows, 7680);
assert.ok(mod.domElements > 300000);
assert.ok(mod.nodes > 600000);
assert.ok(mod.sortTaskMs > 5000);

const n = value => Number(value).toLocaleString("en-GB", { maximumFractionDigits: 2 });
const ratio = (a,b) => (a / b).toFixed(1) + "×";
const reportPath = `atman/${stamp}-PIPELINENEWS-V8-ARCHITECTURE-ATMAN.md`;

const report = `# PipelineNews V8 Architecture — Atman Decision Report

**Status:** DESIGN EVIDENCE ONLY — NO APPLICATION OR RELEASE CHANGE  
**Generated:** ${stamp} UTC by GitHub Actions  
**Repository:** ${repository}  
**Workflow dispatch commit:** \`${dispatchSha}\`  
**Performance evidence:** workflow run \`#${auditRun}\`  
**Audit source commit:** \`f4a5a1a9293a5c4b926062b1bc919c2046ac5c11\`  
**Atlas V8 source commit:** \`c36e41a689a62bdfa13b4258f3cbc48301854108\`

## 1. Decision statement

PipelineNews is not slow because 7,680 project records are intrinsically large. It is slow because every record is expanded into a complex physical DOM row, and every sort/filter destroys and reconstructs the whole table.

The recommended V8 architecture combines:

1. the original dashboard's immediate, compact interface;
2. Atlas V8's declarative registry, dormant cartridges, bounded hydration and failure isolation;
3. PipelineNews's canonical identity, news binding, gauges, filters, export and map links;
4. row virtualisation so browser workload remains bounded as projects, countries and news grow.

**Core invariant:** storage and registry coverage may grow without bound; active network, memory, main-thread and DOM work must remain bounded.

## 2. Actions evidence

The audit completed successfully. “Success” means the harness executed correctly; it does not mean the current application passed a performance budget.

| Mobile metric | Modular PipelineNews | V9.6.1 | V5 | Original |
|---|---:|---:|---:|---:|
| Project rows | ${n(mod.tableRows)} | ${n(v961.tableRows)} | ${n(v5.tableRows)} | ${n(original.tableRows)} |
| DOM elements | ${n(mod.domElements)} | ${n(v961.domElements)} | ${n(v5.domElements)} | ${n(original.domElements)} |
| Browser nodes | ${n(mod.nodes)} | ${n(v961.nodes)} | ${n(v5.nodes)} | ${n(original.nodes)} |
| Decoded resources | ${n(mod.decodedResourceMB)} MB | ${n(v961.decodedResourceMB)} MB | ${n(v5.decodedResourceMB)} MB | ${n(original.decodedResourceMB)} MB |
| Long-task total | ${n(mod.longTaskTotalMs)} ms | ${n(v961.longTaskTotalMs)} ms | ${n(v5.longTaskTotalMs)} ms | ${n(original.longTaskTotalMs)} ms |
| REPD-date sort task | ${n(mod.sortTaskMs)} ms | ${n(v961.sortTaskMs)} ms | not comparable | not comparable |
| Scroll stress task | ${n(mod.scrollTaskMs)} ms | ${n(v961.scrollTaskMs)} ms | ${n(v5.scrollTaskMs)} ms | ${n(original.scrollTaskMs)} ms |

PipelineNews creates ${ratio(mod.domElements, original.domElements)} the original dashboard's DOM elements and ${ratio(mod.nodes, original.nodes)} its browser nodes. Its mobile date sort blocks the main thread for approximately ${(mod.sortTaskMs / 1000).toFixed(1)} seconds.

The audit observed no failed requests, console errors or uncaught exceptions. The apparent break is main-thread starvation and DOM/memory pressure, not a missing asset.

The audit's \`settledMs\` includes a deliberate five-second observation delay and must not be used as a load-time comparison.

## 3. Code-level cause

Current PipelineNews:

\`\`\`js
body.innerHTML = filtered.map(project => {
  // creates the complete rich record row
}).join("");
\`\`\`

Every filter or REPD-date sort performs:

1. scan the complete project array;
2. sort matching project objects;
3. update gauges;
4. destroy the previous table;
5. construct thousands of rich HTML rows;
6. parse and lay out hundreds of thousands of elements.

The loader also downloads all 16 partitions through one unrestricted \`Promise.all()\`. Loading all records into background memory is acceptable at the present scale; coupling that load to full DOM materialisation is not.

## 4. Trusted Atlas V8 pattern

Atlas V8 performs five separate operations that PipelineNews currently conflates:

| Responsibility | Atlas implementation | Effect |
|---|---|---|
| Declaration | immutable layer configuration | capability exists without activation |
| Registration | empty hidden MapLibre source/layer | interface is ready before data |
| Activation | \`hydrateLayer(layerId)\` | data loads only when selected/preloaded |
| Bounded loading | \`FetchQueue(4)\` | prevents request storms |
| Deduplication | URL promise cache | shared cartridges download once |
| Health state | WAIT/LOAD/OK/EMPTY/FAIL | failure remains local to one layer |
| Rendering gate | visibility and \`minzoom\` | only useful detail is drawn |

### Large Atlas examples at the pinned commit

| Cartridge | Stored size | Startup |
|---|---:|---|
| 400 kV lines | 1.80 MB | selectively preloaded |
| major substations | 1.82 MB | selectively preloaded |
| UKPN 11 kV substations | 3.13 MB; approximately 15,126 points | \`preload:false\`, \`minzoom:13.5\` |
| global ports | 10.19 MB | \`preload:false\`; major/minor views share one URL |
| UK motorways | 11.49 MB | \`preload:false\` |
| UK mainline railways | 55.05 MB | \`preload:false\` |

Actions/Python fetches and converts upstream data before publication. The live browser does not call Overpass. A failed dormant cartridge cannot prevent the shell or unrelated layers from working.

## 5. V8 conceptual architecture

\`\`\`text
Actions producers
  → validate cartridges
  → compile registry + indexes + summaries
  → immutable shared data
  → lightweight application shell
  → bounded runtime activator
      → virtual project table
      → virtual news stream
      → lazy map/details/export plugins
\`\`\`

### 5.1 Registry

The registry remains pure data. It may declare:

- identity and schema version;
- country, region, technology and period;
- cartridge URL, byte size, record count and digest;
- activation condition;
- preload policy;
- dependencies;
- indexes and supported operations;
- renderer capability;
- expected non-empty/empty state.

It must not contain executable joins, arbitrary expressions or business logic.

### 5.2 Runtime lifecycle

Every cartridge/plugin uses:

\`WAIT → QUEUED → LOAD → INDEX → OK\`  
\`                         ↘ EMPTY\`  
\`                         ↘ FAIL\`

A bounded queue, request-promise cache and AbortController protect the runtime. Failure affects only the requested capability.

### 5.3 Canonical project store

All 7,680 current projects may remain in background memory. Growth is partitioned by country, technology and/or stable hash range. The canonical identity record remains singular; filters hold references or integer offsets rather than duplicated objects.

Sorting must reorder an index/reference array. It must never rebuild the complete DOM.

### 5.4 Virtual project renderer

The table preserves all 11 columns and horizontal mobile scrolling, but creates only the visible window plus overscan.

- target physical rows: 30–60;
- spacer height represents off-screen records;
- row elements are recycled;
- delegated events remain attached once;
- details are created only when opened;
- scrolling changes indexes bound to existing rows.

### 5.5 Infinite news model

News follows the Atlas UKPN principle: complete availability, dormant history and bounded visibility.

Partition news by country, period and optionally technology. Compile small indexes for latest headlines, project IDs, countries, technologies and dates. At startup load only registry metadata and the newest visible slice.

Scrolling, filters, search or opening a project activates the required partition. Only 20–40 article cards exist physically. Project-news binding operates on IDs/indexes, not pre-rendered cards.

### 5.6 Plugin activation

| Plugin | Startup policy |
|---|---|
| shell/navigation | immediate |
| precompiled totals | immediate |
| first project window | immediate after minimal index |
| remaining project cartridges | background/need-driven |
| gauges | precompiled initially; recompute in worker after filters |
| news latest slice | after shell or when visible |
| historic news | dormant |
| map | dormant until requested |
| project details | dormant until opened |
| CSV export | activate on request; stream/generate from records |

## 6. Actions compiler responsibilities

Actions—not the browser—must perform brute-force work:

1. validate schemas, digests, counts and referential integrity;
2. reject malformed cartridges and unexpected empty outputs;
3. compile registry and activation dependencies;
4. compile sort/filter/search indexes;
5. compile initial totals and latest-news slice;
6. ensure one canonical project identity;
7. browser-test mobile and desktop under cold/warm conditions;
8. enforce performance budgets;
9. emit a new immutable compiler and release only after every gate passes;
10. retain shared root data cartridges without copying them into each release.

## 7. Proposed performance gates

| Gate | V8 budget |
|---|---:|
| Physical project rows | ≤80 |
| Total DOM elements after boot | ≤5,000 |
| Browser nodes after repeated sorting | no sustained growth above 10% |
| Filter/sort interaction | ≤100 ms desktop; ≤200 ms mobile |
| Long task | none above 200 ms during ordinary interaction |
| Initial decoded application payload | ≤2 MB before optional cartridges |
| Main-thread scroll work | frame budget targeted; no multi-second task |
| Console/page/request errors | 0 |
| Record parity | exactly 7,680 for current UK release |
| Headline parity | exactly 133 for current release |
| Existing totals | exact parity |
| Existing columns/features | exact parity |

Budgets should be measured by Actions on the same four trusted comparison URLs until V8 becomes the new baseline.

## 8. Options

| Option | Description | Verdict |
|---|---|---|
| A | Retain full table and optimise templates | rejected; still scales with record count |
| B | Virtual table plus Atlas-style registry/cartridges | recommended |
| C | Server-side API/query service immediately | unnecessary for 7,680; retain as later scale step |
| D | Render pages of fixed rows only | viable fallback, but weaker continuous mobile experience |

## 9. Staged implementation proposal

1. Freeze the current modular release and evidence.
2. Build a virtual-table prototype against existing cartridges without changing data.
3. Prove 7,680-record parity and bounded DOM.
4. Introduce the schema-validated registry and lifecycle state.
5. Move filter/sort/search indexes behind the registry; use a worker where measured.
6. Convert news into latest/index/cartridge structure.
7. Lazy-activate news, map, details and export.
8. Run comparative Actions performance and functional parity gates.
9. Compile a new immutable PipelineNews V8 candidate.
10. Deploy only after explicit owner decision.

## 10. Risks and deliberate limits

- Atlas V8's registry is embedded in HTML; V8 should extract and validate it.
- Atlas \`minzoom\` prevents rendering but does not by itself prevent a selected source from downloading. News requires both activation and partition gates.
- Existing Atlas producer scripts do not uniformly enforce schema/minimum-count checks. PipelineNews must fail closed in Actions.
- Some historical workflows copied below application folders are inert because GitHub recognises workflows only at repository-root \`.github/workflows/\`.
- Parquet, DuckDB-Wasm, PMTiles or a query API should be adopted only when measured scale requires them.
- “Infinite” means unbounded storage/catalogue growth, not loading infinite data into one browser session.

## 11. Owner decisions required before implementation

1. Confirm virtual scrolling rather than numbered pagination.
2. Confirm the original dashboard as the mobile visual baseline.
3. Confirm V8 numbering/name for the first candidate.
4. Confirm initial news partition axis: month, country+month, or country+technology+month.
5. Confirm whether initial totals are permitted to come from compiler-generated summaries before background records finish loading.

## 12. Recommendation

Proceed with Option B only after owner approval: original-dashboard presentation, Atlas-style registry and activation, virtual projects/news, shared cartridges, and Actions-enforced parity/performance gates.

No source application, compiler, release or deployment was changed by this report.
`;

fs.mkdirSync(path.dirname(reportPath), { recursive: true });
fs.writeFileSync(reportPath, report);
fs.writeFileSync("atman-report-path.txt", reportPath + "\n");
console.log(reportPath);

Performance Audit

A JavaScript module in the atman folder of PipelineNews that sorts Renewable Energy Planning Database (REPD) (`sortByRepd`), covering the REPD register.

renderpipelinenews / atman/202608262120-performance-audit.mjs · lines 1–246 of 246 · version 2026-08-26 21:20 · Entry point · pattern metrics (shared by 6 files)

What it does
It lists and searches the REPD register. Defines 6 functions or classes, including delta, metrics, snapshot, sortByRepd, stressScroll. Uses libraries playwright, node:fs/promises. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
Out: JSON file performance-audit.json.
Downstream impact
Used directly by 1 file: PipelineNews Performance Audit Workflow (pipelinenews).
What it achieves
It sorts REPD (`sortByRepd`) and is built from the stress scroll helper (`stressScroll`) and the median step (`median`). Defines `delta`, `metrics`, `snapshot` and 3 more. It writes `audit-results/performance-audit.json`.
Why it matters
Run by PipelineNews Performance Audit Workflow.
Application
pipelinenews · atman · JavaScript module
Uses
PipelineNews — Releases Page (estate URL), UK Renewables Pipeline — V9 6 1 Page (estate URL), Dashboard V5 Live (estate URL), Dashboard (estate URL), playwright, node:fs/promises
Used by
run by PipelineNews Performance Audit Workflow (workflow run)
Produces
delta, metrics, snapshot, sortByRepd, stressScroll, median
Defines here
delta, metrics, snapshot, sortByRepd, stressScroll, median
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 atman/202608262120-performance-audit.mjs:1-246 · blob 61e21c056bbe87fbb66eea739f8391c41dfd37d6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { chromium } from "playwright";
import fs from "node:fs/promises";

const targets = [
  { id: "pipelinenews-modular", url: "https://ventusltd.github.io/pipelinenews/releases/202608261927-index.html" },
  { id: "globalgrid-v9.6.1", url: "https://globalgrid2050.com/uk_renewables_pipeline/v9.6.1/?technology=solar&sort=updated_desc" },
  { id: "globalgrid-v5", url: "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v5_live.html" },
  { id: "globalgrid-original", url: "https://globalgrid2050.com/uk_renewables_pipeline/dashboard.html" },
];

const profiles = [
  { id: "mobile", viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true },
  { id: "desktop", viewport: { width: 1440, height: 900 }, isMobile: false, hasTouch: false },
];

const rounds = Number(process.env.AUDIT_ROUNDS || 3);
const browser = await chromium.launch({ headless: true });
const results = [];

function delta(after, before, key) {
  return Number(((after[key] || 0) - (before[key] || 0)).toFixed(3));
}

async function metrics(cdp) {
  const { metrics } = await cdp.send("Performance.getMetrics");
  return Object.fromEntries(metrics.map(({ name, value }) => [name, value]));
}

async function snapshot(page, cdp) {
  const perf = await page.evaluate(() => {
    const nav = performance.getEntriesByType("navigation")[0];
    const resources = performance.getEntriesByType("resource");
    const rows = [...document.querySelectorAll("tbody tr")];
    const visibleRows = rows.filter((el) => {
      const r = el.getBoundingClientRect();
      const s = getComputedStyle(el);
      return r.height > 0 && s.display !== "none" && s.visibility !== "hidden";
    });
    return {
      title: document.title,
      readyState: document.readyState,
      textLength: document.body?.innerText.length || 0,
      domElements: document.getElementsByTagName("*").length,
      tableRows: rows.length,
      visibleRows: visibleRows.length,
      bodyHeight: document.documentElement.scrollHeight,
      viewportHeight: innerHeight,
      navigation: nav ? {
        ttfb: nav.responseStart,
        domContentLoaded: nav.domContentLoadedEventEnd,
        load: nav.loadEventEnd,
        transferSize: nav.transferSize,
        encodedBodySize: nav.encodedBodySize,
        decodedBodySize: nav.decodedBodySize,
      } : null,
      resources: {
        count: resources.length,
        transferSize: resources.reduce((n, r) => n + (r.transferSize || 0), 0),
        encodedBodySize: resources.reduce((n, r) => n + (r.encodedBodySize || 0), 0),
        decodedBodySize: resources.reduce((n, r) => n + (r.decodedBodySize || 0), 0),
        json: resources.filter((r) => /\.json(?:\?|$)/i.test(r.name)).length,
        scripts: resources.filter((r) => r.initiatorType === "script").length,
      },
      longTasks: globalThis.__auditLongTasks || [],
    };
  });
  return { ...perf, engine: await metrics(cdp) };
}

async function sortByRepd(page) {
  return page.evaluate(async () => {
    const started = performance.now();
    const selects = [...document.querySelectorAll("select")];
    for (const select of selects) {
      const option = [...select.options].find((o) =>
        /repd.*(updated|date)|updated.*(newest|desc)|newest/i.test(o.textContent || "")
      );
      if (option) {
        select.value = option.value;
        select.dispatchEvent(new Event("change", { bubbles: true }));
        await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
        return { found: true, method: "select", label: option.textContent.trim(), duration: performance.now() - started };
      }
    }
    const clickable = [...document.querySelectorAll("button,[role=button],th,a")].find((el) =>
      /repd.*(updated|date)|updated.*(newest|desc)|newest/i.test(el.textContent || "")
    );
    if (clickable) {
      clickable.click();
      await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
      return { found: true, method: "click", label: clickable.textContent.trim(), duration: performance.now() - started };
    }
    return { found: false, duration: performance.now() - started };
  });
}

async function stressScroll(page) {
  return page.evaluate(async () => {
    const started = performance.now();
    const max = Math.max(0, document.documentElement.scrollHeight - innerHeight);
    const samples = [];
    for (let i = 0; i <= 20; i++) {
      scrollTo(0, max * (i / 20));
      await new Promise((r) => requestAnimationFrame(r));
      samples.push({ y: scrollY, height: document.documentElement.scrollHeight });
    }
    for (let i = 20; i >= 0; i--) {
      scrollTo(0, max * (i / 20));
      await new Promise((r) => requestAnimationFrame(r));
    }
    return { duration: performance.now() - started, max, samples };
  });
}

for (const profile of profiles) {
  const context = await browser.newContext(profile);
  for (const target of targets) {
    for (let round = 1; round <= rounds; round++) {
      const page = await context.newPage();
      const cdp = await context.newCDPSession(page);
      await cdp.send("Performance.enable");
      await page.addInitScript(() => {
        globalThis.__auditLongTasks = [];
        new PerformanceObserver((list) => {
          for (const e of list.getEntries()) {
            globalThis.__auditLongTasks.push({ start: e.startTime, duration: e.duration });
          }
        }).observe({ type: "longtask", buffered: true });
      });
      const consoleErrors = [];
      const pageErrors = [];
      const failedRequests = [];
      page.on("console", (m) => { if (m.type() === "error") consoleErrors.push(m.text()); });
      page.on("pageerror", (e) => pageErrors.push(String(e)));
      page.on("requestfailed", (r) => failedRequests.push({ url: r.url(), error: r.failure()?.errorText }));

      const wallStart = Date.now();
      let navigationError = null;
      try {
        await page.goto(target.url, { waitUntil: "domcontentloaded", timeout: 60000 });
        await page.waitForLoadState("load", { timeout: 60000 }).catch(() => {});
        await page.waitForTimeout(5000);
      } catch (e) {
        navigationError = String(e);
      }
      const settledMs = Date.now() - wallStart;
      const before = await snapshot(page, cdp);
      const engineBefore = before.engine;
      const sort = await sortByRepd(page);
      await page.waitForTimeout(1500);
      const afterSort = await snapshot(page, cdp);
      const scroll = await stressScroll(page);
      await page.waitForTimeout(500);
      const afterScroll = await snapshot(page, cdp);

      if (round === 1) {
        await page.screenshot({ path: `audit-results/${target.id}-${profile.id}.png`, fullPage: true });
      }
      results.push({
        target: target.id,
        url: target.url,
        profile: profile.id,
        round,
        settledMs,
        navigationError,
        before,
        sort,
        afterSort,
        scroll,
        afterScroll,
        cost: {
          sortTaskMs: delta(afterSort.engine, engineBefore, "TaskDuration") * 1000,
          sortScriptMs: delta(afterSort.engine, engineBefore, "ScriptDuration") * 1000,
          sortLayoutCount: delta(afterSort.engine, engineBefore, "LayoutCount"),
          sortRecalcStyleCount: delta(afterSort.engine, engineBefore, "RecalcStyleCount"),
          scrollTaskMs: delta(afterScroll.engine, afterSort.engine, "TaskDuration") * 1000,
          scrollScriptMs: delta(afterScroll.engine, afterSort.engine, "ScriptDuration") * 1000,
          scrollLayoutCount: delta(afterScroll.engine, afterSort.engine, "LayoutCount"),
          scrollRecalcStyleCount: delta(afterScroll.engine, afterSort.engine, "RecalcStyleCount"),
          heapAfterLoadMB: Number(((before.engine.JSHeapUsedSize || 0) / 1048576).toFixed(2)),
          heapAfterScrollMB: Number(((afterScroll.engine.JSHeapUsedSize || 0) / 1048576).toFixed(2)),
          nodesAfterLoad: before.engine.Nodes || null,
          nodesAfterScroll: afterScroll.engine.Nodes || null,
        },
        consoleErrors,
        pageErrors,
        failedRequests,
      });
      await page.close();
    }
  }
  await context.close();
}
await browser.close();

const groups = new Map();
for (const r of results) {
  const key = `${r.target}|${r.profile}`;
  const rows = groups.get(key) || [];
  rows.push(r);
  groups.set(key, rows);
}
const median = (values) => {
  const a = values.filter(Number.isFinite).sort((x, y) => x - y);
  return a.length ? a[Math.floor(a.length / 2)] : null;
};
const summary = [...groups].map(([key, rows]) => {
  const [target, profile] = key.split("|");
  return {
    target, profile,
    settledMs: median(rows.map((r) => r.settledMs)),
    domElements: median(rows.map((r) => r.before.domElements)),
    tableRows: median(rows.map((r) => r.before.tableRows)),
    bodyHeight: median(rows.map((r) => r.before.bodyHeight)),
    resourceTransferKB: median(rows.map((r) => r.before.resources.transferSize / 1024)),
    decodedResourceMB: median(rows.map((r) => r.before.resources.decodedBodySize / 1048576)),
    longTaskCount: median(rows.map((r) => r.before.longTasks.length)),
    longTaskTotalMs: median(rows.map((r) => r.before.longTasks.reduce((n, x) => n + x.duration, 0))),
    loadTaskMs: median(rows.map((r) => (r.before.engine.TaskDuration || 0) * 1000)),
    loadScriptMs: median(rows.map((r) => (r.before.engine.ScriptDuration || 0) * 1000)),
    heapMB: median(rows.map((r) => r.cost.heapAfterLoadMB)),
    nodes: median(rows.map((r) => r.cost.nodesAfterLoad)),
    sortTaskMs: median(rows.map((r) => r.cost.sortTaskMs)),
    sortLayoutCount: median(rows.map((r) => r.cost.sortLayoutCount)),
    scrollWallMs: median(rows.map((r) => r.scroll.duration)),
    scrollTaskMs: median(rows.map((r) => r.cost.scrollTaskMs)),
    scrollLayoutCount: median(rows.map((r) => r.cost.scrollLayoutCount)),
    errors: rows.reduce((n, r) => n + r.consoleErrors.length + r.pageErrors.length + r.failedRequests.length, 0),
  };
});

await fs.writeFile("audit-results/performance-audit.json", JSON.stringify({ generatedAt: new Date().toISOString(), rounds, summary, results }, null, 2));
const cols = ["target","profile","settledMs","resourceTransferKB","decodedResourceMB","domElements","tableRows","longTaskCount","longTaskTotalMs","loadTaskMs","heapMB","nodes","sortTaskMs","sortLayoutCount","scrollWallMs","scrollTaskMs","scrollLayoutCount","errors"];
const md = [
  "# PipelineNews performance audit",
  "",
  "Measured in GitHub Actions Chromium. Medians are reported; raw runs and screenshots are in the artifact.",
  "",
  "| " + cols.join(" | ") + " |",
  "|" + cols.map(() => "---").join("|") + "|",
  ...summary.map((r) => "| " + cols.map((c) => r[c] == null ? "" : typeof r[c] === "number" ? Number(r[c].toFixed(2)) : r[c]).join(" | ") + " |"),
  "",
  "Interpretation must use the raw evidence. This audit performs no deployment and changes no release.",
].join("\n");
await fs.writeFile("audit-results/performance-audit.md", md);
console.log(md);