#!/usr/bin/env node
// Browser verification for public/tools/offset-ledger/.
// Real Chromium checks, without installations or permanent services.
// node research/offset-ledger/verify-browser.mjs --output-dir=/tmp/offset-browser
// Optional: --base-url=https://artwaste.land --playwright=/path/index.mjs --chromium=/path/chrome
// Arithmetic expectations below are literal, independent fixtures. Downloaded
// reports are also recomputed by the public Python checker in an empty directory.
import assert from 'node:assert/strict';
import http from 'node:http';
import { readFile, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath, pathToFileURL } from 'node:url';
import path from 'node:path';
import os from 'node:os';
import { performance } from 'node:perf_hooks';

const arg = name => process.argv.find(s => s.startsWith(`--${name}=`))?.slice(name.length + 3);
const PUBLIC = fileURLToPath(new URL('../../public/', import.meta.url));
const OUTPUT = path.resolve(arg('output-dir') || await mkdtemp(path.join(os.tmpdir(), 'offset-browser-')));
await mkdir(OUTPUT, { recursive: true });
let pw;
for (const candidate of [arg('playwright'), 'playwright', '/home/liam/tools/node_modules/playwright/index.mjs'].filter(Boolean)) {
  try { pw = await import(candidate.startsWith('/') ? pathToFileURL(candidate).href : candidate); break; } catch {}
}
if (!pw) throw new Error('Provide existing Playwright with --playwright=/path/index.mjs. This verifier does not install dependencies.');
const TYPES = { '.html': 'text/html', '.mjs': 'text/javascript', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.woff2': 'font/woff2', '.woff': 'font/woff', '.png': 'image/png', '.svg': 'image/svg+xml', '.csv': 'text/csv', '.zip': 'application/zip', '.py': 'text/plain' };
let server, browser, base = arg('base-url');
if (!base) {
  server = http.createServer(async (req, res) => {
    try {
      let pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
      if (pathname.endsWith('/')) pathname += 'index.html';
      const filename = path.resolve(PUBLIC, '.' + pathname);
      if (!filename.startsWith(PUBLIC)) throw new Error('outside public');
      const body = await readFile(filename);
      res.writeHead(200, { 'content-type': TYPES[path.extname(filename)] || 'application/octet-stream' });
      res.end(body);
    } catch { if (!res.headersSent) res.writeHead(404); res.end('not found'); }
  });
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
  base = `http://127.0.0.1:${server.address().port}`;
}
const TOOL = new URL('/tools/offset-ledger/', base).href;
const HEAD = 'date,loan,offset,annualRatePercent';
const CSV = `${HEAD}\r\n2026-01-01,365,0,0.5\r\n2026-01-02,365,0,0.5\r\n2026-01-03,365,0,0.5\r\n`;
const DECLARATIONS = ['completePeriod', 'endOfDayBalances', 'effectiveRates', 'eligibleOffsets', 'chargePeriod', 'modelAccepted'];
const EXPORTS = ['export-report', 'export-csv', 'export-ledger', 'export-text', 'print'];
const CANARY = '812345678901.234567891234', PRIVATE_NAME = 'PRIVATE-OFFSET-READER-72931.csv';
const HUGE_CHARGE = '9007199254740993.01';
const requests = [], errors = [], downloads = [], timings = [], contrast = [];
let passed = 0;
const equal = (actual, expected, label) => { assert.equal(actual, expected, label); passed++; };
const truth = (value, label) => { assert.ok(value, label); passed++; };
const deep = (actual, expected, label) => { assert.deepEqual(actual, expected, label); passed++; };
const text = async (page, selector) => (await page.locator(selector).textContent()).trim();
async function ready(page) { await page.waitForFunction(() => document.querySelector('#run-status').textContent.startsWith('Calculated'), null, { timeout: 90000 }); }
async function run(page) { await page.click('#run'); await ready(page); }
async function example(page, kind = 'timing') { await page.selectOption('#example-kind', kind); await page.click('#demo'); await ready(page); }
async function stale(page, label) {
  truth(await page.locator('#results').isHidden(), `${label}: old results hidden`);
  for (const id of EXPORTS) truth(await page.locator('#' + id).isDisabled(), `${label}: ${id} disabled`);
}
async function importCsv(page, csv = CSV, { name = PRIVATE_NAME, valid = true } = {}) {
  await page.setInputFiles('#csv-file', { name, mimeType: 'text/csv', buffer: Buffer.from(csv) });
  await page.waitForFunction(() => /^(Loaded|Cannot load records:)/.test(document.querySelector('#import-status').textContent));
  const note = await text(page, '#import-status');
  truth(note.startsWith(valid ? 'Loaded' : 'Cannot load records:'), `CSV ${valid ? 'accepted' : 'refused'}: ${note}`);
  await stale(page, 'CSV import');
}
async function declarations(page, checked = true) { for (const id of DECLARATIONS) await page.locator('#' + id).setChecked(checked); }
async function downloaded(page, id) {
  const pending = page.waitForEvent('download'); await page.click(id); const download = await pending;
  const filename = download.suggestedFilename(), target = path.join(OUTPUT, `${downloads.length + 1}-${filename}`);
  await download.saveAs(target); downloads.push(filename);
  return { filename, target, text: await readFile(target, 'utf8') };
}
async function reopen(page, contents, valid = true) {
  await page.setInputFiles('#report-file', { name: valid ? 'saved.json' : 'tampered.json', mimeType: 'application/json', buffer: Buffer.from(contents) });
  await page.waitForFunction(() => /^(PASS:|FAILED:)/.test(document.querySelector('#report-status').textContent));
  const note = await text(page, '#report-status');
  truth(note.startsWith(valid ? 'PASS:' : 'FAILED:'), `report ${valid ? 'accepted' : 'refused'}: ${note}`);
  if (valid) await ready(page); else await stale(page, 'Rejected report');
}
function canonical(value) {
  if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
  if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + canonical(value[k])).join(',') + '}';
  return JSON.stringify(value);
}
function rehash(report) {
  const { sha256, ...body } = report;
  report.sha256 = createHash('sha256').update(canonical(body)).digest('hex');
  return report;
}
function python(reader, file) {
  return spawnSync('python3', ['-I', 'check_report.py', file], { cwd: reader, encoding: 'utf8', timeout: 60000 });
}

