import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { inflateSync } from 'node:zlib';
import {
  PIXEL_CAP, FILE_BYTE_CAP, GIF_FRAME_CAP, GIF_COMPOSITE_PIXEL_CAP, HISTOGRAM_BINS, LLOYD_CAP, CIEDE_TOLERANCE, CIEDE2000_TESTS,
  makeFallbackPixels, preparePixels, medianCut, assignBins, refineLloyd,
  materializeIndices, paletteBytes, encodeLzw, decodeLzw, encodeGif, parseGif,
  validateCiede2000, colourMetrics, anchorFixture, inspectRasterMagic,
  preflightFile, degeneracyOf, activeCentres, distortionFor, lloydAccepts,
  recomputedDistortions, dictionaryRows, expandEntry
} from '../../public/strata/the-palette-your-gif-was-given/core.mjs';

const root = new URL('../../', import.meta.url);
const pageUrl = new URL('public/strata/the-palette-your-gif-was-given/', root);
const html = await readFile(new URL('index.html', pageUrl), 'utf8');
const pageJs = await readFile(new URL('page.mjs', pageUrl), 'utf8');
const coreJs = await readFile(new URL('core.mjs', pageUrl), 'utf8');
const generatorJs = await readFile(new URL('generate-fallback.mjs', pageUrl), 'utf8');
const markdown = await readFile(new URL('src/content/strata/the-palette-your-gif-was-given.md', root), 'utf8');
const pngBytes = new Uint8Array(await readFile(new URL('palette-stress-test.png', pageUrl)));
let checks = 0;
function check(condition, message) { assert.ok(condition, message); checks++; }
function equal(actual, expected, message) { assert.deepEqual(actual, expected, message); checks++; }
function close(actual, expected, tolerance, message) { assert.ok(Math.abs(actual - expected) <= tolerance, `${message}: got ${actual}, expected ${expected} within ${tolerance}`); checks++; }

function pngRgba(bytes) {
  equal(Array.from(bytes.subarray(0,8)), [137,80,78,71,13,10,26,10], 'fallback has PNG signature');
  let p=8,width=0,height=0,depth=0,type=0;const chunks=[];
  while(p<bytes.length){
    const n=(bytes[p]<<24)|(bytes[p+1]<<16)|(bytes[p+2]<<8)|bytes[p+3],name=String.fromCharCode(...bytes.subarray(p+4,p+8));
    const data=bytes.subarray(p+8,p+8+n);p+=12+n;
    if(name==='IHDR'){width=(data[0]<<24)|(data[1]<<16)|(data[2]<<8)|data[3];height=(data[4]<<24)|(data[5]<<16)|(data[6]<<8)|data[7];depth=data[8];type=data[9];}
    if(name==='IDAT')chunks.push(data);if(name==='IEND')break;
  }
  equal([width,height,depth,type],[512,512,8,6],'fallback PNG is 512 by 512, 8-bit RGBA');
  const packed=new Uint8Array(chunks.reduce((n,c)=>n+c.length,0));let q=0;for(const c of chunks){packed.set(c,q);q+=c.length;}
  const raw=inflateSync(packed),rgba=new Uint8ClampedArray(width*height*4);
  for(let y=0;y<height;y++){equal(raw[y*(1+width*4)],0,`fallback scanline ${y} uses deterministic filter 0`);rgba.set(raw.subarray(y*(1+width*4)+1,(y+1)*(1+width*4)),y*width*4);}
  return {width,height,rgba};
}

function equalBytes(a,b,message){
  equal(a.length,b.length,`${message}, length`);
  for(let i=0;i<a.length;i++)if(a[i]!==b[i])assert.fail(`${message}: byte ${i} is ${a[i]}, expected ${b[i]}`);
  checks++;
}

// Every refusal fixture must name its code AND the byte it happened at. Codes alone were the
// hole an earlier pass found: the LZW refusals reported a position in the concatenated
// compressed payload while printing it as a file offset, and a code-only assertion could not
// see the difference. exercised records which codes were reached, so the page's claim to test
// every named refusal path is enforced rather than asserted.
const exercised = new Set();
function expectRefusal(name,bytes,code,offset=null,detail=null){
  let caught=null;try{parseGif(new Uint8Array(bytes));}catch(error){caught=error;}
  check(caught,`${name} must refuse`);equal(caught.code,code,`${name} refusal code`);
  exercised.add(caught.code);
  check(Number.isInteger(caught.offset)&&caught.offset>=0&&caught.offset<=bytes.length,`${name} refusal offset is inside the specimen`);
  if(offset!==null)equal(caught.offset,offset,`${name} refusal offset`);
  if(detail!==null)check(caught.message.includes(detail),`${name} refusal detail names ${detail}`);
  return caught;
}
function expectLzwRefusal(name,fn,code){
  let caught=null;try{fn();}catch(error){caught=error;}
  check(caught,`${name} must refuse`);equal(caught.code,code,`${name} refusal code`);
  exercised.add(caught.code);
  return caught;
}

function subBlocks(payload){const out=[];for(let p=0;p<payload.length;p+=255){const n=Math.min(255,payload.length-p);out.push(n,...payload.subarray(p,p+n));}out.push(0);return out;}
function frameBlock(left,top,width,height,storedIndices,min=2,interlaced=false){
  const lzw=encodeLzw(new Uint8Array(storedIndices),min),out=[0x2c,left&255,left>>8,top&255,top>>8,width&255,width>>8,height&255,height>>8,interlaced?0x40:0,min,...subBlocks(lzw.bytes)];return out;
}
function tinyAnimation(){
  const out=[...new TextEncoder().encode('GIF89a'),2,0,2,0,0x81,0,0,0,0,0,255,0,0,0,255,0,0,0,0];
  out.push(0x21,0xf9,4,8,0,0,0,0,...frameBlock(0,0,2,2,[1,1,1,1]));
  out.push(0x21,0xf9,4,0,0,0,0,0,...frameBlock(0,0,1,1,[2]),0x3b);return new Uint8Array(out);
}

const anchor=anchorFixture();
equal([anchor.encoded.clear,anchor.encoded.eoi,anchor.encoded.firstFree,anchor.encoded.initialWidth],[256,257,258,9],'8-bit GIF anchor values');
equal(anchor.encoded.maxAssigned,4095,'anchor reaches the 12-bit code ceiling');
check([10,11,12].every(w=>anchor.encoded.transitions.some(t=>t.to===w)),'anchor crosses all three width transitions');
equal(anchor.indices.length,24000,'anchor fixture length shown on page');
check(anchor.roundTrip,'independent anchor decoder returns all indices exactly');
equalBytes(anchor.indices,anchor.decoded.indices,'anchor index round trip');
check(anchor.encoded.codes[0].code===256&&anchor.encoded.codes.at(-1).code===257,'anchor begins Clear and ends EOI');
// The branch that decides whether a decoder is independent or merely agreeable. The first
// version of this fixture was a plain pseudo-random stream and reached it zero times in
// 24,000 indices, which is the vacuous-anchor failure in person.
equal(anchor.decoded.selfReferential,1690,"the anchor drives the decoder through Welch's self-referential case 1,690 times");
equal(anchor.encoded.codes.filter(c=>c.code===256).length,4,'the anchor fills and clears the 12-bit table four times, so the clear-when-full path is exercised too');
equal(anchor.decoded.entries.length,2248,'2,248 dictionary entries survive in the table after the last Clear');

const ciede=validateCiede2000();
equal(ciede.rows,34,'all published CIEDE2000 rows are used');
equal(CIEDE2000_TESTS.length,34,'embedded published row count');
check(ciede.pass,'CIEDE2000 implementation stays inside chosen tolerance');
check(ciede.maxError>0.00004&&ciede.maxError<0.00005,'CIEDE2000 maximum error is nonzero and tight enough that 0.00001 would fail');
equal(CIEDE_TOLERANCE,0.0001,'visible CIEDE2000 tolerance');

