#!/usr/bin/env node

'use strict';

import { readFileSync } from 'node:fs';

const P = 5;
const Q = 13;
const DEGREE = P + 1;
const LPS_PUBLISHED_ORDER = 2184;
const LPS_PUBLISHED_DEGREE = 6;
const EXPECTED_GENERATORS = [
  [11, 0, 0, 4],
  [4, 0, 0, 11],
  [1, 2, 11, 1],
  [1, 11, 2, 1],
  [1, 10, 10, 1],
  [1, 3, 3, 1]
];
const EXPECTED_SHELLS = [1, 6, 30, 150, 550, 890, 511, 46];
const EXPECTED_CUTS = [
  [1, 6],
  [7, 30],
  [37, 150],
  [187, 750],
  [737, 2550]
];

let checks = 0;

function assert(condition, message) {
  if (!condition) {
    throw new Error(`FAILED: ${message}`);
  }
  checks += 1;
}

function mod(value, modulus = Q) {
  return ((value % modulus) + modulus) % modulus;
}

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return Math.abs(a);
}

function isPrime(n) {
  if (n < 2) return false;
  for (let d = 2; d * d <= n; d += 1) {
    if (n % d === 0) return false;
  }
  return true;
}

function inverse(value) {
  for (let candidate = 1; candidate < Q; candidate += 1) {
    if (mod(value * candidate) === 1) return candidate;
  }
  throw new Error(`No inverse for ${value}`);
}

function legendre(value) {
  const reduced = mod(value);
  if (reduced === 0) return 0;
  let power = 1;
  for (let i = 0; i < (Q - 1) / 2; i += 1) {
    power = mod(power * reduced);
  }
  return power === Q - 1 ? -1 : power;
}

function canonical(matrix) {
  const reduced = matrix.map((value) => mod(value));
  const first = reduced.find((value) => value !== 0);
  assert(first !== undefined, 'projective representative is nonzero');
  const scale = inverse(first);
  return reduced.map((value) => mod(value * scale));
}

function key(matrix) {
  return canonical(matrix).join(',');
}

function multiply(left, right) {
  return [
    mod(left[0] * right[0] + left[1] * right[2]),
    mod(left[0] * right[1] + left[1] * right[3]),
    mod(left[2] * right[0] + left[3] * right[2]),
    mod(left[2] * right[1] + left[3] * right[3])
  ];
}

function determinant(matrix) {
  return mod(matrix[0] * matrix[3] - matrix[1] * matrix[2]);
}

function sortedMatrixKeys(matrices) {
  return matrices.map((matrix) => matrix.join(',')).sort();
}

function deriveGenerators() {
  const quaternions = [];
  for (let a0 = -2; a0 <= 2; a0 += 1) {
    for (let a1 = -2; a1 <= 2; a1 += 1) {
      for (let a2 = -2; a2 <= 2; a2 += 1) {
        for (let a3 = -2; a3 <= 2; a3 += 1) {
          const norm = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
          const parityConvention = a0 > 0 && a0 % 2 !== 0 &&
            a1 % 2 === 0 && a2 % 2 === 0 && a3 % 2 === 0;
          if (norm === P && parityConvention) {
            quaternions.push([a0, a1, a2, a3]);
          }
        }
      }
    }
  }

  const squareRootMinusOne = Array.from({ length: Q - 1 }, (_, i) => i + 1)
    .find((value) => mod(value * value) === Q - 1);
  assert(squareRootMinusOne === 5, 'least square root of -1 modulo 13 is 5');
  assert(quaternions.length === DEGREE, 'norm-5 equation gives six parity-selected quaternions');

  const matrices = quaternions.map(([a0, a1, a2, a3]) => [
    mod(a0 + squareRootMinusOne * a1),
    mod(a2 + squareRootMinusOne * a3),
    mod(-a2 + squareRootMinusOne * a3),
    mod(a0 - squareRootMinusOne * a1)
  ]);

  return { quaternions, matrices, squareRootMinusOne };
}

function buildGraph(generators) {
  const vertices = [];
  const index = new Map();

  for (let a = 0; a < Q; a += 1) {
    for (let b = 0; b < Q; b += 1) {
      for (let c = 0; c < Q; c += 1) {
        for (let d = 0; d < Q; d += 1) {
          const matrix = [a, b, c, d];
          if (determinant(matrix) === 0) continue;
          const representative = canonical(matrix);
          const matrixKey = representative.join(',');
          if (!index.has(matrixKey)) {
            index.set(matrixKey, vertices.length);
            vertices.push(representative);
          }
        }
      }
    }
  }

  const adjacency = Array.from({ length: vertices.length }, () => []);
  for (let i = 0; i < vertices.length; i += 1) {
    for (const generator of generators) {
      const neighborKey = key(multiply(vertices[i], generator));
      const neighbor = index.get(neighborKey);
      assert(neighbor !== undefined, 'right multiplication stays in PGL_2(F_13)');
      adjacency[i].push(neighbor);
    }
  }

  return { vertices, index, adjacency };
}

