Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

bento check: a headless check for the agent loop — findings by slide, a PNG per slide, a contact sheet (#487)

nyblneteeb804cabb57
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d7e89823..2e505e6d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -452,6 +452,17 @@ jobs:
# serializeAuto — so a NEW export path cannot reintroduce either.
run: node scripts/test-export-secrets.ts
+ - name: bento check rig (browser)
+ # scripts/bento-check.mjs is the closing half of an agent's loop: load
+ # a deck in headless Chrome and report what validate() finds, with
+ # element ids and paths, plus one PNG per slide through #480's render
+ # path and a contact sheet. The rig drives it as a child process on
+ # the built shell: a deck with an overflowing box and an off-canvas
+ # rect names both; --json, --png, exit codes; a compact document is
+ # refused in plain words on a shell without compact input. Self-skips
+ # only OUTSIDE CI where Chrome or the shell is missing.
+ run: node scripts/test-bento-check.ts
+
- name: Blob content-address rig
# Encrypted assets are fetched by content address from a relay the
# threat model treats as untrusted. Nothing verified that what came
diff --git a/AGENTS.md b/AGENTS.md
index f9429294..c96864ac 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -156,6 +156,27 @@ node ../scripts/test-preview.ts # first-page preview rig (encryption veto, o
node ../scripts/shell-gate.mjs dist-single/Bento_Slides.bento.html # splice conformance
```
+## Check your deck
+
+You wrote a deck; now look at it. `bento check` loads it in headless Chrome —
+the real shell, the real fonts — and tells you what the runtime would otherwise
+swallow, then hands you pictures:
+
+```sh
+node scripts/bento-check.mjs deck.bento.html # findings, by slide, with element ids
+node scripts/bento-check.mjs doc.json --png out/ # a document JSON in the built shell, + one PNG per slide
+node scripts/bento-check.mjs doc.json --json --fail-on warning # machine-readable, strict exit code
+```
+
+The loop: write the document JSON (compact where the shell accepts it) → `bento
+check --png` → read `findings` (`text-overflow` says how many px the box is
+short and on which element; `out-of-canvas`, dead links, effects that can
+never run, unknown keys the gate dropped) → look at `contact.png`, one image of
+every slide, or a single `page-NN.png` when a finding points at it → fix →
+run again. Exit 0 means no finding at or above `--fail-on` (default `error`).
+Needs Chrome (`BENTO_CHROME` to point at a binary) and the built shell
+(`cd slides && npm run build:single`, or `--shell path`).
+
## Repo layout
```
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d6a94777..37fe8d83 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,16 @@ pre-1.0.
## [Unreleased]
+- **`bento check`: an agent can look at what it wrote.** `node
+ scripts/bento-check.mjs deck.bento.html` loads the deck in headless Chrome
+ and prints what the editor would otherwise keep to itself — text that
+ overflows its box (and by how many pixels), elements off the canvas, dead
+ links, effects that can never run — by slide, with element ids; `--png out/`
+ adds one PNG per slide through the same render path as *Export slides as
+ images*, and a contact sheet of the whole deck in one picture; `--json` for
+ scripts, `--fail-on warning` for a strict exit code. A document JSON works
+ as input too, checked inside the built shell. The other half of the agent
+ loop that `AGENTS.md` describes: write, check, fix, check again.
- **A deck can be written the short way.** An AI agent writing a deck used
to spend most of its output on fields nobody chose — rotation 0, opacity 1,
the font stack, weight 400, centre, middle, line height 1.25, on every
diff --git a/scripts/bento-check.mjs b/scripts/bento-check.mjs
new file mode 100644
index 00000000..98902ac7
--- /dev/null
+++ b/scripts/bento-check.mjs
@@ -0,0 +1,319 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento check — the closing half of an agent's loop: write a deck, LOOK at it.
+//
+// node scripts/bento-check.mjs <deck.bento.html | doc.json>
+// [--shell path] [--png outdir] [--json] [--fail-on error|warning]
+//
+// Loads the deck in headless Chrome — the real shell, the real renderer, the
+// deck's own fonts — and reports what the runtime would otherwise swallow:
+// `window.bento.validate()` findings (unknown keys, text that overflows its
+// box, elements off the canvas, entrances that can never run, broken links and
+// asset refs), the load report when the input was JSON (what the gate dropped,
+// what compact expansion filled — fields a shell without #484 does not carry,
+// tolerated), and with --png one PNG per slide in show order through the same
+// render→canvas path Save ▾ Export slides as images uses (#480), plus a
+// contact sheet so an agent can look at the whole deck in one image.
+//
+// HOW IT DRIVES CHROME. The harness the sanitize and embed rigs use, reused:
+// a local http server hands Chrome the deck with a probe module appended and
+// a load gate (an <img> the server answers only once the probe has POSTed its
+// report), Chrome runs `--headless=new --dump-dom` and exits at load. No
+// puppeteer, no CDP client, no new dependency — system Chrome via the same
+// BENTO_CHROME lookup the rigs share. The probe is bundled by esbuild against
+// the repo's own sources, so the pixels are the shipping code path.
+//
+// INPUT. A .bento.html is used as-is (it IS shell + document). A .json is a
+// document — full, or compact once the shell accepts `"compact": true` — and
+// is handed to `window.bento.loadDoc()` inside a shell: --shell, else
+// slides/dist-single/Bento_Slides.bento.html (build it with
+// `cd slides && npm run build:single`).
+
+import { spawn, spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import http from 'node:http'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
+
+// ---- args -------------------------------------------------------------------
+const argv = process.argv.slice(2)
+const opt = (name) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined }
+const flag = (name) => argv.includes(name)
+const input = argv.find((a, i) => !a.startsWith('--') && !['--shell', '--png', '--fail-on'].includes(argv[i - 1]))
+const asJson = flag('--json')
+const pngDir = opt('--png')
+const failOn = opt('--fail-on') ?? 'error'
+const shellPath = opt('--shell') ?? path.join(root, 'slides/dist-single/Bento_Slides.bento.html')
+
+const die = (msg, code = 2) => { console.error(`bento check: ${msg}`); process.exit(code) }
+if (!input) die('usage: node scripts/bento-check.mjs <deck.bento.html | doc.json> [--shell path] [--png outdir] [--json] [--fail-on error|warning]')
+if (!['error', 'warning'].includes(failOn)) die(`--fail-on takes error or warning, not "${failOn}"`)
+if (!fs.existsSync(input)) die(`no such file: ${input}`)
+
+// ---- Chrome — the rigs' lookup ------------------------------------------------
+const findChrome = () => [
+ process.env.BENTO_CHROME,
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
+ '/usr/bin/google-chrome',
+ '/usr/bin/google-chrome-stable',
+ '/usr/bin/chromium',
+ '/usr/bin/chromium-browser',
+].find((p) => !!p && fs.existsSync(p))
+ ?? (spawnSync('which', ['google-chrome']).status === 0 ? 'google-chrome' : undefined)
+const chrome = findChrome()
+if (!chrome) die('no Chrome found — install Google Chrome or set BENTO_CHROME to a binary')
+
+// ---- input → the html Chrome will load + the JSON the probe will load --------
+const isHtml = /\.html?$/i.test(input)
+let deckHtml
+let docJson = null
+if (isHtml) {
+ deckHtml = fs.readFileSync(input, 'utf8')
+} else {
+ if (!fs.existsSync(shellPath)) die(`no shell at ${shellPath} — run \`cd slides && npm run build:single\`, or pass --shell`)
+ deckHtml = fs.readFileSync(shellPath, 'utf8')
+ docJson = fs.readFileSync(input, 'utf8')
+ try { JSON.parse(docJson) } catch (e) { die(`${input} is not JSON: ${e.message}`) }
+}
+if (!deckHtml.includes('id="bento-doc"')) die(`${isHtml ? input : shellPath} carries no #bento-doc block — not a Bento file`)
+
+// ---- the probe, bundled against the repo's own sources ----------------------
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-check-'))
+const esbuild = path.join(root, 'slides/node_modules/.bin/esbuild')
+if (!fs.existsSync(esbuild)) die('slides/node_modules is missing — run `cd slides && npm install`')
+const exportImagesPath = path.join(root, 'slides/src/editor/exportimages.ts')
+const exportDecisionsPath = path.join(root, 'slides/src/exportimages.ts')
+
+// Written by concatenation: never a literal script-close in a source file.
+const probeSrc = `
+import { rasterizeSlide } from ${JSON.stringify(exportImagesPath)}
+import { exportableSlides, pixelSize } from ${JSON.stringify(exportDecisionsPath)}
+
+const WANT_PNG = ${JSON.stringify(!!pngDir)}
+const DOC_JSON = ${JSON.stringify(docJson)}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+const post = (body) => fetch('/report', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
+
+async function main() {
+ const t0 = performance.now()
+ let bento
+ for (let i = 0; i < 600 && !(bento = window.bento?.doc && window.bento); i++) await sleep(50)
+ if (!bento) return post({ fatal: 'the shell did not boot (window.bento never appeared)' })
+ if (document.fonts?.ready) await document.fonts.ready
+
+ let load = null
+ if (DOC_JSON !== null) {
+ // A compact document on a shell that predates compact input (#484) is not
+ // refused by the gate — it is accepted and then the editor throws on the
+ // first missing field. Say so before that happens.
+ let parsed = null
+ try { parsed = JSON.parse(DOC_JSON) } catch {}
+ if (parsed && parsed.compact === true && typeof bento.compact !== 'function') {
+ return post({ fatal: 'this shell does not accept compact documents ("compact": true needs a shell built with #484 — window.bento.compact is absent); pass a full document, or --shell a newer build' })
+ }
+ let r
+ try { r = bento.loadDoc(DOC_JSON) } catch (e) { return post({ fatal: 'the shell threw while loading the document: ' + String(e && e.message || e) }) }
+ if (r === false) return post({ fatal: 'the shell refused the document: loadDoc() returned false (not valid bento/slides JSON, or a compact document on a shell without #484)' })
+ load = r && typeof r === 'object' ? r : { ok: true }
+ await sleep(50)
+ }
+ const doc = bento.doc
+ const v = bento.validate()
+ const pages = []
+ let contact = null
+ const shown = exportableSlides(doc)
+ if (WANT_PNG) {
+ const thumbs = []
+ for (const slide of shown) {
+ const blob = await rasterizeSlide(doc, slide, 'png', 1)
+ const url = await new Promise((res) => { const fr = new FileReader(); fr.onload = () => res(fr.result); fr.readAsDataURL(blob) })
+ pages.push(url)
+ thumbs.push(url)
+ }
+ // contact sheet: up to 4 across, 320 px wide each, the deck's aspect
+ const { width: w, height: h } = doc.size
+ const tw = 320, th = Math.round(320 * h / w), gap = 12, cols = Math.min(4, Math.max(1, thumbs.length))
+ const rows = Math.ceil(thumbs.length / cols)
+ const c = document.createElement('canvas')
+ c.width = cols * tw + (cols + 1) * gap
+ c.height = rows * (th + 22) + (rows + 1) * gap
+ const ctx = c.getContext('2d')
+ ctx.fillStyle = '#e9ecef'; ctx.fillRect(0, 0, c.width, c.height)
+ ctx.fillStyle = '#334'; ctx.font = '12px system-ui, sans-serif'
+ for (let i = 0; i < thumbs.length; i++) {
+ const img = new Image(); img.src = thumbs[i]; await img.decode()
+ const x = gap + (i % cols) * (tw + gap), y = gap + Math.floor(i / cols) * (th + 22 + gap)
+ ctx.drawImage(img, x, y, tw, th)
+ ctx.fillText(String(i + 1).padStart(2, '0'), x, y + th + 15)
+ }
+ contact = c.toDataURL('image/png')
+ }
+ return post({
+ ok: v.ok,
+ title: doc.title,
+ size: doc.size,
+ slides: doc.slides.length,
+ shown: shown.length,
+ pixel: pixelSize(doc, 1),
+ counts: v.counts,
+ measured: v.measured,
+ findings: v.findings,
+ load,
+ pages,
+ contact,
+ ms: Math.round(performance.now() - t0),
+ })
+}
+main().catch((e) => post({ fatal: String(e && e.stack || e) }))
+`
+fs.writeFileSync(path.join(tmp, 'probe-entry.js'), probeSrc)
+const built = spawnSync(esbuild, [
+ path.join(tmp, 'probe-entry.js'), '--bundle', '--format=esm', '--log-level=error',
+ '--outfile=' + path.join(tmp, 'probe.js'),
+], { stdio: ['ignore', 'pipe', 'pipe'] })
+if (built.status !== 0) die(`could not bundle the probe:\n${built.stderr}`)
+const probe = fs.readFileSync(path.join(tmp, 'probe.js'), 'utf8')
+
+// The deck, with the probe appended and the load gate after it. The gate is
+// load-bearing (see test-sanitize): the new headless fires --dump-dom at the
+// load event, so the page must not finish loading until the report is in.
+const page = deckHtml +
+ '\n<scr' + 'ipt type="module" src="/probe.js"></scr' + 'ipt>' +
+ '<img src="/gate.gif" width="1" height="1" alt="">'
+
+// ---- serve, run, collect -------------------------------------------------------
+const started = Date.now()
+let report = null
+let releaseGate = null
+let child = null
+const gif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==', 'base64')
+const dbg = (...a) => { if (process.env.BENTO_CHECK_DEBUG) console.error(`[${Date.now() - started} ms]`, ...a) }
+const server = http.createServer((req, res) => {
+ const url = (req.url ?? '/').split('?')[0]
+ dbg(req.method, url)
+ if (url === '/deck.html') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page); return }
+ if (url === '/probe.js') { res.writeHead(200, { 'content-type': 'text/javascript' }); res.end(probe); return }
+ if (url === '/report' && req.method === 'POST') {
+ let body = ''
+ req.on('data', (b) => { body += b })
+ req.on('end', () => {
+ try { report = JSON.parse(body) } catch { report = { fatal: 'the probe posted something that was not JSON' } }
+ res.writeHead(204); res.end()
+ dbg('report received', releaseGate ? '(gate waiting → released)' : '(gate not yet requested)')
+ releaseGate?.()
+ // The report is the deliverable, not the dump: the shell keeps the page
+ // busy past load (measured: Chrome sat 88 s after the gate opened), so
+ // Chrome is closed the moment the report is in.
+ setTimeout(() => child?.kill('SIGTERM'), 100)
+ })
+ return
+ }
+ if (url === '/gate.gif') {
+ const send = () => { res.writeHead(200, { 'content-type': 'image/gif' }); res.end(gif) }
+ if (report) send(); else releaseGate = send
+ return
+ }
+ res.writeHead(404); res.end()
+})
+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
+const port = server.address().port
+
+// spawn, never spawnSync: the server lives in this process.
+child = spawn(chrome, [
+ '--headless=new', '--disable-gpu', '--no-sandbox', '--no-first-run',
+ '--no-default-browser-check', '--disable-background-networking',
+ '--disable-component-update', '--disable-sync', '--disable-default-apps',
+ '--hide-scrollbars', '--window-size=1600,1000',
+ '--user-data-dir=' + path.join(tmp, 'profile'),
+ '--dump-dom', `http://127.0.0.1:${port}/deck.html`,
+], { stdio: ['ignore', 'ignore', 'ignore'] })
+const TIMEOUT = 90_000
+await new Promise((resolve) => {
+ const timer = setTimeout(() => { report ??= { fatal: `no report within ${TIMEOUT / 1000}s — the shell did not boot, or Chrome hung` }; child.kill('SIGKILL') }, TIMEOUT)
+ child.on('close', (code) => { dbg('chrome exited', code); clearTimeout(timer); resolve() })
+})
+server.close()
+fs.rmSync(tmp, { recursive: true, force: true })
+const wall = Date.now() - started
+
+if (!report) report = { fatal: 'Chrome exited before the probe reported' }
+if (report.fatal) {
+ if (asJson) console.log(JSON.stringify({ ok: false, fatal: report.fatal, ms: wall }, null, 2))
+ else console.error(`bento check: ${report.fatal}`)
+ process.exit(2)
+}
+
+// ---- files ------------------------------------------------------------------------
+const written = []
+if (pngDir) {
+ fs.mkdirSync(pngDir, { recursive: true })
+ const toFile = (dataUrl, name) => {
+ const p = path.join(pngDir, name)
+ fs.writeFileSync(p, Buffer.from(dataUrl.slice(dataUrl.indexOf(',') + 1), 'base64'))
+ written.push(p)
+ }
+ report.pages.forEach((u, i) => toFile(u, `page-${String(i + 1).padStart(2, '0')}.png`))
+ if (report.contact) toFile(report.contact, 'contact.png')
+}
+
+// ---- the report ----------------------------------------------------------------------
+const findings = report.findings ?? []
+const overflow = findings.filter((f) => f.code === 'text-overflow')
+const dropped = report.load?.dropped ?? []
+const errors = findings.filter((f) => f.severity === 'error').length
+const warnings = findings.filter((f) => f.severity === 'warning').length
+const failed = failOn === 'error' ? errors > 0 : errors + warnings > 0
+const out = {
+ ok: !failed,
+ file: input,
+ title: report.title,
+ slides: report.slides,
+ shown: report.shown,
+ counts: report.counts,
+ measured: report.measured,
+ findings,
+ overflow,
+ dropped,
+ expanded: report.load?.expanded ?? null,
+ pages: written.filter((p) => !p.endsWith('contact.png')),
+ contact: written.find((p) => p.endsWith('contact.png')) ?? null,
+ ms: wall,
+}
+
+if (asJson) {
+ console.log(JSON.stringify(out, null, 2))
+} else {
+ console.log(`bento check — ${report.title ?? input}`)
+ console.log(` ${report.slides} slides (${report.shown} shown), ${errors} error${errors === 1 ? '' : 's'}, ${warnings} warning${warnings === 1 ? '' : 's'}${report.measured === false ? ' (text not measured: no layout)' : ''}, ${wall} ms`)
+ if (dropped.length) {
+ console.log(`\n dropped on load (${dropped.length}):`)
+ for (const d of dropped) console.log(` ${d.path} ${d.reason}`)
+ }
+ if (out.expanded) console.log(` compact expansion filled ${out.expanded} field${out.expanded === 1 ? '' : 's'}`)
+ const bySlide = new Map()
+ for (const f of findings) {
+ const k = f.slide ?? '(document)'
+ if (!bySlide.has(k)) bySlide.set(k, [])
+ bySlide.get(k).push(f)
+ }
+ for (const [slide, list] of bySlide) {
+ console.log(`\n ${slide}`)
+ for (const f of list) {
+ const where = f.element ? ` [${f.element}]` : ''
+ const at = f.path ? ` (${f.path})` : ''
+ console.log(` ${f.severity.padEnd(7)} ${f.code}${where}: ${f.message}${at}`)
+ }
+ }
+ if (written.length) {
+ console.log(`\n images: ${out.pages.length} page${out.pages.length === 1 ? '' : 's'} in ${pngDir}${out.contact ? ' + contact.png' : ''}`)
+ }
+ console.log(`\n${out.ok ? 'OK' : 'FAILED'} (--fail-on ${failOn})`)
+}
+process.exit(out.ok ? 0 : 1)
diff --git a/scripts/test-bento-check.ts b/scripts/test-bento-check.ts
new file mode 100644
index 00000000..f89f8159
--- /dev/null
+++ b/scripts/test-bento-check.ts
@@ -0,0 +1,163 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento check rig: drives scripts/bento-check.mjs as a child process against
+// the built shell, the way an agent would.
+//
+// node scripts/test-bento-check.ts
+//
+// WHAT THIS PROVES. The CLI loads a real deck in headless Chrome and reports
+// what validate() finds, with element ids and paths; a deck with an off-canvas
+// element and an overflowing text box names both; --json parses and carries
+// the same findings; --png writes one PNG per shown slide at the deck's pixel
+// size plus a contact sheet; exit codes follow --fail-on; a compact document
+// loads, expands and reports what was filled and dropped (#484/#490) rather
+// than a stack trace. A browser rig: it needs Chrome and the built shell, and
+// SKIPS (with the reason printed) where either is missing locally — in CI
+// both exist and a skip is a failure.
+
+import { execFileSync, spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..')
+const cli = path.join(root, 'scripts/bento-check.mjs')
+const shell = path.join(root, 'slides/dist-single/Bento_Slides.bento.html')
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const CHROME = [
+ process.env.BENTO_CHROME,
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
+ '/usr/bin/google-chrome',
+ '/usr/bin/google-chrome-stable',
+ '/usr/bin/chromium',
+ '/usr/bin/chromium-browser',
+].find((p): p is string => !!p && fs.existsSync(p))
+ ?? (spawnSync('which', ['google-chrome']).status === 0 ? 'google-chrome' : undefined)
+
+const inCI = !!process.env.CI || !!process.env.GITHUB_ACTIONS
+if (!CHROME || !fs.existsSync(shell)) {
+ const why = !CHROME ? 'no Chrome found (set BENTO_CHROME)' : `no built shell at ${shell} (cd slides && npm run build:single)`
+ if (inCI) { console.log(` FAIL ${why} — a browser rig cannot skip in CI`); process.exit(1) }
+ console.log(` ⚠ SKIPPED — ${why}`)
+ process.exit(0)
+}
+
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-check-rig-'))
+const run = (args: string[]) => {
+ const r = spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8', timeout: 120_000 })
+ return { code: r.status, out: r.stdout, err: r.stderr }
+}
+const write = (name: string, obj: unknown) => { const p = path.join(tmp, name); fs.writeFileSync(p, JSON.stringify(obj)); return p }
+
+// a full document with the two mistakes an agent makes most
+const full = {
+ format: 'bento/slides', version: 1, title: 'Check me', size: { width: 1280, height: 720 },
+ theme: { background: '#0f1724', color: '#fff', accent: '#f7a600', fontFamily: 'system-ui, sans-serif' },
+ slides: [
+ { id: 's1', background: '#0f1724', transition: 'fade', notes: '', elements: [
+ { id: 't1', type: 'text', x: 96, y: 80, w: 600, h: 40, rotation: 0, opacity: 1,
+ html: 'This is a paragraph of text that is far too long for a box that is only forty pixels tall, so it overflows by several lines.',
+ fontSize: 32, fontFamily: 'system-ui, sans-serif', fontWeight: 400, color: '#fff', align: 'left', valign: 'top', lineHeight: 1.3 },
+ { id: 'r1', type: 'shape', shape: 'rect', x: 1200, y: 600, w: 300, h: 300, rotation: 0, opacity: 1, fill: '#f7a600', stroke: 'none', strokeWidth: 0 },
+ ] },
+ { id: 's2', background: '#0f1724', transition: 'fade', notes: '', hidden: true, elements: [] },
+ { id: 's3', background: '#0f1724', transition: 'fade', notes: '', stateOf: 's1', elements: [] },
+ ],
+}
+
+console.log('the starter deck\n')
+const t0 = Date.now()
+const starter = run([shell, '--json'])
+const starterMs = Date.now() - t0
+ok(starter.code === 0, `exits 0 on the starter deck with --fail-on error (exit ${starter.code})`)
+let sj: any = null
+try { sj = JSON.parse(starter.out) } catch {}
+ok(!!sj && sj.ok === true && Array.isArray(sj.findings), '--json parses into { ok, findings, … }')
+ok(sj?.slides === 19 && sj?.shown === 15, `19 slides, 15 shown — states and hidden slides excluded (${sj?.slides}/${sj?.shown})`)
+ok(sj?.counts?.error === 0, `the starter deck has no errors (${sj?.counts?.error})`)
+// its known warnings: the showcase's deliberate bleeds and a few tight boxes —
+// pinned by kind, not count, so a starter-deck edit does not fail this rig
+ok((sj?.findings ?? []).every((f: any) => ['text-overflow', 'out-of-canvas', 'collab-secrets-present', 'font-not-embedded'].includes(f.code) || f.severity !== 'warning'),
+ 'every starter-deck warning is a known kind (text-overflow / out-of-canvas)')
+ok(sj?.measured === true, 'text was measured (the shell had layout)')
+ok(starterMs < 30_000, `the whole run took ${starterMs} ms (budget: a 30-slide deck under 15 s; this one has 19)`)
+
+console.log('\na deck with mistakes\n')
+const p = write('full.json', full)
+const r = run([p, '--json', '--fail-on', 'warning'])
+let j: any = null
+try { j = JSON.parse(r.out) } catch {}
+ok(r.code === 1, `--fail-on warning exits 1 when there is a warning (exit ${r.code})`)
+ok(!!j && j.ok === false, 'the JSON says ok: false')
+const over = (j?.findings ?? []).find((f: any) => f.code === 'text-overflow' && f.element === 't1')
+ok(!!over && /needs (\d+)px/.test(over.message), `the overflowing text box is named with the px it needs: ${over?.message?.slice(0, 60)}…`)
+ok((j?.overflow ?? []).length === 1 && j.overflow[0].element === 't1', 'overflow is surfaced as its own list')
+const off = (j?.findings ?? []).find((f: any) => f.code === 'out-of-canvas' && f.element === 'r1')
+ok(!!off, 'the off-canvas rect is named')
+ok(over?.slide === 's1' && off?.slide === 's1', 'both carry the slide id')
+ok(j?.shown === 1 && j?.slides === 3, 'the hidden slide and the state slide are not shown')
+const r2 = run([p, '--fail-on', 'error'])
+ok(r2.code === 0, `the same deck exits 0 with --fail-on error (warnings only) (exit ${r2.code})`)
+ok(/warning text-overflow \[t1\]/.test(r2.out) && /out-of-canvas \[r1\]/.test(r2.out), 'the human summary lists both with their ids')
+
+console.log('\nimages\n')
+const outDir = path.join(tmp, 'png')
+const r3 = run([p, '--png', outDir, '--json'])
+let j3: any = null
+try { j3 = JSON.parse(r3.out) } catch {}
+ok(fs.existsSync(path.join(outDir, 'page-01.png')) && !fs.existsSync(path.join(outDir, 'page-02.png')), 'one PNG per SHOWN slide (page-01 only: s2 hidden, s3 a state)')
+ok(fs.existsSync(path.join(outDir, 'contact.png')), 'a contact sheet is written')
+const png = fs.readFileSync(path.join(outDir, 'page-01.png'))
+const dims = (b: Buffer) => ({ w: b.readUInt32BE(16), h: b.readUInt32BE(20) })
+ok(png.subarray(1, 4).toString() === 'PNG' && dims(png).w === 1280 && dims(png).h === 720, `page-01.png is a 1280×720 PNG (${JSON.stringify(dims(png))})`)
+const contact = fs.readFileSync(path.join(outDir, 'contact.png'))
+ok(dims(contact).w > 300 && dims(contact).h > 150, `contact.png has real dimensions (${JSON.stringify(dims(contact))})`)
+ok(Array.isArray(j3?.pages) && j3.pages.length === 1 && j3.contact?.endsWith('contact.png'), 'the JSON lists the page paths and the contact sheet')
+// not blank: a PNG of a dark slide with orange and white ink is not one colour
+ok(png.length > 5_000, `the page is not a blank image (${png.length} bytes)`)
+
+console.log('\ncompact input\n')
+const c = write('compact.json', { compact: true, format: 'bento/slides', version: 1, title: 'C', slides: [{ id: 's1', elements: [{ id: 't1', type: 'text', x: 96, y: 80, w: 600, h: 80, html: 'Hi', fontSize: 32 }] }] })
+const r4 = run([c, '--json'])
+let j4: any = null
+try { j4 = JSON.parse(r4.out) } catch {}
+// Since #484 every shell accepts compact input: the doc loads, expands, and
+// the report says how much was filled and that nothing was dropped. (The
+// earlier case pinned the pre-#484 world by sniffing the shell for a plaintext
+// marker — which the deflated shell never carries — and went stale the day
+// #484 landed. The plain-words refusal on an older shell stays in the CLI but
+// is not rigged: building a pre-#484 shell here is not cheap.)
+ok(r4.code === 0 && j4?.ok === true && j4.slides === 1, `a compact document loads and checks clean (exit ${r4.code})`)
+ok(typeof j4?.expanded === 'number' && j4.expanded > 0, `compact expansion filled fields (${j4?.expanded})`)
+ok(Array.isArray(j4?.dropped) && j4.dropped.length === 0, 'nothing was dropped by the gate')
+// the checked-in agent decks (#490) go through the same path
+const agentDir = path.join(root, 'scripts/fixtures/agent-decks')
+for (const f of fs.readdirSync(agentDir).filter((f) => f.endsWith('.json')).sort()) {
+ const r = run([path.join(agentDir, f), '--json'])
+ let j: any = null
+ try { j = JSON.parse(r.out) } catch {}
+ ok(r.code === 0 && j?.ok === true && j.dropped?.length === 0 && j.expanded > 0, `agent deck ${f}: loads, ${j?.expanded ?? '?'} fields filled, zero drops (exit ${r.code})`)
+}
+
+console.log('\nerrors are exits, not traces\n')
+ok(run(['/nonexistent.json']).code === 2, 'a missing file exits 2')
+const bad = write('bad.json', { hello: 'world' })
+const r5 = run([bad, '--json'])
+ok(r5.code === 2, `a non-deck JSON exits 2 (exit ${r5.code})`)
+ok(run([p, '--fail-on', 'maybe']).code === 2, 'an unknown --fail-on value exits 2')
+ok(fs.readFileSync(cli, 'utf8').includes("rasterizeSlide") && fs.readFileSync(cli, 'utf8').includes('editor/exportimages.ts'), 'pixels come from #480\'s rasterizeSlide, not a second renderer')
+
+fs.rmSync(tmp, { recursive: true, force: true })
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)