const generated=makeFallbackPixels(),decodedPng=pngRgba(pngBytes);
equal([generated.width,generated.height],[512,512],'generated fallback dimensions');
equalBytes(generated.rgba,decodedPng.rgba,'shipped PNG pixels equal first-principles generator pixels');
equal(generated.width*generated.height,262144,'fallback decoded pixel count');
equal(PIXEL_CAP,16777216,'visible decoded-pixel safety cap');
equal(FILE_BYTE_CAP,268435456,'visible in-memory file-byte safety cap');
equal(GIF_FRAME_CAP,128,'visible GIF frame safety cap');
equal(GIF_COMPOSITE_PIXEL_CAP,33554432,'visible GIF composite-pixel safety cap');
equal(HISTOGRAM_BINS,32768,'visible 15-bit histogram bin count');
equal(LLOYD_CAP,20,'visible Lloyd iteration cap');
let prepRefusal=null;try{preparePixels(new Uint8ClampedArray(),4097,4097);}catch(error){prepRefusal=error;}check(prepRefusal?.message.includes(String(PIXEL_CAP)),'decoded-raster allocation refusal names the pixel cap');
prepRefusal=null;try{preparePixels(new Uint8ClampedArray([0,0,0,0]),1,1,{alphaMode:'threshold',alphaThreshold:128});}catch(error){prepRefusal=error;}check(prepRefusal?.message.includes('excluded every pixel'),'all-transparent metric refusal names the threshold outcome');

const prep=preparePixels(generated.rgba,generated.width,generated.height,{alphaMode:'matte',matte:[255,255,255],alphaThreshold:128});
equal(prep.activeCount,262144,'white-matte fallback includes every pixel');
equal(prep.transparentCount,0,'white-matte fallback excludes no pixel');
equal(prep.occupied.length,3589,'visible fallback occupied histogram-bin count');
// The swept K values are read out of the page's own control rather than restated here. The
// previous form iterated a literal list and then asserted that the list it had just iterated
// was the visible one, which is a check that cannot fail. If an option is added, removed or
// renamed in index.html, this now disagrees with the page's own published sweep figures.
const selectHtml=html.match(/<select id="palette-size">([\s\S]*?)<\/select>/)?.[1]||'';
const K_VALUES=[...selectHtml.matchAll(/<option[^>]*>(\d+)<\/option>/g)].map(m=>Number(m[1]));
equal(K_VALUES,[2,4,8,16,32,64,128,256],'the K settings the reader can pick, read out of index.html');
const pageKValues=pageJs.match(/const K_VALUES\s*=\s*\[([\d,\s]+)\]/)?.[1].split(',').map(Number);
equal(pageKValues,K_VALUES,'the sweep list in page.mjs equals the reader-visible option list');
const results=[];
for(const K of K_VALUES){
  const rawPalette=medianCut(prep,K),rawAssigned=assignBins(prep,rawPalette),refined=refineLloyd(prep,rawPalette,LLOYD_CAP);
  // Not the list refineLloyd filtered: D resummed pixel by pixel from the stored bytes for
  // every palette the loop kept, by code that shares no arithmetic with assignBins.
  const recomputed=recomputedDistortions(prep,refined);
  equal(recomputed.length,refined.distortions.length,`K ${K} one independently recomputed D per kept step`);
  check(recomputed.every((d,i)=>!i||d<=recomputed[i-1]+Math.max(1e-7,Math.abs(recomputed[i-1])*1e-12)),`K ${K} independently recomputed D never increases across kept steps`);
  refined.distortions.forEach((d,i)=>close(recomputed[i],d,Math.max(1e-6,Math.abs(d)*1e-9),`K ${K} step ${i} recomputed D agrees with the reported D`));
  check(refined.proposals.length>=refined.iterations,`K ${K} every fixed-point proposal is recorded, accepted or not`);
  const indices=materializeIndices(prep,refined.map),pal=paletteBytes(refined.palette),gif=encodeGif(prep.width,prep.height,pal,indices),decoder=decodeLzw(gif.lzw.bytes,gif.minCodeSize,indices.length);
  equalBytes(indices,decoder.indices,`K ${K} independent index round trip`);
  const parsed=parseGif(gif.bytes);equal(parsed.frames.length,1,`K ${K} emitted GIF has one image block`);equalBytes(parsed.frames[0].indices,indices,`K ${K} full parser round trip`);equal(Object.values(parsed.ledger).reduce((n,v)=>n+v,0),gif.bytes.length,`K ${K} parsed byte ledger is disjoint and complete`);
  check(gif.blocks.every(n=>n<=255),`K ${K} sub-blocks stay at or below 255 bytes`);
  equal(Array.from(gif.bytes.slice(-2)),[0,0x3b],`K ${K} ends with zero sub-block and trailer`);
  equal(gif.ledger.reduce((n,row)=>n+row[1],0),gif.bytes.length,`K ${K} byte ledger sums to exact Blob length`);
  const metrics=colourMetrics(prep,refined.map,refined.palette),rawMetrics=colourMetrics(prep,rawAssigned.map,rawPalette);
  results.push({K,rawD:rawAssigned.D,D:refined.D,iterations:refined.iterations,rawMean:rawMetrics.mean,mean:metrics.mean,p95:metrics.p95,bytes:gif.bytes.length,payload:gif.lzw.bytes.length,occupied:prep.occupied.length});
}

// Negative control for the independent recomputation. Move one palette entry and the
// pixel-by-pixel resum must rise. Without this the agreement above could be two routes to the
// same blindness rather than two routes to the same number.
{
  const pal=medianCut(prep,16),ref=refineLloyd(prep,pal);
  const good=distortionFor(prep,ref.palette,ref.map);
  close(good,ref.D,Math.max(1e-6,Math.abs(ref.D)*1e-9),'the pixel-by-pixel resum agrees with the reported D on the unperturbed palette');
  const moved=ref.palette.map((p,i)=>i===0?[(p[0]+128)%256,p[1],p[2]]:p.slice());
  const worse=distortionFor(prep,moved,ref.map);
  check(worse>good,`moving one of sixteen palette entries raises the recomputed D from ${good.toFixed(0)} to ${worse.toFixed(0)}, so the recomputation can see a wrong palette`);
  const allMoved=ref.palette.map(p=>[255-p[0],255-p[1],255-p[2]]);
  check(distortionFor(prep,allMoved,ref.map)>good*4,'inverting every palette entry raises it by more than a factor of four');
}