function componentLabels(adjacency) {
  const labels = new Int32Array(adjacency.length);
  labels.fill(-1);
  let count = 0;
  for (let start = 0; start < adjacency.length; start += 1) {
    if (labels[start] !== -1) continue;
    labels[start] = count;
    const queue = [start];
    for (let head = 0; head < queue.length; head += 1) {
      const vertex = queue[head];
      for (const neighbor of adjacency[vertex]) {
        if (labels[neighbor] === -1) {
          labels[neighbor] = count;
          queue.push(neighbor);
        }
      }
    }
    count += 1;
  }
  return { labels, count };
}

function distancesFrom(adjacency, source) {
  const distance = new Int16Array(adjacency.length);
  distance.fill(-1);
  distance[source] = 0;
  const queue = [source];
  for (let head = 0; head < queue.length; head += 1) {
    const vertex = queue[head];
    for (const neighbor of adjacency[vertex]) {
      if (distance[neighbor] === -1) {
        distance[neighbor] = distance[vertex] + 1;
        queue.push(neighbor);
      }
    }
  }
  return distance;
}

function shellCounts(distance) {
  const shells = [];
  for (const value of distance) {
    shells[value] = (shells[value] || 0) + 1;
  }
  return shells;
}

function ballCut(adjacency, distance, radius) {
  const chosen = new Uint8Array(adjacency.length);
  let size = 0;
  for (let i = 0; i < distance.length; i += 1) {
    if (distance[i] <= radius) {
      chosen[i] = 1;
      size += 1;
    }
  }
  let boundary = 0;
  for (let i = 0; i < adjacency.length; i += 1) {
    if (!chosen[i]) continue;
    for (const neighbor of adjacency[i]) {
      if (!chosen[neighbor]) boundary += 1;
    }
  }
  return { size, boundary, ratio: boundary / size };
}

function lazyWalk(adjacency, source, steps) {
  let distribution = new Float64Array(adjacency.length);
  distribution[source] = 1;
  for (let step = 0; step < steps; step += 1) {
    const next = new Float64Array(adjacency.length);
    for (let i = 0; i < distribution.length; i += 1) {
      const mass = distribution[i];
      next[i] += mass / 2;
      for (const neighbor of adjacency[i]) {
        next[neighbor] += mass / (2 * DEGREE);
      }
    }
    distribution = next;
  }
  const uniform = 1 / adjacency.length;
  let squared = 0;
  let total = 0;
  for (const probability of distribution) {
    squared += (probability - uniform) ** 2;
    total += probability;
  }
  return { distribution, l2: Math.sqrt(squared), total };
}

function numericalSquaredRitz(vertices, adjacency, iterations = 2000) {
  const squares = new Set([1, 3, 4, 9, 10, 12]);
  const left = [];
  const right = [];
  for (let i = 0; i < vertices.length; i += 1) {
    const target = squares.has(determinant(vertices[i])) ? left : right;
    target.push(i);
  }

  let vector = new Float64Array(vertices.length);
  let scratch = new Float64Array(vertices.length);
  const middle = new Float64Array(vertices.length);
  for (const i of left) {
    vector[i] = Math.sin((i + 1) * 1.234567);
  }

  function projectAndNormalize(values) {
    let mean = 0;
    for (const i of left) mean += values[i];
    mean /= left.length;
    let squared = 0;
    for (const i of left) {
      values[i] -= mean;
      squared += values[i] * values[i];
    }
    const length = Math.sqrt(squared);
    for (const i of left) values[i] /= length;
  }

  function applySquared(input, output) {
    middle.fill(0);
    output.fill(0);
    for (const i of left) {
      for (const neighbor of adjacency[i]) {
        middle[neighbor] += input[i];
      }
    }
    for (const i of right) {
      for (const neighbor of adjacency[i]) {
        output[neighbor] += middle[i];
      }
    }
  }

  projectAndNormalize(vector);
  for (let iteration = 0; iteration < iterations; iteration += 1) {
    applySquared(vector, scratch);
    projectAndNormalize(scratch);
    [vector, scratch] = [scratch, vector];
  }

  applySquared(vector, scratch);
  let squaredRitz = 0;
  for (const i of left) squaredRitz += vector[i] * scratch[i];
  let residualSquared = 0;
  for (const i of left) {
    const residual = scratch[i] - squaredRitz * vector[i];
    residualSquared += residual * residual;
  }
  return {
    magnitude: Math.sqrt(squaredRitz),
    squaredRitz,
    squaredResidual: Math.sqrt(residualSquared),
    leftSize: left.length,
    rightSize: right.length
  };
}

function zeroMatrix(size) {
  return Array.from({ length: size }, () => Array(size).fill(0));
}

function matrixMultiply(left, right) {
  const size = left.length;
  const product = zeroMatrix(size);
  for (let i = 0; i < size; i += 1) {
    for (let k = 0; k < size; k += 1) {
      if (left[i][k] === 0) continue;
      for (let j = 0; j < size; j += 1) {
        product[i][j] += left[i][k] * right[k][j];
      }
    }
  }
  return product;
}

