GLOBALGRID2050 / EXPLORE CODE

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

Verify Mobile UI Browser and 1 more file

A JavaScript module in the atman folder of PipelineNews that applies area (`applySafeArea`), attaches diagnostics (`attachDiagnostics`) and selects full page capture (`selectFullPageCapture`), using SHA-256.

650 lines of JavaScript from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1005 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. Verify Mobile UI Browser interaction · pipelinenews / atman/202608271656-verify-mobile-ui-browser.mjs lines 1401–1963
  2. Verify V9 6 2 Equivalence render · pipelinenews / atman/202608282150-verify-v9-6-2-equivalence.mjs lines 1–87

Verify Mobile UI Browser

A JavaScript module in the atman folder of PipelineNews that applies area (`applySafeArea`), attaches diagnostics (`attachDiagnostics`) and selects full page capture (`selectFullPageCapture`), using SHA-256.

interactionpipelinenews / atman/202608271656-verify-mobile-ui-browser.mjs · lines 1401–1963 of 1963 · version 2026-08-27 16:56 (continued from section 1003) · Entry point · pattern sha256File (shared by 4 files)

What it does
It draws its content. Defines 55 functions or classes, including selectedIds, slug, serialiseError, relativeEvidencePath, writeJson. Uses libraries node:crypto, node:fs, node:fs/promises, node:path, node:module. 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.
Inputs & outputs
In: JSON file run.json; command-line arguments.
Downstream impact
Used directly by 1 file: PipelineNews Mobile CSS Repair Workflow (pipelinenews).
What it achieves
It serialises error (`serialiseError`), writes JSON (`writeJson`) and applies safe area (`applySafeArea`). Its name says it verifies mobile UI browser. Defines `selectedIds`, `slug`, `serialiseError` and 52 more.
Why it matters
Run by PipelineNews Mobile CSS Repair Workflow.
Application
pipelinenews · atman · JavaScript module
Uses
Mobile UI Invariants (import), node:crypto, node:fs, node:fs/promises, node:path, node:module, playwright, sharp, playwright/package.json
Used by
run by PipelineNews Mobile CSS Repair Workflow (workflow run)
Produces
selectedIds, slug, serialiseError, relativeEvidencePath, writeJson, sha256File, invariantResult, emptyInvariantResults, applySafeArea, attachDiagnostics, favicon, retain
Defines here
appendRotationTrace, rotationGeometryMatchesExpected, runRotationPhase, rotationViewportReady, applyRotationViewport, isStrictlyMonotonicGrowth, rotationMeasurement, runStaticCell, captureAndRestoreRotationScreenshot, runRotateCell, expectedGeometry, phase, unavailableRecord, saveRecord
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/202608271656-verify-mobile-ui-browser.mjs:1401-1963 · blob fcba98c5336221df52e233d5acc0f42a15c188f8 · 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
      playwright_viewport: playwrightViewport,
      browser,
      observation_error: null,
    };
  } catch (error) {
    return {
      captured_at: new Date().toISOString(),
      playwright_viewport: playwrightViewport,
      browser: null,
      observation_error: serialiseError(error),
    };
  }
}

function appendRotationTrace(trace, entry) {
  if (trace.length >= 96) trace.shift();
  trace.push(entry);
}

function rotationGeometryMatchesExpected(observed, expected) {
  if (!expected) return true;
  const browser = observed?.browser;
  const playwright = observed?.playwright_viewport;
  if (!browser || !playwright || observed.observation_error) return false;
  const orientationMatches = expected.orientation === "landscape"
    ? browser.landscape && !browser.portrait
    : browser.portrait && !browser.landscape;
  return (
    playwright.width === expected.width
    && playwright.height === expected.height
    && browser.inner_width === expected.width
    && browser.inner_height === expected.height
    && browser.device_pixel_ratio === expected.device_pixel_ratio
    && orientationMatches
  );
}