const defaultResult=results.at(-1);
close(defaultResult.rawD,47610039.485123806,0.001,'visible fallback raw median-cut D');
close(defaultResult.D,28893860.67794425,0.001,'visible fallback refined D');
equal(defaultResult.iterations,20,'visible fallback accepted iteration count');
close(defaultResult.rawMean,2.2881379897691017,1e-9,'visible fallback raw mean CIEDE2000');
close(defaultResult.mean,1.816375995700501,1e-9,'visible fallback refined mean CIEDE2000');
close(defaultResult.p95,5.625653266906738,1e-9,'visible fallback 95th percentile CIEDE2000');
equal(defaultResult.bytes,41316,'visible fallback complete GIF bytes');
equal(defaultResult.payload,40363,'visible fallback LZW payload bytes');
equal(results.map(r=>r.K),K_VALUES,'the eight measured points are exactly the eight settings the page offers');
// The guard that decides whether a fixed-point step is kept, asked a question it must answer
// with no. Reading back the already-filtered distortion list can never do this.
const guardD=results.at(-1).D;
check(lloydAccepts(guardD,guardD),'the fixed-point guard accepts a proposal that leaves D unchanged');
check(lloydAccepts(guardD,guardD-1),'the fixed-point guard accepts a proposal that lowers D');
check(!lloydAccepts(guardD,guardD*1.000001),'the fixed-point guard rejects a proposal that raises D by one part in a million');
check(!lloydAccepts(guardD,guardD+Math.max(1e-6,Math.abs(guardD)*1e-9)),'the fixed-point guard rejects a rise just above its own tolerance');
check(lloydAccepts(1,1+1e-8),'the guard tolerance is a floating-point allowance, not a licence: 1e-8 on D of 1 is still accepted');
check(!lloydAccepts(1,1.001),'the guard tolerance is far below a real increase: 0.1 percent on D of 1 is rejected');
equal(results.map(r=>r.bytes),[7135,10459,13306,16207,20043,23291,30820,41316],'all visible fallback sweep GIF byte counts');
equal(results.map(r=>r.payload),[7075,10380,13204,16069,19843,22982,30291,40363],'all visible fallback sweep LZW payload byte counts');
const expectedMeans=[25.092349,19.988604,12.819619,9.410760,6.349646,5.012192,2.788526,1.816376];
const expectedP95=[42.654484,43.906784,24.426023,19.252136,14.452491,11.713492,8.103053,5.625653];
results.forEach((r,i)=>{close(r.mean,expectedMeans[i],0.0000006,`K ${r.K} visible mean CIEDE2000`);close(r.p95,expectedP95[i],0.0000006,`K ${r.K} visible 95th percentile CIEDE2000`);});
const flat={width:1,height:1,rgba:new Uint8ClampedArray([17,17,17,255])},flatPrep=preparePixels(flat.rgba,1,1),flatPalette=medianCut(flatPrep,256),flatRefined=refineLloyd(flatPrep,flatPalette),flatIndices=materializeIndices(flatPrep,flatRefined.map),flatGif=encodeGif(1,1,paletteBytes(flatRefined.palette),flatIndices,{tableSize:256});
equal(flatRefined.palette.length,1,'flat specimen honestly has one active centre');equal(flatGif.tableSize,256,'requested K remains a 256-entry GIF table');equal(flatGif.ledger.find(r=>r[0]==='global colour table')[1],768,'unused K entries are deterministic table padding');

// ---------------------------------------------------------------- vacuity, named not hidden
// A one-colour raster is reachable through the page's own file input at every K it offers, and
// on it the headline comparison compares a quantity with itself: raw D, refined D, mean and
// 95th percentile error are all exactly zero and cannot say anything about quantization.
// These assertions prove both that this is true and that the page says so.
const oneColour=new Uint8ClampedArray(2*2*4);for(let i=0;i<4;i++){oneColour[i*4]=200;oneColour[i*4+1]=30;oneColour[i*4+2]=90;oneColour[i*4+3]=255;}
const onePrep=preparePixels(oneColour,2,2);
for(const K of K_VALUES){
  const pal=medianCut(onePrep,K),ref=refineLloyd(onePrep,pal),met=colourMetrics(onePrep,ref.map,ref.palette);
  const deg=degeneracyOf(onePrep,ref.map,met);
  equal(activeCentres(onePrep,ref.map),1,`one-colour specimen at K ${K} uses one centre`);
  equal([assignBins(onePrep,pal).D,ref.D,met.mean,met.p95,met.max],[0,0,0,0,0],`one-colour specimen at K ${K} makes every headline figure exactly zero`);
  check(deg.degenerate,`one-colour specimen at K ${K} is reported as degenerate rather than as a result`);
  check(deg.reason.includes('compare a quantity with itself'),`the K ${K} degeneracy notice says what is wrong with the comparison`);
}
// A specimen whose colours already sit on the palette: 4 distinct colours, K 4. Error is zero
// by construction, not by measurement, and the second degeneracy rule is the one that fires.
const exact=new Uint8ClampedArray([0,0,0,255, 255,0,0,255, 0,255,0,255, 0,0,255,255]);
const exactPrep=preparePixels(exact,4,1),exactPal=medianCut(exactPrep,4),exactRef=refineLloyd(exactPrep,exactPal);
const exactMet=colourMetrics(exactPrep,exactRef.map,exactRef.palette),exactDeg=degeneracyOf(exactPrep,exactRef.map,exactMet);
equal(activeCentres(exactPrep,exactRef.map),4,'the four-colour specimen at K 4 uses four centres, so the first degeneracy rule does not fire');
equal(exactMet.max,0,'every pixel already sits exactly on a palette entry');
check(exactDeg.degenerate&&exactDeg.reason.includes('by construction'),'zero error with four live centres is still named as vacuous, by the second rule');
// The control: a specimen that is genuinely quantized must NOT be called degenerate, or the
// notice would be decoration that fires on everything.
const liveDeg=degeneracyOf(prep,refineLloyd(prep,medianCut(prep,256)).map,{max:defaultResult.p95});
check(!liveDeg.degenerate&&liveDeg.centres>1,`the shipped fallback at K 256 is not degenerate: ${liveDeg.centres} live centres`);
check(html.includes('id="degenerate"')&&pageJs.includes("$('degenerate')"),'the page has somewhere to print the degeneracy notice and code that prints it');

// ---------------------------------------------------------------- specimens the builder had not seen
// Three constructed files, one deliberately malformed, run end to end through the same path a
// reader's file takes: magic, parse, composite, prepare, quantize, encode, independent decode.
function gifFromIndices(w,h,indices,tableSize,palette){
  const bits=Math.log2(tableSize)-1,out=[...new TextEncoder().encode('GIF89a'),w&255,w>>8,h&255,h>>8,0x80|(7<<4)|bits,0,0];
  for(let i=0;i<tableSize*3;i++)out.push(palette[i]??0);
  const min=Math.max(2,Math.ceil(Math.log2(tableSize)));
  out.push(...frameBlock(0,0,w,h,indices,min),0x3b);
  return new Uint8Array(out);
}
// Specimen A: GIF87a, 3 by 4, comment extension, local colour table, interlaced.
const specA=(()=>{
  const out=[...new TextEncoder().encode('GIF87a'),3,0,4,0,0,0,0];
  out.push(0x21,0xfe,3,65,66,67,0);
  const lzw=encodeLzw(new Uint8Array([0,1,2, 1,2,0, 2,0,1, 0,0,2]),2);
  out.push(0x2c,0,0,0,0,3,0,4,0,0xc1,1,2,3, 255,0,0, 0,255,0, 0,0,255, 2,...subBlocks(lzw.bytes).slice(0));
  out.push(0x3b);
  return new Uint8Array(out);
})();
equal(inspectRasterMagic(specA).kind,'gif','unseen specimen A is identified as a GIF by its magic');
const parsedA=parseGif(specA);
equal([parsedA.signature,parsedA.width,parsedA.height,parsedA.frames.length],['GIF87a',3,4,1],'unseen specimen A parses as a GIF87a 3 by 4 with one image block');
check(parsedA.frames[0].interlaced&&parsedA.frames[0].localTable,'unseen specimen A really does use interlace and a local colour table');
equal(Array.from(parsedA.frames[0].indices),[0,1,2,2,0,1,1,2,0,0,0,2],'unseen specimen A four-pass interlace is restored to display order');
const prepA=preparePixels(parsedA.frames[0].rgba,3,4),refA=refineLloyd(prepA,medianCut(prepA,4));
const gifA=encodeGif(3,4,paletteBytes(refA.palette),materializeIndices(prepA,refA.map),{tableSize:4});
equalBytes(materializeIndices(prepA,refA.map),decodeLzw(gifA.lzw.bytes,gifA.minCodeSize,12).indices,'unseen specimen A re-encodes and independently decodes index for index');
// Specimen B: a 40 by 40 two-colour checkerboard, chosen because a run-friendly layout is the
// re-derivation's third vacuity case: it can leave the width-growth half of the claim untested.
const checkIdx=new Uint8Array(1600);for(let i=0;i<1600;i++)checkIdx[i]=(((i%40)>>2)^((i/40|0)>>2))&1;
const specB=gifFromIndices(40,40,checkIdx,2,[10,10,10, 240,240,240]);
const parsedB=parseGif(specB);
equalBytes(parsedB.frames[0].indices,checkIdx,'unseen specimen B round trips through the parser');
const widthsB=[...new Set(parsedB.frames[0].lzw.codes.map(c=>c.width))];
check(widthsB.length>1,`unseen specimen B does cross a code-width boundary: widths ${widthsB.join(', ')}`);
check(parsedB.frames[0].lzw.selfReferential>0,`unseen specimen B reaches the self-referential case ${parsedB.frames[0].lzw.selfReferential} times`);
const prepB=preparePixels(parsedB.frames[0].rgba,40,40),refB=refineLloyd(prepB,medianCut(prepB,2));
equal(activeCentres(prepB,refB.map),2,'unseen specimen B keeps both of its colours at K 2');
// Specimen C, deliberately malformed: a local colour table that lies about its own size.
const specC=new Uint8Array([...new TextEncoder().encode('GIF89a'),1,0,1,0,0,0,0,0x2c,0,0,0,0,1,0,1,0,0x87,7,8,9]);
const refusedC=expectRefusal('unseen malformed specimen C, lying local colour table',specC,'TRUNCATED',null,'local colour table declared as 256 entries');
check(refusedC.message.includes('needs 768 byte(s), only 3 remain'),'unseen specimen C refusal counts the bytes that were actually there');
equal(refusedC.offset,23,'unseen specimen C refusal names byte 23, where the local colour table should have started');
// Specimen D, also malformed and also unseen: valid header, valid image, one trailing byte.
const specD=new Uint8Array([...gifFromIndices(2,2,new Uint8Array([0,1,1,0]),2,[0,0,0, 255,255,255]),0x21]);
expectRefusal('unseen malformed specimen D, one byte after the trailer',specD,'BYTES_AFTER_TRAILER',null,'1 byte(s) follow trailer');
// Specimen E: a zero-byte file, which is what an empty drop looks like.
equal(preflightFile({size:0,name:'empty'}),0,'a zero-byte file survives preflight');
check(inspectRasterMagic(new Uint8Array(0)).reason.includes('0 byte(s)'),'a zero-byte file is refused by name, not by a generic error');

