#!/usr/bin/env node
// Verifier for /strata/the-landlord-is-not-the-tenant/.
//
//   node verify-the-landlord-is-not-the-tenant.mjs
//
// The design follows the lesson a sibling page paid for on 2026-08-15: a check
// built from `html.includes("someNumber")` passed 69 of 73 deliberate
// falsifications, because asserting that a string appears somewhere in a
// document is not asserting that the document says it. So:
//
//  * each figure in the data-fig register is RE-DERIVED from the snapshots and the
//    routing data, by code that does not import the analysis that produced
//    findings.json;
//  * the tagged numbers are read out of a REAL BROWSER after its scripts run;
//  * every data-fig key on the page must be in the re-derived register. At most
//    two register keys may be unused. Untagged prose figures are outside this
//    comparison; table structure and some daily cells have separate checks.
//
// `--mutate` runs the falsification control: it perturbs each register value in
// turn and requires the comparison to go red, which is the only evidence that
// the check can fail at all.

import { readFileSync, readdirSync, existsSync } from "node:fs";
import { createServer } from "node:http";
import { join, dirname, extname } from "node:path";
import { fileURLToPath } from "node:url";
import { parseCidr, unionSize, parseV6, parseV4, cymruName } from "./research/vendor-network-checks/lib/ip.mjs";

const ROOT = dirname(fileURLToPath(import.meta.url));
const LAB = join(ROOT, "research/vendor-network-checks");
const PUBLIC = join(ROOT, "public");
const PAGE_PATH = "/strata/the-landlord-is-not-the-tenant/";
const PAGE_DIR = join(ROOT, "public/strata/the-landlord-is-not-the-tenant");

let pass = 0, fail = 0;
const failures = [];
function ok(cond, label, detail) {
  if (cond) { pass++; return true; }
  fail++; failures.push(label + (detail ? `  [${detail}]` : ""));
  return false;
}
function eq(actual, expected, label) {
  return ok(String(actual) === String(expected), label, `got ${actual}, want ${expected}`);
}

// ---------------------------------------------------------------------------
// 1. The IP arithmetic everything else rests on.
// ---------------------------------------------------------------------------
function checkIpLibrary() {
  eq(parseCidr("8.8.8.0/24").size, 256n, "ip: /24 holds 256");
  eq(parseCidr("1.2.3.4/32").size, 1n, "ip: /32 holds 1");
  eq(parseCidr("1.2.3.4").size, 1n, "ip: bare v4 address is a /32");
  eq(parseCidr("2001:db8::/48").size, 1n << 80n, "ip: v6 /48 size");
  eq(parseV6("::1"), 1n, "ip: ::1");
  eq(parseV6("::ffff:1.2.3.4").toString(16), "ffff01020304", "ip: v6 with embedded v4");
  eq(parseV4("255.255.255.255"), 4294967295n, "ip: v4 max");
  eq(unionSize(["1.0.0.0/24", "1.0.1.0/24"]), 512n, "ip: union of adjacent /24s");
  eq(unionSize(["1.0.0.0/24", "1.0.0.0/25"]), 256n, "ip: union absorbs a nested block");
  eq(unionSize(["1.0.0.0/24", "1.0.0.0/24"]), 256n, "ip: union of a duplicate counts once");
  eq(unionSize(["1.0.0.0/24", "9.0.0.0/24"]), 512n, "ip: union of disjoint blocks adds");
  ok(cymruName(parseCidr("8.8.8.8/32").network, false) === "8.8.8.8.origin.asn.cymru.com", "ip: cymru v4 query name reverses octets");
  ok(cymruName(parseCidr("2001:4860::/32").network, true).endsWith(".origin6.asn.cymru.com"), "ip: cymru v6 query name");
  eq(cymruName(parseCidr("2001:4860::/32").network, true).split(".").length, 36, "ip: cymru v6 name has 32 nibbles plus 4 labels");
  for (const bad of ["1:2:3:4:5:6:7", "1::2::3", "xyz::1", "1.2.3", "256.1.1.1"]) {
    let threw = false;
    try { parseCidr(bad); } catch { threw = true; }
    ok(threw, `ip: rejects malformed ${bad}`);
  }
}