async function runRotationPhase(page, trace, descriptor, operation) {
  const before = await observeRotationGeometry(page);
  appendRotationTrace(trace, {
    phase: descriptor.phase,
    operation: descriptor.operation,
    status: "STARTED",
    expected_geometry: descriptor.expected_geometry || null,
    observed_geometry: before,
  });
  try {
    const value = await operation();
    const after = await observeRotationGeometry(page);
    if (!rotationGeometryMatchesExpected(after, descriptor.expected_geometry)) {
      const mismatch = new Error(
        `Post-operation geometry does not match phase ${descriptor.phase}`,
      );
      mismatch.name = "RotationGeometryMismatchError";
      mismatch.expected_geometry = descriptor.expected_geometry || null;
      mismatch.observed_geometry = after;
      throw mismatch;
    }
    appendRotationTrace(trace, {
      phase: descriptor.phase,
      operation: descriptor.operation,
      status: "COMPLETED",
      expected_geometry: descriptor.expected_geometry || null,
      observed_geometry: after,
    });
    return value;
  } catch (cause) {
    const observed = await observeRotationGeometry(page);
    appendRotationTrace(trace, {
      phase: descriptor.phase,
      operation: descriptor.operation,
      status: "FAILED",
      expected_geometry: descriptor.expected_geometry || null,
      observed_geometry: observed,
      cause: serialiseError(cause),
    });
    const browserGeometry = observed.browser;
    const observedLabel = browserGeometry
      ? `${browserGeometry.inner_width}x${browserGeometry.inner_height}; `
        + `portrait=${browserGeometry.portrait}; landscape=${browserGeometry.landscape}`
      : "unavailable";
    const error = new Error(
      `Rotation phase ${descriptor.phase} (${descriptor.operation}) failed; observed ${observedLabel}`,
      { cause },
    );
    error.name = "RotationPhaseError";
    error.rotation_phase = descriptor.phase;
    error.rotation_operation = descriptor.operation;
    error.expected_geometry = descriptor.expected_geometry || null;
    error.observed_geometry = observed;
    error.rotation_trace = trace.slice();
    throw error;
  }
}

function rotationViewportReady({ width, height, orientation }) {
  return (
    innerWidth === width
    && innerHeight === height
    && matchMedia(`(orientation: ${orientation})`).matches
  );
}

async function applyRotationViewport(page, trace, viewport, dpr, phase) {
  const expectedGeometry = {
    width: viewport.width,
    height: viewport.height,
    orientation: viewport.orientation,
    device_pixel_ratio: dpr,
    driver: "playwright-page-set-viewport-size",
  };
  return runRotationPhase(page, trace, {
    phase,
    operation: "page.setViewportSize",
    expected_geometry: expectedGeometry,
  }, async () => {
    await page.setViewportSize({ width: viewport.width, height: viewport.height });
    await page.waitForFunction(rotationViewportReady, viewport, { timeout: 5_000 });
    await page.evaluate(() => new Promise((resolve) => {
      requestAnimationFrame(() => requestAnimationFrame(resolve));
    }));
  });
}

function isStrictlyMonotonicGrowth(values) {
  return values.length > 1 && values.slice(1).every((value, index) => value > values[index]);
}