// ---------------------------------------------------------------- reconciliation with the blinded re-derivation
// An independent derivation, working from the GIF89a spec and Welch 1984 without seeing this
// page, reached five numerical claims that this instrument can be asked directly. They are
// checked here rather than believed, and where the page disagrees it says so with its own
// arithmetic.

// (a) A colour table is a ceiling on one table, not on one picture. Two image blocks with two
// two-entry local tables composite to four distinct colours.
const twoTables=new Uint8Array([...new TextEncoder().encode('GIF89a'),4,0,1,0,0,0,0,
  0x2c,0,0,0,0,2,0,1,0,0x80, 255,0,0, 0,255,0, 2, ...subBlocks(encodeLzw(new Uint8Array([0,1]),2).bytes),
  0x2c,2,0,0,0,2,0,1,0,0x80, 0,0,255, 255,255,0, 2, ...subBlocks(encodeLzw(new Uint8Array([0,1]),2).bytes),
  0x3b]);
const twoParsed=parseGif(twoTables);
equal(twoParsed.frames.length,2,'a picture can carry more than one image block, each with its own colour table');
check(!twoParsed.frames.every(f=>f.localTable===false),'both blocks use local colour tables, not the absent global one');
const composite=twoParsed.frames.at(-1).rgba;
const compositeColours=new Set();for(let i=0;i<4;i++)compositeColours.add(`${composite[i*4]},${composite[i*4+1]},${composite[i*4+2]}`);
equal([...compositeColours].sort(),['0,0,255','0,255,0','255,0,0','255,255,0'],'two two-entry local tables composite to four distinct colours, so 256 bounds a table and not a picture');
for(const bits of [0,1,2,3,4,5,6,7])equal(1<<(bits+1),[2,4,8,16,32,64,128,256][bits],`a ${bits}-valued size field means ${1<<(bits+1)} entries, and no other size is expressible`);
let oddTable=null;try{encodeGif(1,1,new Uint8Array(600),new Uint8Array([0]),{tableSize:200});}catch(error){oddTable=error;}
check(oddTable instanceof RangeError,'a 200-entry GIF colour table cannot be requested, because the format cannot express one');

// (b) Permuting the palette cannot change the compressed size. LZW parses on the pattern of
// repeats, so a bijection on the alphabet leaves the parse structure and the width schedule
// untouched: different bytes, identical length and identical code count.
for(const K of [16,256]){
  const pal=medianCut(prep,K),ref=refineLloyd(prep,pal),idx=materializeIndices(prep,ref.map),bytes=paletteBytes(ref.palette);
  const base=encodeGif(512,512,bytes,idx,{tableSize:K});
  const perm=[...Array(K).keys()];let s=12345;
  for(let i=K-1;i>0;i--){s^=s<<13;s^=s>>>17;s^=s<<5;const j=(s>>>0)%(i+1);[perm[i],perm[j]]=[perm[j],perm[i]];}
  const permPal=new Uint8Array(K*3);for(let i=0;i<K;i++){permPal[perm[i]*3]=bytes[i*3];permPal[perm[i]*3+1]=bytes[i*3+1];permPal[perm[i]*3+2]=bytes[i*3+2];}
  const permIdx=new Uint8Array(idx.length);for(let i=0;i<idx.length;i++)permIdx[i]=perm[idx[i]];
  const permuted=encodeGif(512,512,permPal,permIdx,{tableSize:K});
  equal(permuted.lzw.bytes.length,base.lzw.bytes.length,`K ${K}: permuting the palette leaves the payload length identical`);
  equal(permuted.lzw.codes.length,base.lzw.codes.length,`K ${K}: permuting the palette leaves the code count identical`);
  let identical=true;for(let i=0;i<base.lzw.bytes.length;i++)if(base.lzw.bytes[i]!==permuted.lzw.bytes[i]){identical=false;break;}
  check(!identical,`K ${K}: the permuted payload is different bytes, so the length equality is a result and not a tautology`);
}
// Ordering does matter through the largest used index, which sets the minimum code size.
equal(encodeGif(1,32,new Uint8Array(96),new Uint8Array(32).map((v,i)=>i),{tableSize:32}).minCodeSize,5,'32 colours packed into indices 0 to 31 need a 5-bit minimum code size');
equal(encodeGif(1,32,new Uint8Array(768),new Uint8Array(32).map((v,i)=>i*8),{tableSize:256}).minCodeSize,8,'the same 32 colours scattered over 0 to 255 need 8, and pay for it in every code');

// (c) Fixed overhead. The independent derivation put the floor for a single-image 256-colour
// GIF at 793 bytes, from header 6 + screen 7 + descriptor 10 + minimum code size 1 + trailer 1
// plus a 768-byte table. That omits the zero block terminator that ends the sub-block chain,
// which section 16 of the spec requires, and any real image also needs at least one sub-block
// length byte. This encoder's own ledger settles it.
const minimalGif=encodeGif(1,1,new Uint8Array(768),new Uint8Array([0]),{tableSize:256});
const fixedNames=['header','logical screen descriptor','global colour table','image descriptor','LZW minimum-size byte','block terminator','trailer'];
const fixedBytes=fixedNames.reduce((n,name)=>n+minimalGif.ledger.find(r=>r[0]===name)[1],0);
equal(fixedBytes,794,'the fixed cost of a single-image 256-colour GIF is 794 bytes, one more than the 793 that leaves out the block terminator');
equal(minimalGif.ledger.find(r=>r[0]==='block terminator')[1],1,'the omitted byte is the zero-length block that closes the image data');
equal(minimalGif.ledger.find(r=>r[0]==='sub-block length bytes')[1],1,'and any nonempty payload adds at least one sub-block length byte, so 795 is the practical floor');
equal(minimalGif.bytes.length,799,'a 1 by 1 256-colour GIF from this encoder is 799 bytes: 794 fixed, 1 length byte, 4 payload');

