/** * The review page for `audit:compare --review`: before and after, side by side, for every render * whose drawing changed, grouped by shape bucket and sorted by weighted impact. Writes * `/review.html` (with its drawings in `/review/`) and `/review.pdf`. */ import fs from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { chromium } from 'playwright-core'; const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]); const signed = (n, digits = 1) => (n > 0 ? '+' : n < 0 ? '−' : '±') + Math.abs(n).toFixed(digits); const tone = n => (n > 0 ? 'worse' : n < 0 ? 'better' : 'same'); export async function writeReview(o) { const assets = path.join(o.outDir, 'review'); fs.rmSync(assets, { recursive: true, force: true }); fs.mkdirSync(assets, { recursive: true }); const svgOf = (side, p) => { const f = path.join(o.outDir, side, p.set, p.head.slug, p.head.file.replace('.draft', '.svg')); return fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : undefined; }; // Every render whose drawing or defect index changed. const items = []; for (const p of o.moves) { if (!p.base || p.base.error || p.head.error) continue; const [before, after] = [svgOf('base', p), svgOf('head', p)]; const d = +(p.head.defectIndex - p.base.defectIndex).toFixed(1); if (!d && before === after) continue; const id = `${p.set}-${p.head.slug}-${p.head.file.replace('.draft', '')}`; for (const [side, svg] of [ ['base', before], ['head', after], ]) if (svg) fs.writeFileSync(path.join(assets, `${id}.${side}.svg`), svg); const [kb, kh] = [o.kindsOf(p.base), o.kindsOf(p.head)]; const kinds = [...new Set([...Object.keys(kb), ...Object.keys(kh)])] .map(k => ({ kind: k, d: (kh[k] ?? 0) - (kb[k] ?? 0) })) .filter(k => k.d) .sort((a, b) => b.d - a.d); const bucket = o.bucketOf(p.set, p.head); const weight = o.weightOf(p.set, p.key); items.push({ ...p, id, d, from: p.base.defectIndex, to: p.head.defectIndex, bucket, weight, impact: d * weight, limit: o.limitOf(bucket), kinds, hasSvg: !!before && !!after, }); } // Buckets in order of how often the shape occurs; within one, the largest weighted moves first. const buckets = new Map(); for (const it of items) { if (!buckets.has(it.bucket)) buckets.set(it.bucket, []); buckets.get(it.bucket).push(it); } const order = [...buckets.keys()].sort((a, b) => o.shareOf(b) - o.shareOf(a)); for (const list of buckets.values()) list.sort((a, b) => Math.abs(b.impact) - Math.abs(a.impact) || Math.abs(b.d) - Math.abs(a.d)); const pct = b => `${((100 * (o.population.buckets[b] ?? 0)) / o.population.total).toFixed(0)}%`; const net = list => list.reduce((s, it) => s + it.impact, 0); const maxShare = Math.max(...Object.values(o.population.buckets)) / o.population.total; const gateBlock = ([name, flag], g) => `

${esc(name)} ${esc(flag)} ${g.verdict}

${g.rows .map(([rule, result, evidence]) => { const parts = (evidence || '').split('; ').filter(Boolean); const shown = parts.slice(0, 3).join('; ') + (parts.length > 3 ? `; +${parts.length - 3} more` : ''); return `
${result}${esc(rule)}${shown ? `${esc(shown)}` : ''}
`; }) .join('')}
`; const setRows = Object.entries(o.loaded) .map(([set, { base, head }]) => { const ok = l => l.filter(r => !r.error); const m = l => ok(l).reduce((s, r) => s + r.defectIndex, 0) / Math.max(1, ok(l).length); const wm = side => o.setMean(set, side); const moved = items.filter(it => it.set === set).length; return `${esc(set)}${ok(head).length}${moved} ${m(base).toFixed(2)} → ${m(head).toFixed(2)}${signed(m(head) - m(base), 2)} ${wm('base').toFixed(2)} → ${wm('head').toFixed(2)}${signed(wm('head') - wm('base'), 2)}`; }) .join(''); const bucketNav = order .map(b => { const list = buckets.get(b); const share = (o.population.buckets[b] ?? 0) / o.population.total; const n = net(list); return `${esc(b)} ${pct(b)}${list.filter(it => it.d).length}${list.filter(it => !it.d).length} ${signed(n, 2)}`; }) .join(''); const card = it => `
${esc(it.set)}/${esc(it.head.slug)} ${esc(it.head.file.replace('.draft', ''))}
${it.from} → ${it.to} ${signed(it.d)}
Weighted
${signed(it.impact, 2)}
Weight
${it.weight.toFixed(2)}
Limit
${it.limit.toFixed(1)}${it.d > it.limit ? ' · over' : ''}
Size
${it.head.nodes} boxes · ${it.head.edges} lines
    ${ it.kinds.length ? it.kinds .map( k => `
  • ${signed(k.d, 0)} ${esc(k.kind)}
  • `, ) .join('') : '
  • Same issues; the drawing moved
  • ' }
${ it.hasSvg ? `
Before
After
` : '

No drawing saved for this render.

' }
`; const moved = list => list.filter(it => it.d); const redrawn = list => list.filter(it => !it.d); const small = it => `
${esc(it.set)}/${esc(it.head.slug)} ${esc(it.head.file.replace('.draft', ''))} DI ${it.to}
${ it.hasSvg ? `
Before
After
` : '' }
`; const sections = order .map(b => { const list = buckets.get(b); const seen = o.population.buckets[b]; return `

${esc(b)}

${seen ? `${pct(b)} of docs diagrams (${seen} of ${o.population.total})` : 'No docs diagram has this shape'} · ${moved(list).length} moved DI · ${redrawn(list).length} redrawn · net weighted ${signed(net(list), 2)} · limit ${o.limitOf(b).toFixed(1)} DI

${moved(list).length ? `
BeforeAfter
${moved(list).map(card).join('')}` : ''} ${ redrawn(list).length ? `

Redrawn with the same DI (${redrawn(list).length}) · before, after

${redrawn(list).map(small).join('')}
` : '' }
`; }) .join(''); const html = ` Audit review

Audit review

${esc(o.title)} · ${items.filter(it => it.d).length} renders moved DI, ${items.filter(it => !it.d).length} redrawn with the same DI · weights from ${o.population.total} docs diagrams measured ${esc(o.population.measured)}

${Object.entries(o.gates) .map(([name, g]) => gateBlock(name === 'flat' ? ['Flat gate', '--gate=flat'] : ['Weighted gate', '--gate'], g), ) .join('')}

Buckets by share of docs diagrams

BucketShare%DI movedRedrawnNet w.
${bucketNav}
${setRows}
SetRendersChangedMean DIΔWeighted mean DIΔw
${sections || '

No render changed.

'}
`; const htmlFile = path.join(o.outDir, 'review.html'); fs.writeFileSync(htmlFile, html); const pdfFile = path.join(o.outDir, 'review.pdf'); const browser = await chromium.launch(); try { const page = await browser.newPage(); await page.goto(pathToFileURL(htmlFile).href, { waitUntil: 'load' }); await page.pdf({ path: pdfFile, preferCSSPageSize: true, printBackground: true }); } finally { await browser.close(); } return [htmlFile, pdfFile]; }