function rotationMeasurement(snapshots) {
  const initial = snapshots[0];
  const final = snapshots.at(-1);
  const ratio = CONTRACT.thresholds.rotation_node_delta_ratio;
  const floor = CONTRACT.thresholds.rotation_node_delta_floor;
  const connectedTolerance = Math.max(floor, Math.ceil(initial.connected_elements * ratio));
  const cdpTolerance = Math.max(floor, Math.ceil(initial.cdp_nodes * ratio));
  const documentTolerance = Math.max(floor, Math.ceil(initial.cdp_documents * ratio));
  const listenerTolerance = Math.max(floor, Math.ceil(initial.cdp_js_event_listeners * ratio));
  const connectedDelta = final.connected_elements - initial.connected_elements;
  const cdpDelta = final.cdp_nodes - initial.cdp_nodes;
  const documentDelta = final.cdp_documents - initial.cdp_documents;
  const listenerDelta = final.cdp_js_event_listeners - initial.cdp_js_event_listeners;
  const connectedSeries = snapshots.map((snapshot) => snapshot.connected_elements);
  const cdpSeries = snapshots.map((snapshot) => snapshot.cdp_nodes);
  const detachedSupported = snapshots.every((snapshot) => snapshot.detached.supported);
  const detachedSeries = detachedSupported
    ? snapshots.map((snapshot) => snapshot.detached.detached_total)
    : [];
  const detachedInitial = detachedSeries[0] ?? null;
  const detachedFinal = detachedSeries.at(-1) ?? null;
  const detachedTolerance = detachedSupported ? 0 : null;
  const connectedStable = Math.abs(connectedDelta) <= connectedTolerance;
  const cdpStable = Math.abs(cdpDelta) <= cdpTolerance;
  const documentsStable = Math.abs(documentDelta) <= documentTolerance;
  const listenersStable = Math.abs(listenerDelta) <= listenerTolerance;
  const detachedStable = detachedSupported && detachedFinal <= detachedInitial;
  const monotonicGrowth = isStrictlyMonotonicGrowth(connectedSeries)
    || isStrictlyMonotonicGrowth(cdpSeries)
    || (detachedSupported && isStrictlyMonotonicGrowth(detachedSeries));
  return {
    viewport_driver: "playwright-page-set-viewport-size",
    viewport_readiness_gate: "inner-viewport-and-match-media-orientation",
    screen_fields_observed_not_gated: true,
    snapshots,
    connected_delta: connectedDelta,
    connected_tolerance: connectedTolerance,
    cdp_node_delta: cdpDelta,
    cdp_node_tolerance: cdpTolerance,
    cdp_document_delta: documentDelta,
    cdp_document_tolerance: documentTolerance,
    cdp_listener_delta: listenerDelta,
    cdp_listener_tolerance: listenerTolerance,
    detached_supported: detachedSupported,
    detached_total_initial: detachedInitial,
    detached_total_final: detachedFinal,
    detached_total_delta: detachedSupported ? detachedFinal - detachedInitial : null,
    detached_tolerance: detachedTolerance,
    connected_stable: connectedStable,
    cdp_nodes_stable: cdpStable,
    cdp_documents_stable: documentsStable,
    cdp_listeners_stable: listenersStable,
    detached_stable: detachedStable,
    monotonic_growth: monotonicGrowth,
    pass: connectedStable
      && cdpStable
      && documentsStable
      && listenersStable
      && detachedSupported
      && detachedStable,
  };
}

async function runStaticCell(browser, target, cell) {
  const context = await browser.newContext({
    viewport: { width: cell.width, height: cell.height },
    screen: { width: cell.width, height: cell.height },
    deviceScaleFactor: cell.dpr,
    isMobile: true,
    hasTouch: true,
    colorScheme: "dark",
  });
  const page = await context.newPage();
  const diagnostics = attachDiagnostics(page);
  const cdp = await context.newCDPSession(page);
  const safeArea = await applySafeArea(cdp, cell.id, cell.orientation);
  const capturedAt = new Date().toISOString();
  try {
    const ready = await navigate(page, target);
    const screenshots = await captureScreenshots(page, target.id, cell.id, "", cell);
    const menuExercise = await exerciseReleaseMenu(page);
    const measurements = await collectStaticMeasurements(page, cell, safeArea, menuExercise);
    return {
      schema: "pipelinenews.mobile-ui-cell-evidence.v1",
      generation: GENERATION,
      project_posture: CONTRACT.project_posture,
      source_commit: SOURCE_COMMIT,
      candidate_generation: candidateGeneration,
      mode: MODE,
      target,
      cell,
      availability: "MEASURED",
      captured_at: capturedAt,
      ready,
      diagnostics,
      safe_area_emulation: safeArea,
      screenshots,
      invariants: staticInvariantResults(measurements, cell),
    };
  } finally {
    await context.close();
  }
}

async function captureAndRestoreRotationScreenshot(steps) {
  const screenshot = await steps.capture();
  await steps.restoreViewport();
  await steps.restoreSafeArea();
  await steps.settle();
  return screenshot;
}