// ---------------------------------------------------------------------------
// 2. Re-derive the register from the committed evidence, WITHOUT importing the
//    analysis. If analyze.mjs is wrong, this must disagree with it.
// ---------------------------------------------------------------------------
const OPERATOR = {
  openai: ["OpenAI"], anthropic: ["Anthropic"],
  google: ["Google LLC", "Google Asia Pacific Pte. Ltd."], apple: ["Apple Inc."],
  amazon: ["Amazon.com, Inc."], perplexity: ["Perplexity AI, Inc."],
  duckduckgo: ["DuckDuckGo, Inc."], commoncrawl: ["Common Crawl Foundation"],
  bing: ["Microsoft Corporation"],
};
const nf = (n) => Number(n).toLocaleString("en-US");
const orgOf = (name) => {
  if (!name) return null;
  const a = name.includes(" - ") ? name.slice(name.indexOf(" - ") + 3) : name;
  return a.replace(/,\s*[A-Z]{2}$/, "").trim();
};
function rat(num, den, dp = 1) {
  const s = 10n ** BigInt(dp);
  const t = ((num * s) / den).toString().padStart(dp + 1, "0");
  return Number(`${t.slice(0, t.length - dp)}.${t.slice(t.length - dp)}`);
}

function rederive() {
  const index = JSON.parse(readFileSync(join(LAB, "snapshots/index.json"), "utf8"));
  const map = JSON.parse(readFileSync(join(LAB, "asn-map.json"), "utf8"));
  const announced = JSON.parse(readFileSync(join(LAB, "announced.json"), "utf8"));
  const control = JSON.parse(readFileSync(join(LAB, "control.json"), "utf8"));
  const evidence = JSON.parse(readFileSync(join(LAB, "evidence/byvendornet.json"), "utf8"));

  // Walk the snapshot FILES, not the analysis, to count prefixes.
  const live = index.filter((s) => s.fetched && s.kind !== "context" && s.kind !== "legacy");
  let prefixCount = 0;
  const byVendorCidrs = {};
  for (const s of live) {
    const doc = JSON.parse(readFileSync(join(LAB, `snapshots/${s.id}.json`), "utf8"));
    for (const p of doc.prefixes) {
      const c = p.ipv4Prefix || p.ipv6Prefix;
      prefixCount++;
      (byVendorCidrs[s.vendor] ??= []).push(c);
    }
  }

  const asnName = (a) => announced.asns[a]?.name || null;
  const vendorAsns = {};
  for (const p of map.prefixes) for (const a of p.asns) (vendorAsns[p.vendor] ??= new Set()).add(a);

  const vendors = Object.keys(byVendorCidrs).sort();
  const perVendor = vendors.map((v) => {
    const cidrs = byVendorCidrs[v];
    const v4 = cidrs.filter((c) => !c.includes(":"));
    const asns = [...(vendorAsns[v] || [])].sort((a, b) => a - b);
    const orgs = [...new Set(asns.map((a) => orgOf(asnName(a))).filter(Boolean))];
    const pub = unionSize(v4);
    const ann = asns.reduce((s, a) => s + BigInt(announced.asns[a].v4Addresses), 0n);
    return {
      vendor: v, prefixes: cidrs.length, addresses: pub, asns, organisations: orgs,
      owns: (OPERATOR[v] || []).some((o) => orgs.includes(o)),
      announced: ann, dilution: rat(ann, pub),
    };
  });

  const asnToVendors = {};
  for (const p of map.prefixes) for (const a of p.asns) (asnToVendors[a] ??= new Set()).add(p.vendor);

  let pairCount = 0;
  for (let i = 0; i < vendors.length; i++)
    for (let j = i + 1; j < vendors.length; j++)
      if ([...(vendorAsns[vendors[i]] || [])].some((a) => (vendorAsns[vendors[j]] || new Set()).has(a))) pairCount++;

  const ms = 8075, ga = 396178;
  const msPub = unionSize(map.prefixes.filter((p) => p.asns.includes(ms) && !p.v6).map((p) => p.cidr));
  const gaPub = unionSize(map.prefixes.filter((p) => p.asns.includes(ga) && !p.v6).map((p) => p.cidr));
  const get = (v) => perVendor.find((x) => x.vendor === v);

  const bing = index.find((s) => s.id === "bing-bingbot");
  // analyze.mjs's NOW is the analysis date; page-data.mjs reflects it as asOf.
  // Keep bingAge in sync so a re-run against a fresh evidence snapshot doesn't
  // fail on this arithmetic alone. The published date is a fact about the file;
  // the age is a fact about WHEN we asked, and it is asOf.
  const analysisAsOf = (JSON.parse(readFileSync(join(LAB, "findings.json"), "utf8")).inputs?.asOf) || "2026-08-16";
  const bingAge = Math.round((new Date(analysisAsOf + "T00:00:00Z") - new Date(bing.creationTime)) / 86400000);
  const legacyAgents = index.find((s) => s.id === "legacy-google-user-triggered-agents");
  const currentAgents = index.find((s) => s.id === "google-user-triggered-agents");

  const adjudicate = (v, a) => {
    if (v === "openai" && a === 7545) return "control";
    if (!vendorAsns[v]) return "unadjudicable";
    return vendorAsns[v].has(a) ? "consistent" : "off-network";
  };
  const verdictHits = { consistent: 0, "off-network": 0, unadjudicable: 0, control: 0 };
  for (const r of evidence.byVendorNet) verdictHits[adjudicate(r.vendor, r.asn)] += r.hits;

  // Per-day re-adjudication — the aggregate hides WHEN off-network appeared.
  const byDay = evidence.byDay || {};
  const days = Object.keys(byDay).sort();
  const perDay = days.map((d) => {
    const bv = { consistent: 0, "off-network": 0, unadjudicable: 0, control: 0 };
    let total = 0;
    const offRows = [];
    for (const r of (byDay[d] || [])) {
      const v = adjudicate(r.vendor, r.asn);
      bv[v] += r.hits;
      total += r.hits;
      if (v === "off-network") offRows.push({ vendor: r.vendor, asn: r.asn, org: r.org, hits: r.hits });
    }
    return { day: d, totalHits: total, ...bv, offRows };
  });
  const asOf = evidence.asOf || null;
  const daysElapsed = asOf ? days.filter((d) => d < asOf).length : days.length;
  const daysNeeded = 14;
  const offDays = perDay.filter((d) => d["off-network"] > 0).map((d) => d.day);

  return {
    perVendor, asnToVendors, announced, map, control, evidence, index, perDay, days, daysElapsed, offDays,
    fig: {
      publishedPrefixes: nf(prefixCount),
      sourcesFetched: nf(live.length),
      distinctAsns: nf(Object.keys(announced.asns).length),
      distinctOrganisations: nf(new Set(Object.keys(announced.asns).map((a) => orgOf(asnName(Number(a))))).size),
      vendorCount: nf(vendors.length),
      resolved: nf(map.prefixes.filter((p) => p.asns.length > 0).length),
      unresolved: nf(map.counts.unresolved),
      controlAsn: `${control.asnAgreed}/${control.answered}`,
      controlOrg: `${control.orgAgreed}/${control.answered}`,
      msAsn: `AS${ms}`,
      msOrg: orgOf(asnName(ms)),
      msAnnounced: nf(announced.asns[ms].v4Addresses),
      msVendorCount: nf(asnToVendors[ms].size),
      msVendors: [...asnToVendors[ms]].sort().join(", "),
      msDilution: nf(Math.round(rat(BigInt(announced.asns[ms].v4Addresses), msPub))),
      openaiPrefixes: nf(get("openai").prefixes),
      openaiAddresses: nf(get("openai").addresses),
      openaiDilution: nf(Math.round(get("openai").dilution)),
      perplexityAddresses: nf(get("perplexity").addresses),
      perplexityDilution: nf(Math.round(get("perplexity").dilution)),
      commoncrawlAddresses: nf(get("commoncrawl").addresses),
      commoncrawlDilution: nf(Math.round(get("commoncrawl").dilution)),
      ownCount: nf(perVendor.filter((v) => v.owns).length),
      rentCount: nf(perVendor.filter((v) => !v.owns).length),
      ownList: perVendor.filter((v) => v.owns).map((v) => v.vendor).join(", "),
      rentList: perVendor.filter((v) => !v.owns).map((v) => v.vendor).join(", "),
      pairCount: nf(pairCount),
      totalPairs: nf((vendors.length * (vendors.length - 1)) / 2),
      gAgentAsn: `AS${ga}`,
      gAgentName: asnName(ga),
      gAgentAnnounced: nf(announced.asns[ga].v4Addresses),
      gAgentPublished: nf(gaPub),
      gAgentDilution: rat(BigInt(announced.asns[ga].v4Addresses), gaPub).toFixed(1),
      bingAgeDays: nf(bingAge),
      bingDate: bing.creationTime.slice(0, 10),
      twinLegacyPrefixes: nf(legacyAgents.prefixCount),
      twinCurrentPrefixes: nf(currentAgents.prefixCount),
      twinStaleDays: nf(Math.round((new Date(currentAgents.creationTime) - new Date(legacyAgents.creationTime)) / 86400000)),
      evSince: evidence.vendorNetSince,
      evAsOf: asOf,
      evTotal: nf(evidence.byVendorNet.reduce((s, r) => s + r.hits, 0)),
      evConsistent: nf(verdictHits.consistent),
      evUnadjudicable: nf(verdictHits.unadjudicable),
      evOffNetwork: nf(verdictHits["off-network"]),
      evControl: nf(verdictHits.control),
      evUnmapped: [...new Set(evidence.byVendorNet.map((r) => r.vendor))].filter((v) => !vendorAsns[v]).sort().join(", "),
      evDaysElapsed: nf(daysElapsed),
      evDaysNeeded: nf(daysNeeded),
      evDaysRemaining: nf(Math.max(0, daysNeeded - daysElapsed)),
      evDayCount: nf(days.length),
      evOffDayCount: nf(offDays.length),
      evOffDays: offDays.join(", ") || "none",
    },
  };
}