// (d) Interlacing the same indices costs payload. The independent derivation measured a 15
// percent penalty on a 192 by 128 photograph; this fixture is a different image, so the
// magnitude is its own and only the direction is shared.
{
  const pal=medianCut(prep,256),ref=refineLloyd(prep,pal),idx=materializeIndices(prep,ref.map);
  const rows=[];for(const [start,step] of [[0,8],[4,8],[2,4],[1,2]])for(let y=start;y<512;y+=step)rows.push(y);
  equal(rows.length,512,'the four interlace passes name every row exactly once');
  const interleaved=new Uint8Array(idx.length);rows.forEach((y,i)=>interleaved.set(idx.subarray(y*512,(y+1)*512),i*512));
  const sequential=encodeLzw(idx,8),interlaced=encodeLzw(interleaved,8);
  equal(sequential.bytes.length,40363,'sequential row order gives the published payload');
  equal(interlaced.bytes.length,51451,'the same pixels in four-pass interlace order cost 51,451 payload bytes');
  check(interlaced.bytes.length>sequential.bytes.length,'row order is a free parameter that changes the byte count without changing one pixel');
}

// (e) The two objectives really do pull apart at fixed K, on the shipped fallback, in the
// page's own default apparatus. At K 4 the refinement lowers D, which is all it promises, and
// makes the perceptual mean worse while making the file smaller.
{
  const pal=medianCut(prep,4),raw=assignBins(prep,pal),ref=refineLloyd(prep,pal);
  const rawMetrics=colourMetrics(prep,raw.map,pal),refMetrics=colourMetrics(prep,ref.map,ref.palette);
  const rawGif=encodeGif(512,512,paletteBytes(pal),materializeIndices(prep,raw.map),{tableSize:4});
  const refGif=encodeGif(512,512,paletteBytes(ref.palette),materializeIndices(prep,ref.map),{tableSize:4});
  close(raw.D,1821097566.5469937,0.001,'K 4 raw median-cut D');
  close(ref.D,1651870985.5568771,0.001,'K 4 refined D');
  check(ref.D<raw.D,'K 4 refinement lowers D, which is the only thing it promises');
  close(rawMetrics.mean,19.94245398432514,1e-9,'K 4 raw mean CIEDE2000');
  close(refMetrics.mean,19.988604166434182,1e-9,'K 4 refined mean CIEDE2000');
  check(refMetrics.mean>rawMetrics.mean,'K 4 refinement makes the perceptual mean worse while lowering D, so the two objectives are not the same objective');
  equal([rawGif.bytes.length,refGif.bytes.length],[11119,10459],'K 4 raw and refined GIF byte counts');
  check(refGif.bytes.length<rawGif.bytes.length,'and at K 4 the worse-looking result is also the smaller file');
  for(const text of ['1,821,097,567','1,651,870,986','19.942','19.989','11,119','10,459'])check(html.includes(text),`the page prints the K 4 counterexample figure ${text}`);
}

const transparentPrep=preparePixels(generated.rgba,512,512,{alphaMode:'threshold',alphaThreshold:128});
check(transparentPrep.transparentCount>0&&transparentPrep.activeCount>0,'one-bit alpha mode has both transparent and measured pixels');
equal([transparentPrep.activeCount,transparentPrep.transparentCount,transparentPrep.occupied.length],[247148,14996,3484],'visible one-bit fallback pixel and bin counts');
const tp=medianCut(transparentPrep,255),tr=refineLloyd(transparentPrep,tp),ti=materializeIndices(transparentPrep,tr.map,1),tg=encodeGif(512,512,paletteBytes(tr.palette,true),ti,{transparentIndex:0}),tparsed=parseGif(tg.bytes);
equal(tparsed.frames[0].transparentIndex,0,'transparent GIF reserves index 0');
check(tparsed.frames[0].rgba.some((v,i)=>i%4===3&&v===0),'transparent GIF decode contains alpha 0');

const badPaletteHeader=[...new TextEncoder().encode('GIF89a'),1,0,1,0,0x80,0,0,0,0,0,255,255,255];
equal(badPaletteHeader.length,19,'refusal fixture header is 19 bytes, so the image separator sits at byte 19');
expectRefusal('truncated header',[71,73,70],'TRUNCATED',0,'GIF header needs 6 byte(s), only 3 remain');
expectRefusal('wrong magic',[66,65,68,56,57,97],'BAD_MAGIC',0,'"BAD89a"');
expectRefusal('lying global table',[71,73,70,56,57,97,1,0,1,0,128,0,0,1,2,3],'TRUNCATED',13,'declared as 2 entries');
expectRefusal('zero screen',[71,73,70,56,57,97,0,0,1,0,0,0,0,0x3b],'ZERO_SCREEN',6,'0 by 1');
expectRefusal('pixel cap',[71,73,70,56,57,97,1,16,1,16,0,0,0,0x3b],'PIXEL_CAP',6,String(PIXEL_CAP));
expectRefusal('background index outside table',[...badPaletteHeader.slice(0,11),2,...badPaletteHeader.slice(12),0x3b],'BAD_BACKGROUND_INDEX',11,'index 2 exceeds 2-entry');
expectRefusal('bad GCE size',[...badPaletteHeader,0x21,0xf9,3,0,0,0,0,0x3b],'BAD_GCE_SIZE',21,'found 3, expected 4');
expectRefusal('bad GCE terminator',[...badPaletteHeader,0x21,0xf9,4,0,0,0,0,1,0x3b],'BAD_GCE_TERMINATOR',26,'found 1, expected 0');
expectRefusal('unknown block',[71,73,70,56,57,97,1,0,1,0,0,0,0,0x22],'UNKNOWN_BLOCK',13,'marker 0x22');
expectRefusal('zero frame',[...badPaletteHeader,0x2c,0,0,0,0,0,0,1,0,0],'ZERO_FRAME',19,'frame is 0 by 1');
expectRefusal('frame outside screen',[...badPaletteHeader,...frameBlock(1,0,1,1,[0])],'FRAME_OUTSIDE_SCREEN',19,'exceeds 1 by 1');
const noTableHeader=[...new TextEncoder().encode('GIF89a'),1,0,1,0,0,0,0];
expectRefusal('no active colour table',[...noTableHeader,0x2c,0,0,0,0,1,0,1,0,0],'NO_COLOUR_TABLE',13,'neither a local nor a global');
// The two rebased LZW refusals. Both used to report byte 0 because the decoder counted in
// compressed-payload coordinates and the message printed it as a file offset. Byte 29 is the
// LZW minimum code size, byte 30 the sub-block length, byte 31 the first compressed byte.
expectRefusal('bad LZW minimum, at its own file byte',[...badPaletteHeader,0x2c,0,0,0,0,1,0,1,0,0,1,0],'BAD_LZW_MINIMUM',29,'value 1, expected 2 through 8');
expectRefusal('LZW without initial clear, at its own file byte',[...badPaletteHeader,0x2c,0,0,0,0,1,0,1,0,0,2,1,40,0,0x3b],'LZW_NO_INITIAL_CLEAR',31,'expected Clear 4');
expectRefusal('LZW produces too many pixels',[...badPaletteHeader,...frameBlock(0,0,1,1,[0,0]),0x3b],'LZW_TOO_MANY_PIXELS',32,'declared 1 indices');
expectRefusal('stream with no image',[...badPaletteHeader,0x3b],'NO_IMAGE',19,'no image descriptor');
const missingTrailer=encodeGif(1,1,new Uint8Array([0,0,0,255,255,255]),new Uint8Array([0])).bytes.slice(0,-1);
expectRefusal('missing trailer',missingTrailer,'MISSING_TRAILER',missingTrailer.length,'before trailer 0x3b');
const extra=encodeGif(1,1,new Uint8Array([0,0,0,255,255,255]),new Uint8Array([0])).bytes;const extraAfter=new Uint8Array(extra.length+1);extraAfter.set(extra);extraAfter[extra.length]=9;
expectRefusal('bytes after trailer',extraAfter,'BYTES_AFTER_TRAILER',extra.length,'1 byte(s) follow');
// Every bounded read inside a GIF has to be bounded. One truncation per context, each one byte
// short of what its own declared length demands.
const gceHead=[...badPaletteHeader,0x21,0xf9,4,0,0,0];
expectRefusal('truncated logical screen descriptor',[71,73,70,56,57,97,1,0,1,0,0,0],'TRUNCATED',6,'logical screen descriptor needs 7');
expectRefusal('truncated extension label',[...badPaletteHeader,0x21],'TRUNCATED',20,'extension label needs 1');
expectRefusal('truncated graphic control body',gceHead,'TRUNCATED',22,'graphic control body and terminator needs 5');
expectRefusal('truncated comment sub-block length',[...badPaletteHeader,0x21,0xfe],'TRUNCATED',21,'sub-block length needs 1');
expectRefusal('truncated comment sub-block payload',[...badPaletteHeader,0x21,0xfe,4,65,66],'TRUNCATED',22,'declared as 4 byte(s)');
expectRefusal('truncated image descriptor',[...badPaletteHeader,0x2c,0,0,0,0,1,0,1],'TRUNCATED',20,'image descriptor needs 9');
expectRefusal('truncated local colour table',[...badPaletteHeader,0x2c,0,0,0,0,1,0,1,0,0x80,1,2,3],'TRUNCATED',29,'local colour table declared as 2 entries');
expectRefusal('truncated LZW minimum code size',[...badPaletteHeader,0x2c,0,0,0,0,1,0,1,0,0],'TRUNCATED',29,'LZW minimum code size needs 1');
expectRefusal('truncated image-data sub-block length',[...badPaletteHeader,0x2c,0,0,0,0,1,0,1,0,0,2],'TRUNCATED',30,'image data sub-block length needs 1');
expectRefusal('truncated image-data payload',[...badPaletteHeader,0x2c,0,0,0,0,1,0,1,0,0,2,4,1,2],'TRUNCATED',31,'image data sub-block payload declared as 4');
expectLzwRefusal('truncated LZW refuses missing EOI',()=>{const good=encodeLzw(new Uint8Array([0]),2);decodeLzw(good.bytes.slice(0,-1),2,1);},'LZW_MISSING_EOI');
expectLzwRefusal('out-of-range LZW code is refused',()=>decodeLzw(new Uint8Array([4|(7<<3)]),2),'BAD_LZW_CODE');
expectLzwRefusal('lying image pixel count is refused',()=>{const good=encodeLzw(new Uint8Array([0]),2);decodeLzw(good.bytes,2,2);},'LZW_PIXEL_COUNT');
const standaloneMinimum=expectLzwRefusal('standalone bad minimum names its own coordinate',()=>decodeLzw(new Uint8Array([0]),1,1),'BAD_LZW_MINIMUM');
check(standaloneMinimum.scope==='compressed payload byte'&&standaloneMinimum.message.includes('byte before payload byte 0'),'a payload-relative refusal says so instead of printing a file offset it does not have');
expectRefusal('palette index outside table',new Uint8Array([...badPaletteHeader,...frameBlock(0,0,1,1,[2]),0x3b]),'BAD_PALETTE_INDEX',30,'index 2 exceeds 2-entry');
const badTransparent=new Uint8Array([...badPaletteHeader,0x21,0xf9,4,1,0,0,2,0,...frameBlock(0,0,1,1,[0]),0x3b]);expectRefusal('transparent index outside table',badTransparent,'BAD_TRANSPARENT_INDEX',27,'transparent index 2');
const badDisposal=new Uint8Array([...badPaletteHeader,0x21,0xf9,4,16,0,0,0,0,...frameBlock(0,0,1,1,[0]),0x3b]);expectRefusal('reserved disposal method',badDisposal,'BAD_DISPOSAL',22,'method 4 is reserved');


