Skip to content
← Public packages

@kentcdodds/closing-the-agentic-loop

Closing the Agentic Loop: Kent C. Dodds's talk and workshop deck. Default short talk; ?event=aie-2026 is the AIE hour cut with a Podium QR; ?format=full adds labs.

FollowForkOpen app

Files

verify.mjs

729 lines · 41.4 KB · JavaScript
// Opens the built Reveal.js deck in headless Chromium with all network access blocked, in both
// prefers-color-scheme light and dark. In each scheme it checks the theme applied, walks every
// slide with the keyboard, and screenshots each one into <outDir>/<scheme>/. It also checks the
// speaker view (S), overview (O), the T theme toggle, the break countdown, deep links, and loading
// with transitions on, and prints the word count of each slide. It fails on text under 44px, console errors, any network request, missing fonts, content that
// overflows the canvas (checked at 1920x1080 and 1280x720, in the default, ?format=full, ?format=hour and ?event=aie-2026 modes), or a slide without notes.
// It also checks the two formats (lab slides only with ?format=full), the lab timers (they resume, not restart), and
// the FAQ links (index to every FAQ, every FAQ back to the index, every Questions slide to the index),
// and event mode (Podium QR, no overlap, alias from ?format=hour).
// Usage: node scripts/verify.mjs [url-or-file] [outDir]
// Needs `playwright` (devDependency); set CHROMIUM_PATH to pick a browser binary.
import { mkdirSync } from 'node:fs'
import { pathToFileURL } from 'node:url'
import { chromium } from 'playwright'
import jsQR from 'jsqr'
import { PNG } from 'pngjs'

const target = process.argv[2] ?? 'dist/index.html'
const url = /^https?:|^file:/.test(target) ? target : pathToFileURL(target).href
const outDir = process.argv[3] ?? 'verify-shots'
const docPath = url.split(/[?#]/)[0]
const problems = []
const timelineIds = []
const timelineChecks = []
const timerChecks = []
const thesisChecks = []
const pad = (n) => String(n).padStart(2, '0')
const decodeQr = (buf) => {
	const png = PNG.sync.read(buf)
	return jsQR(new Uint8ClampedArray(png.data.buffer, png.data.byteOffset, png.data.byteLength), png.width, png.height)?.data ?? null
}
const clipOf = async (page, selector) => {
	const box = await page.evaluate((selector) => {
		const el = document.querySelector(selector)
		if (!el || el.hidden) return null
		const r = el.getBoundingClientRect()
		return { x: r.x, y: r.y, width: r.width, height: r.height }
	}, selector)
	if (!box || box.width < 8 || box.height < 8) return null
	const pad = 8
	return {
		x: Math.max(0, box.x - pad),
		y: Math.max(0, box.y - pad),
		width: box.width + pad * 2,
		height: box.height + pad * 2,
	}
}


const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined })

