import { readFile } from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { deflateRawSync } from 'node:zlib';
import { fileURLToPath } from 'node:url';
import {
  SIGNATURES, FIXED, LIMITS, crc32, rawHex, parseZip, inspect, makeFixture, mutateLocalName,
  mutateCentralCrc, compareRsids, signatureVector, inflateRawJs, makeZip, sameBytes,
  makeZip64, makeDuplicatePairing, makeHiddenEntry, makeMalformedOpc, scanXml, documentElement
} from '../../public/strata/the-archive-that-disagrees-with-itself/archive.mjs';

const root = fileURLToPath(new URL('../../', import.meta.url));
const pub = root + 'public/strata/the-archive-that-disagrees-with-itself/';
const contentPath = root + 'src/content/strata/the-archive-that-disagrees-with-itself.md';
const researchPath = root + 'research/the-archive-that-disagrees-with-itself/';
const [html, page, core, css, frontmatter, readme, harness] = await Promise.all([
  readFile(pub + 'index.html', 'utf8'), readFile(pub + 'page.mjs', 'utf8'), readFile(pub + 'archive.mjs', 'utf8'),
  readFile(pub + 'page.css', 'utf8'), readFile(contentPath, 'utf8'), readFile(researchPath + 'README.md', 'utf8'),
  readFile(researchPath + 'dom-harness.mjs', 'utf8')
]);

const checks = [];
function check(condition, label) {
  if (!condition) throw new Error('FAIL: ' + label);
  checks.push(label);
}
function must(text, fragment, label = fragment) { check(text.includes(fragment), label); }
function refusalCode(bytes, options) { try { parseZip(bytes, options); return 'NO_REFUSAL'; } catch (error) { return error.code || error.name; } }
function refusalDetail(bytes, options) { try { parseZip(bytes, options); return { code: 'NO_REFUSAL', message: '' }; } catch (error) { return { code: error.code || error.name, message: error.message || '' }; } }
/* Every refusal path is reached with real bytes and asserted by code and by the reason its
   message retains, including the reasons that arrive wrapped inside NO_VALID_EOCD. */
const exercised = new Set();
function expectRefusal(spec) {
  const got = refusalDetail(spec.bytes, spec.options);
  check(got.code === spec.code, spec.label + ' refuses as ' + spec.code + ', not ' + got.code);
  if (spec.fragment) check(got.message.includes(spec.fragment), spec.label + ' keeps its reason in the message: ' + spec.fragment);
  for (const code of spec.exercises || [spec.code]) exercised.add(code);
  return got;
}
function w32(bytes, at, value) { bytes[at] = value & 255; bytes[at + 1] = (value >>> 8) & 255; bytes[at + 2] = (value >>> 16) & 255; bytes[at + 3] = (value >>> 24) & 255; }
function w16(bytes, at, value) { bytes[at] = value & 255; bytes[at + 1] = (value >>> 8) & 255; }
function u16(bytes, at) { return bytes[at] | (bytes[at + 1] << 8); }
function u32(bytes, at) { return (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16) | (bytes[at + 3] << 24)) >>> 0; }
function occurrences(bytes, signature) { let n = 0; for (let i = 0; i + 4 <= bytes.length; i++) if (u32(bytes, i) === signature) n++; return n; }

function independentZip(bytes) {
  const eocd = bytes.length - FIXED.eocd;
  check(u32(bytes, eocd) === 0x06054b50, 'independent reader finds EOCD at file length minus 22');
  const disk = u16(bytes, eocd + 4), centralDisk = u16(bytes, eocd + 6), entriesDisk = u16(bytes, eocd + 8), entries = u16(bytes, eocd + 10), centralSize = u32(bytes, eocd + 12), centralOffset = u32(bytes, eocd + 16), commentLength = u16(bytes, eocd + 20);
  check(disk === 0 && centralDisk === 0 && entriesDisk === entries, 'independent EOCD disk and count fields describe one disk');
  check(commentLength === 0 && eocd + FIXED.eocd === bytes.length, 'independent EOCD comment boundary ends at EOF');
  check(centralOffset + centralSize === eocd, 'independent central byte range ends exactly at EOCD');
  const records = []; let p = centralOffset;
  for (let i = 0; i < entries; i++) {
    check(u32(bytes, p) === 0x02014b50, 'independent central signature for entry ' + i);
    const flags = u16(bytes, p + 8), method = u16(bytes, p + 10), crc = u32(bytes, p + 16), csize = u32(bytes, p + 20), usize = u32(bytes, p + 24), nameLength = u16(bytes, p + 28), extraLength = u16(bytes, p + 30), comment = u16(bytes, p + 32), localOffset = u32(bytes, p + 42);
    const name = new TextDecoder().decode(bytes.slice(p + 46, p + 46 + nameLength));
    const totalLength = 46 + nameLength + extraLength + comment;
    check(p + totalLength <= eocd, 'independent central variable boundary for ' + name);
    records.push({ centralOffset:p, totalLength, flags, method, crc, csize, usize, nameLength, name, localOffset });
    p += totalLength;
  }
  check(p === eocd, 'independent walk consumes the complete central directory');
  for (const r of records) {
    const l = r.localOffset;
    check(u32(bytes, l) === 0x04034b50, 'independent local signature for ' + r.name);
    const flags = u16(bytes, l + 6), method = u16(bytes, l + 8), localCrc = u32(bytes, l + 14), localCsize = u32(bytes, l + 18), localUsize = u32(bytes, l + 22), nameLength = u16(bytes, l + 26), extraLength = u16(bytes, l + 28), data = l + 30 + nameLength + extraLength;
    check(flags === r.flags && method === r.method, 'independent flags and method agree for ' + r.name);
    check(new TextDecoder().decode(bytes.slice(l + 30, l + 30 + nameLength)) === r.name, 'independent raw local name agrees for ' + r.name);
    const content = bytes.slice(data, data + r.csize);
    check(r.method === 0, 'fixture method is STORE for ' + r.name);
    check(content.length === r.usize, 'independent uncompressed size for ' + r.name);
    check(crc32Independent(content) === r.crc, 'independent CRC-32 for ' + r.name);
    if (r.flags & 8) {
      check(localCrc === 0 && localCsize === 0 && localUsize === 0, 'independent bit 3 local zeros for ' + r.name);
      const d = data + r.csize;
      check(u32(bytes, d) === 0x08074b50, 'independent signed descriptor for ' + r.name);
      check(u32(bytes, d + 4) === r.crc && u32(bytes, d + 8) === r.csize && u32(bytes, d + 12) === r.usize, 'independent descriptor values match central values for ' + r.name);
    } else check(localCrc === r.crc && localCsize === r.csize && localUsize === r.usize, 'independent ordinary copied fields for ' + r.name);
  }
  return { eocd, entries, centralSize, centralOffset, records };
}

function crc32Independent(bytes) {
  let register = 0xffffffff;
  for (const byte of bytes) {
    register ^= byte;
    for (let bit = 0; bit < 8; bit++) register = register & 1 ? (register >>> 1) ^ 0xedb88320 : register >>> 1;
  }
  return (register ^ 0xffffffff) >>> 0;
}

execFileSync(process.execPath, ['--check', pub + 'archive.mjs'], { stdio: 'pipe' });
execFileSync(process.execPath, ['--check', pub + 'page.mjs'], { stdio: 'pipe' });
checks.push('both external JavaScript modules pass node --check');