// The final End of Information can be one bit narrower than this decoder's own counter
// reached. Three branches, each of which must behave differently: the ordinary ending, the
// narrow ending rescued by the retry, and a genuine truncation that must still be refused.
function boundaryStream(n){const idx=new Uint8Array(n);let x=2*7919+n;for(let i=0;i<n;i++){x^=x<<13;x^=x>>>17;x^=x<<5;idx[i]=(x>>>0)%2;}return idx;}
const narrowIdx=boundaryStream(19),narrowEnc=encodeLzw(narrowIdx,2);
equal(Array.from(narrowEnc.bytes),[0x04,0x72,0x17,0x6b,0xcc,0x50],'the recorded narrow-ending payload is byte for byte what gifsicle 1.94 writes for these indices');
equal(narrowEnc.codes.reduce((s,c)=>s+c.width,0),48,'that payload ends exactly on a byte boundary, leaving no pad bit for a wider read');
equal(narrowEnc.maxAssigned+1,1<<narrowEnc.codes.at(-1).width,'its final free code lands exactly on a power of two, which is the condition for the narrow ending');
const narrowDec=decodeLzw(narrowEnc.bytes,2,19);
check(narrowDec.narrowEoi,'the narrow ending is recognised and reported rather than silently absorbed');
equalBytes(narrowIdx,narrowDec.indices,'the narrow ending still round trips index for index');
const ordinary=encodeLzw(boundaryStream(64),2),ordinaryDec=decodeLzw(ordinary.bytes,2,64);
check(!ordinaryDec.narrowEoi,'an ordinary ending is not reported as narrow, so the flag can distinguish the two');
expectLzwRefusal('a truncated payload is still refused, retry or no retry',()=>decodeLzw(narrowEnc.bytes.slice(0,-1),2,19),'LZW_MISSING_EOI');
expectLzwRefusal('a narrow-ending payload with its final code removed is refused',()=>decodeLzw(narrowEnc.bytes.slice(0,-2),2,19),'LZW_MISSING_EOI');
let narrowSurvivors=0,narrowSeen=0;
for(let n=2;n<=1200;n++){
  const idx=boundaryStream(n),enc=encodeLzw(idx,2);
  const dec=decodeLzw(enc.bytes,2,n);
  if(dec.narrowEoi)narrowSeen++;
  let same=dec.indices.length===n;for(let i=0;same&&i<n;i++)if(dec.indices[i]!==idx[i])same=false;
  if(same)narrowSurvivors++;
}
equal(narrowSurvivors,1199,'1,199 consecutive stream lengths round trip through the independent decoder');
check(narrowSeen>0,`${narrowSeen} of those streams needed the narrow-ending retry, so the retry is exercised rather than dead code`);

// The dictionary the page shows a reader is the one the decoder built, and every row expands
// back to the phrase the encoder meant.
const dictSource=encodeLzw(new Uint8Array([1,2,1,2,3,2,1,2,1,2,1,1,1,1,1,1,1]),2);
const dictDec=decodeLzw(dictSource.bytes,2,17),dict=dictionaryRows(dictDec,4);
equal(dict.total,dictDec.entries.length,'the visible dictionary total is the decoder entry count');
equal(dict.first[0].code,6,'the first dictionary entry a 2-bit stream can create is code 6, Clear 4 plus EOI 5 plus one');
for(const row of [...dict.first,...dict.last]){
  const phrase=expandEntry(dictDec.entries,dictDec.clear,row.code);
  equal(phrase.length,row.length,`dictionary code ${row.code} reports its own phrase length`);
  check(row.phrase.startsWith(String(phrase[0])),`dictionary code ${row.code} shows the phrase it expands to`);
  equal(phrase.at(-1),row.suffix,`dictionary code ${row.code} ends with the index it appended`);
  equal(expandEntry(dictDec.entries,dictDec.clear,row.prefix).length,row.length-1,`dictionary code ${row.code} is exactly its prefix plus one index`);
}
// T. A. Welch, "A Technique for High-Performance Data Compression", Computer 17(6):8-19,
// June 1984, figure 5 and table 3, page 16. His alphabet a, b, c becomes GIF indices 0, 1, 2
// and his symbol codes are 1-based, so Welch's code n is this stream's code n - 1 for a
// literal and n + 2 for a table entry at GIF minimum code size 2.
const welch=[0,1,0,1,2,1,0,1,0,1,0,0,0,0,0,0,0];
const welchEnc=encodeLzw(new Uint8Array(welch),2);
const welchDec=decodeLzw(welchEnc.bytes,2,welch.length);
equal(welch.length,17,"Welch's figure 5 input is 17 symbols");
equalBytes(new Uint8Array(welch),welchDec.indices,"Welch's 17-symbol figure 5 input survives this encoder and decoder");
equal(welchEnc.codes.slice(1,-1).map(c=>c.code),[0,1,6,2,7,10,0,12,13,0],
  "figure 5 OUTPUT CODES 1 2 4 3 5 8 1 10 11 1 reproduce exactly under the GIF renumbering");