async function newContext(colorScheme) {
	const context = await browser.newContext({ viewport: { width: 1920, height: 1080 }, colorScheme })
	// Only the deck page itself (including the speaker view's ?receiver frames) and data: URIs may load.
	await context.route('**/*', (route) => {
		const u = route.request().url()
		if (u.startsWith('data:') || u.split(/[?#]/)[0] === docPath) return route.continue()
		problems.push(`network request: ${u}`)
		return route.abort()
	})
	return context
}
const watch = (p, name) => {
	p.on('console', (m) => { if (m.type() === 'error') problems.push(`${name} console: ${m.text()}`) })
	p.on('pageerror', (e) => problems.push(`${name} pageerror: ${e.message}`))
}
const ready = (p) => p.waitForFunction(() => window.__deck?.isReady() && document.fonts.status === 'loaded')


// Timelines (every .tl, e.g. pr-3782): the rail (.tl::before) must run through every dot centre, from the first dot to the last.
async function checkTimeline(page, label, id) {
	const r = await page.evaluate((id) => {
		const tl = document.querySelector(`section#${id} .tl`)
		if (!tl) return null
		const box = tl.getBoundingClientRect()
		const scale = box.width / tl.offsetWidth
		const cs = getComputedStyle(tl, '::before')
		const left = box.left + parseFloat(cs.left) * scale
		const top = box.top + parseFloat(cs.top) * scale
		const width = parseFloat(cs.width) * scale
		const height = parseFloat(cs.height) * scale
		const dots = [...tl.querySelectorAll('.dot')].map((d) => d.getBoundingClientRect()).map((b) => ({ cx: b.left + b.width / 2, cy: b.top + b.height / 2, left: b.left, right: b.right }))
		return { rail: { cx: left + width / 2, left, right: left + width, top, bottom: top + height }, dots }
	}, id)
	if (!r) return problems.push(`${id} timeline (${label}): no .tl found`)
	if (r.dots.length < 2) return problems.push(`${id} timeline (${label}): only ${r.dots.length} dots`)
	timelineChecks.push(`${id}@${label}`)
	const bad = []
	r.dots.forEach((d, i) => {
		if (Math.abs(d.cx - r.rail.cx) > 1) bad.push(`dot ${i + 1} centre x ${d.cx.toFixed(1)} vs rail ${r.rail.cx.toFixed(1)}`)
		if (r.rail.left < d.left || r.rail.right > d.right) bad.push(`rail box [${r.rail.left.toFixed(1)}, ${r.rail.right.toFixed(1)}] not inside dot ${i + 1} box [${d.left.toFixed(1)}, ${d.right.toFixed(1)}]`)
	})
	if (Math.abs(r.rail.top - r.dots[0].cy) > 1) bad.push(`rail starts at y ${r.rail.top.toFixed(1)}, first dot centre ${r.dots[0].cy.toFixed(1)}`)
	if (Math.abs(r.rail.bottom - r.dots.at(-1).cy) > 1) bad.push(`rail ends at y ${r.rail.bottom.toFixed(1)}, last dot centre ${r.dots.at(-1).cy.toFixed(1)}`)
	if (bad.length) problems.push(`${id} timeline (${label}): ${bad.join('; ')}`)
}

let ids = []
const wordCounts = []
for (const scheme of ['dark', 'light']) {
	const dir = `${outDir}/${scheme}`
	mkdirSync(dir, { recursive: true })
	const context = await newContext(scheme)
	const page = await context.newPage()
	watch(page, `${scheme} deck`)
	await page.goto(`${docPath}?static`)
	await ready(page)
	const theme = await page.evaluate(() => document.documentElement.dataset.theme)
	if (theme !== scheme) problems.push(`${scheme}: data-theme is ${theme}`)
	ids = await page.evaluate(() => window.__deck.getSlides().map((s) => s.id))
	const fonts = await page.evaluate(() => [...document.fonts].filter((f) => f.status === 'loaded').map((f) => f.family))
	for (const fam of ['Bricolage Grotesque', 'Wix Madefor Text']) if (!fonts.some((f) => f.includes(fam))) problems.push(`font not loaded: ${fam}`)
	for (let i = 0; i < ids.length; i++) {
		if (i > 0) await page.keyboard.press('ArrowRight')
		await page.waitForFunction((id) => location.hash === `#/${id}`, ids[i], { timeout: 3000 }).catch(() => {})
		const hash = await page.evaluate(() => location.hash)
		if (hash !== `#/${ids[i]}`) problems.push(`${scheme} slide ${i + 1}: hash ${hash} != #/${ids[i]}`)
		const overflow = await page.evaluate(() => {
			const slide = window.__deck.getCurrentSlide()
			const box = slide.getBoundingClientRect()
			const bad = []
			for (const el of slide.querySelectorAll('*')) {
				if (el.closest('aside.notes') || el.tagName === 'STYLE') continue
				const r = el.getBoundingClientRect()
				if (!r.width && !r.height) continue
				if (r.right > box.right + 1 || r.bottom > box.bottom + 1 || r.left < box.left - 1 || r.top < box.top - 1) bad.push(`${el.tagName}.${el.className}`)
			}
			return bad.slice(0, 5)
		})
		if (overflow.length) problems.push(`${scheme} slide ${ids[i]} overflows: ${overflow.join(', ')}`)
		if (scheme === 'dark') {
			// Audience text: at least 44px (on the 1920x1080 canvas), and about 25 words or fewer.
			const { small, words } = await page.evaluate(() => {
				const slide = window.__deck.getCurrentSlide()
				const small = new Set()
				const walker = document.createTreeWalker(slide, NodeFilter.SHOW_TEXT)
				let text = ''
				while (walker.nextNode()) {
					const node = walker.currentNode
					const el = node.parentElement
					if (!node.textContent.trim() || el.closest('aside.notes, style, .event-qr')) continue
					text += ` ${node.textContent}`
					if (parseFloat(getComputedStyle(el).fontSize) < 43.5) small.add(`${el.tagName}.${el.className} "${node.textContent.trim().slice(0, 30)}"`)
				}
				return { small: [...small], words: text.split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length }
			})
			if (small.length) problems.push(`slide ${ids[i]} has text under 44px: ${small.join(', ')}`)
			wordCounts.push(`${ids[i]}:${words}`)
		}
		if (scheme === 'dark') {
			const notes = await page.evaluate(() => !!window.__deck.getCurrentSlide().querySelector('aside.notes')?.textContent.trim())
			if (!notes) problems.push(`slide ${ids[i]} has no speaker notes`)
		}
		if (await page.evaluate(() => !!window.__deck.getCurrentSlide().querySelector('.tl'))) {
			if (!timelineIds.includes(ids[i])) timelineIds.push(ids[i])
			await checkTimeline(page, `${scheme} 1920x1080`, ids[i])
		}
		await page.screenshot({ path: `${dir}/${pad(i + 1)}-${ids[i]}.png` })
	}
	// T toggles the theme and back.
	await page.keyboard.press('t')
	const flipped = await page.evaluate(() => document.documentElement.dataset.theme)
	if (flipped === scheme) problems.push(`${scheme}: T did not toggle the theme`)
	await page.keyboard.press('t')
	if ((await page.evaluate(() => document.documentElement.dataset.theme)) !== scheme) problems.push(`${scheme}: second T did not restore the theme`)
	if ((await page.evaluate(() => localStorage.getItem('ato-deck-theme'))) !== null) problems.push(`${scheme}: theme override not cleared`)
	await context.close()
}

// The timeline at other viewport sizes (Reveal scales the canvas).
if (!timelineIds.includes('pr-3782')) problems.push('pr-3782 timeline was not found')
for (const id of timelineIds) for (const [w, h] of [[1280, 720], [1366, 768], [900, 1200], [2560, 1440]]) {
	const ctx = await newContext('light')
	const p = await ctx.newPage()
	await p.setViewportSize({ width: w, height: h })
	watch(p, `timeline ${w}x${h}`)
	await p.goto(`${docPath}?static#/${id}`)
	await ready(p)
	await checkTimeline(p, `${w}x${h}`, id)
	await ctx.close()
}

// Dark context: keyboard, overview, countdown, speaker view, deep links, transitions on.
const context = await newContext('dark')
const page = await context.newPage()
watch(page, 'deck')
await page.goto(`${docPath}?static`)
await ready(page)
await page.keyboard.press('Home')
if ((await page.evaluate(() => window.__deck.getIndices().h)) !== 0) problems.push('Home did not go to slide 1')
await page.keyboard.press('End')
await page.keyboard.press('ArrowLeft')
if ((await page.evaluate(() => window.__deck.getIndices().h)) !== ids.length - 2) problems.push('ArrowLeft did not go back')
await page.keyboard.press('o')
if (!(await page.evaluate(() => window.__deck.isOverview()))) problems.push('O did not open the overview')
await page.keyboard.press('Escape')
await page.evaluate(() => window.__deck.slide(window.__deck.getSlides().findIndex((s) => s.id === 'break')))
await page.waitForTimeout(1300)
const countdown = await page.evaluate(() => document.querySelector('[data-countdown]').value)
if (!/^7:5\d$/.test(countdown)) problems.push(`break countdown shows ${countdown}, expected 7:5x`)

// Editable timer: keyboard-reachable; S/T/F typed while editing stay in the input; Escape and blur
// cancel; invalid input is flagged and ignored; 0:05 + Enter restarts and counts down to 0:00.
{
	const timer = page.locator('section#break [data-countdown]')
	const state = () =>
		page.evaluate(() => {
			const el = document.querySelector('section#break [data-countdown]')
			return { value: el.value, remaining: Number(el.dataset.remaining), editing: el.matches('.editing'), invalid: el.matches('.invalid'), aria: el.getAttribute('aria-invalid'), focused: document.activeElement === el, theme: document.documentElement.dataset.theme, fullscreen: !!document.fullscreenElement, slide: window.__deck.getCurrentSlide().id }
		})
	const fail = (msg) => problems.push(`timer: ${msg}`)
	await page.evaluate(() => document.activeElement?.blur())
	let reached = false
	for (let i = 0; i < 12 && !reached; i++) {
		await page.keyboard.press('Tab')
		reached = (await state()).focused
	}
	if (!reached) fail('not reachable with Tab')
	const outline = await page.evaluate(() => getComputedStyle(document.querySelector('section#break [data-countdown]')).outlineColor)
	if (/rgba\(0, 0, 0, 0\)|transparent/.test(outline)) fail(`no visible focus style (outline ${outline})`)
	await page.evaluate(() => document.activeElement?.blur())

	const pagesBefore = context.pages().length
	const themeBefore = (await state()).theme
	await timer.click()
	let st = await state()
	if (!st.editing || !st.focused) fail('click did not start editing')
	await page.keyboard.type('stf')
	await page.waitForTimeout(800)
	st = await state()
	if (context.pages().length !== pagesBefore) fail('typing s opened another window (speaker view)')
	if (st.theme !== themeBefore) fail('typing t switched the theme')
	if (st.fullscreen) fail('typing f went fullscreen')
	if (st.slide !== 'break') fail(`typing moved to slide ${st.slide}`)
	if (st.value !== 'stf') fail(`typed text not in the input (value ${st.value})`)
	await page.keyboard.press('Escape')
	st = await state()
	if (st.editing || st.focused || !/^7:[45]\d$/.test(st.value) || st.slide !== 'break' || (await page.evaluate(() => window.__deck.isOverview()))) fail(`Escape did not cancel cleanly: ${JSON.stringify(st)}`)

	for (const bad of ['abc', '1:75', '0:00', '']) {
		await timer.click()
		await page.keyboard.press('ControlOrMeta+a')
		if (bad) await page.keyboard.type(bad)
		else await page.keyboard.press('Backspace')
		await page.keyboard.press('Enter')
		st = await state()
		if (!st.invalid || st.aria !== 'true' || !st.focused) fail(`invalid "${bad}" not flagged: ${JSON.stringify(st)}`)
		if (st.remaining < 400) fail(`invalid "${bad}" changed the timer (remaining ${st.remaining}s)`)
		await page.keyboard.press('Escape')
		st = await state()
		if (st.invalid || st.editing || !/^7:[0-5]\d$/.test(st.value)) fail(`Escape after invalid "${bad}" did not restore: ${JSON.stringify(st)}`)
	}

	await timer.click()
	await page.keyboard.type('1:00')
	await page.evaluate(() => document.activeElement.blur())
	st = await state()
	if (st.editing || st.value === '1:00' || st.remaining < 400) fail(`blur without Enter did not cancel: ${JSON.stringify(st)}`)

	await timer.click()
	await page.keyboard.type('2')
	await page.keyboard.press('Enter')
	st = await state()
	if (!/^(2:00|1:59)$/.test(st.value) || st.focused) fail(`plain minutes "2" did not restart at 2:00: ${JSON.stringify(st)}`)

	await timer.click()
	await page.keyboard.type('0:05')
	await page.keyboard.press('Enter')
	st = await state()
	if (!/^0:0[45]$/.test(st.value) || st.editing) fail(`0:05 + Enter did not restart: ${JSON.stringify(st)}`)
	await page.waitForTimeout(2200)
	const mid = (await state()).value
	if (!/^0:0[23]$/.test(mid)) fail(`after 2.2s the timer shows ${mid}, expected 0:02-0:03`)
	await page.waitForTimeout(3500)
	const end = (await state()).value
	if (end !== '0:00') fail(`after 5.7s the timer shows ${end}, expected 0:00`)
	timerChecks.push(`tab-reachable, s/t/f contained, escape, invalid x4, blur, "2", 0:05→${mid}→${end}`)
	// Each timer keeps its own default: re-showing the slide starts from 8:00 again.
	await page.evaluate(() => window.__deck.slide(0))
	await page.evaluate(() => window.__deck.slide(window.__deck.getSlides().findIndex((s) => s.id === 'break')))
	await page.waitForTimeout(400)
	const again = (await state()).value
	if (!/^(8:00|7:59)$/.test(again)) fail(`re-showing break started at ${again}, expected its 8:00 default`)
}

// Thesis slide: the wheel is symmetric about its vertical axis (Build's centre), the label sits at the wheel's
// optical middle (centre of the visible pills + arcs box, lifted by data-optical-lift of its height), the
// Signal card is left of the wheel and its arrow tip lands on the Build node.
for (const theme of ['light', 'dark']) for (const [w, h] of [[1920, 1080], [1440, 900], [1366, 768], [1280, 720]]) {
	const ctx = await newContext(theme)
	const p = await ctx.newPage()
	await p.setViewportSize({ width: w, height: h })
	watch(p, `thesis ${theme}`)
	await p.goto(`${docPath}?static&theme=${theme}#/thesis`)
	await ready(p)
	const r = await p.evaluate(() => {
		const sec = document.querySelector('section#thesis')
		const fly = sec.querySelector('.fly')
		const scale = fly.getBoundingClientRect().width / fly.offsetWidth
		const box = (el, pad = 0) => {
			const b = el.getBoundingClientRect()
			return { l: b.left - pad, r: b.right + pad, t: b.top - pad, b: b.bottom + pad }
		}
		const half = (el) => (parseFloat(getComputedStyle(el).strokeWidth) / 2) * scale
		const node = (n) => box(sec.querySelector(`[data-node="${n}"]`))
		const arc = (n) => { const el = sec.querySelector(`.arc-${n}`); return box(el, half(el)) }
		// Arrowheads sit at each arc's midpoint (data-at-x/y, in SVG units); compare those anchor points.
		const head = (n) => {
			const el = sec.querySelector(`.head-${n}`)
			const q = el.ownerSVGElement.createSVGPoint()
			q.x = Number(el.dataset.atX)
			q.y = Number(el.dataset.atY)
			const s = q.matrixTransform(el.getScreenCTM())
			return { l: s.x, r: s.x, t: s.y, b: s.y }
		}
		const parts = { build: node('build'), verify: node('verify'), deploy: node('deploy'), arcL: arc('left'), arcR: arc('right'), arcB: arc('bottom'), headL: head('left'), headR: head('right') }
		const vis = ['build', 'verify', 'deploy', 'arcL', 'arcR', 'arcB'].map((k) => parts[k])
		const wheel = { l: Math.min(...vis.map((b) => b.l)), r: Math.max(...vis.map((b) => b.r)), t: Math.min(...vis.map((b) => b.t)), b: Math.max(...vis.map((b) => b.b)) }
		const lift = Number(fly.dataset.opticalLift)
		const target = { x: (wheel.l + wheel.r) / 2, y: (wheel.t + wheel.b) / 2 - lift * (wheel.b - wheel.t) }
		// Label ink box: canvas text metrics on each rendered line.
		const hub = sec.querySelector('.hub')
		const cs = getComputedStyle(hub)
		const c2 = document.createElement('canvas').getContext('2d')
		c2.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`
		const lines = hub.innerText.split('\n').filter(Boolean)
		const range = document.createRange()
		range.selectNodeContents(hub)
		const rects = [...range.getClientRects()].filter((x) => x.width > 0)
		let top = Infinity, bottom = -Infinity, left = Infinity, right = -Infinity
		lines.forEach((text, i) => {
			const lr = rects[i]
			const m = c2.measureText(text)
			const fa = m.fontBoundingBoxAscent * scale, fd = m.fontBoundingBoxDescent * scale
			const baseline = lr.top + (lr.height - fa - fd) / 2 + fa
			top = Math.min(top, baseline - m.actualBoundingBoxAscent * scale)
			bottom = Math.max(bottom, baseline + m.actualBoundingBoxDescent * scale)
			const mid = lr.left + lr.width / 2, wid = (m.actualBoundingBoxLeft + m.actualBoundingBoxRight) * scale
			left = Math.min(left, mid - wid / 2)
			right = Math.max(right, mid + wid / 2)
		})
		const card = sec.querySelector('.signal').getBoundingClientRect()
		const fh = sec.querySelector('.feedhead')
		const pt = fh.ownerSVGElement.createSVGPoint()
		pt.x = Number(fh.dataset.tipX)
		pt.y = Number(fh.dataset.tipY)
		const tip = pt.matrixTransform(fh.getScreenCTM())
		return { parts, wheel, target, ink: { x: (left + right) / 2, y: (top + bottom) / 2 }, lines: lines.length, rects: rects.length, cardCx: card.left + card.width / 2, tip: { x: tip.x, y: tip.y }, axis: (parts.build.l + parts.build.r) / 2 }
	})
	const label = `thesis (${theme} ${w}x${h})`
	const fail = (msg) => problems.push(`${label}: ${msg}`)
	const mirror = (name, L, R) => {
		const d = [Math.abs((r.axis - L.l) - (R.r - r.axis)), Math.abs((r.axis - L.r) - (R.l - r.axis)), Math.abs(L.t - R.t), Math.abs(L.b - R.b)]
		if (Math.max(...d) > 2) fail(`${name} are not mirror images (off by ${Math.max(...d).toFixed(1)}px)`)
		return Math.max(...d)
	}
	const sym = Math.max(mirror('left/right arcs', r.parts.arcL, r.parts.arcR), mirror('left/right arrowhead anchors', r.parts.headL, r.parts.headR), mirror('Deploy/Verify pills', r.parts.deploy, r.parts.verify))
	const bc = (r.parts.arcB.l + r.parts.arcB.r) / 2
	if (Math.abs(bc - r.axis) > 2) fail(`bottom arc is off the axis by ${(bc - r.axis).toFixed(1)}px`)
	const ldx = r.ink.x - r.target.x, ldy = r.ink.y - r.target.y
	if (r.lines !== r.rects || Math.abs(ldx) > 2 || Math.abs(ldy) > 2) fail(`label ink centre is (${ldx.toFixed(1)}, ${ldy.toFixed(1)})px from the optical target`)
	if (!(r.cardCx < r.wheel.l)) fail(`Signal card centre x ${r.cardCx.toFixed(1)} is not left of the wheel (${r.wheel.l.toFixed(1)})`)
	const b = r.parts.build
	if (r.tip.x < b.l - 0.5 || r.tip.x > b.r + 0.5 || r.tip.y < b.t - 0.5 || r.tip.y > b.b + 0.5) fail(`Signal arrow tip (${r.tip.x.toFixed(1)}, ${r.tip.y.toFixed(1)}) is outside the Build node`)
	thesisChecks.push(`${theme}@${w}x${h} sym<=${sym.toFixed(1)} label(${ldx.toFixed(1)},${ldy.toFixed(1)})`)
	if (theme === 'light' && w === 1920) {
		const yt = await p.evaluate(() => document.querySelector('section#your-turn').innerText)
		if (/answer/i.test(yt)) problems.push('your-turn slide still tells people how to answer')
	}
	await ctx.close()
}

// Edit-mode screenshots in both themes.
for (const theme of ['light', 'dark']) {
	const ctx = await newContext(theme)
	const p = await ctx.newPage()
	watch(p, `timer ${theme}`)
	await p.goto(`${docPath}?static&theme=${theme}#/break`)
	await ready(p)
	mkdirSync(`${outDir}/timer`, { recursive: true })
	await p.locator('section#break [data-countdown]').click()
	await p.keyboard.type('5:00')
	await p.waitForTimeout(200)
	await p.screenshot({ path: `${outDir}/timer/${theme}-editing.png` })
	await p.keyboard.press('ControlOrMeta+a')
	await p.keyboard.type('5:7x')
	await p.keyboard.press('Enter')
	await p.waitForTimeout(200)
	await p.screenshot({ path: `${outDir}/timer/${theme}-invalid.png` })
	await ctx.close()
}

const prIndex = ids.indexOf('pr-3782')
await page.evaluate((i) => window.__deck.slide(i), prIndex)
const [popup] = await Promise.all([context.waitForEvent('page'), page.keyboard.press('s')])
watch(popup, 'speaker')
await popup.waitForLoadState()
try {
	await popup.waitForFunction(() => document.querySelector('.speaker-controls-notes .value')?.textContent.includes('KODY-9A'), null, { timeout: 15000 })
	const frame = popup.frames().find((f) => f.url().includes('receiver'))
	if (!frame) problems.push('speaker view: no current-slide frame')
	else {
		await frame.waitForFunction(() => window.__deck?.isReady(), null, { timeout: 15000 })
		const cur = await frame.evaluate(() => window.__deck.getCurrentSlide().id)
		if (cur !== 'pr-3782') problems.push(`speaker view current slide is ${cur}, expected pr-3782`)
	}
	await popup.waitForTimeout(800)
	await popup.screenshot({ path: `${outDir}/speaker-view.png` })
} catch (e) {
	problems.push(`speaker view did not render notes: ${e.message.split('\n')[0]}`)
}

for (const [link, want] of [['#/deploy-guard', 'health-checks'], ['#deploy-guard', 'health-checks'], ['#/backup-score', 'ladder'], ['#backup-score', 'ladder'], ['#/backup-mediarss', 'ladder'], ['#backup-mediarss', 'ladder'], ['#/feature-map', 'primitives'], ['#feature-map', 'primitives']]) {
	const p = await context.newPage()
	watch(p, 'moved id')
	await p.goto(`${docPath}?static${link}`)
	await ready(p)
	const got = await p.evaluate(() => window.__deck.getCurrentSlide().id)
	if (got !== want) problems.push(`old link ${link} opened ${got}, expected ${want}`)
	await p.close()
}
for (const gone of ['deploy-guard', 'backup-score', 'feature-map', 'backup-mediarss']) if (ids.includes(gone)) problems.push(`${gone} slide is still in the deck`)
for (const link of ['#/pr-3782', '#/pr-3765', `#${ids.at(-1)}`]) {
	const p = await context.newPage()
	watch(p, 'transitions')
	await p.goto(`${docPath}${link}`) // no ?static: transitions on
	await ready(p)
	const got = await p.evaluate(() => window.__deck.getCurrentSlide().id)
	if (got !== link.replace(/^#\/?/, '')) problems.push(`deep link ${link} opened ${got}`)
	if ((await p.evaluate(() => window.__deck.getConfig().transition)) !== 'slide') problems.push('default transition is not slide')
	await p.keyboard.press('ArrowLeft')
	await p.waitForTimeout(900)
	await p.close()
}
// Formats: the default (short talk) hides the full-day slides; ?format=full shows them and hides short-only ones.
// Every slide is checked for overflow at 1920x1080 and 1280x720 in both formats; full-day slides are screenshotted.
const overflowOf = (p) => p.evaluate(() => {
	const slide = window.__deck.getCurrentSlide()
	const box = slide.getBoundingClientRect()
	const bad = []
	for (const el of slide.querySelectorAll('*')) {
		if (el.closest('aside.notes') || el.tagName === 'STYLE') continue
		const r = el.getBoundingClientRect()
		if (!r.width && !r.height) continue
		if (r.right > box.right + 1 || r.bottom > box.bottom + 1 || r.left < box.left - 1 || r.top < box.top - 1) bad.push(`${el.tagName}.${el.className}`)
	}
	return bad.slice(0, 5)
})
const formatChecks = []
const fullIds = { full: [], short: [], hour: [], event: [] }
const formatQuery = { short: '', full: '&format=full', hour: '&format=hour', event: '&event=aie-2026' }
const formatShows = { short: ['short'], full: ['full'], hour: ['short', 'hour'], event: ['short', 'hour'] }
for (const fmt of ['short', 'full', 'hour', 'event']) for (const [w, h] of [[1920, 1080], [1280, 720]]) {
	const ctx = await newContext('dark')
	const p = await ctx.newPage()
	await p.setViewportSize({ width: w, height: h })
	watch(p, `${fmt} ${w}x${h}`)
	await p.goto(`${docPath}?static${formatQuery[fmt]}`)
	await ready(p)
	const list = await p.evaluate(() => window.__deck.getSlides().map((s) => ({ id: s.id, format: s.dataset.format ?? null, timer: !!s.querySelector('[data-countdown]'), keep: !!s.querySelector('[data-countdown-keep]') })))
	fullIds[fmt] = list.map((x) => x.id)
	const wrong = list.filter((x) => x.format && !formatShows[fmt].includes(x.format)).map((x) => x.id)
	if (wrong.length) problems.push(`${fmt}: slides from the other format are showing: ${wrong.join(', ')}`)
	if (fmt === 'full') for (const x of list.filter((x) => x.format === 'full')) if (!x.timer || !x.keep) problems.push(`full: ${x.id} has no resuming lab timer`)
	if (w === 1920 && fmt === 'full') mkdirSync(`${outDir}/full`, { recursive: true })
	for (let i = 0; i < list.length; i++) {
		await p.evaluate((i) => window.__deck.slide(i), i)
		await p.evaluate(() => window.__placeEventQr?.())
		const over = await overflowOf(p)
		if (over.length) problems.push(`${fmt} ${w}x${h} slide ${list[i].id} overflows: ${over.join(', ')}`)
		if ((fmt === 'hour' || fmt === 'event') && list[i].id !== 'title') {
			const hits = await p.evaluate(() => {
				const qr = document.querySelector('.event-qr')
				if (!qr || qr.hidden) return ['missing-corner-qr']
				const qrBox = qr.getBoundingClientRect()
				const slide = window.__deck.getCurrentSlide()
				const slideBox = slide.getBoundingClientRect()
				const area = (r) => Math.max(0, r.width) * Math.max(0, r.height)
				const overlap = (a, b) => {
					const x = Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left))
					const y = Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top))
					return x * y
				}
				const bad = []
				for (const el of slide.querySelectorAll('*')) {
					if (el.closest('aside.notes, style')) continue
					const r = el.getBoundingClientRect()
					if (r.width < 2 || r.height < 2) continue
					if (area(r) > area(slideBox) * 0.45) continue
					if (overlap(qrBox, r) > 8) bad.push(`${el.tagName}.${(el.className || '').toString().slice(0, 40)}`)
				}
				return bad.slice(0, 6)
			})
			if (hits.length) problems.push(`${fmt} ${w}x${h} slide ${list[i].id} corner QR overlaps: ${hits.join(', ')}`)
			const ticks = await p.evaluate(() => {
				const slide = window.__deck.getCurrentSlide()
				const qr = document.querySelector('.event-qr')
				const url = qr?.querySelector('.event-qr-url')
				const layers = (getComputedStyle(slide, '::after').backgroundImage.match(/linear-gradient/g) || []).length
				return { on: slide.classList.contains('event-qr-on'), layers, url: url?.textContent.trim() ?? '' }
			})
			if (!ticks.on) problems.push(`${fmt} ${w}x${h} slide ${list[i].id} is missing event-qr-on`)
			if (ticks.layers !== 6) problems.push(`${fmt} ${w}x${h} slide ${list[i].id} still has bottom-right ticks (${ticks.layers} layers)`)
			if (!ticks.url.includes('podium/aie-2026')) problems.push(`${fmt} ${w}x${h} slide ${list[i].id} corner URL is ${JSON.stringify(ticks.url)}`)
		}
		if ((fmt === 'hour' || fmt === 'event') && list[i].id === 'title') {
			const titleTicks = await p.evaluate(() => {
				const slide = window.__deck.getCurrentSlide()
				const layers = (getComputedStyle(slide, '::after').backgroundImage.match(/linear-gradient/g) || []).length
				return { on: slide.classList.contains('event-qr-on'), layers, hidden: document.querySelector('.event-qr')?.hidden ?? null }
			})
			if (titleTicks.on || titleTicks.hidden !== true) problems.push(`${fmt} ${w}x${h} title: corner QR should be hidden (on=${titleTicks.on}, hidden=${titleTicks.hidden})`)
			if (titleTicks.layers !== 8) problems.push(`${fmt} ${w}x${h} title should keep all four corner ticks (${titleTicks.layers} layers)`)
		}
		if (fmt === 'short' || fmt === 'full') {
			const visibleQr = await p.evaluate(() => {
				const qr = document.querySelector('.event-qr')
				return !!qr && !qr.hidden
			})
			if (visibleQr) problems.push(`${fmt}: corner QR visible without an event`)
		}
		if (w === 1920 && fmt === 'full' && list[i].format === 'full') await p.screenshot({ path: `${outDir}/full/${pad(i + 1)}-${list[i].id}.png` })
	}
	formatChecks.push(`${fmt}@${w}x${h}:${list.length}`)
	await ctx.close()
}
if (fullIds.event.join() !== fullIds.hour.join()) problems.push(`event: slide order differs from hour alias: ${fullIds.event.join(', ')}`)
for (const fmt of ['short', 'full']) {
	const ctx = await newContext('dark')
	const p = await ctx.newPage()
	watch(p, `${fmt} links`)
	await p.goto(`${docPath}?static${formatQuery[fmt]}`)
	await ready(p)
	const bad = await p.evaluate(() => {
		const hrefs = [...document.querySelectorAll('a')].map((a) => a.getAttribute('href') || '').filter((h) => /aie-chat|bios-chat|kody-discord|discord\.gg/i.test(h))
		const podiumOn = !!document.querySelector('.event-podium.is-on')
		const eventAttr = document.documentElement.dataset.event || ''
		return { hrefs, podiumOn, eventAttr }
	})
	if (bad.hrefs.length) problems.push(`${fmt}: discord chat links still present: ${bad.hrefs.join(', ')}`)
	if (bad.podiumOn || bad.eventAttr) problems.push(`${fmt}: event branding leaked (${bad.eventAttr}, podium=${bad.podiumOn})`)
	await ctx.close()
}
const labIds = ['lab-setup', 'lab-1', 'lab-2', 'lab-3', 'lab-4', 'show-and-tell']
for (const id of labIds) {
	if (!fullIds.full.includes(id)) problems.push(`full: ${id} missing`)
	if (fullIds.short.includes(id)) problems.push(`short: ${id} should only show with ?format=full`)
}
if (fullIds.full.includes('your-turn')) problems.push('full: your-turn should be short-only')
if (!fullIds.short.includes('your-turn')) problems.push('short: your-turn missing')
// ?event=aie-2026 (and the ?format=hour alias): the short talk minus the hidden slides, plus the
// two hour-only slides, with Your turn moved to right before the final slide. Then the event
// details: page title, event name, Podium QR, the speaker notes overrides (deck.js logs a console
// error if one doesn't match), 44px text and notes on the hour-only slides.
const hourChecks = []
{
	const hourHide = ['lineage', 'kody-what', 'agents-md', 'friction-checks', 'doors', 'control-kody', 'pr-3765', 'rollback', 'credentials', 'codebase-cleanup', 'kody-mcp', 'run-autopilot', 'qa-1', 'qa-2', 'break', 'qa-3', 'flags', 'backups']
	for (const id of hourHide) if (!fullIds.short.includes(id)) problems.push(`hour: ${id} is not a short-talk slide`)
	const expected = fullIds.short.filter((id) => !hourHide.includes(id) && id !== 'your-turn')
	expected.splice(expected.indexOf('ladder') + 1, 0, 'autopilot-what')
	expected.splice(expected.indexOf('section-3') + 1, 0, 'deploy-hour')
	expected.splice(expected.indexOf('final'), 0, 'your-turn')
	if (fullIds.hour.join() !== expected.join()) problems.push(`hour: unexpected slide order: ${fullIds.hour.join(', ')}`)
	for (const id of ['autopilot-what', 'deploy-hour']) if (fullIds.short.includes(id) || fullIds.full.includes(id)) problems.push(`${id} should only show with ?format=hour`)
	const ctx = await newContext('dark')
	const p = await ctx.newPage()
	watch(p, 'hour')
	await p.goto(`${docPath}?static&event=aie-2026`)
	await ready(p)
	await p.evaluate(() => window.__placeEventQr?.())
	const r = await p.evaluate(() => {
		const notes = (id) => document.querySelector(`section#${id} aside.notes`)?.textContent ?? ''
		const main = window.__deck.getSlides().map((s) => s.id).filter((id) => id !== 'faq' && !id.startsWith('faq-'))
		const stale = main.filter((id) => /live run|live autopilot|audit runs|back to the run|bios-chat|aie-chat|kody-discord/i.test(notes(id)))
		const podium = document.querySelector('section#title .event-podium')
		const chat = [...document.querySelectorAll('a')].map((a) => a.getAttribute('href') || '').filter((h) => /aie-chat|bios-chat|kody-discord|discord\.gg/i.test(h))
		return {
			title: document.title,
			event: document.querySelector('section#title .event').textContent,
			podiumOn: podium?.classList.contains('is-on') ?? false,
			podiumHref: podium?.querySelector('a')?.getAttribute('href') ?? '',
			podiumText: podium?.querySelector('.qrl')?.textContent ?? '',
			cornerHiddenOnTitle: document.querySelector('.event-qr')?.hidden ?? null,
			chat,
			stale,
		}
	})
	if (!r.title.endsWith('AIE Code Summit 2026')) problems.push(`event: page title is ${r.title}`)
	if (r.event !== 'AIE Code Summit 2026') problems.push(`event: title slide event is ${r.event}`)
	if (!r.podiumOn) problems.push('event: title Podium QR is not shown')
	if (r.podiumHref !== 'https://podium--kentcdodds.kody.run/aie-2026') problems.push(`event: title Podium href is ${r.podiumHref}`)
	if (r.podiumText !== 'podium--kentcdodds.kody.run/aie-2026') problems.push(`event: title Podium label is ${r.podiumText}`)
	if (r.cornerHiddenOnTitle !== true) problems.push('event: corner QR should be hidden on the title slide')
	if (r.chat.length) problems.push(`event: discord chat links still present: ${r.chat.join(', ')}`)
	if (r.stale.length) problems.push(`event: speaker notes still describe a live run or chat links on ${r.stale.join(', ')}`)
	const titleClip = await clipOf(p, 'section#title .event-podium.is-on .qr')
	if (!titleClip) problems.push('event: title Podium QR has no box to screenshot')
	else {
		const decoded = decodeQr(await p.screenshot({ clip: titleClip, type: 'png' }))
		if (decoded !== 'https://podium--kentcdodds.kody.run/aie-2026') problems.push(`event: title QR decoded to ${decoded}`)
	}
	await p.evaluate(() => window.__deck.slide(window.__deck.getSlides().findIndex((s) => s.id === 'ladder')))
	await p.evaluate(() => window.__placeEventQr?.())
	const cornerHidden = await p.evaluate(() => document.querySelector('.event-qr')?.hidden ?? true)
	if (cornerHidden) problems.push('event: corner QR missing on the ladder slide')
	else {
		const cornerClip = await clipOf(p, '.event-qr')
		const decoded = cornerClip ? decodeQr(await p.screenshot({ clip: cornerClip, type: 'png' })) : null
		if (decoded !== 'https://podium--kentcdodds.kody.run/aie-2026') problems.push(`event: corner QR decoded to ${decoded}`)
	}
	for (const id of ['autopilot-what', 'deploy-hour']) {
		await p.evaluate((id) => window.__deck.slide(window.__deck.getSlides().findIndex((s) => s.id === id)), id)
		const { small, words, notes } = await p.evaluate(() => {
			const slide = window.__deck.getCurrentSlide()
			const small = new Set()
			const walker = document.createTreeWalker(slide, NodeFilter.SHOW_TEXT)
			let text = ''
			while (walker.nextNode()) {
				const node = walker.currentNode
				const el = node.parentElement
				if (!node.textContent.trim() || el.closest('aside.notes, style, .event-qr')) continue
				text += ` ${node.textContent}`
				if (parseFloat(getComputedStyle(el).fontSize) < 43.5) small.add(`${el.tagName}.${el.className} "${node.textContent.trim().slice(0, 30)}"`)
			}
			return { small: [...small], words: text.split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length, notes: !!slide.querySelector('aside.notes')?.textContent.trim() }
		})
		if (small.length) problems.push(`hour: ${id} has text under 44px: ${small.join(', ')}`)
		if (!notes) problems.push(`hour: ${id} has no speaker notes`)
		hourChecks.push(`${id}:${words} words`)
	}
	hourChecks.unshift(`${fullIds.event.length} slides`)
	await ctx.close()
	const alias = await newContext('dark')
	const ap = await alias.newPage()
	watch(ap, 'hour alias')
	await ap.goto(`${docPath}?static&format=hour`)
	await ready(ap)
	const aliasState = await ap.evaluate(() => ({
		event: document.documentElement.dataset.event,
		format: document.documentElement.dataset.format,
		ids: window.__deck.getSlides().map((s) => s.id),
		title: document.title,
		label: document.querySelector('section#title .event')?.textContent,
	}))
	if (aliasState.event !== 'aie-2026' || aliasState.format !== 'hour') problems.push(`hour alias: data-event=${aliasState.event} data-format=${aliasState.format}`)
	if (aliasState.ids.join() !== fullIds.event.join()) problems.push('hour alias: slide order differs from ?event=aie-2026')
	if (!aliasState.title.endsWith('AIE Code Summit 2026') || aliasState.label !== 'AIE Code Summit 2026') problems.push(`hour alias: title is ${aliasState.title} / ${aliasState.label}`)
	await alias.close()
}

// Lab timers resume when their slide is shown again (the break timer restarts, checked above).
{
	const ctx = await newContext('dark')
	const p = await ctx.newPage()
	watch(p, 'lab timer')
	await p.goto(`${docPath}?static&format=full#/lab-2`)
	await ready(p)
	await p.waitForTimeout(2300)
	await p.evaluate(() => window.__deck.slide(0))
	await p.waitForTimeout(1200)
	await p.evaluate(() => window.__deck.slide(window.__deck.getSlides().findIndex((s) => s.id === 'lab-2')))
	await p.waitForTimeout(300)
	const v = await p.evaluate(() => document.querySelector('section#lab-2 [data-countdown]').value)
	if (!/^44:5[4-7]$/.test(v)) problems.push(`lab-2 timer did not resume: shows ${v}, expected about 44:56`)
	await p.reload()
	await ready(p)
	await p.waitForTimeout(300)
	const v2 = await p.evaluate(() => document.querySelector('section#lab-2 [data-countdown]').value)
	if (!/^44:5[0-6]$/.test(v2)) problems.push(`lab-2 timer did not resume after reload: shows ${v2}`)
	timerChecks.push(`lab resume ${v}, after reload ${v2}`)
	await ctx.close()
}

// FAQ: the index links to every FAQ slide, each FAQ links back, and every Questions slide (and the final slide) links to the index.
const faqChecks = []
for (const fmt of ['short', 'full', 'hour', 'event']) {
	const ctx = await newContext('light')
	const p = await ctx.newPage()
	watch(p, `faq ${fmt}`)
	await p.goto(`${docPath}?static${formatQuery[fmt]}#/faq`)
	await ready(p)
	const r = await p.evaluate(() => {
		const all = window.__deck.getSlides().map((s) => s.id)
		const faqs = all.filter((id) => id.startsWith('faq-'))
		const idx = [...document.querySelectorAll('section#faq a[href^="#/faq-"]')].map((a) => a.getAttribute('href').slice(2))
		const noBack = faqs.filter((id) => !document.querySelector(`section#${id} a[href="#/faq"]`))
		const qa = all.filter((id) => /^qa-/.test(id) || id === 'final')
		const qaNoLink = qa.filter((id) => !document.querySelector(`section#${id} a[href="#/faq"]`))
		const after = all.slice(all.indexOf('final') + 1)
		return { faqs, idx, noBack, qaNoLink, qa, atEnd: after.every((id) => id === 'faq' || id.startsWith('faq-')) && after.length === faqs.length + 1 }
	})
	if (r.faqs.length !== 12) problems.push(`${fmt}: expected 12 FAQ slides, found ${r.faqs.length}`)
	const missing = r.faqs.filter((id) => !r.idx.includes(id))
	const dead = r.idx.filter((id) => !r.faqs.includes(id))
	if (missing.length) problems.push(`${fmt}: FAQ index does not link to ${missing.join(', ')}`)
	if (dead.length) problems.push(`${fmt}: FAQ index links to missing slides ${dead.join(', ')}`)
	if (r.noBack.length) problems.push(`${fmt}: FAQ slides without a link back to the index: ${r.noBack.join(', ')}`)
	if (r.qaNoLink.length) problems.push(`${fmt}: Questions slides without a FAQ link: ${r.qaNoLink.join(', ')}`)
	if (!r.atEnd) problems.push(`${fmt}: FAQ slides are not all at the end, after final`)
	// Click through: index -> 7th FAQ -> back to the index; qa-2 -> index. The query string (format) must survive.
	await p.click('section#faq a[href="#/faq-security"]')
	await p.waitForFunction(() => window.__deck.getCurrentSlide().id === 'faq-security', null, { timeout: 3000 }).catch(() => problems.push(`${fmt}: clicking the index did not open faq-security`))
	await p.click('section#faq-security a[href="#/faq"]')
	await p.waitForFunction(() => window.__deck.getCurrentSlide().id === 'faq', null, { timeout: 3000 }).catch(() => problems.push(`${fmt}: back link did not return to the index`))
	const from = fmt === 'hour' || fmt === 'event' ? 'final' : 'qa-2'
	await p.evaluate((from) => window.__deck.slide(window.__deck.getSlides().findIndex((s) => s.id === from)), from)
	await p.click(`section#${from} a[href="#/faq"]`)
	await p.waitForFunction(() => window.__deck.getCurrentSlide().id === 'faq', null, { timeout: 3000 }).catch(() => problems.push(`${fmt}: ${from} link did not open the index`))
	const kept = await p.evaluate(() => ({ format: new URLSearchParams(location.search).get('format'), event: new URLSearchParams(location.search).get('event') }))
	if (fmt === 'full' || fmt === 'hour') {
		if (kept.format !== fmt) problems.push(`${fmt}: FAQ links dropped ?format=${fmt}`)
	}
	if (fmt === 'event' && kept.event !== 'aie-2026') problems.push(`event: FAQ links dropped ?event=aie-2026`)
	faqChecks.push(`${fmt}: ${r.faqs.length} faqs, ${r.qa.length} links in`)
	await ctx.close()
}
await browser.close()
console.log(`Format checks: ${formatChecks.join(' ')}`)
console.log(`FAQ checks: ${faqChecks.join('; ')}`)
console.log(`Hour checks: ${hourChecks.join(' ')}`)
console.log(`Words per slide: ${wordCounts.join(' ')}`)
console.log(`Thesis checks: ${thesisChecks.join(" ")}`)
console.log(`Timer checks: ${timerChecks.join(" ") || "none"}`)
console.log(`Timeline checks (${timelineChecks.length}): ${timelineChecks.join(" ")}`)
if (problems.length) {
	console.error([...new Set(problems)].join('\n'))
	process.exit(1)
}
console.log(`OK: ${ids.length} slides in light and dark, speaker view, T toggle, no network requests, no overflow. Screenshots in ${outDir}/{light,dark}/`)