function trace(matrix) {
  let value = 0;
  for (let i = 0; i < matrix.length; i += 1) value += matrix[i][i];
  return value;
}

function characteristicPolynomial(matrix) {
  const size = matrix.length;
  let power = zeroMatrix(size);
  for (let i = 0; i < size; i += 1) power[i][i] = 1;
  const traces = [size];
  for (let exponent = 1; exponent <= size; exponent += 1) {
    power = matrixMultiply(power, matrix);
    traces[exponent] = trace(power);
  }
  const coefficients = [1];
  for (let k = 1; k <= size; k += 1) {
    let sum = 0;
    for (let i = 1; i <= k; i += 1) {
      sum += coefficients[k - i] * traces[i];
    }
    const coefficient = -sum / k;
    assert(Number.isInteger(coefficient), 'Faddeev-LeVerrier coefficient is integral');
    coefficients[k] = Object.is(coefficient, -0) ? 0 : coefficient;
  }
  return coefficients;
}

function convolve(left, right) {
  const result = Array(left.length + right.length - 1).fill(0);
  for (let i = 0; i < left.length; i += 1) {
    for (let j = 0; j < right.length; j += 1) {
      result[i + j] += left[i] * right[j];
    }
  }
  return result;
}

function signedK33(signs) {
  const matrix = zeroMatrix(6);
  for (let row = 0; row < 3; row += 1) {
    for (let column = 0; column < 3; column += 1) {
      const sign = signs[3 * row + column];
      matrix[row][3 + column] = sign;
      matrix[3 + column][row] = sign;
    }
  }
  return matrix;
}

function unsignedK33() {
  return signedK33(Array(9).fill(1));
}

function twoLift(signs) {
  const matrix = zeroMatrix(12);
  for (let row = 0; row < 3; row += 1) {
    for (let column = 0; column < 3; column += 1) {
      const right = 3 + column;
      const sign = signs[3 * row + column];
      for (let sheet = 0; sheet < 2; sheet += 1) {
        const otherSheet = sign === 1 ? sheet : 1 - sheet;
        const a = sheet * 6 + row;
        const b = otherSheet * 6 + right;
        matrix[a][b] = 1;
        matrix[b][a] = 1;
      }
    }
  }
  return matrix;
}

function matrixAdjacency(matrix) {
  return matrix.map((row) => row.flatMap((value, index) => value ? [index] : []));
}

function determinantSmall(matrix) {
  if (matrix.length === 0) return 1;
  if (matrix.length === 1) return matrix[0][0];
  let value = 0;
  for (let column = 0; column < matrix.length; column += 1) {
    const minor = matrix.slice(1).map((row) =>
      row.filter((_, index) => index !== column)
    );
    value += (column % 2 === 0 ? 1 : -1) *
      matrix[0][column] * determinantSmall(minor);
  }
  return value;
}

function exactRamanujanSigning(signs) {
  const signBlock = Array.from({ length: 3 }, (_, row) =>
    signs.slice(3 * row, 3 * row + 3)
  );
  const product = Array.from({ length: 3 }, (_, i) =>
    Array.from({ length: 3 }, (_, j) => {
      let sum = 0;
      for (let k = 0; k < 3; k += 1) {
        sum += signBlock[i][k] * signBlock[j][k];
      }
      return sum;
    })
  );
  const certificate = product.map((row, i) =>
    row.map((value, j) => (i === j ? 8 : 0) - value)
  );

  for (let mask = 1; mask < 8; mask += 1) {
    const indices = [0, 1, 2].filter((index) => mask & (1 << index));
    const principal = indices.map((i) => indices.map((j) => certificate[i][j]));
    if (determinantSmall(principal) < 0) return false;
  }
  return true;
}

function polynomialValue(coefficients, x) {
  return coefficients.reduce((value, coefficient) => value * x + coefficient, 0);
}

function realRoots(coefficients) {
  const c = coefficients.slice();
  while (c.length > 1 && Math.abs(c[0]) < 1e-13) c.shift();
  const degree = c.length - 1;
  if (degree === 1) return [-c[1] / c[0]];

  const derivative = c.slice(0, -1).map((value, index) =>
    value * (degree - index)
  );
  const critical = realRoots(derivative);
  const radius = 1 + Math.max(...c.slice(1).map((value) => Math.abs(value / c[0])));
  const points = [-radius, ...critical, radius];
  const roots = [];

  for (const candidate of critical) {
    if (Math.abs(polynomialValue(c, candidate)) < 1e-7) roots.push(candidate);
  }
  for (let i = 0; i + 1 < points.length; i += 1) {
    let left = points[i];
    let right = points[i + 1];
    let leftValue = polynomialValue(c, left);
    const rightValue = polynomialValue(c, right);
    if (leftValue * rightValue >= 0) continue;
    for (let iteration = 0; iteration < 100; iteration += 1) {
      const middle = (left + right) / 2;
      const middleValue = polynomialValue(c, middle);
      if (leftValue * middleValue <= 0) {
        right = middle;
      } else {
        left = middle;
        leftValue = middleValue;
      }
    }
    roots.push((left + right) / 2);
  }

  const sorted = roots.sort((a, b) => a - b);
  return sorted.filter((value, index) =>
    index === 0 || Math.abs(value - sorted[index - 1]) > 1e-6
  );
}