equal(welchDec.entries.length,9,'figure 5 adds nine table entries, Welch codes 4 through 12');
equal(welchDec.entries.map(e=>expandEntry(welchDec.entries,welchDec.clear,e.code).join('')),
  ['01','10','012','21','101','1010','00','000','0000'],
  "table 3 ALTERNATE TABLE 1b 2a 4c 3b 5b 8a 1a 10a 11a expands to ab ba abc cb bab baba aa aaa aaaa");
// Welch's table 3 prints the STRING TABLE cell for his code 11 as "aa", the same as code 10.
// His own ALTERNATE TABLE cell on that row reads 10a, which forces aaa, and figure 6 prints
// aaa as the ninth output. The reproduction agrees with the two cells that agree with each
// other, so the article's printed cell is the outlier, not this decoder.
equal(expandEntry(welchDec.entries,welchDec.clear,13).join(''),'000',
  "Welch code 11 is aaa, as his own ALTERNATE TABLE and figure 6 require, not the aa his STRING TABLE column misprints");
equal(welchDec.selfReferential,3,"Welch's 17-symbol example drives the decoder through his self-referential case exactly three times, as his figure 6 outputs bab, aa and aaa require");
const flatStream=decodeLzw(encodeLzw(new Uint8Array(4096),8).bytes,8,4096);
equal(flatStream.selfReferential,89,'a constant-colour raster reaches that branch on all but one of its 90 dictionary entries');
const noSelfRef=decodeLzw(encodeLzw(new Uint8Array([0,1,2,3]),2).bytes,2,4);
equal(noSelfRef.selfReferential,0,'a stream with no repeated phrase never reaches that branch, so the counter can read zero and this check can fail');

const animation=parseGif(tinyAnimation());
equal(animation.frames.length,2,'animated GIF parser exposes every image block');
equal(Object.values(animation.ledger).reduce((n,v)=>n+v,0),animation.byteLength,'animated GIF byte ledger is disjoint and complete');
equal(Array.from(animation.frames[0].rgba),[255,0,0,255,255,0,0,255,255,0,0,255,255,0,0,255],'first animation frame composites red');
equal(Array.from(animation.frames[1].rgba),[0,255,0,255,0,0,0,255,0,0,0,255,0,0,0,255],'disposal 2 restores background before second frame');
const frameCapError=expectLzwRefusal('animation frame safety refusal',()=>parseGif(tinyAnimation(),{frameCap:1}),'FRAME_CAP');
equal(frameCapError.offset,56,'the frame-cap refusal names the image separator of the frame it declined');
const frameMemoryError=expectLzwRefusal('animation composite-memory refusal',()=>parseGif(tinyAnimation(),{compositePixelCap:3}),'FRAME_MEMORY_CAP');
check(frameMemoryError.message.includes('3 pixels'),'the composite-memory refusal names the cap it applied');
const interlaceHeader=[...new TextEncoder().encode('GIF89a'),2,0,4,0,0x80,0,0,0,0,0,255,255,255];
const interlaced=new Uint8Array([...interlaceHeader,...frameBlock(0,0,2,4,[0,0,0,0,1,1,1,1],2,true),0x3b]);
const ip=parseGif(interlaced);equal(Array.from(ip.frames[0].indices),[0,0,1,1,0,0,1,1],'four-pass interlace rows are restored to display order');

equal(inspectRasterMagic(new Uint8Array([137,80,78,71,13,10,26,10])).kind,'png','PNG magic accepted');
equal(inspectRasterMagic(new TextEncoder().encode('GIF87a')).kind,'gif','GIF87a magic accepted');
equal(inspectRasterMagic(new Uint8Array([0xff,0xd8,0xff,0xe0])).kind,'jpeg','JPEG magic accepted');
check(inspectRasterMagic(new Uint8Array([1,2,3,4])).reason.includes('01 02 03 04'),'unknown raster refusal names the bytes');

// Every refusal code the page can raise must be reached by a fixture above. Without this the
// sentence "every named refusal path" is a promise about a set nobody counted.
const declaredCodes=[...new Set([...coreJs.matchAll(/(?:GifRefusal|refuse)\('([A-Z_]+)'/g)].map(m=>m[1]))].sort();
check(declaredCodes.length>=25,`core.mjs declares ${declaredCodes.length} refusal codes`);
for(const code of declaredCodes)check(exercised.has(code),`refusal path ${code} is exercised by a fixture, not merely named`);
equal([...exercised].sort(),declaredCodes,'the fixtures exercise exactly the refusal codes core.mjs can raise, no more and no fewer');

const jsonText=html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)?.[1];
check(jsonText,'page contains JSON-LD');const json=JSON.parse(jsonText);
equal([json['@type'],json.name,json.headline,json.datePublished],['Article','GIF Color Quantization: Build and Inspect a Palette','The Palette Your GIF Was Given','2026-08-09T00:00:00Z'],'JSON-LD Article identity');
const dek='Give a photograph 256 colours and watch every compromise become a byte. Your image stays in this browser while median cut and fixed-point refinement build its palette, CIEDE2000 measures the changed pixels, and a real GIF encoder exposes its LZW dictionary and exact file size. The concession is visible beside the result: lower per-pixel error need not look better, and these bytes belong to this encoder rather than the smallest GIF possible.';
// These are consistency checks, not truth checks: they prove one wording is used everywhere a
// stranger meets the page, so a retracted claim cannot survive in a share card. Whether the
// wording is true is settled by the assertions above and by the adversarial pass, not here.
check(html.includes(`content="${dek}"`),'meta description is the same string as the frontmatter dek');check(html.includes(`"description":"${dek}"`),'JSON-LD description is the same string as the frontmatter dek');check(markdown.includes(`dek: "${dek}"`),'frontmatter dek is the string these two are compared against');
check(html.includes('Lower error is not promised to look better, and the result is not a globally smallest GIF.'),'OG description carries both concessions');
// The share cards used to promise inspection of "every emitted GIF byte" and "the exact GIF
// and LZW bytes", while the body showed byte counts by class and no dictionary at all. The
// body now carries a real dictionary table, and the cards describe what is there.
check(html.includes('account for every emitted GIF byte by class, read the LZW dictionary this encoder builds'),'OG description promises the byte ledger and the dictionary, which are what the body has');
check(html.includes('read the exact GIF byte ledger and LZW dictionary this encoder emits'),'Twitter description promises the byte ledger and the dictionary');
check(!/inspect every emitted GIF byte|inspect the exact GIF and LZW bytes/.test(html),'the withdrawn per-byte inspection promise is gone from every share surface');
check(html.includes('id="dictionary-body"')&&pageJs.includes("$('dictionary-body')"),'the dictionary the cards promise has a table and code that fills it');
check(markdown.includes('plain: "Give this page a picture')&&markdown.includes('That metric is not a promise about what looks best'),'plain summary carries the metric concession');
check(markdown.includes('seoTitle: "GIF Color Quantization: Build and Inspect a Palette"'),'search title describes the measured instrument');
// The eyebrow a reader sees must name the seam the site files this page under. The spec
// reassigned it from mechanism to pattern and the page kept the old word.
const seam=markdown.match(/^seam:\s*"([a-z]+)"/m)?.[1];
equal(seam,'pattern','frontmatter seam');
const eyebrow=html.match(/<p class="eyebrow">([^<]*)<\/p>/)?.[1];
check(eyebrow.includes(seam),`the reader-visible eyebrow "${eyebrow}" names the frontmatter seam`);
check(!/mechanism/.test(eyebrow),'the eyebrow no longer names the seam this page was reassigned away from');
check(!/"mechanism"/.test(markdown),'the superseded seam is not left behind in the frontmatter tags either');
for(const text of ['Clear = 2<sup>m</sup> = 256','EOI = Clear + 1 = 257','First free = Clear + 2 = 258','Initial width = m + 1 = 9 bits','2<sup>12</sup> - 1 = 4095','268,435,456','4096 × 4096 = 16,777,216','128 frames','33,554,432 stored composite pixels','Five high bits of R, G, and B make 32,768 histogram bins','all 34 published Sharma'])check(html.includes(text),`reader-visible source contains ${text}`);
// Wiring, not evidence: these prove a container exists and that the module writes to it. They
// are named as wiring so nobody reads a green line here as a claim about a number.
for(const id of ['metric-k','metric-mean','metric-p95','metric-bytes','metric-payload','raw-d','refined-d','raw-mean','refined-mean','raw-bytes','refined-bytes','iteration-count','ledger','sweep-body','degenerate','dictionary-body','dictionary-total','narrow-eoi','specimen-selfref','anchor-selfref','anchor-clears'])
  check(html.includes(`id="${id}"`)&&pageJs.includes(`'${id}'`),`wiring: readout ${id} exists in index.html and is written by page.mjs`);