try {
  browser = await pw.chromium.launch({ headless: true, args: ['--no-sandbox'], ...(arg('chromium') ? { executablePath: arg('chromium') } : {}) });
  const context = await browser.newContext({ viewport: { width: 1440, height: 1100 }, locale: 'en-AU', acceptDownloads: true });
  const page = await context.newPage();
  page.setDefaultTimeout(15000);
  page.on('pageerror', error => errors.push(error.message));
  page.on('request', request => requests.push({ url: request.url(), method: request.method(), body: request.postData() || '' }));
  await page.goto(TOOL, { waitUntil: 'networkidle' }); await ready(page);
  equal(await text(page, '#headline-charge'), '$75.62', 'timing observation');
  equal(await text(page, '#source-label'), 'Invented example', 'prominent synthetic source');
  equal(await text(page, '#result-heading'), 'Invented example', 'synthetic data never give a lender verdict');
  equal(await text(page, '[data-convention="period-end-half-up"] strong'), '$75.62', 'independent period-end fixture');
  equal(await text(page, '[data-convention="daily-half-up"] strong'), '$75.50', 'independent daily-rounding fixture');
  equal(await page.locator('#ledger-body tr').count(), 30, 'all thirty demo days visible');
  await page.screenshot({ path: path.join(OUTPUT, 'desktop.png'), fullPage: true });
  await page.screenshot({ path: path.join(OUTPUT, 'hero.png'), clip: { x: 0, y: 0, width: 1440, height: 1000 } });
  console.log(`VISUALS ${OUTPUT}/desktop.png ${OUTPUT}/hero.png`);

  await example(page, 'rounding');
  equal(await text(page, '#headline-charge'), '$3.07', 'between-candidate observation');
  equal(await text(page, '[data-convention="period-end-half-up"] strong'), '$3.15', '30 times 10.49 cents rounded at end');
  equal(await text(page, '[data-convention="daily-half-up"] strong'), '$3.00', '30 times 10 cents rounded daily');
  equal(await page.locator('#candidates .match').count(), 0, 'intermediate observation matches neither discrete model');

  await declarations(page);
  await importCsv(page);
  equal(await page.inputValue('#observed'), '', 'CSV import clears previous observed charge');
  for (const id of DECLARATIONS) truth(!await page.isChecked('#' + id), `CSV import clears declaration ${id}`);
  equal(await page.inputValue('#start'), '2026-01-01', 'CSV suggests earliest actual day');
  equal(await page.inputValue('#end'), '2026-01-03', 'CSV suggests latest actual day');
  equal(await text(page, '#source-label'), 'Supplied daily records', 'CSV origin is explicitly supplied');
  await page.fill('#observed', '0.02'); await run(page);
  equal(await text(page, '#result-heading'), 'Assumptions need confirmation', 'unconfirmed real data remain conditional');
  equal(await text(page, '[data-convention="period-end-half-up"] strong'), '$0.02', '1.5 cents rounds half up to two');
  equal(await text(page, '[data-convention="daily-half-up"] strong'), '$0.03', 'three half-cent days round to three');
  await declarations(page); await stale(page, 'Declaration changed'); await run(page);
  equal(await text(page, '#result-heading'), 'Matches a selected model', 'six confirmations allow conditional model match');
  equal(await page.locator('#candidates .match').count(), 1, 'only selected compatible candidate matches');
  const saved = await downloaded(page, '#export-report'), report = JSON.parse(saved.text);
  deep(report.input.rows, [1, 2, 3].map(n => ({ date: `2026-01-0${n}`, loan: '365', offset: '0', annualRatePercent: '0.5' })), 'download contains original exact daily records');
  equal(report.context.source, 'user', 'download records supplied provenance');
  equal(report.result.exactCents.withOffset.numerator, '3', 'independent exact fixture numerator');
  equal(report.result.exactCents.withOffset.denominator, '2', 'independent exact fixture denominator');
  deep(report.result.candidates.map(c => [c.chargeCents, c.compatible]), [['2', true], ['3', false]], 'JSON keeps separate exact outcomes');
  truth(!saved.text.includes(PRIVATE_NAME), 'report omits source filename');

  const reader = await mkdtemp(path.join(OUTPUT, 'reader-'));
  const checkerResponse = await context.request.get(new URL('check_report.py', TOOL).href);
  equal(checkerResponse.status(), 200, 'independent Python checker can be downloaded');
  await writeFile(path.join(reader, 'check_report.py'), await checkerResponse.body());
  const zipResponse = await context.request.get(new URL('checker.zip', TOOL).href);
  equal(zipResponse.status(), 200, 'public checker ZIP can be downloaded');
  await writeFile(path.join(reader, 'report.json'), saved.text);
  const checked = python(reader, 'report.json');
  equal(checked.status, 0, `empty-directory Python recomputation passes: ${checked.stderr}`);
  const check = JSON.parse(checked.stdout);
  equal(check.verified, true, 'Python verified downloaded JSON');
  equal(check.daysChecked, 3, 'Python checked each supplied day');
  equal(check.status, 'reconciles-under-selected-model', 'Python agrees about conditional status');
  deep(check.matchingConventions, ['period-end-half-up'], 'Python agrees only one exact candidate matches');
  const tampered = structuredClone(report); tampered.result.candidates[0].chargeCents = '1'; rehash(tampered);
  await writeFile(path.join(reader, 'tampered-result.json'), JSON.stringify(tampered));
  const wrong = python(reader, 'tampered-result.json');
  equal(wrong.status, 1, 'Python rejects changed arithmetic despite correctly recomputed hash');
  equal(JSON.parse(wrong.stderr).code, 'RESULT_MISMATCH', 'arithmetic rejection is independent of self-digest');
  const badHash = structuredClone(report); badHash.sha256 = '0'.repeat(64);
  await writeFile(path.join(reader, 'tampered-hash.json'), JSON.stringify(badHash));
  const hashCheck = python(reader, 'tampered-hash.json');
  equal(hashCheck.status, 1, 'Python rejects bad hash');
  equal(JSON.parse(hashCheck.stderr).code, 'DIGEST', 'digest rejection is explicit');

  const csvDownload = await downloaded(page, '#export-csv');
  equal(csvDownload.text, CSV, 'input CSV round trip preserves exact spellings and CRLF');
  const workings = await downloaded(page, '#export-ledger');
  const workLines = workings.text.trim().split(/\r?\n/);
  equal(workLines.length, 4, 'workings CSV has every actual day');
  equal(workLines[0], 'date,loanDollars,eligibleOffsetDollars,annualRatePercent,interestCentsNumerator,interestCentsDenominator,dailyRoundedInterestCents,noOffsetCentsNumerator,noOffsetCentsDenominator', 'workings columns state units and exact fractions');
  equal(workLines[1], '2026-01-01,365,0,0.5,1,2,1,1,2', 'daily workings show exact half-cent alongside rounded cent');
  const summary = await downloaded(page, '#export-text');
  truth(summary.text.includes('Exact pre-rounding total: 3/2 cents.'), 'readable summary keeps exact total');
  truth(summary.text.includes('not a signature or proof of authenticity'), 'summary explains self-digest limits');
  for (const id of DECLARATIONS) truth(summary.text.includes(`${id}: declared by report author`), 'summary carries declaration ' + id);
  await page.evaluate(() => { window.__printCalls = 0; window.print = () => { window.__printCalls++; }; });
  await page.click('#print'); equal(await page.evaluate(() => window.__printCalls), 1, 'print action invokes native print');
  await page.emulateMedia({ media: 'print' });
  truth(await page.locator('#results').isVisible(), 'print preserves calculated evidence');
  truth(await page.locator('#workspace > aside').isHidden(), 'print omits editing controls');
  truth(await page.locator('#export-report').isHidden(), 'print omits export buttons');
  truth((await text(page, '#print-summary')).includes('completePeriod: declared by report author'), 'print keeps author declarations');
  truth((await text(page, '#day-detail')).includes('2026-01-01'), 'print daily detail identifies its date');
  await page.pdf({ path: path.join(OUTPUT, 'print.pdf'), format: 'A4', printBackground: true });
  await page.emulateMedia({ media: 'screen' });
  console.log('PASS examples, declarations, independent Python verification, tampering and all exports');

  await page.fill('#observed', '0.04'); await stale(page, 'Observed charge changed'); await run(page);
  equal(await text(page, '#result-heading'), 'Differs from the selected models', 'confirmed mismatch stays a model comparison');
  await reopen(page, saved.text);
  equal(await page.inputValue('#observed'), '0.02', 'report restore recovers observed amount');
  equal(await page.inputValue('#start'), report.input.start, 'report restore recovers start date');
  equal(await page.inputValue('#end'), report.input.end, 'report restore recovers end date');
  for (const id of DECLARATIONS) truth(await page.isChecked('#' + id), `report restores ${id}`);
  truth(await page.isChecked('#period-rounding') && await page.isChecked('#daily-rounding'), 'report restores selected conventions');
  equal(await page.inputValue('#csv-text'), CSV.replace(/\r\n/g, '\n'), 'report restores exact daily records to textarea');
  await reopen(page, JSON.stringify(tampered), false);
  await reopen(page, saved.text); await reopen(page, JSON.stringify(badHash), false);
  await importCsv(page, csvDownload.text); await page.fill('#observed', '0.02'); await declarations(page); await run(page);
  const csvRoundtrip = JSON.parse((await downloaded(page, '#export-report')).text);
  deep(csvRoundtrip.result, report.result, 'CSV export imported again recreates all exact workings');

  // Every calculation input must invalidate the result, including edits that
  // would otherwise leave a plausible-looking report visible.
  for (const [id, value] of [['start', '2026-01-02'], ['end', '2026-01-02']]) {
    await page.fill('#' + id, value); await stale(page, id + ' changed'); await reopen(page, saved.text);
  }
  for (const id of ['period-rounding', 'daily-rounding', ...DECLARATIONS]) {
    await page.uncheck('#' + id); await stale(page, id + ' changed'); await reopen(page, saved.text);
  }
  await page.uncheck('#daily-rounding'); await run(page);
  equal(await page.locator('#candidates .candidate').count(), 1, 'only the chosen hypothesis is reported');
  await page.uncheck('#period-rounding'); await page.click('#run');
  await page.waitForFunction(() => document.querySelector('#run-status').textContent.startsWith('Cannot reconcile:'));
  await stale(page, 'No selected conventions');
  await reopen(page, saved.text);
  await page.locator('summary').filter({ hasText: 'Paste daily records' }).click();
  await page.fill('#csv-text', CSV.replace('365', '366')); await stale(page, 'Pasted CSV edited');
  truth(await page.locator('#run').isDisabled(), 'editing CSV requires explicit reimport before calculating');
  await page.click('#use-paste'); equal(await page.inputValue('#observed'), '', 'pasted import clears old observation');
  await page.fill('#observed', '0.02'); await run(page);
  equal(await text(page, '#result-heading'), 'Assumptions need confirmation', 'pasted data need fresh confirmations');

  const gap = `${HEAD}\n2026-01-01,365,0,0.5\n2026-01-03,365,0,0.5\n`;
  await importCsv(page, gap); await page.fill('#observed', '0.02'); await page.click('#run');
  await page.waitForFunction(() => document.querySelector('#run-status').textContent.startsWith('Cannot reconcile:'));
  truth(/missing|every|gap|day/i.test(await text(page, '#run-status')), 'missing day has an actionable refusal');
  await stale(page, 'Missing daily record');
  for (const [label, invalid] of [
    ['duplicate day', CSV + '2026-01-01,365,0,0.5\r\n'],
    ['impossible date', CSV.replace('2026-01-01', '2026-02-30')],
    ['formula cell', CSV.replace(',365,', ',=365,')],
    ['ambiguous header', CSV.replace(HEAD, HEAD + ',loan')],
  ]) {
    await reopen(page, saved.text); await importCsv(page, invalid, { valid: false, name: 'invalid.csv' });
    truth(await page.locator('#run').isDisabled(), `${label} cannot calculate from old rows`);
  }
  console.log('PASS restore, CSV round trip, dirty inputs and invalid/missing records');

  // Delay real File.text promises so an input edit occurs during each read.
  // The late file must never restore old results, and choosing it again works.
  for (const kind of ['csv', 'report']) {
    await reopen(page, saved.text);
    await page.evaluate(() => {
      window.__originalFileText = File.prototype.text;
      File.prototype.text = function () {
        const contents = window.__originalFileText.call(this);
        return new Promise(resolve => { window.__releaseRead = async () => resolve(await contents); });
      };
    });
    const fileId = kind === 'csv' ? '#csv-file' : '#report-file';
    const statusId = kind === 'csv' ? '#import-status' : '#report-status';
    const contents = kind === 'csv' ? CSV : saved.text;
    await page.setInputFiles(fileId, { name: 'delayed.' + (kind === 'csv' ? 'csv' : 'json'), mimeType: 'text/plain', buffer: Buffer.from(contents) });
    await page.waitForFunction(selector => /^(Reading local CSV|Checking saved report locally)/.test(document.querySelector(selector).textContent), statusId);
    await page.fill('#observed', '0.07');
    truth((await text(page, statusId)).startsWith('Reading cancelled'), `${kind} read cancellation is explicit`);
    equal(await page.inputValue(fileId), '', `${kind} cancellation allows selecting the same file again`);
    await page.evaluate(async () => { await window.__releaseRead(); File.prototype.text = window.__originalFileText; });
    await stale(page, `${kind} late read`);
    truth(await page.locator('#run').isDisabled(), `${kind} late read cannot revive earlier rows`);
    truth((await text(page, statusId)).startsWith('Reading cancelled'), `${kind} late promise cannot overwrite cancellation status`);
    if (kind === 'csv') await importCsv(page, contents, { name: 'delayed.csv' });
    else await reopen(page, contents);
  }

  await importCsv(page, `${HEAD}\n2026-01-01,9007199254740993.01,0,36.5\n`);
  await page.fill('#observed', '90071992547409.93'); await declarations(page); await run(page);
  await page.setViewportSize({ width: 390, height: 844 });
  const hugeOverflow = await page.evaluate(() => ({ body: document.body.scrollWidth, document: document.documentElement.scrollWidth }));
  truth(hugeOverflow.body <= 391 && hugeOverflow.document <= 391, `long amounts stay inside 390px page: ${JSON.stringify(hugeOverflow)}`);
  await page.screenshot({ path: path.join(OUTPUT, 'mobile-large-amounts.png'), fullPage: true });
  await page.setViewportSize({ width: 1440, height: 1100 });

  const privateCsv = `${HEAD}\n2026-01-01,${CANARY},0,0\n`;
  await importCsv(page, privateCsv); await page.fill('#observed', HUGE_CHARGE); await declarations(page); await run(page);
  equal(await text(page, '#headline-charge'), '$9,007,199,254,740,993.01', 'huge observation never passes through lossy Number formatting');
  truth((await text(page, '#candidates')).includes('Difference: $9,007,199,254,740,993.01'), 'huge exact difference keeps every cent');
  const giant = await downloaded(page, '#export-report'), giantReport = JSON.parse(giant.text);
  equal(giantReport.input.observedCharge, HUGE_CHARGE, 'export preserves huge observation spelling');
  equal(giantReport.input.rows[0].loan, CANARY, 'export preserves 12 fractional digits');
  equal(giantReport.result.candidates[0].differenceCents, '900719925474099301', 'huge difference is exact cents');
  await writeFile(path.join(reader, 'giant.json'), giant.text);
  equal(python(reader, 'giant.json').status, 0, 'Python independently verifies large exact values');
  const leak = request => [CANARY, PRIVATE_NAME, HUGE_CHARGE].some(value => request.url.includes(value) || request.body.includes(value));
  truth(!requests.some(leak), 'private numeric and filename canaries never appear in network URLs or bodies');
  truth(leak({ url: 'https://example.invalid/', body: PRIVATE_NAME }), 'privacy detector catches an actual filename body leak');
  truth(leak({ url: 'https://example.invalid/?amount=' + CANARY, body: '' }), 'privacy detector catches an actual numeric URL leak');
  const storage = await page.evaluate(() => [...Object.entries(localStorage), ...Object.entries(sessionStorage)].map(([k, v]) => k + v).join('\n'));
  truth(![CANARY, PRIVATE_NAME, HUGE_CHARGE].some(value => storage.includes(value)), 'private values never enter localStorage/sessionStorage');
  await page.reload({ waitUntil: 'networkidle' }); await ready(page);
  equal(await text(page, '#source-label'), 'Invented example', 'reload does not persist private records');
  equal(await page.inputValue('#observed'), '75.62', 'reload does not retain private observation');

  const first = Date.UTC(2020, 0, 1);
  const full = HEAD + '\n' + Array.from({ length: 3660 }, (_, i) => `${new Date(first + i * 86400000).toISOString().slice(0, 10)},365,0,0`).join('\n') + '\n';
  const started = performance.now(); await importCsv(page, full, { name: 'invented-3660-days.csv' });
  await page.fill('#observed', '0'); await declarations(page); await run(page);
  timings.push({ scenario: '3660 complete daily rows through CSV and browser calculation', milliseconds: Math.round(performance.now() - started) });
  truth((await text(page, '#run-status')).startsWith('Calculated 3660 days.'), 'maximum supported daily period calculates');
  truth(await page.locator('#export-report').isEnabled(), 'maximum supported period can be exported');
  const maxReport = await downloaded(page, '#export-report');
  equal(JSON.parse(maxReport.text).result.daily.length, 3660, 'maximum report includes every day');
  await writeFile(path.join(reader, 'max-days.json'), maxReport.text);
  equal(python(reader, 'max-days.json').status, 0, 'independent checker handles full 3660-day report');
  const extra = new Date(first + 3660 * 86400000).toISOString().slice(0, 10);
  await importCsv(page, full + `${extra},365,0,0\n`, { valid: false, name: 'too-many-days.csv' });
  truth(await page.locator('#run').isDisabled(), '3661 rows are refused before calculation');
  console.log('PASS privacy, exact large observations and maximum supported period');

  await example(page);
  await page.keyboard.press('Tab'); await page.locator('#demo').focus(); await page.keyboard.press('Enter'); await ready(page);
  truth(await page.locator('#demo').evaluate(el => getComputedStyle(el).outlineStyle !== 'none' && parseFloat(getComputedStyle(el).outlineWidth) >= 2), 'keyboard activation retains visible focus indication');
  await page.locator('#run').focus(); await page.keyboard.press('Enter'); await ready(page);
  equal(await page.evaluate(() => document.activeElement.id), 'result-heading', 'keyboard reconcile moves focus to result heading');
  await page.waitForFunction(() => { const rect = document.querySelector('#result-heading').getBoundingClientRect(); return rect.top >= 0 && rect.bottom <= innerHeight; });
  truth(true, 'keyboard reconcile scrolls the newly focused result into view');
  await page.locator('.table-wrap').focus();
  equal(await page.evaluate(() => document.activeElement.className), 'table-wrap', 'daily table region is keyboard reachable');
  const samples = await page.evaluate(() => {
    function rgb(value) { return value.match(/[\d.]+/g).map(Number); }
    function luminance(channels) {
      const linear = channels.slice(0, 3).map(v => { const s = v / 255; return s <= .04045 ? s / 12.92 : ((s + .055) / 1.055) ** 2.4; });
      return linear[0] * .2126 + linear[1] * .7152 + linear[2] * .0722;
    }
    return [
      ['primary copy', '.dek'], ['muted hint', '#workspace .hint'],
      ['accent link', '.hero-note a'], ['candidate label', '.candidate h3'],
      ['input placeholder', '#observed', '::placeholder'],
    ].map(([name, selector, pseudo]) => {
      const element = document.querySelector(selector), style = getComputedStyle(element, pseudo);
      let node = element, background;
      while (node) { background = getComputedStyle(node).backgroundColor; if (rgb(background)[3] !== 0) break; node = node.parentElement; }
      const foregroundL = luminance(rgb(style.color)), backgroundL = luminance(rgb(background));
      return { name, foreground: style.color, background, ratio: (Math.max(foregroundL, backgroundL) + .05) / (Math.min(foregroundL, backgroundL) + .05) };
    });
  });
  for (const sample of samples) { truth(sample.ratio >= 4.5, `${sample.name} has at least 4.5:1 contrast (${sample.ratio.toFixed(2)}:1)`); contrast.push(sample); }
  for (const width of [390, 768, 1440]) {
    await page.setViewportSize({ width, height: width === 390 ? 844 : 1100 });
    const overflow = await page.evaluate(() => ({ viewport: innerWidth, body: document.body.scrollWidth, document: document.documentElement.scrollWidth }));
    truth(overflow.body <= width + 1 && overflow.document <= width + 1, `no page overflow at ${width}px: ${JSON.stringify(overflow)}`);
    await page.screenshot({ path: path.join(OUTPUT, `viewport-${width}.png`), fullPage: true });
    truth(await page.locator('#source-label').isVisible(), `source remains visible at ${width}px`);
    truth(await page.locator('#results').isVisible(), `results remain visible at ${width}px`);
    if (width === 390) { await page.evaluate(() => window.scrollTo({ top: 0, left: 0, behavior: 'instant' })); await page.screenshot({ path: path.join(OUTPUT, 'mobile-top.png') }); }
  }
  await page.emulateMedia({ reducedMotion: 'reduce' });
  equal(await page.evaluate(() => getComputedStyle(document.documentElement).scrollBehavior), 'auto', 'reduced-motion preference disables smooth scrolling');
  await page.setViewportSize({ width: 1200, height: 630 });
  await page.evaluate(() => { document.documentElement.style.zoom = '0.8'; window.scrollTo({ top: 0, left: 0, behavior: 'instant' }); });
  await page.screenshot({ path: path.join(OUTPUT, 'og-candidate.png') });
  equal(errors.length, 0, `no uncaught browser exceptions: ${errors.join('; ')}`);
  truth(!requests.some(leak), 'privacy canaries remain absent from requests after all workflows');
  const qa = { passed, baseURL: base, output: OUTPUT, browser: browser.version(), timings, downloads, contrast,
    requestMethods: [...new Set(requests.map(r => r.method))], offOrigin: [...new Set(requests.filter(r => !r.url.startsWith(new URL(base).origin)).map(r => r.url))] };
  await writeFile(path.join(OUTPUT, 'qa-results.json'), JSON.stringify(qa, null, 2) + '\n');
  console.log(JSON.stringify(qa, null, 2));
} catch (error) {
  await writeFile(path.join(OUTPUT, 'qa-failure.json'), JSON.stringify({ passed, message: error.message, stack: error.stack, errors, output: OUTPUT }, null, 2) + '\n');
  throw error;
} finally {
  if (browser) await browser.close();
  if (server) await new Promise(resolve => server.close(resolve));
}