async function runRotateCell(browser, target) {
  const rotate = CONTRACT.rotate_cell;
  const initialViewport = rotate.sequence[0];
  const context = await browser.newContext({
    viewport: { width: initialViewport.width, height: initialViewport.height },
    screen: { width: initialViewport.width, height: initialViewport.height },
    deviceScaleFactor: rotate.dpr,
    isMobile: true,
    hasTouch: true,
    colorScheme: "dark",
  });
  const page = await context.newPage();
  const diagnostics = attachDiagnostics(page);
  const cdp = await context.newCDPSession(page);
  await cdp.send("DOM.enable");
  await cdp.send("Memory.enable").catch(() => {});
  await cdp.send("HeapProfiler.enable");
  const capturedAt = new Date().toISOString();
  const rotationTrace = [];
  const expectedGeometry = (viewport) => ({
    width: viewport.width,
    height: viewport.height,
    orientation: viewport.orientation,
    device_pixel_ratio: rotate.dpr,
  });
  const phase = (phaseId, operation, viewport, action) => runRotationPhase(page, rotationTrace, {
    phase: phaseId,
    operation,
    expected_geometry: viewport ? expectedGeometry(viewport) : null,
  }, action);
  try {
    const ready = await phase(
      "initial-P1-navigation",
      "navigate-and-ready",
      initialViewport,
      () => navigate(page, target),
    );
    await applyRotationViewport(
      page,
      rotationTrace,
      initialViewport,
      rotate.dpr,
      "initial-P1-viewport",
    );
    const initialSafeArea = await phase(
      "initial-P1-safe-area",
      "applySafeArea",
      initialViewport,
      () => applySafeArea(cdp, "P1", initialViewport.orientation),
    );
    const screenshots = {
      initial: await phase(
        "initial-P1-screenshot",
        "captureScreenshots",
        initialViewport,
        () => captureScreenshots(page, target.id, rotate.id, "initial", initialViewport),
      ),
      landscape: null,
      final: null,
    };
    const snapshots = [await phase(
      "initial-P1-node-snapshot",
      "nodeSnapshot",
      initialViewport,
      () => nodeSnapshot(page, cdp, "initial-P1", initialViewport),
    )];
    for (let cycle = 1; cycle <= rotate.cycles; cycle += 1) {
      const landscape = rotate.sequence[1];
      await applyRotationViewport(
        page,
        rotationTrace,
        landscape,
        rotate.dpr,
        `cycle-${cycle}-L1-transition`,
      );
      await phase(
        `cycle-${cycle}-L1-safe-area`,
        "applySafeArea",
        landscape,
        () => applySafeArea(cdp, "L1", landscape.orientation),
      );
      await phase(
        `cycle-${cycle}-L1-settle`,
        "waitForTimeout",
        landscape,
        () => page.waitForTimeout(rotate.settle_ms),
      );
      if (cycle === 1) {
        screenshots.landscape = await captureAndRestoreRotationScreenshot({
          capture: () => phase(
            `cycle-${cycle}-L1-screenshot`,
            "captureScreenshots",
            landscape,
            () => captureScreenshots(page, target.id, rotate.id, "landscape", landscape),
          ),
          restoreViewport: () => applyRotationViewport(
            page,
            rotationTrace,
            landscape,
            rotate.dpr,
            `cycle-${cycle}-L1-post-screenshot-restore`,
          ),
          restoreSafeArea: () => phase(
            `cycle-${cycle}-L1-post-screenshot-safe-area`,
            "applySafeArea",
            landscape,
            () => applySafeArea(cdp, "L1", landscape.orientation),
          ),
          settle: () => phase(
            `cycle-${cycle}-L1-post-screenshot-settle`,
            "waitForTimeout",
            landscape,
            () => page.waitForTimeout(rotate.settle_ms),
          ),
        });
      }
      snapshots.push(await phase(
        `cycle-${cycle}-L1-node-snapshot`,
        "nodeSnapshot",
        landscape,
        () => nodeSnapshot(page, cdp, `cycle-${cycle}-L1`, landscape),
      ));

      const portrait = rotate.sequence[2];
      await applyRotationViewport(
        page,
        rotationTrace,
        portrait,
        rotate.dpr,
        `cycle-${cycle}-P1-transition`,
      );
      await phase(
        `cycle-${cycle}-P1-safe-area`,
        "applySafeArea",
        portrait,
        () => applySafeArea(cdp, "P1", portrait.orientation),
      );
      await phase(
        `cycle-${cycle}-P1-settle`,
        "waitForTimeout",
        portrait,
        () => page.waitForTimeout(rotate.settle_ms),
      );
      snapshots.push(await phase(
        `cycle-${cycle}-P1-node-snapshot`,
        "nodeSnapshot",
        portrait,
        () => nodeSnapshot(page, cdp, `cycle-${cycle}-P1`, portrait),
      ));
    }
    const finalViewport = rotate.sequence[2];
    screenshots.final = await phase(
      "final-P1-screenshot",
      "captureScreenshots",
      finalViewport,
      () => captureScreenshots(page, target.id, rotate.id, "final", finalViewport),
    );
    const measurement = rotationMeasurement(snapshots);
    const invariants = CONTRACT.invariants
      .filter(({ id }) => id !== "I12")
      .map((descriptor) => descriptor.id === "I9"
        ? invariantResult("I9", true, measurement.pass, measurement)
        : invariantResult(descriptor.id, false, null, { reason: "not evaluated in rotation cell" }));
    return {
      schema: "pipelinenews.mobile-ui-cell-evidence.v1",
      generation: GENERATION,
      project_posture: CONTRACT.project_posture,
      source_commit: SOURCE_COMMIT,
      candidate_generation: candidateGeneration,
      mode: MODE,
      target,
      cell: rotate,
      availability: "MEASURED",
      captured_at: capturedAt,
      ready,
      diagnostics: { ...diagnostics, rotation_trace: rotationTrace },
      safe_area_emulation: initialSafeArea,
      screenshots,
      invariants,
    };
  } catch (cause) {
    const error = cause instanceof Error ? cause : new Error(String(cause));
    error.rotation_trace ||= rotationTrace.slice();
    error.browser_diagnostics = diagnostics;
    throw error;
  } finally {
    await context.close();
  }
}