// The disclosure the reconcile pass owes the reader: a rule that changed after measurement.
for(const text of ['One decoder rule was changed after measurement, on 9 August 2026','gifsicle 1.94','ImageMagick 6.9.12','440 of 440 streams compared','8,966 deliberately shortened streams, none accepted'])
  check(html.includes(text),`the changed-after-measurement disclosure states ${text}`);
check(html.includes('Degenerate specimens.')&&html.includes('compare a quantity with itself'),'the apparatus names the setting in which the headline comparison is vacuous');

// The privacy scan used to read page.mjs and core.mjs only. The page also executes
// /media/home-banner.js, which loads /media/plain-button.js, and the inline stylesheet can
// reach the network through url() or @import. Everything the page actually runs is scanned,
// including the two shared scripts this page does not own: it cannot fix them, but it can
// refuse to ship while they carry a request path.
const bannerJs=await readFile(new URL('public/media/home-banner.js',root),'utf8');
const plainButtonJs=await readFile(new URL('public/media/plain-button.js',root),'utf8');
const inlineCss=[...html.matchAll(/<style>([\s\S]*?)<\/style>/g)].map(m=>m[1]).join('\n');
const executableSource=pageJs+coreJs;
const everythingExecuted=pageJs+coreJs+bannerJs+plainButtonJs;
for(const forbidden of ['fetch(', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'sendBeacon', 'navigator.serviceWorker'])check(!executableSource.includes(forbidden),`no ${forbidden} code path in this page's own modules`);
for(const forbidden of ['fetch(', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'sendBeacon', 'navigator.serviceWorker', 'importScripts', 'new Image('])
  check(!everythingExecuted.includes(forbidden),`no ${forbidden} code path in anything this page executes, shared scripts included`);
check(pageJs.includes("$('browser-decode').src=state.lastObjectUrl"),'the only src assignment in page.mjs is the blob: URL of the GIF it just made');
const srcAssignments=[...everythingExecuted.matchAll(/\.src\s*=\s*([^;\n]+)/g)].map(m=>m[1].trim());
check(srcAssignments.every(v=>/state\.lastObjectUrl|['"]\/media\/plain-button\.js['"]/.test(v)),`every .src assignment is same-origin or a blob: URL of this page's own bytes: ${srcAssignments.join(' | ')}`);
const cssUrls=[...inlineCss.matchAll(/url\(\s*["']?([^"')]+)/g),...inlineCss.matchAll(/@import\s+["']?([^"';]+)/g)].map(m=>m[1].trim());
equal(cssUrls.length,0,'the inline stylesheet fetches nothing at all: zero url() and zero @import, so there is no font, image or sheet to place off-origin');
const linkedSheets=[...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*href="([^"]+)"/g)].map(m=>m[1]);
equal(linkedSheets,['/fonts/fonts.css'],'the one linked stylesheet is the self-hosted font sheet');
check(html.includes("connect-src 'none'"),'inline CSP disables connections');
// form-action 'none' is absolute, and it costs the injected banner search box its submit. The
// page says so rather than leaving a reader with a control that silently does nothing.
check(/form-action 'none'/.test(html),'the CSP forbids every form submission, including the one the shared banner injects');
check(bannerJs.includes("<form class=\"aw-search\""),'the shared banner does inject a form, which is why that cost is real and is disclosed');
check(html.includes('the search box in the site banner above cannot submit from this page'),'the page discloses the cost of its own form policy');
// Executed, not grepped. A mock File records whether its bytes were ever asked for, so the
// cap is proved to act before the allocation rather than merely appearing in the source.
let arrayBufferTouched=false;
const oversizeFile={size:FILE_BYTE_CAP+1,name:'huge.png',async arrayBuffer(){arrayBufferTouched=true;return new ArrayBuffer(0);}};
let preflightError=null;try{preflightFile(oversizeFile);}catch(error){preflightError=error;}
check(preflightError instanceof RangeError,'a file one byte above the cap is refused');
check(!arrayBufferTouched,'the oversize file was refused before arrayBuffer() was called');
check(preflightError.message.includes('268,435,456'),'the file-cap refusal names the visible cap');
equal(preflightFile({size:FILE_BYTE_CAP,name:'exact.png'}),FILE_BYTE_CAP,'a file exactly at the cap is accepted');
equal(preflightFile({size:0,name:'empty.png'}),0,'a zero-byte file passes preflight and is identified later by its magic');
let noSize=null;try{preflightFile({name:'not-a-file'});}catch(error){noSize=error;}check(noSize instanceof RangeError,'an object without a byte size is refused');
check(pageJs.indexOf('preflightFile(file)')>=0&&pageJs.indexOf('preflightFile(file)')<pageJs.indexOf('await file.arrayBuffer()'),'page.mjs runs the preflight before it reads the file');
const resourceUrls=[...html.matchAll(/<(?:script|img)\b[^>]*\bsrc="([^"]+)"/g),...html.matchAll(/<link\b[^>]*\bhref="([^"]+)"/g)].map(m=>m[1]);
check(resourceUrls.every(url=>url.startsWith('/')||url.startsWith('./')||url.startsWith('blob:')||url.startsWith('data:')||url.startsWith('https://artwaste.land/')),'all automatically loaded resources and canonical metadata are same-origin or local schemes');
check(!/[\u2014]/u.test(html+pageJs+coreJs+generatorJs+markdown),'published files contain no em dash');
check(html.endsWith('</html>\n'),'load-bearing HTML closing tag is present');
// Wiring, not provenance: this proves the same licence string is printed in both places. That
// the fallback has no external author is established by the pixel-for-pixel equality above
// between the shipped PNG and the generator's own output, not by this line.
check(generatorJs.includes('CC0-1.0')&&html.includes('CC0-1.0'),'wiring: generator and page print the same fallback licence string');

console.log(`PASS ${checks} checks`);
console.log(`anchor: Clear ${anchor.encoded.clear}, EOI ${anchor.encoded.eoi}, first free ${anchor.encoded.firstFree}, initial ${anchor.encoded.initialWidth} bits, maximum ${anchor.encoded.maxAssigned}`);
console.table(results.map(r=>({K:r.K,mean:r.mean.toFixed(6),p95:r.p95.toFixed(6),gifBytes:r.bytes,lzwBytes:r.payload,D:r.D.toFixed(3)})));
console.log(`CIEDE2000: ${ciede.rows} rows, maximum absolute error ${ciede.maxError.toFixed(9)}, tolerance ${CIEDE_TOLERANCE}`);