function largestMeanRoot(sum, count) {
  const yPolynomial = [sum[0], sum[2], sum[4], sum[6]].map((value) => value / count);
  const yRoots = realRoots(yPolynomial);
  assert(yRoots.length >= 1, 'conditional mean polynomial has a real squared root');
  assert(yRoots.every((value) => value >= -1e-6), 'conditional mean roots are real');
  return Math.sqrt(Math.max(...yRoots.map((value) => Math.max(0, value))));
}

function signingFromMask(mask) {
  return Array.from({ length: 9 }, (_, edge) =>
    mask & (1 << edge) ? 1 : -1
  );
}

function prefixSum(polynomials, prefix) {
  const sum = Array(7).fill(0);
  let count = 0;
  for (let mask = 0; mask < 512; mask += 1) {
    let matches = true;
    for (let edge = 0; edge < prefix.length; edge += 1) {
      if (signingFromMask(mask)[edge] !== prefix[edge]) {
        matches = false;
        break;
      }
    }
    if (!matches) continue;
    count += 1;
    for (let i = 0; i < 7; i += 1) sum[i] += polynomials[mask][i];
  }
  return { sum, count };
}

function arraysEqual(left, right) {
  return left.length === right.length &&
    left.every((value, index) => value === right[index]);
}

function format(value, digits = 6) {
  return value.toFixed(digits);
}

/*
  Printed forms, DERIVED from the coefficient arrays this file computed.

  The summary used to end with a string literal reading
  'chosen new polynomial=x^6-9x^4+24x^2-16, new spectrum=-2,-2,-1,1,2,2'.
  Every number in that line was true, and none of it was connected to anything:
  the branch search could have landed somewhere else and the line would have gone
  on printing the old answer. These three helpers build the same line out of the
  computed coefficients instead.
*/
function polynomialString(coefficients) {
  const degree = coefficients.length - 1;
  let text = '';
  coefficients.forEach((coefficient, index) => {
    if (Math.abs(coefficient) < 1e-12) return;
    const power = degree - index;
    const size = Math.abs(coefficient);
    const magnitude = Math.abs(size - 1) < 1e-12 && power > 0 ? ''
      : (Number.isInteger(size) ? String(size) : format(size));
    const variable = power === 0 ? '' : (power === 1 ? 'x' : `x^${power}`);
    text += (coefficient < 0 ? '-' : (text ? '+' : '')) + magnitude + variable;
  });
  return text || '0';
}

/** Synthetic division by (x - root), with the remainder asserted rather than dropped. */
function deflate(coefficients, root) {
  const quotient = [coefficients[0]];
  for (let index = 1; index < coefficients.length - 1; index += 1) {
    quotient.push(coefficients[index] + root * quotient[index - 1]);
  }
  const remainder = coefficients[coefficients.length - 1] +
    root * quotient[quotient.length - 1];
  assert(Math.abs(remainder) < 1e-6,
    `deflating by root ${root} left remainder ${remainder}`);
  return quotient;
}

/*
  realRoots() returns the DISTINCT real roots, which is the right answer for the
  interlacing bound and the wrong one for a printed spectrum: the chosen signing's
  new eigenvalues contain -2 and 2 twice each. Deflating one root at a time recovers
  multiplicity, and the count is asserted against the degree, so a signing whose new
  polynomial had a complex pair would fail here instead of printing a short spectrum.
*/
function rootsWithMultiplicity(coefficients) {
  let working = coefficients.slice();
  const found = [];
  while (working.length > 1) {
    const roots = realRoots(working);
    if (!roots.length) break;
    found.push(roots[0]);
    working = deflate(working, roots[0]);
  }
  assert(found.length === coefficients.length - 1,
    `degree ${coefficients.length - 1} polynomial yielded ${found.length} real roots`);
  return found.sort((a, b) => a - b);
}

function rootString(value) {
  const nearest = Math.round(value);
  if (Math.abs(value - nearest) < 1e-9) return String(nearest === 0 ? 0 : nearest);
  return format(value);
}

