Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(ui-review): give the visual sweep the same routes as the DOM audit

nirholas90f24a5a8d1e
diff --git a/package.json b/package.json
index 4a6655797..5fdde471e 100644
--- a/package.json
+++ b/package.json
@@ -229,6 +229,8 @@
"audit:garments": "node scripts/audit-garments.mjs",
"audit:web:login": "node scripts/page-audit.mjs --login",
"audit:web:provision": "node scripts/provision-audit-account.mjs",
+ "snapshot:authed": "node scripts/page-snapshot.mjs --authed",
+ "ui:review": "node scripts/ui-review.mjs",
"logs": "node scripts/gcp-logs.mjs",
"logs:tail": "node scripts/gcp-logs.mjs --follow",
"gpu": "node scripts/gpu-capacity.mjs",
diff --git a/scripts/lib/audit-routes.mjs b/scripts/lib/audit-routes.mjs
new file mode 100644
index 000000000..a4b017dee
--- /dev/null
+++ b/scripts/lib/audit-routes.mjs
@@ -0,0 +1,117 @@
+/**
+ * audit-routes.mjs — the one route list every browser sweep works from.
+ *
+ * page-audit (console/network/layout findings) and page-snapshot (the visual
+ * record) both have to answer the same question: what pages does this site
+ * have? They answered it separately, which meant the authenticated route list
+ * existed only inside page-audit, and the visual sweep could never see a
+ * dashboard page. This module is that answer, once.
+ *
+ * Sources, in order of authority:
+ * 1. data/pages.json — the manifest that also drives /sitemap, llms.txt and
+ * the changelog. Every public, user-discoverable page.
+ * 2. AUTHED_ROUTES — signed-in pages the manifest intentionally omits
+ * (dashboard sub-pages that are not marketing surfaces).
+ * 3. seedDynamicRoutes() — parameterised routes filled with REAL ids read
+ * from the live API at run time, never placeholders.
+ */
+import { readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
+
+// Machine-readable endpoints (.xml/.txt/.json/...) have no DOM to audit.
+export const isHtmlRoute = (path) => !/\.[a-z0-9]+$/i.test(path) || /\.html$/i.test(path);
+
+/**
+ * Pages from data/pages.json.
+ *
+ * @param {object} [opts]
+ * @param {'public'|'authed'|'all'} [opts.access] which pages to include; the
+ * manifest flags a signed-in page with `auth` (true or "required").
+ * @returns {{path:string,title:string,section:string,auth:string|boolean|null}[]}
+ */
+export function manifestPages({ access = 'public' } = {}) {
+ const pages = JSON.parse(readFileSync(resolve(ROOT, 'data/pages.json'), 'utf8'));
+ const out = [];
+ const seen = new Set();
+ for (const s of pages.sections || []) {
+ // `machine` section = non-HTML endpoints (.xml/.txt/.json/.well-known);
+ // no DOM, no console. Not part of a browser sweep.
+ if (s.id === 'machine') continue;
+ for (const p of s.pages || []) {
+ const path = p.path;
+ if (!path || !path.startsWith('/') || /[:*]/.test(path)) continue;
+ if (!isHtmlRoute(path)) continue;
+ if (path.startsWith('/.well-known')) continue;
+ if (seen.has(path)) continue;
+ const authed = Boolean(p.auth);
+ if (access === 'public' && authed) continue;
+ if (access === 'authed' && !authed) continue;
+ seen.add(path);
+ out.push({ path, title: p.title || path, section: s.title || s.id, auth: p.auth || null });
+ }
+ }
+ return out;
+}
+
+/** Just the paths, for callers that do not need the metadata. */
+export function manifestRoutes(opts) {
+ return manifestPages(opts).map((p) => p.path);
+}
+
+// Authenticated routes the manifest omits: dashboard sub-pages and account
+// surfaces that are product, not marketing, so they never belonged in the
+// public page index. A sweep with a session replays these too.
+export const AUTHED_ROUTES = [
+ '/dashboard',
+ '/dashboard/actions',
+ '/dashboard/sessions',
+ '/dashboard/analytics',
+ '/dashboard/wallets',
+ '/dashboard/settings',
+ '/dashboard/memory',
+ '/dashboard/strategy',
+ '/dashboard/voice',
+ '/dashboard/sns',
+ '/dashboard/delegation',
+ '/dashboard/embed-policy',
+ '/dashboard/agent-pumpfun',
+ '/dashboard/x402',
+ '/dashboard/portfolio',
+ '/profile',
+ '/settings',
+ '/my-agents',
+ '/dashboard/developers',
+];
+
+/**
+ * Parameterised routes filled with real ids from the live API.
+ * @param {import('playwright').BrowserContext} ctx a context whose `request`
+ * can reach `baseUrl` (it carries the session when there is one).
+ */
+export async function seedDynamicRoutes(ctx, baseUrl) {
+ const routes = [];
+ try {
+ const res = await ctx.request.get(`${baseUrl}/api/explore?limit=5`, { timeout: 15000 });
+ if (res.ok()) {
+ const body = await res.json();
+ const items = body.items || body.agents || [];
+ const onchain = items.find((i) => i.agentId && i.chainId);
+ if (onchain) {
+ routes.push(`/a/${onchain.chainId}/${onchain.agentId}`);
+ routes.push(`/agent/${onchain.chainId}:${onchain.agentId}`);
+ }
+ }
+ } catch {
+ /* live API unreachable — dynamic routes simply skipped */
+ }
+ return routes;
+}
+
+/** '/' → 'home', '/docs/api' → 'docs-api'. Filesystem-safe, stable across runs. */
+export function slugFor(path) {
+ if (path === '/') return 'home';
+ return path.replace(/^\//, '').replace(/\/$/, '').replace(/[^a-zA-Z0-9._-]+/g, '-') || 'home';
+}
diff --git a/scripts/page-audit.mjs b/scripts/page-audit.mjs
index 4a23c240f..b48eed1b2 100644
--- a/scripts/page-audit.mjs
+++ b/scripts/page-audit.mjs
@@ -50,6 +50,12 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { config as dotenv } from 'dotenv';
+import {
+ AUTHED_ROUTES,
+ isHtmlRoute,
+ manifestRoutes,
+ seedDynamicRoutes,
+} from './lib/audit-routes.mjs';
// The QA credentials live in .env, so `npm run audit:web:login` has to read it:
// without this the script only ever saw an inline-prefixed environment and told
@@ -128,83 +134,16 @@ const ignorePatterns = IS_LOCAL ? [...ALWAYS_IGNORE, ...LOCAL_ONLY_IGNORE] : ALW
const shouldIgnore = (text) => ignorePatterns.some((re) => re.test(text || ''));
// ── Route discovery ───────────────────────────────────────────────────────────
-// Public, user-discoverable pages come straight from the manifest that already
-// drives /sitemap, llms.txt and the changelog — the single source of truth.
-function manifestRoutes() {
- try {
- const pages = JSON.parse(readFileSync(resolve(ROOT, 'data/pages.json'), 'utf8'));
- const out = [];
- for (const s of pages.sections || []) {
- // `machine` section = non-HTML endpoints (.xml/.txt/.json/.well-known);
- // no DOM, no console. Not part of a browser sweep.
- if (s.id === 'machine') continue;
- for (const p of s.pages || []) {
- if (!p.path || !p.path.startsWith('/') || /[:*]/.test(p.path)) continue;
- // Skip anything that resolves to a static file rather than an HTML page.
- if (!isHtmlRoute(p.path)) continue;
- out.push(p.path);
- }
- }
- return out;
- } catch {
- return [];
- }
-}
-
-// Authenticated and parameterised routes the manifest intentionally omits.
-// Dynamic params are filled with REAL ids fetched from the live API at runtime
-// (see seedDynamicRoutes) — never placeholders.
-const STATIC_AUTHED_ROUTES = [
- '/dashboard',
- '/dashboard/actions',
- '/dashboard/sessions',
- '/dashboard/analytics',
- '/dashboard/wallets',
- '/dashboard/settings',
- '/dashboard/memory',
- '/dashboard/strategy',
- '/dashboard/voice',
- '/dashboard/sns',
- '/dashboard/delegation',
- '/dashboard/embed-policy',
- '/dashboard/agent-pumpfun',
- '/dashboard/x402',
- '/dashboard/portfolio',
- '/profile',
- '/settings',
- '/my-agents',
- '/dashboard/developers',
-];
-
-async function seedDynamicRoutes(ctx) {
- const routes = [];
- try {
- const res = await ctx.request.get(`${BASE_URL}/api/explore?limit=5`, { timeout: 15000 });
- if (res.ok()) {
- const body = await res.json();
- const items = body.items || body.agents || [];
- const onchain = items.find((i) => i.agentId && i.chainId);
- if (onchain) {
- routes.push(`/a/${onchain.chainId}/${onchain.agentId}`);
- routes.push(`/agent/${onchain.chainId}:${onchain.agentId}`);
- }
- }
- } catch {
- /* live API unreachable — dynamic routes simply skipped */
- }
- return routes;
-}
-
-// Machine-readable endpoints (.xml/.txt/.json/...) have no DOM to audit.
-const isHtmlRoute = (path) => !/\.[a-z0-9]+$/i.test(path) || /\.html$/i.test(path);
-
+// Public pages, the authenticated route list and the dynamic-id seeder all come
+// from scripts/lib/audit-routes.mjs, shared with the visual sweep so the two
+// can never disagree about what pages exist.
function buildRouteList(dynamic) {
if (explicitRoutes.length) {
const skipped = explicitRoutes.filter((r) => !isHtmlRoute(r));
for (const r of skipped) console.log(` skipping ${r} (non-HTML endpoint, nothing to audit)`);
return [...new Set(explicitRoutes.filter(isHtmlRoute))];
}
- const authed = existsSync(AUTH_STATE) ? STATIC_AUTHED_ROUTES : [];
+ const authed = existsSync(AUTH_STATE) ? AUTHED_ROUTES : [];
return [...new Set([...manifestRoutes(), ...authed, ...dynamic])];
}
@@ -850,7 +789,7 @@ async function main() {
const seedCtx = await browser.newContext(
authed ? { storageState: AUTH_STATE } : {},
);
- const dynamic = explicitRoutes.length ? [] : await seedDynamicRoutes(seedCtx);
+ const dynamic = explicitRoutes.length ? [] : await seedDynamicRoutes(seedCtx, BASE_URL);
await seedCtx.close();
const routes = buildRouteList(dynamic);
console.log(` routes: ${routes.length}\n`);
diff --git a/scripts/page-snapshot.mjs b/scripts/page-snapshot.mjs
index 096780974..aa2406da4 100644
--- a/scripts/page-snapshot.mjs
+++ b/scripts/page-snapshot.mjs
@@ -32,6 +32,15 @@
* node scripts/page-snapshot.mjs --concurrency 4 # parallel pages per viewport (default 3)
* node scripts/page-snapshot.mjs --settle 5000 # ms to wait after load for 3D/animations
* node scripts/page-snapshot.mjs --quality 80 # JPEG quality (default 72)
+ * node scripts/page-snapshot.mjs --authed # signed-in sweep (dashboard, settings, profile)
+ * node scripts/page-snapshot.mjs --out reports/x # write somewhere other than snapshots/current
+ *
+ * ── Authenticated sweep ───────────────────────────────────────────────────────
+ * `--authed` replays the Playwright storageState that `npm run audit:web:login`
+ * writes to .auth/audit-state.json, and widens the route list to every page a
+ * signed-in visitor can reach. Those shots show the QA account's own data, so
+ * they default to reports/ui-shots/ (gitignored) rather than the committed
+ * public design record under snapshots/.
*
* Note: headless Chromium renders WebGL via SWANGLE/SwiftShader. Most 3D heroes
* render, but some heavy GPU scenes (and backdrop-filter) may come out dark. The
@@ -39,13 +48,14 @@
* is the design record. Raise --settle if a page's data loads slowly.
*/
import { chromium, devices } from 'playwright';
-import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, statSync } from 'node:fs';
+import { writeFileSync, mkdirSync, existsSync, rmSync, statSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { AUTHED_ROUTES, manifestPages, slugFor } from './lib/audit-routes.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');
-const OUT_DIR = resolve(ROOT, 'snapshots/current');
+const AUTH_STATE = resolve(ROOT, '.auth/audit-state.json');
// ── CLI parsing ───────────────────────────────────────────────────────────────
const argv = process.argv.slice(2);
@@ -60,34 +70,17 @@ const CONCURRENCY = Math.max(1, Number(opt('concurrency', 3)) || 3);
const SETTLE_MS = Math.max(0, Number(opt('settle', 3500)) || 3500);
const QUALITY = Math.min(100, Math.max(30, Number(opt('quality', 72)) || 72));
const explicitRoutes = argv.filter((a) => a.startsWith('/'));
+// Signed-in sweep. The session comes from the storageState `npm run
+// audit:web:login` writes, and it changes where the shots land: the committed
+// design record under snapshots/ is a PUBLIC record, and an authenticated run
+// shows the QA account's own data, so it defaults to a gitignored directory.
+const AUTHED = flag('authed');
+const OUT_DIR = resolve(ROOT, opt('out', AUTHED ? 'reports/ui-shots' : 'snapshots/current'));
// ── Route discovery ────────────────────────────────────────────────────────────
-// Public, user-discoverable pages from the manifest that drives /sitemap and
-// llms.txt — the single source of truth. Machine-readable endpoints (.xml/.txt/
-// .json, .well-known) and parameterised routes are skipped: they have no design.
-function manifestPages() {
- const pages = JSON.parse(readFileSync(resolve(ROOT, 'data/pages.json'), 'utf8'));
- const out = [];
- const seen = new Set();
- for (const s of pages.sections || []) {
- if (s.id === 'machine') continue;
- for (const p of s.pages || []) {
- const path = p.path;
- if (!path || !path.startsWith('/') || /[:*]/.test(path)) continue;
- if (/\.(xml|txt|json)$/.test(path) || path.startsWith('/.well-known')) continue;
- if (seen.has(path)) continue;
- seen.add(path);
- out.push({ path, title: p.title || path, section: s.title || s.id, auth: p.auth || null });
- }
- }
- return out;
-}
-
-// Map a route to a filesystem-safe slug: '/' → 'home', '/docs/api' → 'docs-api'.
-function slugFor(path) {
- if (path === '/') return 'home';
- return path.replace(/^\//, '').replace(/\/$/, '').replace(/[^a-zA-Z0-9._-]+/g, '-') || 'home';
-}
+// Pages, the authenticated route list and the slug rule come from
+// scripts/lib/audit-routes.mjs, shared with page-audit so the visual record and
+// the console/layout audit always cover the same site.
// ── Snapshot one route in one viewport ──────────────────────────────────────────
async function snapshotRoute(ctx, page, route, viewport) {
@@ -257,13 +250,37 @@ render();
// ── Main ────────────────────────────────────────────────────────────────────────
async function main() {
- const pages = explicitRoutes.length
- ? explicitRoutes.map((p) => ({ path: p, title: p, section: 'Selected', auth: null }))
- : manifestPages();
- // Public design record: skip auth-gated pages unless explicitly requested.
- const targets = pages.filter((p) => explicitRoutes.length || !p.auth);
+ let targets;
+ if (explicitRoutes.length) {
+ targets = explicitRoutes.map((p) => ({ path: p, title: p, section: 'Selected', auth: null }));
+ } else if (AUTHED) {
+ // Everything a signed-in visitor can reach: the public pages plus the
+ // auth-gated ones the manifest flags plus the dashboard sub-pages it
+ // deliberately leaves out of the public index.
+ const inManifest = new Set(manifestPages({ access: 'all' }).map((p) => p.path));
+ targets = [
+ ...manifestPages({ access: 'all' }),
+ ...AUTHED_ROUTES.filter((path) => !inManifest.has(path)).map((path) => ({
+ path,
+ title: path,
+ section: 'Signed in',
+ auth: 'required',
+ })),
+ ];
+ } else {
+ // Public design record: auth-gated pages would only show a login wall.
+ targets = manifestPages({ access: 'public' });
+ }
const routes = targets.map((p) => p.path);
+ if (AUTHED && !existsSync(AUTH_STATE)) {
+ console.error(
+ '--authed needs a session. Run `npm run audit:web:login` first (it writes .auth/audit-state.json).',
+ );
+ process.exitCode = 1;
+ return;
+ }
+
const viewports = MOBILE_ONLY ? ['mobile'] : DESKTOP_ONLY ? ['desktop'] : ['desktop', 'mobile'];
// `date` is the local calendar day this run belongs to — stamped into the
@@ -302,6 +319,7 @@ async function main() {
viewport === 'mobile'
? { ...devices['iPhone 13'] }
: { viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 };
+ if (AUTHED) ctxOpts.storageState = AUTH_STATE;
const ctx = await browser.newContext(ctxOpts);
ctx.setDefaultTimeout(45000);
console.log(`── ${viewport} ──`);
diff --git a/scripts/ui-review.mjs b/scripts/ui-review.mjs
new file mode 100644
index 000000000..29119d680
--- /dev/null
+++ b/scripts/ui-review.mjs
@@ -0,0 +1,285 @@
+#!/usr/bin/env node
+/**
+ * ui-review.mjs — the queue that hands a screenshot of every page to an agent,
+ * one batch at a time, and remembers what it already looked at.
+ *
+ * ── Why ───────────────────────────────────────────────────────────────────────
+ * The layout bugs that reach a user are the ones no assertion is watching: a
+ * floating pill sitting on the chat composer, a card action clipped mid-word, a
+ * tab strip sliced in half, a prompt used as a title. `page-audit` finds the
+ * mechanical half (console errors, overflow, tap targets). The other half is
+ * only visible to something that can LOOK at the page. That is what an agent
+ * with vision is for, and this script is the conveyor belt that feeds it.
+ *
+ * ── The loop ──────────────────────────────────────────────────────────────────
+ * 1. `--start` captures a signed-in screenshot of every page (page-snapshot
+ * --authed) and runs the DOM audit over the same routes
+ * (page-audit), then merges both into one queue.
+ * 2. `--next N` prints the next N unreviewed pages: shot paths, the audit's
+ * findings, the page's title and section. The agent READS those
+ * image files, judges them, and fixes what is really wrong.
+ * 3. `--done` records the verdict for a page and advances the queue.
+ * 4. `--report` writes the run's findings as markdown.
+ *
+ * State lives in the run directory, so the loop survives a context reset, a
+ * restarted session, or a machine reboot: `--next` always knows where it got to.
+ *
+ * ── Usage ─────────────────────────────────────────────────────────────────────
+ * npm run ui:review -- --start # full signed-in sweep, then queue
+ * npm run ui:review -- --start --routes /,/gallery,/dashboard
+ * npm run ui:review -- --start --viewport mobile # phone only (where most bugs are)
+ * npm run ui:review -- --start --no-audit # shots only, skip page-audit
+ * npm run ui:review -- --next 6 # next batch to look at
+ * npm run ui:review -- --done /gallery --clean
+ * npm run ui:review -- --done /app --issue "language pill covers the composer" --fixed "corner-stack now clears page docks"
+ * npm run ui:review -- --status
+ * npm run ui:review -- --report
+ *
+ * BASE_URL selects the target (default https://three.ws; use
+ * http://localhost:3000 to review the working tree before it ships).
+ */
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { manifestPages } from './lib/audit-routes.mjs';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const RUN_DIR = resolve(ROOT, 'reports/ui-review');
+const SHOT_DIR = resolve(RUN_DIR, 'shots');
+const QUEUE = resolve(RUN_DIR, 'queue.json');
+const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');
+
+const argv = process.argv.slice(2);
+const flag = (name) => argv.includes(`--${name}`);
+const opt = (name, fallback) => {
+ const i = argv.indexOf(`--${name}`);
+ return i !== -1 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : fallback;
+};
+
+const rel = (p) => p.replace(`${ROOT}/`, '');
+
+// ── Queue state ───────────────────────────────────────────────────────────────
+
+function loadQueue() {
+ if (!existsSync(QUEUE)) {
+ console.error('No review queue yet. Run: npm run ui:review -- --start');
+ process.exit(2);
+ }
+ return JSON.parse(readFileSync(QUEUE, 'utf8'));
+}
+
+function saveQueue(q) {
+ writeFileSync(QUEUE, `${JSON.stringify(q, null, 2)}\n`);
+}
+
+// ── Step 1: capture ───────────────────────────────────────────────────────────
+
+function run(cmd, args, label) {
+ console.log(`\n▸ ${label}\n ${cmd} ${args.join(' ')}`);
+ const res = spawnSync(cmd, args, {
+ cwd: ROOT,
+ stdio: 'inherit',
+ env: { ...process.env, BASE_URL },
+ });
+ // page-audit exits non-zero only under --strict; a findings-only exit is fine.
+ if (res.error) throw res.error;
+ return res.status ?? 0;
+}
+
+/** Newest reports/page-audit-*.json as { file, data }, or null when skipped. */
+function latestAuditReport() {
+ const dir = resolve(ROOT, 'reports');
+ if (!existsSync(dir)) return null;
+ const files = readdirSync(dir)
+ .filter((f) => /^page-audit-.*\.json$/.test(f))
+ .sort();
+ if (!files.length) return null;
+ const file = resolve(dir, files[files.length - 1]);
+ try {
+ return { file: rel(file), data: JSON.parse(readFileSync(file, 'utf8')) };
+ } catch {
+ return null;
+ }
+}
+
+function startRun() {
+ const explicit = (opt('routes', '') || '')
+ .split(',')
+ .map((r) => r.trim())
+ .filter((r) => r.startsWith('/'));
+ const viewport = opt('viewport', 'both');
+ const vpFlags =
+ viewport === 'mobile' ? ['--mobile-only'] : viewport === 'desktop' ? ['--desktop-only'] : [];
+
+ mkdirSync(RUN_DIR, { recursive: true });
+
+ run(
+ 'node',
+ ['scripts/page-snapshot.mjs', '--authed', '--out', rel(SHOT_DIR), ...vpFlags, ...explicit],
+ `Screenshotting ${explicit.length || 'every'} page at ${BASE_URL} (signed in)`,
+ );
+
+ if (!flag('no-audit')) {
+ run(
+ 'node',
+ ['scripts/page-audit.mjs', ...vpFlags, ...explicit],
+ 'Running the DOM audit over the same routes',
+ );
+ }
+
+ const manifest = JSON.parse(readFileSync(resolve(SHOT_DIR, 'manifest.json'), 'utf8'));
+ const audit = flag('no-audit') ? null : latestAuditReport();
+ const auditByRoute = new Map();
+ for (const p of audit?.data?.pages || []) auditByRoute.set(p.route, p);
+
+ const sectionOf = new Map(manifestPages({ access: 'all' }).map((p) => [p.path, p.section]));
+
+ const pages = manifest.pages
+ .filter((p) => Object.keys(p.shots || {}).length)
+ .map((p) => ({
+ route: p.path,
+ title: p.title,
+ section: p.section || sectionOf.get(p.path) || '',
+ shots: Object.fromEntries(
+ Object.keys(p.shots).map((vp) => [vp, rel(resolve(SHOT_DIR, vp, `${p.slug}.jpg`))]),
+ ),
+ audit: (auditByRoute.get(p.path)?.findings || [])
+ .filter((f) => f.severity !== 'info')
+ .slice(0, 12)
+ .map((f) => ({ severity: f.severity, type: f.type, detail: (f.detail || f.message || '').slice(0, 240) })),
+ status: 'pending',
+ issues: [],
+ fixes: [],
+ }));
+
+ // Pages the audit flagged hardest come first: an agent that runs out of
+ // budget mid-queue should have spent it where the evidence already points.
+ const weight = (p) =>
+ p.audit.reduce((n, f) => n + (f.severity === 'error' ? 10 : f.severity === 'warn' ? 3 : 1), 0);
+ pages.sort((a, b) => weight(b) - weight(a));
+
+ const queue = {
+ startedAt: new Date().toISOString(),
+ baseUrl: BASE_URL,
+ viewport,
+ shotDir: rel(SHOT_DIR),
+ auditReport: audit?.file || null,
+ pages,
+ };
+ saveQueue(queue);
+
+ console.log(
+ `\n■ Queue ready: ${pages.length} page(s) with shots at ${rel(SHOT_DIR)}.\n` +
+ ` Next: npm run ui:review -- --next 6`,
+ );
+}
+
+// ── Step 2: hand out a batch ──────────────────────────────────────────────────
+
+function printBatch(n) {
+ const q = loadQueue();
+ const batch = q.pages.filter((p) => p.status === 'pending').slice(0, n);
+ if (!batch.length) {
+ console.log('■ Queue empty: every page has been reviewed. Run --report for the summary.');
+ return;
+ }
+ const total = q.pages.length;
+ const done = q.pages.filter((p) => p.status !== 'pending').length;
+ console.log(`■ UI review batch — ${batch.length} page(s), ${done}/${total} reviewed, target ${q.baseUrl}\n`);
+ console.log('Read each screenshot below with the Read tool, judge it as a user would,');
+ console.log('confirm anything suspicious against the live DOM, then fix it and record');
+ console.log('the verdict with --done. Screenshots are full-page.\n');
+ for (const p of batch) {
+ console.log(`── ${p.route} ${p.title ? `(${p.title})` : ''}`);
+ if (p.section) console.log(` section: ${p.section}`);
+ for (const [vp, file] of Object.entries(p.shots)) console.log(` ${vp}: ${file}`);
+ if (p.audit.length) {
+ console.log(' audit already found:');
+ for (const f of p.audit) console.log(` [${f.severity}] ${f.type}: ${f.detail}`);
+ }
+ console.log('');
+ }
+ console.log('Record each one:');
+ console.log(' npm run ui:review -- --done <route> --clean');
+ console.log(' npm run ui:review -- --done <route> --issue "what is wrong" --fixed "what you changed"');
+}
+
+// ── Step 3: record a verdict ──────────────────────────────────────────────────
+
+function recordDone() {
+ const route = opt('done', '');
+ if (!route.startsWith('/')) {
+ console.error('--done needs a route, e.g. --done /gallery');
+ process.exit(2);
+ }
+ const q = loadQueue();
+ const page = q.pages.find((p) => p.route === route);
+ if (!page) {
+ console.error(`${route} is not in this queue.`);
+ process.exit(2);
+ }
+ const issue = opt('issue', '');
+ const fixed = opt('fixed', '');
+ if (issue) page.issues.push(issue);
+ if (fixed) page.fixes.push(fixed);
+ page.status = issue || fixed ? 'issues' : 'clean';
+ page.reviewedAt = new Date().toISOString();
+ saveQueue(q);
+ const left = q.pages.filter((p) => p.status === 'pending').length;
+ console.log(`✓ ${route} → ${page.status}${issue ? `: ${issue}` : ''}. ${left} page(s) left.`);
+}
+
+// ── Status + report ───────────────────────────────────────────────────────────
+
+function printStatus() {
+ const q = loadQueue();
+ const by = (s) => q.pages.filter((p) => p.status === s);
+ console.log(`■ UI review — ${q.baseUrl} — started ${q.startedAt}`);
+ console.log(` pending ${by('pending').length} · clean ${by('clean').length} · with issues ${by('issues').length}`);
+ for (const p of by('issues')) {
+ console.log(`\n ${p.route}`);
+ for (const i of p.issues) console.log(` issue: ${i}`);
+ for (const f of p.fixes) console.log(` fix: ${f}`);
+ }
+}
+
+function writeReport() {
+ const q = loadQueue();
+ const withIssues = q.pages.filter((p) => p.issues.length || p.fixes.length);
+ const lines = [
+ '# UI review',
+ '',
+ `- target: ${q.baseUrl}`,
+ `- started: ${q.startedAt}`,
+ `- pages reviewed: ${q.pages.filter((p) => p.status !== 'pending').length} of ${q.pages.length}`,
+ `- pages with issues: ${withIssues.length}`,
+ '',
+ ];
+ if (!withIssues.length) {
+ lines.push('No visual defects recorded in this run.');
+ }
+ for (const p of withIssues) {
+ lines.push(`## ${p.route}${p.title ? ` — ${p.title}` : ''}`, '');
+ for (const i of p.issues) lines.push(`- **found:** ${i}`);
+ for (const f of p.fixes) lines.push(`- **fixed:** ${f}`);
+ for (const [vp, file] of Object.entries(p.shots)) lines.push(`- ${vp} shot: \`${file}\``);
+ lines.push('');
+ }
+ const out = resolve(RUN_DIR, 'findings.md');
+ writeFileSync(out, `${lines.join('\n')}\n`);
+ console.log(`■ Wrote ${rel(out)}`);
+}
+
+// ── Entry ─────────────────────────────────────────────────────────────────────
+
+if (flag('start')) startRun();
+else if (argv.includes('--done')) recordDone();
+else if (flag('status')) printStatus();
+else if (flag('report')) writeReport();
+else if (flag('next') || !argv.length) printBatch(Math.max(1, Number(opt('next', 5)) || 5));
+else {
+ console.error('Unknown arguments. See the header of scripts/ui-review.mjs for usage.');
+ process.exit(2);
+}