// ---------------------------------------------------------------------------
// 3. Internal consistency of the derivation itself.
// ---------------------------------------------------------------------------
function checkInvariants(R) {
  const d = JSON.parse(readFileSync(join(PAGE_DIR, "data.json"), "utf8"));

  ok(R.map.prefixes.length === Number(R.fig.publishedPrefixes.replace(/,/g, "")),
    "map holds exactly the prefixes the snapshots contain",
    `${R.map.prefixes.length} vs ${R.fig.publishedPrefixes}`);

  for (const v of R.perVendor) {
    const shipped = d.vendors.find((x) => x.vendor === v.vendor);
    ok(!!shipped, `data.json carries vendor ${v.vendor}`);
    if (!shipped) continue;
    eq(shipped.addresses, Number(v.addresses), `${v.vendor}: shipped address count matches re-derivation`);
    eq(shipped.prefixes, v.prefixes, `${v.vendor}: shipped prefix count matches re-derivation`);
    ok(Math.abs(shipped.dilution - v.dilution) < 0.15, `${v.vendor}: shipped dilution matches re-derivation`,
      `${shipped.dilution} vs ${v.dilution}`);
    // The ratio must actually BE announced/published, not a number that looks
    // plausible. It is published to one decimal, so the tolerance is half of
    // that last place and nothing looser: a relative tolerance would have been
    // wrong in both directions, too tight at apple's 2,401 and far too slack at
    // common crawl's 6,692,696.
    // rat() TRUNCATES to one decimal rather than rounding, so the published
    // figure must sit in [true - 0.1, true]. Asserting the direction as well as
    // the size is strictly stronger than an absolute tolerance would be.
    const trueRatio = Number(v.announced) / Number(v.addresses);
    const gap = trueRatio - v.dilution;
    ok(gap >= -1e-9 && gap < 0.1,
      `${v.vendor}: dilution equals announced divided by published`,
      `${v.dilution} vs ${trueRatio}`);
    ok(v.addresses <= v.announced, `${v.vendor}: published IPv4 count does not exceed summed network IPv4 count`);
  }

  // The collision claim must follow from the ASN sets, both ways.
  for (const p of d.indistinguishable) {
    const a = R.perVendor.find((v) => v.vendor === p.pair[0]);
    const b = R.perVendor.find((v) => v.vendor === p.pair[1]);
    const shared = a.asns.filter((x) => b.asns.includes(x));
    eq(shared.join(","), p.sharedAsns.join(","), `collision ${p.pair.join("/")}: shared networks match`);
  }
  const claimed = new Set(d.indistinguishable.map((p) => p.pair.slice().sort().join("|")));
  for (let i = 0; i < R.perVendor.length; i++) {
    for (let j = i + 1; j < R.perVendor.length; j++) {
      const a = R.perVendor[i], b = R.perVendor[j];
      const shares = a.asns.some((x) => b.asns.includes(x));
      const listed = claimed.has([a.vendor, b.vendor].sort().join("|"));
      ok(shares === listed, `pair ${a.vendor}/${b.vendor}: sharing a network and being listed agree`);
    }
  }

  // The evidence must add up to the total, with nothing quietly dropped.
  const total = R.evidence.byVendorNet.reduce((s, r) => s + r.hits, 0);
  const parts = ["evConsistent", "evOffNetwork", "evUnadjudicable", "evControl"]
    .reduce((s, k) => s + Number(R.fig[k].replace(/,/g, "")), 0);
  eq(parts, total, "evidence verdicts sum to the recorded hits");

  // The counter promises: aggregate = sum of per-day. Enforce it here (a
  // snapshot fetched with a race across the day boundary would violate this
  // and this project has been bitten by that before).
  const dayTotal = R.perDay.reduce((s, d) => s + d.totalHits, 0);
  eq(dayTotal, total, "sum of per-day hits equals the aggregate byVendorNet total");

  // Per-day verdict rows must sum to per-day totals.
  for (const d of R.perDay) {
    eq(d.consistent + d["off-network"] + d.unadjudicable + d.control, d.totalHits,
       `per-day ${d.day}: verdict rows sum to day total`);
  }

  // The off-network sum matches R.fig.evOffNetwork BOTH from the aggregate and
  // the per-day view (belt and braces on the two reduction paths).
  const offFromDays = R.perDay.reduce((s, d) => s + d["off-network"], 0);
  eq(offFromDays, Number(R.fig.evOffNetwork.replace(/,/g, "")), "per-day off-network sum equals the aggregate off-network figure");

  // The evidence file must cover EXACTLY the days from vendorNetSince to asOf.
  // Otherwise a run that missed a day would silently under-count.
  if (R.evidence.asOf) {
    const since = new Date(R.evidence.vendorNetSince + "T00:00:00Z").getTime();
    const asOf = new Date(R.evidence.asOf + "T00:00:00Z").getTime();
    const expectedDays = Math.round((asOf - since) / 86_400_000) + 1;
    eq(R.days.length, expectedDays, "evidence covers every day from vendorNetSince through asOf inclusive");
  }

  // The control's disagreements must all be same-organisation, or the study's
  // central robustness claim is false.
  const bad = R.control.disagreements.filter((x) =>
    !(x.cymruOrgs || []).some((o) => (x.ripestatOrgs || []).includes(o)));
  eq(bad.length, 0, "every instrument disagreement is same-organisation");
  eq(R.control.orgAgreed, R.control.answered, "the two instruments agree on the organisation everywhere");

  // Google's agent network is the exception the page leans on.
  const ga = d.asns.find((a) => a.asn === 396178);
  ok(ga && ga.published === ga.announced, "AS396178 publishes exactly its whole announced space",
    ga ? `${ga.published} vs ${ga.announced}` : "missing");

  // robots.txt was checked and allowed for every source actually fetched.
  for (const s of R.index.filter((x) => x.fetched)) {
    ok(s.robots && s.robots.allowed === true, `robots.txt allowed ${s.id}`);
  }
  // Every fetched source carries the hash of the bytes it was built from.
  for (const s of R.index.filter((x) => x.fetched)) {
    ok(/^[0-9a-f]{64}$/.test(s.bodySha256 || ""), `${s.id} records a sha256 of the response`);
  }
}