function unavailableRecord(target, cell, error, rotate = false) {
  const failure = serialiseError(error);
  const browserDiagnostics = error?.browser_diagnostics || {
    console_errors: [],
    page_errors: [],
    failed_requests: [],
    http_errors: [],
  };
  return {
    schema: "pipelinenews.mobile-ui-cell-evidence.v1",
    generation: GENERATION,
    project_posture: CONTRACT.project_posture,
    source_commit: SOURCE_COMMIT,
    candidate_generation: candidateGeneration,
    mode: MODE,
    target,
    cell,
    availability: "UNAVAILABLE",
    captured_at: new Date().toISOString(),
    ready: null,
    diagnostics: {
      ...browserDiagnostics,
      failure_class: rotate ? "rotation-instrument" : "navigation-readiness-or-instrument",
      navigation_error: failure,
      rotation_failure: rotate ? failure : null,
    },
    safe_area_emulation: null,
    screenshots: null,
    invariants: emptyInvariantResults("target unavailable", rotate),
  };
}

async function saveRecord(record) {
  const filename = `${slug(record.target.id)}--${slug(record.cell.id)}.json`;
  const bytes = Buffer.from(`${JSON.stringify(record, null, 2)}\n`, "utf8");
  if (bytes.length > CELL_RECORD_LIMIT_BYTES) {
    throw new Error(`${filename} exceeds the ${CELL_RECORD_LIMIT_BYTES}-byte bounded record budget`);
  }
  await writeFile(path.join(RAW_DIR, filename), bytes);
  recordFiles.push(filename);
}