const scripts = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];
// The site-wide chrome generators (site-bar, way-out, plain-cards, check-placard) inject
  // their own script and style blocks into every shipped page, so an assertion that pins the
  // exact script inventory or the exact bytes before </body> fails on a page that is
  // perfectly correct. Assert the property being claimed instead of an incidental order.
  const ownScripts = scripts.filter((s) => !/\/media\/home-banner\.js|aw-(sitebar|wayout|plain|placard)/.test(s));
  check(ownScripts.length === 2, "the page's own scripts: one JSON-LD and one external module");
const jsonScript = scripts.find(m => /application\/ld\+json/.test(m[1]));
const moduleScript = scripts.find(m => /type="module"/.test(m[1]));
check(jsonScript && moduleScript && /src="\.\/page\.mjs"/.test(moduleScript[1]) && !moduleScript[2].trim(), 'page code is external and the module tag has no inline body');
const jsonLd = JSON.parse(jsonScript[2]);
check(jsonLd['@type'] === 'Article' && jsonLd.name && jsonLd.headline && jsonLd.description && jsonLd.url && jsonLd.image && jsonLd.datePublished && jsonLd.dateModified && jsonLd.author && jsonLd.publisher, 'JSON-LD parses and contains required Article fields');
// The site-wide chrome generators inject an inline <style> into every shipped page, so a
// blanket 'this page has no inline style' assertion fails on a page that is perfectly
// correct. What matters is COHERENCE: if inline style is present, the policy must permit
// it, or the chrome silently renders unstyled. Checked in both directions.
{
  const hasInlineStyle = /<style\b/i.test(html) || /\sstyle=/.test(html);
  const allowsInlineStyle = /style-src[^;"]*'unsafe-inline'/.test(html);
  check(hasInlineStyle === allowsInlineStyle,
    'the style policy and the page agree about inline style',
    `inline style present ${hasInlineStyle}, policy allows ${allowsInlineStyle}`);
}
must(html, "connect-src 'none'", 'deployed CSP contains connect-src none');
for (const directive of ["default-src 'self'", "script-src 'self'", "style-src 'self' 'unsafe-inline'", "object-src 'none'", "frame-src 'none'", "form-action 'none'", "base-uri 'none'"]) must(html, directive, 'CSP contains ' + directive);
const remoteResourceTags = [...html.matchAll(/<(?:script|link|a)\b[^>]*(?:src|href)="(https?:\/\/[^\"]+)"/gi)].map(m => m[1]);
check(remoteResourceTags.every(url => new URL(url).hostname === 'artwaste.land'), 'no third-party URL appears in a script, stylesheet, or anchor request position');

const files = [html,page,core,css,frontmatter,readme,harness];
check(files.every(text => !text.includes('\u2014')), 'all written text contains no em dash');
check(html.trimEnd().endsWith('</html>') && /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'load-bearing script, body, and html closing tags are present');
check(css.includes('overflow-x:hidden') && css.includes('@media (max-width:760px)') && css.includes('@media (max-width:420px)'), 'responsive CSS contains the horizontal overflow guard and narrow breakpoints');
check(css.includes('@media (prefers-reduced-motion:reduce)') && css.includes(':focus-visible'), 'reduced motion and visible keyboard focus are implemented');
check(html.includes('role="status"') && html.includes('aria-live="polite"'), 'live status output is labelled for assistive technology');

const aBytes = makeFixture('A'), bBytes = makeFixture('B');
check(aBytes.length === bBytes.length, 'both deterministic fixtures have the same byte length');
const independentA = independentZip(aBytes), independentB = independentZip(bBytes);
check(independentA.entries === 5 && independentB.entries === 5, 'both fixtures contain exactly five entries');
check(occurrences(aBytes,SIGNATURES.LOCAL) === 5, 'fixture A contains five local signatures');
check(occurrences(aBytes,SIGNATURES.CENTRAL) === 5, 'fixture A contains five central signatures');
check(occurrences(aBytes,SIGNATURES.DESCRIPTOR) === 1, 'fixture A contains one signed descriptor signature');
check(occurrences(aBytes,SIGNATURES.EOCD) === 1, 'fixture A contains one EOCD signature');

const signatureExpect = new Map([
  [SIGNATURES.LOCAL,'50 4b 03 04'],[SIGNATURES.CENTRAL,'50 4b 01 02'],[SIGNATURES.DESCRIPTOR,'50 4b 07 08'],
  [SIGNATURES.ZIP64_EOCD,'50 4b 06 06'],[SIGNATURES.ZIP64_LOCATOR,'50 4b 06 07'],[SIGNATURES.EOCD,'50 4b 05 06']
]);
for (const [signature, expected] of signatureExpect) check(rawHex(signatureVector(signature)) === expected, 'signature vector ' + expected + ' matches ' + signature.toString(16));
check(FIXED.local === 30 && FIXED.central === 46 && FIXED.eocd === 22 && FIXED.zip64Eocd === 56 && FIXED.zip64Locator === 20, 'fixed record lengths recompute to 30, 46, 22, 56, and 20');
const z64 = new Uint8Array(FIXED.zip64Eocd), z64v = new DataView(z64.buffer); z64v.setUint32(0,SIGNATURES.ZIP64_EOCD,true); z64v.setBigUint64(4,44n,true); z64v.setBigUint64(24,5n,true); z64v.setBigUint64(32,5n,true); z64v.setBigUint64(40,321n,true); z64v.setBigUint64(48,654n,true);
check(z64.byteLength === 56 && z64v.getUint32(0,true) === SIGNATURES.ZIP64_EOCD && z64v.getBigUint64(4,true) === 44n && z64v.getBigUint64(24,true) === 5n && z64v.getBigUint64(32,true) === 5n && z64v.getBigUint64(40,true) === 321n && z64v.getBigUint64(48,true) === 654n, 'synthetic ZIP64 EOCD field offsets round-trip independently');
const locator = new Uint8Array(FIXED.zip64Locator), locatorView = new DataView(locator.buffer); locatorView.setUint32(0,SIGNATURES.ZIP64_LOCATOR,true); locatorView.setUint32(4,0,true); locatorView.setBigUint64(8,654n,true); locatorView.setUint32(16,1,true);
check(locator.byteLength === 20 && locatorView.getUint32(0,true) === SIGNATURES.ZIP64_LOCATOR && locatorView.getUint32(4,true) === 0 && locatorView.getBigUint64(8,true) === 654n && locatorView.getUint32(16,true) === 1, 'synthetic ZIP64 locator field offsets round-trip independently');
const descriptorLengths = [new Uint8Array(12),new Uint8Array(16),new Uint8Array(20),new Uint8Array(24)];
new DataView(descriptorLengths[0].buffer).setUint32(0,0x12345678,true); new DataView(descriptorLengths[1].buffer).setUint32(0,SIGNATURES.DESCRIPTOR,true); new DataView(descriptorLengths[2].buffer).setBigUint64(4,7n,true); new DataView(descriptorLengths[3].buffer).setBigUint64(8,7n,true);
check(descriptorLengths.map(x=>x.length).join(',') === '12,16,20,24' && new DataView(descriptorLengths[0].buffer).getUint32(0,true) === 0x12345678 && new DataView(descriptorLengths[1].buffer).getUint32(0,true) === SIGNATURES.DESCRIPTOR && new DataView(descriptorLengths[2].buffer).getBigUint64(4,true) === 7n && new DataView(descriptorLengths[3].buffer).getBigUint64(8,true) === 7n, 'ordinary and ZIP64 descriptor layout vectors cover unsigned and signed forms');

const a = await inspect(aBytes), b = await inspect(bBytes);
check(a.entries.length === 5 && a.entries.every(e => e.local && e.central), 'production parser pairs all five fixture A records');
check(a.entries.every(e => e.local.offset === e.central.localOffset), 'production parser resolves every fixture central-to-local offset');
check(a.entries.filter(e => e.descriptor).length === 1 && a.entries.find(e => e.descriptor).descriptor.state === 'signed', 'production parser uniquely chooses the signed descriptor form');
check(a.expectedBit3 === 3 && a.unexplained === 0, 'fixture A has three expected bit 3 fields and zero unexplained fields');
check(a.crcPass === 5 && a.crcFail === 0, 'production parser recomputes five passing CRCs and zero failures');
check(a.opcVerdict === 'PASS' && b.opcVerdict === 'PASS', 'both generated fixtures pass implemented OPC and Annex B.2 checks');
check(a.opc.contentTypes.size === 5 && a.opc.relationships.length === 2 && a.opc.relationships.every(r => r.exists), 'fixture A has five typed parts and two resolved internal relationships');
check(a.opc.mainPart === 'word/document.xml' && a.opc.settingsPart === 'word/settings.xml' && a.opc.namespace === 'transitional', 'relationships select the main and settings parts in the transitional namespace');
const pair = compareRsids(a.opc,b.opc);
check(pair.defined && pair.root === '10000001', 'RSID comparison is defined under synthetic root 10000001');
check(pair.shared.join(',') === '10000001,10000002', 'shared unordered RSID set has 10000001 and 10000002');
check(pair.onlyA.join(',') === '10000003' && pair.onlyB.join(',') === '10000004', 'branch-only RSID sets have 10000003 and 10000004');
check(pair.bodyHitsA === 3 && pair.bodyHitsB === 3, 'each fixture body contains three RSID attribute hits');

const nameBroken = await inspect(mutateLocalName(aBytes));
check(nameBroken.unexplained === 1 && nameBroken.opcVerdict === 'FAIL', 'changed local filename byte creates exactly one unexplained field and OPC FAIL');
const crcBroken = await inspect(mutateCentralCrc(aBytes));
check(crcBroken.unexplained === 3 && crcBroken.crcFail === 1 && crcBroken.opcVerdict === 'FAIL', 'changed central CRC creates three copied-field differences, one CRC failure, and OPC FAIL');

expectRefusal({ label:'a 10-byte truncation', bytes:aBytes.slice(0,10), code:'TRUNCATED_FILE', fragment:'fewer than the 22-byte fixed EOCD record' });
expectRefusal({ label:'22 wrong-magic bytes', bytes:new Uint8Array(22), code:'EOCD_NOT_FOUND', fragment:'no 0x06054b50 EOCD signature' });
expectRefusal({ label:'valid local and central records with the EOCD removed', bytes:aBytes.slice(0,aBytes.length-22), code:'EOCD_NOT_FOUND', fragment:'a local header begins at byte 0' });
const lyingComment = aBytes.slice(); lyingComment[lyingComment.length-2] = 1;
expectRefusal({ label:'a lying EOCD comment length', bytes:lyingComment, code:'NO_VALID_EOCD', fragment:'declares 1 comment bytes', exercises:['NO_VALID_EOCD','EOCD_COMMENT_LENGTH'] });
const bigComment = aBytes.slice(); w16(bigComment, independentA.eocd+20, 0xffff);
expectRefusal({ label:'a comment running past EOF under trailing-data recovery', bytes:bigComment, options:{allowTrailing:true}, code:'NO_VALID_EOCD', fragment:'comment ending beyond the file', exercises:['EOCD_COMMENT_OUT_OF_RANGE'] });
const lyingCentralName = aBytes.slice(); w16(lyingCentralName, independentA.centralOffset+28, 0xffff);
expectRefusal({ label:'a lying central filename length', bytes:lyingCentralName, code:'NO_VALID_EOCD', fragment:'declares filename length 65535', exercises:['CENTRAL_VALIDATION','OUT_OF_RANGE'] });
const lyingLocalName = aBytes.slice(); w16(lyingLocalName, 26, 0xffff);
const rangeRefusal = expectRefusal({ label:'a local filename length of 65535', bytes:lyingLocalName, code:'OUT_OF_RANGE', fragment:'declares filename length 65535' });
check(/local file header at byte 0 declares filename length 65535 \(field at byte 26\) and extra length \d+ \(field at byte 28\), so the record needs \d+ bytes, but only \d+ remain/.test(rangeRefusal.message), 'the range refusal names the offending length field, its byte offset, the value it claimed, and how many bytes actually remain');
const lyingCentralComment = aBytes.slice(); w16(lyingCentralComment, independentA.records[4].centralOffset+32, 0xffff);
const centralRange = refusalDetail(lyingCentralComment);
check(centralRange.code === 'NO_VALID_EOCD' && /central file header at byte \d+ declares filename length \d+ \(field at byte \d+\), extra length \d+ \(field at byte \d+\), and comment length 65535 \(field at byte \d+\)/.test(centralRange.message), 'the central range refusal names all three declared lengths and their byte offsets');
const badCentralSignature = aBytes.slice(); badCentralSignature[independentA.records[1].centralOffset] ^= 0xff;
expectRefusal({ label:'a corrupted second central signature', bytes:badCentralSignature, code:'NO_VALID_EOCD', fragment:'expected central file header signature 0x02014b50', exercises:['BAD_CENTRAL_SIGNATURE'] });
const fewerEntries = aBytes.slice(); w16(fewerEntries, independentA.eocd+8, 4); w16(fewerEntries, independentA.eocd+10, 4);
expectRefusal({ label:'an EOCD claiming four of the five records', bytes:fewerEntries, code:'NO_VALID_EOCD', fragment:'central records end at byte', exercises:['CENTRAL_SIZE_MISMATCH'] });
const hugeCentral = aBytes.slice(); w32(hugeCentral, independentA.eocd+12, 0xfffffffe);
expectRefusal({ label:'a central directory size that reaches before byte 0', bytes:hugeCentral, code:'NO_VALID_EOCD', fragment:'reaches before byte 0', exercises:['CENTRAL_RANGE'] });
const split = aBytes.slice(); split[independentA.eocd+4] = 1;
expectRefusal({ label:'a split-archive disk marker', bytes:split, code:'NO_VALID_EOCD', fragment:'split archives are not opened', exercises:['MULTI_DISK'] });
expectRefusal({ label:'a selected input cap below the file length', bytes:aBytes, options:{inputCap:10}, code:'INPUT_CAP', fragment:'exceeds the selected input cap' });
const badLocal = aBytes.slice(); badLocal[0] = 0;
expectRefusal({ label:'a central pointer to bytes that are not a local header', bytes:badLocal, code:'BAD_LOCAL_SIGNATURE', fragment:'where 0x04034b50 was required' });
const shortExtra = aBytes.slice(); shortExtra[28] = 1;
expectRefusal({ label:'a local extra field shorter than one tag header', bytes:shortExtra, code:'TRUNCATED_EXTRA_HEADER', fragment:'fewer than the 4-byte tag header' });
const lyingExtra = aBytes.slice(); lyingExtra[28] = 4;
expectRefusal({ label:'a local extra tag whose data length exceeds its container', bytes:lyingExtra, code:'LYING_EXTRA_LENGTH', fragment:'data bytes, but only' });
const zip64WithoutLocator = aBytes.slice(); w16(zip64WithoutLocator, independentA.eocd+10, 0xffff);
expectRefusal({ label:'a ZIP64 sentinel with no locator before the EOCD', bytes:zip64WithoutLocator, code:'NO_VALID_EOCD', fragment:'no 0x07064b50 locator begins 20 bytes before it', exercises:['MISSING_ZIP64_LOCATOR'] });
const sentinelSize = aBytes.slice(); w32(sentinelSize, independentA.records[0].centralOffset+24, 0xffffffff);
expectRefusal({ label:'a ZIP64 size sentinel with no 0x0001 extra field', bytes:sentinelSize, code:'NO_VALID_EOCD', fragment:'does not contain the required 8 bytes', exercises:['MISSING_ZIP64_VALUE'] });
const sentinelDisk = aBytes.slice(); w16(sentinelDisk, independentA.records[0].centralOffset+34, 0xffff);
expectRefusal({ label:'a ZIP64 disk sentinel with no 4-byte replacement', bytes:sentinelDisk, code:'NO_VALID_EOCD', fragment:'without a 4-byte replacement', exercises:['MISSING_ZIP64_DISK'] });
const emptyZip = makeZip([]);
let emptyNameCode='NO_REFUSAL'; try{mutateLocalName(emptyZip);}catch(error){emptyNameCode=error.code;}
let emptyCrcCode='NO_REFUSAL'; try{mutateCentralCrc(emptyZip);}catch(error){emptyCrcCode=error.code;}
check(emptyNameCode === 'NO_NAME_TO_MUTATE' && emptyCrcCode === 'NO_ENTRY_TO_MUTATE', 'mutation demonstrations refuse an empty archive with explicit reasons');
exercised.add('NO_NAME_TO_MUTATE'); exercised.add('NO_ENTRY_TO_MUTATE');

const encrypted = aBytes.slice(); encrypted[independentA.records[2].localOffset+6] |= 1; encrypted[independentA.records[2].centralOffset+8] |= 1;
const encryptedParsed = await inspect(encrypted);
check(encryptedParsed.entries[2].contentState === 'NOT CHECKED: encrypted' && encryptedParsed.opcVerdict === 'FAIL', 'encrypted OPC item retains metadata, skips content, and fails implemented OPC rules');
const unsupported = aBytes.slice(); unsupported[independentA.records[2].localOffset+8] = 99; unsupported[independentA.records[2].localOffset+9] = 0; unsupported[independentA.records[2].centralOffset+10] = 99; unsupported[independentA.records[2].centralOffset+11] = 0;
const unsupportedParsed = await inspect(unsupported);
check(unsupportedParsed.entries[2].contentState === 'NOT CHECKED: compression method 99' && unsupportedParsed.opcVerdict === 'FAIL', 'unsupported method 99 retains metadata, skips content, and fails implemented OPC rules');

const samples = [new Uint8Array(0), new TextEncoder().encode('raw deflate fallback check '.repeat(300)), Uint8Array.from({length:4096},(_,i)=>(i*i+17*i)&255)];
for (const [i,sample] of samples.entries()) {
  const packed = new Uint8Array(deflateRawSync(sample));
  const unpacked = inflateRawJs(packed,Math.max(1,sample.length+8));
  check(unpacked.length === sample.length && unpacked.every((v,j)=>v===sample[j]), 'pure JavaScript raw DEFLATE fallback round-trips sample ' + i);
}
const capPacked = new Uint8Array(deflateRawSync(new Uint8Array(1000)));
let capCode = 'NO_REFUSAL'; try { inflateRawJs(capPacked,100); } catch (error) { capCode=error.code; }
check(capCode === 'ENTRY_INFLATE_CAP', 'pure JavaScript inflater stops during output at its cap');
exercised.add('ENTRY_INFLATE_CAP');
let truncatedDeflate='NO_REFUSAL';try{inflateRawJs(Uint8Array.of(1),100);}catch(error){truncatedDeflate=error.code;}
let reservedDeflate='NO_REFUSAL';try{inflateRawJs(Uint8Array.of(7),100);}catch(error){reservedDeflate=error.code;}
let storedLength='NO_REFUSAL';try{inflateRawJs(Uint8Array.of(1,1,0,1,0),100);}catch(error){storedLength=error.code;}
check(truncatedDeflate === 'DEFLATE_TRUNCATED' && reservedDeflate === 'DEFLATE_RESERVED_BLOCK' && storedLength === 'DEFLATE_STORED_LENGTH', 'raw DEFLATE refusal vectors cover truncation, reserved type, and lying stored length');

/* A genuine ZIP64 archive, built from the fixture, through the production parser. The
   record layout was previously exercised only by writing values with a DataView and reading
   them back, which is why an offset basis that refused every real ZIP64 archive passed. */
const zip64Bytes = makeZip64(aBytes);
const zip64Parsed = await inspect(zip64Bytes);
check(zip64Bytes.length === aBytes.length + 76, 'the ZIP64 rewrite adds exactly the 56-byte ZIP64 EOCD and the 20-byte locator');
check(occurrences(zip64Bytes,SIGNATURES.ZIP64_EOCD) === 1 && occurrences(zip64Bytes,SIGNATURES.ZIP64_LOCATOR) === 1, 'the ZIP64 specimen carries exactly one ZIP64 EOCD record and one locator');
check(zip64Parsed.entries.length === 5 && zip64Parsed.eocd.zip64 && zip64Parsed.eocd.zip64.entries === 5, 'a genuine ZIP64 archive parses through its ZIP64 EOCD and locator to five entries');
check(zip64Parsed.eocd.directoryEndAnchor === 'ZIP64 EOCD record' && zip64Parsed.eocd.centralStart === independentA.centralOffset, 'the ZIP64 central directory is measured back from the ZIP64 EOCD record and starts at the same byte as the ordinary fixture');
check(zip64Parsed.opcVerdict === 'PASS' && zip64Parsed.crcPass === 5 && zip64Parsed.unexplained === 0 && zip64Parsed.expectedBit3 === 3, 'the ZIP64 rewrite reproduces every result of the ordinary fixture');
check(refusalCode(makeZip64(aBytes).slice(0,-1)) !== 'NO_REFUSAL', 'truncating the ZIP64 specimen by one byte is refused rather than parsed');
const zip64At = zip64Bytes.length - 22 - FIXED.zip64Locator - FIXED.zip64Eocd, locatorAt = zip64Bytes.length - 22 - FIXED.zip64Locator;
const brokenLocator = zip64Bytes.slice(); brokenLocator[locatorAt] ^= 0xff;
expectRefusal({ label:'a ZIP64 locator with a corrupted signature', bytes:brokenLocator, code:'NO_VALID_EOCD', fragment:'no 0x07064b50 locator begins 20 bytes before it', exercises:['MISSING_ZIP64_LOCATOR'] });
const brokenZip64Eocd = zip64Bytes.slice(); brokenZip64Eocd[zip64At] ^= 0xff;
expectRefusal({ label:'a locator pointing at bytes that are not a ZIP64 EOCD', bytes:brokenZip64Eocd, code:'NO_VALID_EOCD', fragment:'which does not contain 0x06064b50', exercises:['BAD_ZIP64_EOCD_SIGNATURE'] });
const hugeZip64Offset = zip64Bytes.slice(); w32(hugeZip64Offset, locatorAt+12, 0xffffffff);
expectRefusal({ label:'a ZIP64 EOCD offset above the safe integer range', bytes:hugeZip64Offset, code:'NO_VALID_EOCD', fragment:'above Number.MAX_SAFE_INTEGER', exercises:['ZIP64_TOO_LARGE'] });
const tooManyEntries = zip64Bytes.slice(); w32(tooManyEntries, zip64At+24, 200000); w32(tooManyEntries, zip64At+32, 200000);
expectRefusal({ label:'a ZIP64 EOCD declaring 200000 entries', bytes:tooManyEntries, code:'NO_VALID_EOCD', fragment:'above the hard cap of 100000', exercises:['TOO_MANY_ENTRIES'] });
const zip64MultiDisk = zip64Bytes.slice(); zip64MultiDisk[zip64At+16] = 1;
expectRefusal({ label:'a ZIP64 EOCD describing more than one disk', bytes:zip64MultiDisk, code:'NO_VALID_EOCD', fragment:'describes more than one disk', exercises:['MULTI_DISK'] });
let notTrailingCode = 'NO_REFUSAL';
try { makeZip64(new Uint8Array(40)); } catch (error) { notTrailingCode = error.code; }
check(notTrailingCode === 'NOT_A_TRAILING_EOCD', 'the ZIP64 rewrite refuses input whose last 22 bytes are not an EOCD record');
exercised.add('NOT_A_TRAILING_EOCD');

/* Pairing specimens the fixture generator cannot produce. */
const duplicateBytes = makeDuplicatePairing(), duplicateParsed = await inspect(duplicateBytes);
check(duplicateParsed.entries.length === 2 && duplicateParsed.distinctLocals === 1 && duplicateParsed.duplicatePairings === 1, 'two central records aimed at one local header count as one distinct pairing and one duplicate');
check(duplicateParsed.entries[1].duplicateOf === 0 && duplicateParsed.entries[0].duplicateOf === null, 'the second central record is the one named as the duplicate, and the first is not');
check(duplicateParsed.unreferenced.length === 1, 'the genuine second local record, which nothing now points at, is reported as unreferenced');
const hiddenParsed = await inspect(makeHiddenEntry());
check(hiddenParsed.entries.length === 1 && hiddenParsed.entries[0].central.name === 'listed.txt', 'an index that omits a real entry still walks cleanly and lists one record');
check(hiddenParsed.unreferenced.length === 1 && hiddenParsed.unreferenced[0].name === 'front-only.txt' && hiddenParsed.unreferenced[0].offset === 0, 'the omitted local record is found at byte 0 and named rather than left as unclassified bytes');
check(a.unreferenced.length === 0 && a.duplicatePairings === 0 && a.distinctLocals === 5, 'the cooperative fixture reports no duplicate pairing and no unreferenced local header, so neither counter is always positive');
const prepended = new Uint8Array(4 + aBytes.length); prepended.set([0x4d,0x5a,0x00,0xff],0); prepended.set(aBytes,4);
const prependedParsed = await inspect(prepended);
check(prependedParsed.eocd.basis === 'prepended archive base' && prependedParsed.eocd.archiveBase === 4 && prependedParsed.entries.length === 5, 'a four-byte stub before the archive selects the prepended basis and still pairs five records');
check(prependedParsed.unreferenced.length === 0, 'the unreferenced scan starts at the archive base and does not report the stub bytes as an entry');

/* XML well-formedness: recognition must not be reachable through malformed parts, and it
   must still be reachable through well-formed ones. */
for (const kind of ['two-roots','trailing-root','stray-text','buried-root','unclosed','bad-utf8']) {
  const parsed = await inspect(makeMalformedOpc(kind));
  check(!parsed.opc.recognized && parsed.opcVerdict === 'NOT AN OPC VERDICT', 'malformed OPC XML (' + kind + ') is refused recognition and receives no ECMA-376 verdict');
  check(parsed.opc.errors.length > 0, 'malformed OPC XML (' + kind + ') states a reason rather than failing silently');
}
check(a.opc.recognized && a.opc.word, 'the well-formed fixture is still recognized as WordprocessingML, so those refusals are not refusing everything');
let strayCode = ''; try { scanXml('<a/><b/>'); } catch (error) { strayCode = error.message; }
check(/more than one document element/.test(strayCode), 'the XML scanner names a second document element as the reason');
check(documentElement(scanXml('<?xml version="1.0"?><root><child/></root>')).localName === 'root', 'the document element of a well-formed part is its root, not any matching descendant');

/* The assay found that the prose described a wider XML audit than this parser performs. */
const assayParts = () => a.entries.map(e => ({ name:e.central.name, data:e.content, descriptor:!!e.descriptor }));
const assayUtf16 = text => Buffer.concat([Buffer.from([0xff,0xfe]), Buffer.from(text.replace('UTF-8','UTF-16'),'utf16le')]);
const extraRoots = await inspect(makeZip([...assayParts(), { name:'extra.xml', text:'<one/><two/>' }]));
check(extraRoots.opc.recognized && extraRoots.opcVerdict === 'PASS', 'unrelated XML is outside the XML scan, even when it has two roots');
const extraUtf16 = await inspect(makeZip([...assayParts(), { name:'extra.xml', data:assayUtf16('<one/>') }]));
check(extraUtf16.opc.recognized && extraUtf16.opcVerdict === 'PASS', 'UTF-16 in an unscanned XML part does not prevent this audit from passing');
for (const name of ['[Content_Types].xml','_rels/.rels','word/_rels/document.xml.rels','word/document.xml','word/settings.xml']) {
  const parts = assayParts().map(f => f.name === name ? { ...f, data:assayUtf16(new TextDecoder().decode(f.data)) } : f);
  const parsed = await inspect(makeZip(parts));
  const recognitionPart = name === '[Content_Types].xml' || name === '_rels/.rels';
  check(parsed.opc.recognized === !recognitionPart && parsed.opcVerdict === (recognitionPart ? 'NOT AN OPC VERDICT' : 'FAIL'), 'UTF-16 outcome follows the scan stage for ' + name);
}
const manyXml = await inspect(makeZip([...assayParts(), ...Array.from({length:1001}, (_,i) => ({name:'extra'+i+'.xml',text:'<one/>'}))]));
check(manyXml.entries.length === 1006 && manyXml.opcVerdict === 'PASS', 'the 1000-part cap does not count unrelated XML parts');
const emptyRels = '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"/>';
const relParts = Array.from({length:998}, (_,i) => ({name:'_rels/extra'+i+'.xml.rels',text:emptyRels}));
const atRelCap = await inspect(makeZip([...assayParts(), ...relParts]));
const overRelCap = await inspect(makeZip([...assayParts(), ...relParts, {name:'_rels/last.xml.rels',text:emptyRels}]));
check(atRelCap.opcVerdict === 'PASS' && overRelCap.opc.errors.includes('relationship XML part count exceeds the 1000-part cap'), '1000 relationship parts pass and 1001 reaches the relationship cap');
for (const flags of [0,0x0800]) {
  const bytes = makeZip([...assayParts(), {name:'x.xml',text:'<one/>'}]);
  const entry = parseZip(bytes).entries.at(-1);
  bytes[entry.central.offset + 46] = 0xe9; bytes[entry.local.offset + 30] = 0xe9;
  w16(bytes, entry.central.offset + 8, flags); w16(bytes, entry.local.offset + 6, flags);
  const parsed = await inspect(bytes, {nameMode:'utf8'});
  check(parsed.entries.at(-1).central.flags === flags && parsed.opc.errors.includes('item name bytes are not valid UTF-8 under the selected decoding: e9 2e 78 6d 6c') && !parsed.opc.errors.some(e => e.includes('flag is set')), 'invalid UTF-8 reports the decoding failure without inventing a flag, stored flags ' + flags);
  if (flags === 0) {
    const legacy = await inspect(bytes, {nameMode:'cp437'});
    check(!legacy.opc.errors.some(e => e.includes('not valid UTF-8')), 'the same unflagged bytes decode under CP437 without an invalid-UTF-8 diagnostic');
  }
}

/* The shipped fixture stores every part, so method 8 never reached checkContents through
   inspect(). This builds a DEFLATE-compressed package and runs it through the same path. */
function makeDeflatedZip(files) {
  const encoder = new TextEncoder(), local = [], central = [], records = [];
  const put16 = (out, n) => out.push(n & 255, (n >>> 8) & 255);
  const put32 = (out, n) => out.push(n & 255, (n >>> 8) & 255, (n >>> 16) & 255, (n >>> 24) & 255);
  for (const file of files) {
    const name = encoder.encode(file.name), data = encoder.encode(file.text);
    const packed = new Uint8Array(deflateRawSync(data)), crc = crc32(data), offset = local.length;
    put32(local, SIGNATURES.LOCAL); put16(local, 20); put16(local, 0x0800); put16(local, 8); put16(local, 0); put16(local, 0);
    put32(local, crc); put32(local, packed.length); put32(local, data.length); put16(local, name.length); put16(local, 0);
    local.push(...name, ...packed);
    records.push({ name, crc, csize: packed.length, usize: data.length, offset });
  }
  const centralOffset = local.length;
  for (const r of records) {
    put32(central, SIGNATURES.CENTRAL); put16(central, 20); put16(central, 20); put16(central, 0x0800); put16(central, 8); put16(central, 0); put16(central, 0);
    put32(central, r.crc); put32(central, r.csize); put32(central, r.usize); put16(central, r.name.length); put16(central, 0); put16(central, 0); put16(central, 0); put16(central, 0);
    put32(central, 0); put32(central, r.offset); central.push(...r.name);
  }
  const out = [...local, ...central];
  put32(out, SIGNATURES.EOCD); put16(out, 0); put16(out, 0); put16(out, records.length); put16(out, records.length); put32(out, central.length); put32(out, centralOffset); put16(out, 0);
  return Uint8Array.from(out);
}
const deflatedParts = [
  { name:'[Content_Types].xml', text:'<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/></Types>' },
  { name:'_rels/.rels', text:'<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"/>' },
  { name:'payload.xml', text:'<?xml version="1.0" encoding="UTF-8"?><payload>'+'compressible text. '.repeat(200)+'</payload>' }
];
const deflated = makeDeflatedZip(deflatedParts);
const deflatedParsed = await inspect(deflated);
check(deflatedParsed.entries.every(e => e.central.method === 8), 'the DEFLATE specimen stores every part with method 8');
check(deflatedParsed.entries.length === 3 && deflatedParsed.crcPass === 3 && deflatedParsed.crcFail === 0 && deflatedParsed.crcNotChecked === 0, 'method 8 parts decompress and match their stored CRC-32 through the production content check');
check(deflatedParsed.opc.recognized && deflatedParsed.opcVerdict === 'PASS', 'the DEFLATE package is recognized as OPC and passes the implemented checks');
const guttedDeflate = deflated.slice(); guttedDeflate[deflatedParsed.entries[2].dataOffset + 5] ^= 0xff;
const guttedParsed = await inspect(guttedDeflate);
check(guttedParsed.crcPass + guttedParsed.crcFail + guttedParsed.crcNotChecked === guttedParsed.entries.length, 'the three content counters always add up to the record count');
check(guttedParsed.crcFail + guttedParsed.crcNotChecked === 1 && guttedParsed.opcVerdict === 'FAIL', 'one flipped compressed byte is reported and turns the OPC verdict to FAIL rather than passing an unreadable part');
const guttedStore = aBytes.slice(); guttedStore[independentA.records[2].localOffset + 200] ^= 0xff;
const guttedStoreParsed = await inspect(guttedStore);
check(guttedStoreParsed.crcFail === 1 && guttedStoreParsed.crcNotChecked === 0 && guttedStoreParsed.opcVerdict === 'FAIL', 'one flipped stored byte fails its CRC-32 and turns the OPC verdict to FAIL');
check(a.crcNotChecked === 0 && b.crcNotChecked === 0, 'neither shipped fixture leaves any entry unchecked, so that counter is not always positive');

/* CRC anchors, reproduced from the printed constants. */
check(crc32(new TextEncoder().encode('123456789')) === 0xcbf43926, 'the printed catalogue check value CRC-32("123456789") recomputes to 0xcbf43926');
function residualOf(message) {
  const stored = crc32(message), withCrc = new Uint8Array(message.length + 4);
  withCrc.set(message, 0);
  for (let i = 0; i < 4; i++) withCrc[message.length + i] = (stored >>> (8 * i)) & 255;
  return (~crc32(withCrc)) >>> 0;
}
const crcMessages = [];
for (let n = 0; n <= 512; n++) crcMessages.push(Uint8Array.from({length:n},(_,i)=>(i*31+n*17)&255));
crcMessages.push(Uint8Array.from({length:4095},(_,i)=>(i*i+17*i)&255));
check(crcMessages.every(m => residualOf(m) === 0xdebb20e3), 'the APPNOTE 4.4.7 residual 0xdebb20e3 is single-valued over ' + crcMessages.length + ' messages of length 0 to 4095');
check(crcMessages.every(m => crc32Independent(m) === crc32(m)), 'the table-driven CRC-32 agrees with a from-scratch bitwise CRC-32 on every one of those messages');

/* Every DEFLATE refusal path, reached by a deterministic seeded sweep of corrupted streams. */
let deflateSeed = 20260809 >>> 0;
const nextByte = () => ((deflateSeed = (deflateSeed * 1103515245 + 12345) >>> 0) >>> 16) & 255;
const deflateSeen = new Set();
for (let trial = 0; trial < 40000; trial++) {
  const length = 1 + (nextByte() % 24), stream = new Uint8Array(length);
  for (let i = 0; i < length; i++) stream[i] = nextByte();
  try { inflateRawJs(stream, 4096); } catch (error) { if (error.code) deflateSeen.add(error.code); }
}
const deflateCodes = ['DEFLATE_CODE_LENGTHS','DEFLATE_DISTANCE','DEFLATE_DISTANCE_CODE','DEFLATE_HUFFMAN','DEFLATE_LENGTH_CODE','DEFLATE_REPEAT','DEFLATE_RESERVED_BLOCK','DEFLATE_STORED_LENGTH','DEFLATE_TRUNCATED'];
check(deflateCodes.every(code => deflateSeen.has(code)), 'a deterministic sweep of 40000 corrupted DEFLATE streams reaches all nine DEFLATE refusal codes');
for (const code of deflateSeen) exercised.add(code);

/* The inventory check now measures behavioural coverage, not vocabulary. It fails both when
   a new refusal code appears and when a code stops being reached by a real specimen. */
const refusalInventory = new Set([...core.matchAll(/ZipRefusal\('([A-Z0-9_]+)'/g)].map(m=>m[1]));
const notExercised = [...refusalInventory].filter(code => !exercised.has(code)).sort();
check(notExercised.length === 0, 'every one of the ' + refusalInventory.size + ' explicit ZipRefusal codes is reached by a specimen in this file, leaving none inventory-only (' + (notExercised.join(', ') || 'none') + ')');
check([...exercised].every(code => refusalInventory.has(code)), 'no assertion claims to exercise a refusal code that the source does not define');

/* RSID vacuity: the two settings this instrument must refuse to call a linkage signal. */
const selfPair = compareRsids(a.opc, a.opc);
check(selfPair.defined && selfPair.linkage && selfPair.shared.length === a.opc.rsids.settings.size && selfPair.onlyA.length === 0, 'comparing the fixture with itself shares every identifier, which is exactly why the page tests byte identity rather than trusting the shared count');
check(sameBytes(aBytes, aBytes.slice()) && !sameBytes(aBytes, bBytes), 'the byte-identity test used for that refusal separates equal bytes from the two different fixtures');
const emptyRoot = makeZip([
  { name:'[Content_Types].xml', text:'<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/></Types>' },
  { name:'_rels/.rels', text:'<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>' },
  { name:'word/document.xml', text:'<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p/><w:sectPr/></w:body></w:document>' },
  { name:'word/_rels/document.xml.rels', text:'<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdSettings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/></Relationships>' },
  { name:'word/settings.xml', text:'<?xml version="1.0" encoding="UTF-8"?><w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:rsids><w:rsidRoot w:val="10000001"/></w:rsids></w:settings>' }
]);
const emptyRootParsed = await inspect(emptyRoot);
const emptyPair = compareRsids(emptyRootParsed.opc, emptyRootParsed.opc);
check(emptyRootParsed.opcVerdict === 'PASS' && emptyPair.defined && emptyPair.shared.length === 0 && emptyPair.linkage === false, 'two documents sharing a root but no session identifier are defined with linkage false, not a linkage signal');
must(page,"if (selfComparison) return 'NO LINKAGE RESULT",'the page refuses to call a self-comparison a linkage signal');
must(page,"if (!cmp.linkage) return 'DEFINED BUT NO LINKAGE EVIDENCE",'the page refuses to call a matching root alone a linkage signal');

/* No third-party request path can hide inside the JavaScript. */
const jsUrls = [...(page + core).matchAll(/https?:\/\/[^\s"'`)]+/g)].map(m => m[0]);
const allowedJsHosts = new Set(['schemas.openxmlformats.org','purl.oclc.org']);
check(jsUrls.every(url => allowedJsHosts.has(new URL(url).hostname)), 'every absolute URL literal in the two JavaScript modules is an inert XML namespace or relationship type, never a request target');
check(!/\bfetch\s*\(|\bnew\s+WebSocket|\bnew\s+EventSource|sendBeacon\s*\(|\bimportScripts\b/.test(core), 'the parser module contains no request construction at all');
check(!/\.src\s*=|new\s+Image\(|\bfetch\s*\(\s*['"`]/.test(page), 'the page module assigns no resource URL and calls fetch on no literal address');

check(LIMITS.input === 536870912 && LIMITS.entries === 100000 && LIMITS.entryInflated === 33554432 && LIMITS.totalInflated === 134217728 && LIMITS.xmlParts === 1000 && LIMITS.xmlText === 10485760 && LIMITS.relationshipDepth === 128, 'the seven declared limit values match, including the unused relationship depth');
for (const shown of ['512 MiB','100000','32 MiB','128 MiB','1000','10 MiB','128']) must(html,shown,'declared limit value appears: '+shown);
const anchorParagraph = /<p>(PKWARE APPNOTE 6\.3\.10 prints[\s\S]*?)<\/p>/.exec(html)?.[1] || '';
const anchorFigures = [...anchorParagraph.matchAll(/<span class="mono">([^<]+)<\/span>/g)].map(m => m[1]);
check(anchorFigures.length === 6, 'the published signature and fixed-length sentences contain exactly six figures');
for (const [i, expected] of ['0x04034b50','0x02014b50','0x06054b50','30','46','22'].entries()) check(anchorFigures[i] === expected, 'published signature/length figure ' + (i + 1) + ' equals ' + expected + ' in its own sentence');
for (const id of ['10000001','10000002','10000003','10000004']) must(html,id,'synthetic RSID appears: '+id);
must(html,'more than 400','published study scope is rendered as more than 400');
must(html,'five original XML parts','fixture part count is rendered');
check(!html.includes(String(aBytes.length)), 'fixture byte length is not hardcoded in HTML and is rendered from a.inputLength');
must(page,"metric('fixture bytes',a.inputLength)",'fixture byte length is rendered from the parsed result');
must(page,"metric('entries',a.entries.length)",'fixture entry count is rendered from the parsed result');
must(page,"metric('bit 3 fields',a.expectedBit3",'fixture exception count is rendered from the parsed result');
must(page,"metric('CRC pass',a.crcPass",'fixture CRC count is rendered from the parsed result');

const title = /<title>([^<]+)<\/title>/.exec(html)?.[1];
const metaDescription = /<meta name="description" content="([^"]+)"/.exec(html)?.[1];
const ogDescription = /<meta property="og:description" content="([^"]+)"/.exec(html)?.[1];
const plainMeta = /<meta name="aw-plain" content="([^"]+)"/.exec(html)?.[1];
const fm = key => new RegExp('^'+key+': "([^"]*)"','m').exec(frontmatter)?.[1];
check(title === fm('seoTitle') && jsonLd.name === title, 'SEO title agrees across HTML, frontmatter, and JSON-LD');
check(metaDescription === fm('dek') && jsonLd.description === metaDescription, 'dek agrees across meta description, frontmatter, and JSON-LD');
check(plainMeta === fm('plain'), 'plain-language description agrees across HTML and frontmatter');
check(jsonLd.headline === fm('title') && /og:title" content="The Archive That Disagrees With Itself/.test(html), 'poetic title agrees across frontmatter, JSON-LD, and OG');
check(jsonLd.datePublished === '2026-08-09T00:00:00Z' && frontmatter.includes('date: 2026-08-09T00:00:00Z'), 'publication date is exact on both surfaces');
check(frontmatter.includes('seam: "pattern"') && frontmatter.includes('"the specimen is yours"') && frontmatter.includes('draft: false'), 'frontmatter seam, wave tag, and publication state are correct');
check((frontmatter.match(/  - to:/g)||[]).length === 4, 'frontmatter declares four real relates edges');

for (const surface of [metaDescription,ogDescription,jsonLd.description,fm('plain'),fm('seoTitle')]) {
  check(!/two director|universally authoritative|proves? (?:malware|authorship|plagiarism|misconduct)/i.test(surface), 'shareable surface avoids retracted or overreaching claims');
}
check(/generic ZIP differences receive no universal winner/.test(metaDescription) && /only recognized OPC packages receive/.test(metaDescription), 'dek states both central concessions');
check(/never names a universal winner/.test(ogDescription) && /reserves conformance verdicts for OPC/.test(ogDescription), 'OG surface keeps both central concessions');
must(html,'A raw disagreement is not automatically an error','body states the bit 3 concession before results');
must(html,'The central directory is not called universally authoritative here','body rejects universal authority explicitly');
must(html,'They do not prove a person, author, device, time, exact save order, fork direction, plagiarism, misconduct','RSID limitations are explicit beside the instrument');
must(html,'It records what this page\'s application code can observe. It does not cover browser extensions or the initial HTML request.','privacy ledger scope is explicit');
must(html,'What changed after this page was first built','the page discloses the rules changed after the build');
for (const disclosed of ['central directory boundary','XML well-formedness','Counting pairs','Orphan references','The RSID sentence']) must(html,disclosed,'the disclosure names the changed rule: '+disclosed);
must(html,'A random-access reader enumerates through the directory','the body states the reader-class distinction rather than a universal claim about readers');
must(html,'cannot disagree with itself in these fields','the body states that a conforming OPC package cannot carry this disagreement');
must(html,'The informative outcomes are the failures','the body says which outcome carries information');
must(html,'requires each to have a single document element in its expected namespace','the named uncertainties state the requirement for the two recognition parts');
must(html,'no linkage result','the named uncertainties state the self-comparison refusal');
must(page,"metric('distinct local headers'",'the first screen counts distinct local headers');
must(page,"metric('unreferenced local headers'",'the first screen counts unreferenced local headers');
check(!page.includes("metric('paired headers'"), 'the retired paired-headers metric, which displayed the entry count a second time, is gone');
check(!core.includes('orphaned') && !page.includes('parsed.orphaned'), 'the retired orphan metric, whose value could not become nonzero, is gone from both modules');
must(page,'artifactLedger.bytesSent +=','the ledger byte counter can become nonzero, so asserting it is zero is not decoration');
must(page,'artifactLedger.bytesSent===0','visible check asserts exactly zero artifact bytes sent');
must(page,'the check panel itself refused to complete','a thrown check becomes a red line rather than a panel left on its placeholder');
must(page,'third-party resource requests','privacy ledger renders third-party resource count');
must(page,'application upload-capable API counters remain zero','visible check asserts every application network counter');

/* The page module is executed against a document shim so these are assertions about what
   the page renders, not about which strings appear in its source. */
const { installDom, settle } = await import('./dom-harness.mjs');
const deployedCsp = /<meta http-equiv="Content-Security-Policy" content="([^"]+)"/.exec(html);
check(!!deployedCsp, 'the deployed HTML carries a Content-Security-Policy meta element for the page to read back');
const registry = installDom(deployedCsp[1]);
await import('../../public/strata/the-archive-that-disagrees-with-itself/page.mjs');
check(await settle(registry, 'check-score'), 'the page module runs to completion and fills its check panel');
const rendered = id => registry.get(id).textContent;
const redLines = registry.get('check-list').elements('fail').map(node => node.textContent);
const anchorRed = registry.get('anchor-checks').elements('fail').map(node => node.textContent);
check(redLines.length === 0, 'the rendered check list contains no red line (' + (redLines[0] || 'none') + ')');
check(anchorRed.length === 0, 'the rendered anchor list contains no red line (' + (anchorRed[0] || 'none') + ')');
const liveScore = /^(\d+)\/(\d+) live checks pass/.exec(rendered('check-score'));
const anchorScore = /^(\d+)\/(\d+) pass$/.exec(rendered('anchor-score'));
check(liveScore && liveScore[1] === liveScore[2] && Number(liveScore[2]) >= 50, 'the rendered live score is a full pass over at least 50 checks: ' + rendered('check-score').split('.')[0]);
check(anchorScore && anchorScore[1] === anchorScore[2] && Number(anchorScore[2]) >= 15, 'the rendered anchor score is a full pass over at least 15 checks: ' + rendered('anchor-score'));
check(registry.get('check-list').children.length === Number(liveScore[2]) + registry.get('check-list').elements('quiet').length, 'every rendered check line is either scored or explicitly marked as a note');
check(rendered('summary').includes(String(aBytes.length)) && rendered('anchor-summary').includes(String(aBytes.length)), 'the rendered summaries show the parsed fixture byte length ' + aBytes.length + ' rather than a literal in the HTML');
check(rendered('summary').includes('distinct local headers') && rendered('summary').includes('unreferenced local headers') && rendered('summary').includes('CRC not checked'), 'the rendered first screen carries the three counters added during reconciliation');
check(!rendered('summary').includes('paired headers') && !rendered('summary').includes('orphan references'), 'the rendered first screen no longer carries the retired self-comparing and always-zero counters');
check(/OPC RECOGNIZED\. ECMA-376 Annex B\.2 PASS/.test(rendered('package-verdict')) && /the informative results here are the failures/.test(rendered('package-verdict')), 'the rendered verdict states the pass and says which outcome carries information');
check(/Standard-consistent linkage signal: 2 shared session identifier/.test(rendered('rsid-panel')), 'the rendered RSID panel reports the two shared fixture sessions as the signal');
check(rendered('rsid-panel').includes('10000001') && rendered('rsid-panel').includes('10000004'), 'the rendered RSID panel shows the root and the branch-only identifier');
check(/Central directory: bytes 1921\.\.2242/.test(rendered('map-note')), 'the rendered byte map names the exact central directory range of the fixture');
check(registry.get('byte-map').children.length >= 16, 'the rendered byte map has a segment for every classified range');
check(rendered('choice-list').includes('direct offsets') && rendered('choice-list').includes('Central directory boundary') && rendered('choice-list').includes('Pairing:'), 'the rendered free-choice list names the offset basis, the directory boundary, and the pairing account');
const ledgerText = rendered('privacy-ledger');
check(/artifact bytes sent0/.test(ledgerText), 'the rendered privacy ledger reports exactly zero artifact bytes sent');
check(/third-party resource requests0/.test(ledgerText) && /fetch calls0/.test(ledgerText) && /sendBeacon calls0/.test(ledgerText), 'the rendered privacy ledger reports zero third-party requests, zero fetch calls, and zero beacons');
check(ledgerText.includes('Archive Fork A.docx') && ledgerText.includes('Archive Fork B.docx'), 'the rendered privacy ledger names both specimens it holds');
check(rendered('csp-readout') === 'connect-src none is present in the deployed meta policy', 'the page reads the deployed policy back from the document and finds connect-src none');
check(registry.get('results').hidden === false && registry.get('refusal').hidden === true, 'the results panel is shown and the refusal panel is hidden for an accepted specimen');

check(rendered('parse-status') === 'Complete. 5 central records paired with 5 distinct local headers.', 'the completion status counts the five distinct fixture headers');
const assayInput = registry.get('archive-file');
assayInput.files = [{name:'duplicate.zip',size:duplicateBytes.length,arrayBuffer:async () => duplicateBytes.buffer}];
await assayInput.listeners.change[0]();
check(rendered('parse-status') === 'Complete. 2 central records paired with 1 distinct local header.', 'the completion status counts a shared local header once for two central records');
check(rendered('package-verdict').includes('This checker treats a shared local-header offset as a duplicate pairing.'), 'the duplicate-pairing explanation names the checker policy');

console.log('PASS ' + checks.length + '/' + checks.length);
console.log('fixture A bytes: ' + aBytes.length + '; entries: ' + a.entries.length + '; expected bit 3 fields: ' + a.expectedBit3 + '; unexplained: ' + a.unexplained + '; CRC pass: ' + a.crcPass + '; OPC: ' + a.opcVerdict);
console.log('mutations: local-name unexplained ' + nameBroken.unexplained + '; central-CRC unexplained ' + crcBroken.unexplained + '; central-CRC failures ' + crcBroken.crcFail);
console.log('RSIDs: root ' + pair.root + '; shared ' + pair.shared.join(',') + '; A only ' + pair.onlyA.join(',') + '; B only ' + pair.onlyB.join(','));
console.log('ZIP64: ' + zip64Bytes.length + ' bytes; entries ' + zip64Parsed.entries.length + '; directory anchored at the ' + zip64Parsed.eocd.directoryEndAnchor + '; OPC ' + zip64Parsed.opcVerdict);
console.log('pairing: duplicate specimen distinct ' + duplicateParsed.distinctLocals + '/' + duplicateParsed.entries.length + '; hidden specimen unreferenced ' + hiddenParsed.unreferenced.length + ' (' + hiddenParsed.unreferenced.map(x => x.name + ' at byte ' + x.offset).join(', ') + ')');
console.log('refusals: ' + refusalInventory.size + ' codes defined, ' + exercised.size + ' reached by a specimen, ' + notExercised.length + ' inventory-only');
console.log('rendered: anchor ' + rendered('anchor-score') + '; live ' + rendered('check-score').split('.')[0] + '; notes ' + registry.get('check-list').elements('quiet').length);
console.log('CRC: check value 0x' + crc32(new TextEncoder().encode('123456789')).toString(16) + '; residual 0xdebb20e3 over ' + crcMessages.length + ' messages');