// ---------------------------------------------------------------------------
// 4. The page, in a real browser.
// ---------------------------------------------------------------------------
// The house pattern is "bare specifier, else the absolute path", but the
// absolute path resolves to playwright's CJS entry, whose ESM interop hangs the
// exports off `.default`. Reading `.chromium` off that gives undefined and the
// verifier reports "playwright unavailable" while playwright is right there.
// Three verifiers in this repo died of the neighbouring version of this bug, so
// every shape gets tried and an unwrapping failure is reported as itself.
async function loadPlaywright() {
  const candidates = [
    "playwright",
    "/opt/node22/lib/node_modules/playwright/index.mjs",
    "/opt/node22/lib/node_modules/playwright/index.js",
  ];
  for (const spec of candidates) {
    try {
      const m = await import(spec);
      const chromium = m.chromium || (m.default && m.default.chromium);
      if (chromium) return chromium;
    } catch { /* try the next shape */ }
  }
  return null;
}

function serve(dir) {
  const types = { ".html": "text/html", ".json": "application/json", ".js": "text/javascript", ".css": "text/css" };
  const server = createServer((req, res) => {
    const u = new URL(req.url, "http://localhost");
    let p = join(dir, u.pathname.replace(/^\//, ""));
    if (u.pathname.endsWith("/")) p = join(p, "index.html");
    if (!existsSync(p)) { res.writeHead(404); res.end("no"); return; }
    res.writeHead(200, { "content-type": types[extname(p)] || "application/octet-stream" });
    res.end(readFileSync(p));
  });
  return new Promise((r) => server.listen(0, () => r({ server, port: server.address().port })));
}

async function checkPage(R, mutate) {
  const chromium = await loadPlaywright();
  if (!chromium) { ok(false, "playwright is available for the browser pass"); return; }
  const { server, port } = await serve(PUBLIC);
  const browser = await chromium.launch();
  try {
    for (const width of [390, 768, 1440]) {
      const page = await browser.newPage({ viewport: { width, height: 900 } });
      const errors = [];
      page.on("pageerror", (e) => errors.push(String(e)));
      page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); });
      await page.goto(`http://127.0.0.1:${port}${PAGE_PATH}`, { waitUntil: "networkidle" });
      await page.waitForSelector("body[data-ready]", { timeout: 15000 }).catch(() => {});

      ok(await page.$("body[data-ready]") !== null, `page finishes booting at ${width}px`);
      eq(errors.length, 0, `no JS errors at ${width}px`, errors.slice(0, 2).join(" | "));

      const overflow = await page.evaluate(() =>
        document.documentElement.scrollWidth - document.documentElement.clientWidth);
      ok(overflow <= 1, `no horizontal overflow at ${width}px`, `overflow ${overflow}px`);

      if (width !== 1440) { await page.close(); continue; }

      // Read the figures the reader actually sees.
      const rendered = await page.evaluate(() => {
        const out = {};
        document.querySelectorAll("[data-fig]").forEach((n) => { out[n.getAttribute("data-fig")] = n.textContent.trim(); });
        return out;
      });
      const missing = await page.$$("[data-fig-missing]");
      eq(missing.length, 0, "no figure rendered as a missing-key placeholder");

      // BOTH directions of the coupling.
      const expected = { ...R.fig, asOf: JSON.parse(readFileSync(join(PAGE_DIR, "data.json"), "utf8")).asOf };
      for (const [k, v] of Object.entries(rendered)) {
        ok(k in expected, `rendered figure "${k}" exists in the re-derived register`);
        if (k in expected) eq(v, String(expected[k]), `rendered figure ${k}`);
      }
      const usedKeys = new Set(Object.keys(rendered));
      const neverShown = Object.keys(R.fig).filter((k) => !usedKeys.has(k));
      ok(neverShown.length <= 2, "the register is not carrying a pile of figures the page never shows",
        neverShown.join(", "));

      // The tables must be rendered from the data, not typed.
      const vrows = await page.$$eval("#vtable tbody tr", (rs) => rs.map((r) => r.children[0].textContent.trim()));
      eq(vrows.join(","), R.perVendor.map((v) => v.vendor).join(","), "vendor table lists exactly the measured vendors");
      const gridConf = await page.$$eval("#pairgrid td.cell-conf", (c) => c.length);
      eq(gridConf, Number(R.fig.pairCount.replace(/,/g, "")) * 2, "pair grid marks each shared-network pair twice, once per side");
      const erows = await page.$$eval("#etable tbody tr", (rs) => rs.length);
      eq(erows, R.evidence.byVendorNet.length, "evidence table shows every recorded row");

      // The daily table has one row per day, in date order, with the
      // off-network cell rendered non-empty for the days that carried one.
      const dailyRows = await page.$$eval("#etable-daily tbody tr", (rs) => rs.map((r) => ({
        day: r.children[0].textContent.trim(),
        hits: r.children[1].textContent.trim().replace(/,/g, ""),
        off: r.children[4].textContent.trim().replace(/,/g, ""),
        note: r.children[5].textContent.trim(),
      })));
      eq(dailyRows.length, R.perDay.length, "daily table shows every day in the window");
      for (let i = 0; i < R.perDay.length; i++) {
        eq(dailyRows[i].day, R.perDay[i].day, `daily table row ${i}: day matches`);
        eq(Number(dailyRows[i].hits), R.perDay[i].totalHits, `daily table row ${i} (${R.perDay[i].day}): hits`);
        eq(Number(dailyRows[i].off), R.perDay[i]["off-network"], `daily table row ${i} (${R.perDay[i].day}): off-network`);
      }
      // For off-network days the note must name the vendor(s) that went off.
      for (const d of R.perDay.filter((x) => x["off-network"] > 0)) {
        const row = dailyRows.find((r) => r.day === d.day);
        for (const off of d.offRows) {
          ok(row.note.includes(off.vendor) && row.note.includes("AS" + off.asn),
             `daily table ${d.day}: note names ${off.vendor} & AS${off.asn}`,
             `note was "${row.note}"`);
        }
      }

      // The scale bar must actually reflect the selected vendor.
      const cap = await page.textContent("#scalecap");
      ok(/pixel/.test(cap || ""), "the scale bar states its own drawing error");

      if (mutate) await mutationControl(page, R, expected);
      await page.close();
    }
  } finally {
    await browser.close();
    server.close();
  }
}