function verify() {
  assert(isPrime(P), 'p=5 is prime');
  assert(isPrime(Q), 'q=13 is prime');
  assert(P % 4 === 1 && Q % 4 === 1, 'both primes are 1 modulo 4');
  assert(legendre(P) === -1, '5 is a quadratic nonresidue modulo 13');
  assert(DEGREE === LPS_PUBLISHED_DEGREE, 'external LPS degree anchor is 6');
  assert(Q * (Q * Q - 1) === LPS_PUBLISHED_ORDER, 'external LPS PGL order anchor is 2,184');

  const derived = deriveGenerators();
  assert(
    arraysEqual(
      sortedMatrixKeys(derived.matrices),
      sortedMatrixKeys(EXPECTED_GENERATORS)
    ),
    'derived generators match the displayed source card'
  );
  for (const generator of derived.matrices) {
    assert(determinant(generator) === P, 'each generator determinant is 5 modulo 13');
  }

  const graph = buildGraph(derived.matrices);
  assert(graph.vertices.length === LPS_PUBLISHED_ORDER, 'projective enumeration has 2,184 vertices');

  const undirectedEdges = new Set();
  for (let i = 0; i < graph.adjacency.length; i += 1) {
    const neighbors = graph.adjacency[i];
    assert(neighbors.length === DEGREE, 'every vertex has six generated neighbors');
    assert(new Set(neighbors).size === DEGREE, 'each neighbor list has six distinct entries');
    assert(!neighbors.includes(i), 'the graph has no loops');
    for (const neighbor of neighbors) {
      assert(graph.adjacency[neighbor].includes(i), 'each generated edge is symmetric');
      undirectedEdges.add(i < neighbor ? `${i},${neighbor}` : `${neighbor},${i}`);
    }
  }
  assert(undirectedEdges.size === LPS_PUBLISHED_ORDER * DEGREE / 2, 'edge count is 6,552');

  const components = componentLabels(graph.adjacency);
  assert(components.count === 1, 'the graph is connected');

  const squares = new Set([1, 3, 4, 9, 10, 12]);
  const sides = graph.vertices.map((matrix) =>
    squares.has(determinant(matrix)) ? 0 : 1
  );
  const sideSizes = [
    sides.filter((side) => side === 0).length,
    sides.filter((side) => side === 1).length
  ];
  assert(arraysEqual(sideSizes, [1092, 1092]), 'determinant character gives two parts of 1,092');
  for (let i = 0; i < graph.adjacency.length; i += 1) {
    for (const neighbor of graph.adjacency[i]) {
      assert(sides[i] !== sides[neighbor], 'every edge crosses the determinant bipartition');
    }
  }

  const identity = graph.index.get(key([1, 0, 0, 1]));
  assert(identity === 156, 'identity has stable displayed projective index 156');
  assert(
    arraysEqual(
      graph.adjacency[identity].map((i) => graph.vertices[i].join(',')).sort(),
      EXPECTED_GENERATORS.map((matrix) => key(matrix)).sort()
    ),
    'the six neighbors of the identity are the generator card'
  );

  const distances = distancesFrom(graph.adjacency, identity);
  const shells = shellCounts(distances);
  assert(arraysEqual(shells, EXPECTED_SHELLS), 'identity shell counts match the page');
  for (let radius = 0; radius <= 4; radius += 1) {
    const cut = ballCut(graph.adjacency, distances, radius);
    assert(
      arraysEqual([cut.size, cut.boundary], EXPECTED_CUTS[radius]),
      `radius-${radius} ball size and boundary match the page`
    );
    assert(cut.size > 0 && cut.size <= graph.vertices.length / 2, 'displayed ball is nonempty and at most half the graph');
  }

  const walkSteps = [0, 1, 2, 10, 40, 80];
  const walkRows = [];
  const contraction = (1 + 2 * Math.sqrt(P) / DEGREE) / 2;
  for (const steps of walkSteps) {
    const walk = lazyWalk(graph.adjacency, identity, steps);
    assert(Math.abs(walk.total - 1) < 2e-12, `lazy walk mass is conserved at t=${steps}`);
    const envelope = Math.sqrt(1 - 1 / graph.vertices.length) * contraction ** steps;
    assert(walk.l2 <= envelope + 2e-12, `lazy walk lies under the LPS contraction envelope at t=${steps}`);
    walkRows.push([steps, walk.l2, envelope]);
  }

  const threshold = 2 * Math.sqrt(P);
  const ritz = numericalSquaredRitz(graph.vertices, graph.adjacency);
  assert(ritz.leftSize === 1092 && ritz.rightSize === 1092, 'numerical diagnostic uses one bipartite block');
  assert(Math.abs(ritz.magnitude - 4.24972) < 0.00002, 'deterministic Ritz magnitude matches the displayed precision');
  assert(ritz.magnitude < threshold, 'observed nontrivial Ritz magnitude lies below 2sqrt(5)');
  assert(ritz.squaredResidual < 0.002, 'squared-adjacency Ritz residual is below the displayed tolerance');

  const oldPolynomial = characteristicPolynomial(unsignedK33());
  assert(arraysEqual(oldPolynomial, [1, 0, -9, 0, 0, 0, 0]), 'K3,3 old characteristic polynomial is x^6 - 9x^4');

  const signedPolynomials = [];
  let connectedLifts = 0;
  let exactRamanujanLifts = 0;
  for (let mask = 0; mask < 512; mask += 1) {
    const signs = signingFromMask(mask);
    const signedPolynomial = characteristicPolynomial(signedK33(signs));
    const lift = twoLift(signs);
    const liftPolynomial = characteristicPolynomial(lift);
    const factorised = convolve(oldPolynomial, signedPolynomial);
    assert(arraysEqual(liftPolynomial, factorised), '2-lift spectrum factors exactly into old and new polynomials');

    const componentCount = componentLabels(matrixAdjacency(lift)).count;
    const ramanujan = exactRamanujanSigning(signs);
    if (componentCount === 1) connectedLifts += 1;
    if (ramanujan) exactRamanujanLifts += 1;
    assert(ramanujan === (componentCount === 1), 'for K3,3, exactly the connected 2-lifts pass the new-root cutoff');
    signedPolynomials.push(signedPolynomial);
  }
  assert(connectedLifts === 480, '480 of 512 K3,3 lifts are connected');
  assert(exactRamanujanLifts === 480, '480 of 512 K3,3 signings satisfy the new-root cutoff');

  const allPositive = signingFromMask(511);
  assert(componentLabels(matrixAdjacency(twoLift(allPositive))).count === 2, 'all-positive lift is two disconnected copies');
  assert(!exactRamanujanSigning(allPositive), 'all-positive signing repeats +3 as a nontrivial new eigenvalue');

  let conditionalNodes = 0;
  function verifyConditional(prefix) {
    const parent = prefixSum(signedPolynomials, prefix);
    const parentLargest = largestMeanRoot(parent.sum, parent.count);
    conditionalNodes += 1;
    if (prefix.length === 9) return;
    const minus = prefixSum(signedPolynomials, prefix.concat(-1));
    const plus = prefixSum(signedPolynomials, prefix.concat(1));
    assert(minus.count + plus.count === parent.count, 'conditional completion counts split exactly');
    for (let coefficient = 0; coefficient < 7; coefficient += 1) {
      assert(
        minus.sum[coefficient] + plus.sum[coefficient] === parent.sum[coefficient],
        'parent mean polynomial is the exact average of its two conditional children'
      );
    }
    const minusLargest = largestMeanRoot(minus.sum, minus.count);
    const plusLargest = largestMeanRoot(plus.sum, plus.count);
    assert(
      Math.min(minusLargest, plusLargest) <= parentLargest + 1e-7,
      'an interlacing child does not increase the largest conditional root'
    );
    verifyConditional(prefix.concat(-1));
    verifyConditional(prefix.concat(1));
  }
  verifyConditional([]);
  assert(conditionalNodes === 1023, 'all 1,023 conditional signing nodes were checked');

  const rootConditional = prefixSum(signedPolynomials, []);
  assert(
    arraysEqual(rootConditional.sum, [512, 0, -4608, 0, 9216, 0, -3072]),
    'unconditioned mean polynomial is x^6 - 9x^4 + 18x^2 - 6'
  );
  const rootLargest = largestMeanRoot(rootConditional.sum, rootConditional.count);
  assert(Math.abs(rootLargest - 2.507976292) < 1e-8, 'unconditioned largest mean root matches the page');

  const branch = [];
  while (branch.length < 9) {
    const minus = prefixSum(signedPolynomials, branch.concat(-1));
    const plus = prefixSum(signedPolynomials, branch.concat(1));
    const minusLargest = largestMeanRoot(minus.sum, minus.count);
    const plusLargest = largestMeanRoot(plus.sum, plus.count);
    branch.push(plusLargest <= minusLargest + 1e-10 ? 1 : -1);
  }
  const branchMask = branch.reduce((mask, sign, edge) =>
    sign === 1 ? mask | (1 << edge) : mask, 0
  );
  assert(exactRamanujanSigning(branch), 'the displayed interlacing branch ends at an exact Ramanujan signing');
  assert(
    arraysEqual(signedPolynomials[branchMask], [1, 0, -9, 0, 24, 0, -16]),
    'displayed branch new polynomial is x^6 - 9x^4 + 24x^2 - 16'
  );

  const meanPolynomial = rootConditional.sum.map((value) => value / rootConditional.count);
  const branchPolynomial = signedPolynomials[branchMask];
  const branchSpectrum = rootsWithMultiplicity(branchPolynomial);
  assert(
    Math.abs(Math.max(...branchSpectrum) - Math.sqrt(Math.max(...realRoots(
      [branchPolynomial[0], branchPolynomial[2], branchPolynomial[4], branchPolynomial[6]]
    )))) < 1e-9,
    'the deflated spectrum agrees with the substitution route on its largest new eigenvalue'
  );

  /* ---------------------------------------------------------------------------
     THE SHIPPED PAGE.

     Everything above re-derives X^{5,13} and the K3,3 2-lift from the primes and
     the published LPS anchors, and reads nothing this site serves. Until 2026-07-31
     that was the whole file, so no defect in the shipped page could turn it red.
     What follows lifts the page's own constants and functions out of the HTML, runs
     them against the routes above over all 512 signings, replays the page's own
     greedy branch search, and asserts the numbers the page prints as static text.

     Extraction is value-agnostic on purpose. Pinning a literal into a pattern would
     make a drifted constant fail the EXTRACTION and skip every check behind it.
     --------------------------------------------------------------------------- */
  const html = readFileSync(
    new URL('../../public/strata/ramanujan-graphs/index.html', import.meta.url),
    'utf8'
  );

  const grab = (marker, open = '{', shut = '}') => {
    const at = html.indexOf(marker);
    if (at < 0) return null;
    const from = html.indexOf(open, at + marker.length - 1);
    if (from < 0) return null;
    let depth = 0;
    for (let i = from; i < html.length; i += 1) {
      if (html[i] === open) depth += 1;
      else if (html[i] === shut) {
        depth -= 1;
        if (depth === 0) return html.slice(at, i + 1) + (open === '{' ? '' : ';');
      }
    }
    return null;
  };
  const span = (pattern) => (html.match(pattern) || [null])[0];

  const lifted = {
    P: span(/var P\s*=[^;]+;/),
    Q: span(/var Q\s*=[^;]+;/),
    DEGREE: span(/var DEGREE\s*=[^;]+;/),
    signState: span(/var signState\s*=[^;]+;/),
    rootCutoff: span(/var rootCutoff\s*=[^;]+;/),
    mod: grab('function mod(value)'),
    inverse: grab('function inverse(value)'),
    canonical: grab('function canonical(matrix)'),
    determinant: grab('function determinant(matrix)'),
    deriveGenerators: grab('function deriveGenerators()'),
    componentCount: grab('function componentCount(adjacency)'),
    signMatrix: grab('function signMatrix(signs)'),
    det3: grab('function det3(matrix)'),
    signedPolynomial: grab('function signedPolynomial(signs)'),
    signedSpectrum: grab('function signedSpectrum(signs)'),
    polynomialValue: grab('function polynomialValue(coefficients, x)'),
    realRoots: grab('function realRoots(coefficients)'),
    rootsOfEvenPolynomial: grab('function rootsOfEvenPolynomial(coefficients)'),
    completions: grab('function completions()'),
    liftAdjacency: grab('function liftAdjacency(signs)'),
    completionSummary: grab('function completionSummary()'),
    formatTerm: grab('function formatTerm(value, exponent, first)'),
    polynomialText: grab('function polynomialText(coefficients)')
  };
  const notLifted = Object.keys(lifted).filter((name) => !lifted[name]);
  assert(notLifted.length === 0,
    `page declares everything this section sweeps (missing: ${notLifted.join(', ')})`);

  const exported = Object.keys(lifted).filter((name) => name !== 'signState');
  const PAGE = new Function(
    Object.values(lifted).join('\n') +
    `\n; return { ${exported.map((name) => `${name}:${name}`).join(', ')},` +
    ' setSigns:function (s) { signState = s; } };'
  )();

  assert(PAGE.P === P && PAGE.Q === Q && PAGE.DEGREE === DEGREE,
    `page ships p=${PAGE.P}, q=${PAGE.Q}, degree=${PAGE.DEGREE}`);
  assert(Math.abs(PAGE.rootCutoff - 2 * Math.sqrt(2)) < 1e-15,
    `page 2-lift cutoff is ${PAGE.rootCutoff}`);

  const pageDerived = PAGE.deriveGenerators();
  assert(pageDerived.root === derived.squareRootMinusOne,
    `page solves the same square root of -1 mod 13: ${pageDerived.root}`);
  assert(
    arraysEqual(sortedMatrixKeys(pageDerived.matrices), sortedMatrixKeys(derived.matrices)),
    'page generators are this file\'s generators, as projective classes'
  );
  for (const generator of pageDerived.matrices) {
    assert(determinant(generator) === P, 'each page generator has determinant 5 modulo 13');
  }

  /* sweep: every one of the 512 signings, through the page's own polynomial */
  let spectrumGap = 0;
  for (let mask = 0; mask < 512; mask += 1) {
    const signs = signingFromMask(mask);
    assert(arraysEqual(PAGE.signedPolynomial(signs), signedPolynomials[mask]),
      `page new polynomial matches this file at signing mask ${mask}`);
    const spectrum = PAGE.signedSpectrum(signs);
    const here = rootsWithMultiplicity(signedPolynomials[mask]);
    assert(spectrum.length === 6, `page spectrum at mask ${mask} has six eigenvalues`);
    spectrum.forEach((value, index) => {
      spectrumGap = Math.max(spectrumGap, Math.abs(value - here[index]));
    });
  }
  assert(spectrumGap < 1e-9,
    `page Jacobi spectrum matches the deflated roots on all 512 signings, worst gap ${spectrumGap.toExponential(2)}`);

  /* the page's own greedy branch search, replayed without its DOM */
  const pageBranch = [];
  const pageSigns = Array(9).fill(null);
  for (let edge = 0; edge < 9; edge += 1) {
    pageSigns[edge] = -1;
    PAGE.setSigns(pageSigns.slice());
    const minusLargest = Math.max(...PAGE.rootsOfEvenPolynomial(PAGE.completionSummary().mean));
    pageSigns[edge] = 1;
    PAGE.setSigns(pageSigns.slice());
    const plusLargest = Math.max(...PAGE.rootsOfEvenPolynomial(PAGE.completionSummary().mean));
    pageSigns[edge] = plusLargest <= minusLargest + 1e-10 ? 1 : -1;
    PAGE.setSigns(pageSigns.slice());
    pageBranch.push(pageSigns[edge]);
  }
  assert(arraysEqual(pageBranch, branch),
    `page branch search ends where this file's does: ${pageBranch.join(',')}`);
  assert(arraysEqual(PAGE.signedPolynomial(pageBranch), branchPolynomial),
    'page new polynomial at the chosen branch is the one printed below');

  /* the opening screen: unconditioned means, and the text shipped in the markup */
  PAGE.setSigns(Array(9).fill(null));
  const pageOpening = PAGE.completionSummary();
  assert(pageOpening.count === 512, `page enumerates ${pageOpening.count} completions`);
  assert(arraysEqual(pageOpening.mean, meanPolynomial),
    'page unconditioned mean polynomial equals this file\'s');
  assert(pageOpening.connected === connectedLifts,
    `page counts ${pageOpening.connected} connected lifts, this file counts ${connectedLifts}`);
  assert(pageOpening.good === exactRamanujanLifts,
    `page cutoff count ${pageOpening.good} equals this file's exact Ramanujan count ${exactRamanujanLifts}`);

  const printed = [
    [`id="meanPolynomial">${PAGE.polynomialText(pageOpening.mean)}<`, 'mean polynomial'],
    [`id="completionCount">${pageOpening.count.toLocaleString('en-US')}<`, 'completion count'],
    [`id="goodCount">${pageOpening.good.toLocaleString('en-US')}<`, 'cutoff passes'],
    [`id="connectedCount">${pageOpening.connected.toLocaleString('en-US')}<`, 'connected lifts'],
    [`largest ${format(rootLargest)} `, 'largest unconditioned mean root'],
    [`Build all ${LPS_PUBLISHED_ORDER.toLocaleString('en-US')} rooms`, 'vertex count on the build button']
  ];
  for (const [fragment, label] of printed) {
    assert(html.includes(fragment), `page prints the ${label} its own code produces: ${fragment}`);
  }

  console.log('Ramanujan graph checks');
  console.log(`  primes and residue: p=${P}, q=${Q}, p mod 4=${P % 4}, q mod 4=${Q % 4}, (5/13)=${legendre(P)}`);
  console.log(`  quaternion solutions: ${derived.quaternions.length}, sqrt(-1) mod 13=${derived.squareRootMinusOne}`);
  console.log(`  vertices=${graph.vertices.length}, edges=${undirectedEdges.size}, degree=${DEGREE}`);
  console.log(`  components=${components.count}, bipartition=${sideSizes[0]}+${sideSizes[1]}`);
  console.log(`  identity index=${identity}, shells=${shells.join(',')}`);
  for (let radius = 0; radius <= 4; radius += 1) {
    const cut = ballCut(graph.adjacency, distances, radius);
    console.log(`  ball r=${radius}: |S|=${cut.size}, boundary=${cut.boundary}, h_S=${format(cut.ratio)}`);
  }
  for (const [steps, l2, envelope] of walkRows) {
    console.log(`  lazy t=${steps}: L2=${format(l2, 9)}, envelope=${format(envelope, 9)}`);
  }
  console.log(`  Ramanujan threshold=2sqrt(5)=${format(threshold, 9)}`);
  console.log(`  numerical Ritz magnitude=${format(ritz.magnitude, 9)}, A^2 residual=${format(ritz.squaredResidual, 9)}`);
  console.log('  spectral inequality proof: cited LPS theorem after exact construction checks');
  console.log('K3,3 2-lift checks');
  console.log(`  signings=512, connected=${connectedLifts}, exact new-root passes=${exactRamanujanLifts}`);
  console.log(`  mean polynomial=${polynomialString(meanPolynomial)}, largest root=${format(rootLargest, 9)}`);
  console.log(`  cutoff=2sqrt(2)=${format(2 * Math.sqrt(2), 9)}`);
  console.log(`  conditional nodes=${conditionalNodes}, chosen signs=${branch.join(',')}`);
  console.log(`  chosen new polynomial=${polynomialString(branchPolynomial)}, ` +
    `new spectrum=${branchSpectrum.map(rootString).join(',')}`);
  console.log(`PASS: ${checks.toLocaleString('en-US')} assertions`);
}

try {
  verify();
} catch (error) {
  console.error(error.stack || error.message);
  process.exit(1);
}