const browser = await chromium.launch({ headless: true });
let chromiumVersion;
try {
  chromiumVersion = browser.version();
  for (const target of targets) {
    for (const cell of staticCells) {
      if (target.id === "original" && optionalOriginalFailure) {
        await saveRecord(unavailableRecord(target, cell, optionalOriginalFailure));
        continue;
      }
      try {
        await saveRecord(await runStaticCell(browser, target, cell));
      } catch (error) {
        await saveRecord(unavailableRecord(target, cell, error));
        if (target.required) requiredFailures.push({ target: target.id, cell: cell.id, error: serialiseError(error) });
        else optionalOriginalFailure = error;
      }
    }
  }

  if (includeRotate) {
    for (const targetId of CONTRACT.rotate_cell.targets.filter((id) => selectedTargetIds.includes(id))) {
      const target = targets.find(({ id }) => id === targetId);
      if (!target) throw new Error(`Rotation target ${targetId} is absent`);
      try {
        await saveRecord(await runRotateCell(browser, target));
      } catch (error) {
        await saveRecord(unavailableRecord(target, CONTRACT.rotate_cell, error, true));
        if (target.required) requiredFailures.push({ target: target.id, cell: "R1", error: serialiseError(error) });
      }
    }
  }
} finally {
  await browser.close();
}

const executablePath = chromium.executablePath();
const executableSha256 = await sha256File(executablePath);
const run = {
  schema: "pipelinenews.mobile-ui-browser-run.v1",
  generation: GENERATION,
  project_posture: CONTRACT.project_posture,
  source_commit: SOURCE_COMMIT,
  candidate_generation: candidateGeneration,
  contract_schema: CONTRACT.schema,
  mode: MODE,
  deployment: "not-authorised",
  started_at: startedAt,
  completed_at: new Date().toISOString(),
  browser: {
    engine: "chromium",
    playwright_version: PLAYWRIGHT_VERSION,
    screenshot_encoder: `sharp-${SHARP_VERSION}`,
    chromium_version: chromiumVersion,
    executable_filename: path.basename(executablePath),
    executable_sha256: executableSha256,
  },
  records: recordFiles,
  expected_record_count: staticCells.length * targets.length
    + (includeRotate ? CONTRACT.rotate_cell.targets.filter((id) => selectedTargetIds.includes(id)).length : 0),
  shard: {
    id: shardId,
    target_ids: selectedTargetIds,
    static_cell_ids: selectedCellIds,
    include_rotate: includeRotate,
  },
  required_failures: requiredFailures,
  optional_original_unavailable: Boolean(optionalOriginalFailure),
  status: requiredFailures.length ? "ERROR" : "CAPTURED",
};
await writeJson(path.join(RAW_DIR, "run.json"), run);

if (run.records.length !== run.expected_record_count) {
  throw new Error(`Evidence record count ${run.records.length} != ${run.expected_record_count}`);
}
if (requiredFailures.length) {
  throw new AggregateError(
    requiredFailures.map(({ target, cell, error }) => new Error(`${target}/${cell}: ${error.message}`)),
    "Required mobile UI targets failed navigation, readiness, or instrument execution",
  );
}

process.stdout.write(`${JSON.stringify({
  schema: run.schema,
  generation: GENERATION,
  mode: MODE,
  records: run.records.length,
  browser: run.browser,
  optional_original_unavailable: run.optional_original_unavailable,
  status: run.status,
}, null, 2)}\n`);

Verify V9 6 2 Equivalence

A JavaScript module in the atman folder of PipelineNews that draws relationship governance status and solar.

renderpipelinenews / atman/202608282150-verify-v9-6-2-equivalence.mjs · lines 1–87 of 87 · version 2026-08-28 21:50 · Entry point · pattern observe (shared by 13 files)

What it does
It draws relationship governance status and solar. Defines gate, observe. 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: solar.
Inputs & outputs
In: JSON file 202608282044-relationship-governance-status.json; command-line arguments.
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
What it achieves
Its name says it verifies equivalence. Defines `gate` and `observe`.
Why it matters
Loaded by the Substation Finder page in Code Generator at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
pipelinenews · atman · JavaScript module
Uses
playwright, node:fs/promises
Used by
linked from Code Generator — Substation Finder Page (link)
Produces
gate, observe
Defines here
gate, observe
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/202608282150-verify-v9-6-2-equivalence.mjs:1-87 · blob 1a59ae35cffb223821bf9dc5290b0792ea274f2c · 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
#!/usr/bin/env node
import { chromium } from "playwright";
import { writeFile } from "node:fs/promises";