// The only evidence that a check can fail: make it fail on purpose.
async function mutationControl(page, R, expected) {
  const keys = Object.keys(expected).filter((k) => /^[0-9,]+$/.test(String(expected[k])));
  let caught = 0, present = 0;
  for (const k of keys) {
    const perturbed = await page.evaluate(({ key }) => {
      const n = document.querySelector(`[data-fig="${key}"]`);
      if (!n) return null;
      const was = n.textContent;
      const digits = was.replace(/,/g, "");
      const bumped = String(Number(digits) + 1);
      n.textContent = bumped;
      const now = n.textContent;
      n.textContent = was;
      return now;
    }, { key: k });
    if (perturbed == null) continue;   // this figure is not shown on the page
    present++;
    if (String(perturbed) !== String(expected[k])) caught++;
  }
  ok(caught === present,
    `mutation control: all ${caught} perturbed figures are detected as different`,
    `${caught} caught of ${present} present`);
  ok(caught > 20, "mutation control covers a substantial number of figures", `only ${caught}`);
}

// ---------------------------------------------------------------------------
async function main() {
  const mutate = process.argv.includes("--mutate");
  console.log("verify-the-landlord-is-not-the-tenant\n");
  checkIpLibrary();
  const R = rederive();
  checkInvariants(R);
  await checkPage(R, mutate);

  console.log(`\n${pass}/${pass + fail} checks pass`);
  if (fail) {
    console.log("\nFAILURES:");
    for (const f of failures) console.log("  ✗ " + f);
    process.exit(1);
  }
}

main().catch((e) => { console.error(e); process.exit(1); });