const args=Object.fromEntries(process.argv.slice(2).reduce((a,v,i,x)=>v.startsWith("--")?[...a,[v.slice(2),x[i+1]]]:a,[]));
const candidate=args.candidate, baseline=args.baseline, report=args.report;
if(!candidate||!baseline||!report) throw new Error("--candidate, --baseline and --report are required");
const checks=[]; const sessions=[];
const gate=(id,pass,evidence)=>checks.push({id,pass:Boolean(pass),evidence});

async function observe(label,url,viewport){
  const page=await browser.newPage({viewport,deviceScaleFactor:viewport.width===390?3:1,isMobile:viewport.width===390,hasTouch:viewport.width===390});
  const started=Date.now(), requests=[],consoleErrors=[],pageErrors=[],failed=[];
  page.on("request",r=>requests.push(new URL(r.url()).pathname));
  page.on("console",m=>{if(m.type()==="error")consoleErrors.push(m.text())});
  page.on("pageerror",e=>pageErrors.push(e.message));
  page.on("requestfailed",r=>failed.push(`${r.url()} :: ${r.failure()?.errorText}`));
  await page.goto(url,{waitUntil:"domcontentloaded",timeout:120000});
  if(label==="candidate") await page.waitForFunction(()=>document.body.dataset.fastReady==="true",null,{timeout:120000});
  else await page.waitForFunction(()=>document.querySelector("#resultsMeta")?.dataset.totalCount==="7680",null,{timeout:120000});
  const readyMs=Date.now()-started;
  const expectedNews=label==="candidate"?"136":"133";
  await page.waitForFunction(value=>document.querySelector("#newsMeta")?.textContent.includes(value),expectedNews,{timeout:120000});
  const core=await page.evaluate(()=>({
    total:Number(document.querySelector("#resultsMeta")?.dataset.totalCount),
    filtered:Number(document.querySelector("#resultsMeta")?.dataset.filteredCount),
    capacity:document.querySelector("#v1")?.textContent.trim(),
    largest:document.querySelector("#v3")?.textContent.trim(),
    columns:document.querySelectorAll(".tablewrap thead th").length,
    rows:document.querySelectorAll("#tbody>tr").length,
    rootOverflow:document.scrollingElement.scrollWidth-document.documentElement.clientWidth,
    tableClient:document.querySelector(".tablewrap")?.clientWidth,
    tableScroll:document.querySelector(".tablewrap")?.scrollWidth,
    tableOverflow:getComputedStyle(document.querySelector(".tablewrap")).overflowX,
    news:document.querySelector("#newsMeta")?.textContent.trim(),
    dom:document.querySelectorAll("*").length,
  }));
  gate(`${label}-${viewport.width}-canonical`,core.total===7680&&core.filtered===7680&&core.capacity.includes("356,474.09")&&core.largest.includes("4,100"),core);
  gate(`${label}-${viewport.width}-columns`,core.columns===11,core.columns);
  gate(`${label}-${viewport.width}-news`,core.news.includes(expectedNews),core.news);
  if(label==="candidate") gate(`${label}-${viewport.width}-100-rows-per-page`,core.rows===100,{observed:core.rows,required:100});
  if(viewport.width===390){
    gate(`${label}-390-contained-root`,core.rootOverflow<=1,core.rootOverflow);
    gate(`${label}-390-table-horizontal-scroll`,core.tableScroll>core.tableClient&&["auto","scroll"].includes(core.tableOverflow),core);
  }
  if(label==="candidate"){
    gate(`${label}-${viewport.width}-relationship-zero-startup`,!requests.some(x=>x.includes("202608282044-federated-relationships")||x.includes("202608282044-relationship-governance-status")),requests.filter(x=>x.includes("202608282044")));
    gate(`${label}-${viewport.width}-first-paint`,readyMs<=5000,{ready_ms:readyMs,maximum_ms:5000});
  }
  await page.locator("#search").fill("East Pye");
  await page.waitForFunction(()=>document.querySelector("#resultsMeta")?.dataset.filteredCount==="1");
  gate(`${label}-${viewport.width}-search-east-pye`,await page.locator("#repd-17494").count()===1,await page.locator("#resultsMeta").textContent());
  await page.locator("#clearFilters").click(); await page.waitForFunction(()=>document.querySelector("#resultsMeta")?.dataset.filteredCount==="7680");
  await page.locator('#tech [data-technology="solar"]').click(); await page.waitForFunction(()=>document.querySelector("#resultsMeta")?.dataset.filteredCount==="3563");
  gate(`${label}-${viewport.width}-solar-filter`,true,3563);
  await page.locator("#clearFilters").click(); await page.locator("#sortProjects").selectOption("updated_desc");
  gate(`${label}-${viewport.width}-sort-desc`,await page.locator("#repdUpdatedHeader").getAttribute("aria-sort")==="descending","descending");
  await page.locator("#sortProjects").selectOption("updated_asc");
  gate(`${label}-${viewport.width}-sort-asc`,await page.locator("#repdUpdatedHeader").getAttribute("aria-sort")==="ascending","ascending");
  await page.locator("#clearFilters").click();
  const downloadPromise=page.waitForEvent("download"); await page.locator("#exportInline").click(); const download=await downloadPromise;
  gate(`${label}-${viewport.width}-csv-export`,download.suggestedFilename().endsWith(".csv"),download.suggestedFilename());
  gate(`${label}-${viewport.width}-atlas-links`,await page.locator("a.atlaslink").count()>0,await page.locator("a.atlaslink").count());
  if(label==="candidate"){
    await page.locator("#federatedRelationshipOpen").click();
    await page.waitForFunction(()=>document.querySelector("#federatedRelationshipHost")?.dataset.federatedRelationshipState==="ready",null,{timeout:30000});
    const lazy={module:requests.filter(x=>x.endsWith("/202608282044-federated-relationships.js")).length,payload:requests.filter(x=>x.endsWith("/202608282044-relationship-governance-status.json")).length,rows:await page.locator("#federatedRelationshipHost tbody tr").count(),abstain:await page.locator("#federatedRelationshipHost td",{hasText:"ABSTAIN"}).count()};
    gate(`${label}-${viewport.width}-relationship-lazy-once`,lazy.module===1&&lazy.payload===1,lazy);
    gate(`${label}-${viewport.width}-relationship-abstention`,lazy.rows===3&&lazy.abstain===3,lazy);
  }
  gate(`${label}-${viewport.width}-console-cors`,consoleErrors.length===0&&pageErrors.length===0&&failed.length===0,{consoleErrors,pageErrors,failed});
  sessions.push({label,viewport,ready_ms:readyMs,core,requests:requests.length,console_errors:consoleErrors.length,page_errors:pageErrors.length,failed_requests:failed.length});
  await page.close();
}

const browser=await chromium.launch({headless:true});
try{
  for(const viewport of [{width:1440,height:1000},{width:390,height:844}]){
    await observe("baseline",baseline,viewport);
    await observe("candidate",candidate,viewport);
  }
}catch(error){gate("browser-completion",false,error.stack||error.message)}finally{await browser.close()}
const failures=checks.filter(x=>!x.pass);
const result={schema:"pipelinenews.v9-6-2-equivalence-report.v1",generation:"202608282150",candidate_generation:"202608282044",source_commit:process.env.GITHUB_SHA,workflow_run_id:process.env.GITHUB_RUN_ID,playwright_version:"1.55.0",sessions,checks,summary:{checks:checks.length,passed:checks.length-failures.length,failed:failures.length},promotion_eligible:failures.length===0,state:{candidate:"AR  … [line shortened here: 489 characters; full line on GitHub]
await writeFile(report,JSON.stringify(result,null,2)+"\n");
process.stdout.write(JSON.stringify(result.summary)+"\n");
if(failures.length) process.exitCode=1;