@mushi-mushi/ux 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +33 -0
- package/dist/cli.js +1978 -961
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +46 -5
- package/dist/index.js +140 -22
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cursor-cloud.ts","../src/proc.ts","../src/worktree.ts","../src/agents.ts","../src/capture.ts","../src/guard.ts","../src/ignore.ts","../src/probes.ts","../src/dashboard.ts","../src/agent-events.ts","../src/image.ts","../src/state.ts","../src/studio-page.ts","../src/discover.ts","../src/routes.ts","../src/judge.ts","../src/loop.ts","../src/checker.ts","../src/packet.ts","../src/preflight.ts","../src/verdict.ts","../src/resume.ts","../src/types.ts","../src/sync.ts"],"sourcesContent":["// SPDX-License-Identifier: MIT\n/**\n * `--agent cursor-cloud`: the edit runs in a Cursor Cloud agent (your Cursor\n * plan pays), the measuring stays local. One attempt:\n *\n * push the run branch → POST /v1/agents on it (workOnCurrentBranch, no PR)\n * → poll the run → fetch the branch → apply the agent's commit to the\n * worktree, uncommitted\n *\n * so the loop's own capture, verdict and commit/revert work unchanged. The\n * agent cannot see the local `.mushi-ux/` files, so the prompt text and the\n * screenshots are sent inline.\n *\n * Wire shape: cursor.com/docs/cloud-agent/api/endpoints (read 2026-10-06).\n * `workOnCurrentBranch: true` makes the agent push to the run branch itself\n * instead of a new `cursor/...` branch, so every push of a run is under\n * `mushi-ux/**` and one `branches-ignore` keeps the host's CI quiet. The next\n * attempt's force-with-lease push replaces whatever the loop did not keep.\n * Images are `{ data, mimeType }`, at most 5; if Cursor still refuses them the\n * run goes on text only.\n */\n\nimport { readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { AgentAdapter, AgentRunOptions } from './agents.js'\nimport { run, type RunResult } from './proc.js'\nimport { SCRATCH_DIR } from './worktree.js'\n\nconst API = 'https://api.cursor.com'\nconst POLL_MS = 10_000\nconst MAX_IMAGES = 4 // Cursor allows 5\n\nexport interface CursorCloudDeps {\n fetch?: typeof fetch\n apiKey?: string\n /** Override the repo URL read from `git remote get-url origin` (tests). */\n repoUrl?: string\n sleep?: (ms: number) => Promise<void>\n}\n\nasync function git(cwd: string, args: string[], stdin?: string): Promise<RunResult> {\n return run('git', args, { cwd, stdin, timeoutMs: 120_000 })\n}\n\n/** `git@github.com:o/r.git` / `https://github.com/o/r(.git)` → `https://github.com/o/r`. */\nexport function httpsRepoUrl(remote: string): string | null {\n const s = remote.trim()\n const ssh = s.match(/^git@github\\.com:([\\w.-]+)\\/([\\w.-]+?)(\\.git)?$/)\n if (ssh) return `https://github.com/${ssh[1]}/${ssh[2]}`\n const https = s.match(/^https:\\/\\/(?:[^@/]+@)?github\\.com\\/([\\w.-]+)\\/([\\w.-]+?)(\\.git)?\\/?$/)\n if (https) return `https://github.com/${https[1]}/${https[2]}`\n return null\n}\n\n/** Model spec like `grok-4.7?reasoning_effort=xhigh` → Cursor's `{ id, params }`. */\nexport function cursorModel(spec: string | null | undefined): Record<string, unknown> | undefined {\n if (!spec) return undefined\n const [id, query] = spec.split('?')\n if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/.test(id)) return undefined\n const params = query\n ? query.split('&').filter(Boolean).map((p) => {\n const [k, v] = p.split('=')\n return { id: k, value: v ?? '' }\n })\n : []\n return params.length ? { id, params } : { id }\n}\n\nfunction promptAndImages(cwd: string): { text: string; images: Array<{ data: string; mimeType: 'image/png' }> } {\n const dir = join(cwd, SCRATCH_DIR)\n const text = readFileSync(join(dir, 'PROMPT.md'), 'utf8')\n const images = readdirSync(dir)\n .filter((f) => f.endsWith('.png'))\n .slice(0, MAX_IMAGES)\n .map((f) => ({ data: readFileSync(join(dir, f)).toString('base64'), mimeType: 'image/png' as const }))\n // The cloud agent sees the screenshots inline, not at these paths.\n return { text: text.replace(/\\.mushi-ux\\/(desktop|mobile)\\.png/g, 'the attached $1 screenshot'), images }\n}\n\nexport function cursorCloudAdapter(deps: CursorCloudDeps = {}): AgentAdapter {\n const doFetch = deps.fetch ?? fetch\n const sleep = deps.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)))\n\n return {\n name: 'cursor-cloud',\n verified: false,\n async run({ cwd, model, timeoutMs, onLine }: AgentRunOptions): Promise<RunResult> {\n const started = Date.now()\n const log = (l: string) => onLine?.(l)\n const fail = (tail: string): RunResult => ({ exitCode: 1, timedOut: false, durationMs: Date.now() - started, tail, stdout: '' })\n const apiKey = deps.apiKey ?? process.env.CURSOR_API_KEY\n if (!apiKey) return fail('CURSOR_API_KEY is not set. Create one at cursor.com/settings (Integrations → API keys).')\n\n const branch = (await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim()\n const remote = deps.repoUrl ?? httpsRepoUrl((await git(cwd, ['remote', 'get-url', 'origin'])).stdout)\n if (!remote) return fail('cursor-cloud needs an `origin` remote on GitHub.')\n log(`pushing ${branch} so the cloud agent can start from it`)\n const push = await git(cwd, ['push', '--force-with-lease', 'origin', `HEAD:refs/heads/${branch}`])\n if (push.exitCode !== 0) return fail(`Could not push ${branch}: ${push.tail.trim()}`)\n\n const { text, images } = promptAndImages(cwd)\n const headers = { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' }\n const body = (withImages: boolean) =>\n JSON.stringify({\n prompt: withImages && images.length ? { text, images } : { text },\n repos: [{ url: remote, startingRef: branch }],\n workOnCurrentBranch: true,\n autoCreatePR: false,\n name: `mushi-ux ${branch}`.slice(0, 100),\n ...(cursorModel(model) ? { model: cursorModel(model) } : {}),\n })\n let res = await doFetch(`${API}/v1/agents`, { method: 'POST', headers, body: body(true) })\n if (res.status === 400 && images.length) {\n log('Cursor refused the inline screenshots; retrying with text only')\n res = await doFetch(`${API}/v1/agents`, { method: 'POST', headers, body: body(false) })\n }\n const created = (await res.json().catch(() => null)) as { agent?: { id?: string }; run?: { id?: string }; error?: { message?: string } } | null\n if (!res.ok || !created?.agent?.id || !created.run?.id) {\n return fail(`Cursor did not start the agent (HTTP ${res.status}): ${created?.error?.message ?? 'no agent id'}`)\n }\n const agentId = created.agent.id\n const runId = created.run.id\n log(`cloud agent ${agentId} running`)\n\n let status = 'CREATING'\n let resultBranch: string | null = null\n let result = ''\n while (Date.now() - started < timeoutMs) {\n await sleep(POLL_MS)\n const poll = await doFetch(`${API}/v1/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}`, { headers })\n const r = (await poll.json().catch(() => null)) as { status?: string; result?: string; git?: { branches?: Array<{ branch?: string }> } } | null\n status = r?.status ?? status\n log(`cloud agent ${status.toLowerCase()}`)\n if (status === 'FINISHED' || status === 'ERROR' || status === 'CANCELLED' || status === 'EXPIRED') {\n resultBranch = r?.git?.branches?.find((b) => b.branch)?.branch ?? null\n result = r?.result ?? ''\n break\n }\n }\n if (status !== 'FINISHED') {\n if (Date.now() - started >= timeoutMs) {\n await doFetch(`${API}/v1/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST', headers }).catch(() => undefined)\n return { exitCode: null, timedOut: true, durationMs: Date.now() - started, tail: `Cloud agent still ${status.toLowerCase()} at the time box; cancelled.`, stdout: '' }\n }\n return fail(`Cloud agent ended ${status.toLowerCase()}. ${result}`.trim())\n }\n if (!resultBranch) return { exitCode: 0, timedOut: false, durationMs: Date.now() - started, tail: result || 'Cloud agent made no edits.', stdout: '' }\n\n const fetched = await git(cwd, ['fetch', 'origin', resultBranch])\n if (fetched.exitCode !== 0) return fail(`Could not fetch ${resultBranch}: ${fetched.tail.trim()}`)\n const diff = await git(cwd, ['diff', '--binary', 'HEAD', 'FETCH_HEAD'])\n if (diff.stdout.trim()) {\n const applied = await git(cwd, ['apply', '--whitespace=nowarn'], diff.stdout)\n if (applied.exitCode !== 0) return fail(`The agent's change did not apply: ${applied.tail.trim()}`)\n }\n // The loop commits what it keeps; the next push replaces the agent's commit.\n log(`applied the cloud agent's change from ${resultBranch}`)\n return { exitCode: 0, timedOut: false, durationMs: Date.now() - started, tail: result.slice(-2000), stdout: result }\n },\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Child processes for agents, installs and dev servers. Prompts go on stdin\n * (cmd.exe caps a command line near 8 KB), timeouts kill the whole process\n * tree (`taskkill /T /F` on Windows), and agents get a scrubbed environment.\n */\n\nimport { spawn, spawnSync, type ChildProcess } from 'node:child_process'\n\nexport interface RunResult {\n exitCode: number | null\n timedOut: boolean\n durationMs: number\n /** Last ~4 KB of combined output. */\n tail: string\n /** Full stdout, capped at 1 MB. */\n stdout: string\n}\n\nexport interface RunOptions {\n cwd: string\n env?: NodeJS.ProcessEnv\n stdin?: string\n timeoutMs?: number\n /** Needed for `.cmd` shims and shell syntax in user-given commands. */\n shell?: boolean\n onLine?: (line: string) => void\n /** Stops the process tree when aborted (the studio's Stop button). */\n signal?: AbortSignal\n}\n\nfunction killTree(child: ChildProcess): void {\n if (child.pid === undefined || child.exitCode !== null) return\n if (process.platform === 'win32') {\n spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' })\n } else {\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch {\n child.kill('SIGKILL')\n }\n }\n}\n\nexport function run(cmd: string, args: readonly string[], opts: RunOptions): Promise<RunResult> {\n const started = Date.now()\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: opts.shell ?? false,\n detached: process.platform !== 'win32',\n windowsHide: true,\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n let tail = ''\n let stdout = ''\n let partial = ''\n let timedOut = false\n const onData = (chunk: Buffer) => {\n const text = chunk.toString('utf8')\n tail = (tail + text).slice(-4096)\n if (!opts.onLine) return\n partial += text\n const lines = partial.split(/\\r?\\n/)\n partial = lines.pop() ?? ''\n for (const line of lines) if (line.trim()) opts.onLine(line)\n }\n child.stdout?.on('data', (chunk: Buffer) => {\n if (stdout.length < 1_000_000) stdout += chunk.toString('utf8')\n onData(chunk)\n })\n child.stderr?.on('data', onData)\n child.on('error', reject)\n const timer = opts.timeoutMs\n ? setTimeout(() => {\n timedOut = true\n killTree(child)\n }, opts.timeoutMs)\n : null\n const onAbort = () => killTree(child)\n if (opts.signal?.aborted) onAbort()\n else opts.signal?.addEventListener('abort', onAbort, { once: true })\n child.on('close', (code) => {\n if (timer) clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onAbort)\n if (partial.trim() && opts.onLine) opts.onLine(partial)\n resolve({ exitCode: code, timedOut, durationMs: Date.now() - started, tail, stdout })\n })\n // A child that exits before reading stdin (git, a quick CLI) makes this\n // write fail with EPIPE; without a listener that is an uncaught exception\n // that takes the whole process down (seen in CI, 2026-10-07). The exit\n // code still reports how the child ended.\n child.stdin?.on('error', () => {})\n child.stdin?.end(opts.stdin ?? '')\n })\n}\n\n/** Long-running child (a dev server); the caller stops it with `stop()`. */\nexport function start(command: string, opts: { cwd: string; env?: NodeJS.ProcessEnv; onLine?: (l: string) => void }) {\n const child = spawn(command, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: true,\n detached: process.platform !== 'win32',\n windowsHide: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n const forward = (chunk: Buffer) => {\n for (const line of chunk.toString('utf8').split(/\\r?\\n/)) if (line.trim()) opts.onLine?.(line)\n }\n child.stdout?.on('data', forward)\n child.stderr?.on('data', forward)\n return { child, stop: () => killTree(child) }\n}\n\n/**\n * The tool's own credentials. The dev server and the install run the app's\n * code, which the agent edits, so they get the app's environment without\n * these: on a CI runner that is the Cursor and Anthropic keys and the job's\n * GitHub tokens. App variables (VITE_*_KEY and the like) stay.\n */\nconst TOOL_SECRET_RE = /^(MUSHI_.*|CURSOR_API_KEY|ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN|OPENAI_API_KEY|CODEX_API_KEY|GITHUB_TOKEN|GH_TOKEN|ACTIONS_RUNTIME_TOKEN|ACTIONS_ID_TOKEN_REQUEST_TOKEN|ACTIONS_ID_TOKEN_REQUEST_URL)$/i\n\nexport function appEnv(base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const out: NodeJS.ProcessEnv = {}\n for (const [k, v] of Object.entries(base)) {\n if (v !== undefined && !TOOL_SECRET_RE.test(k)) out[k] = v\n }\n return out\n}\n\nconst SECRET_NAME_RE = /(^MUSHI_|^SUPABASE_|_TOKEN$|_KEY$|_SECRET$|PASSWORD|^GH_|^GITHUB_)/i\n\n/**\n * The environment an agent runs with: everything except credentials, plus\n * the one credential that agent itself needs to talk to its model.\n */\nexport function scrubbedEnv(keep: readonly string[], base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const out: NodeJS.ProcessEnv = {}\n for (const [k, v] of Object.entries(base)) {\n if (v === undefined) continue\n if (SECRET_NAME_RE.test(k) && !keep.includes(k)) continue\n out[k] = v\n }\n return out\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The agent edits a separate git worktree on its own branch, served by its\n * own dev server, so the person's checkout (and any other agent working in\n * it) is never touched. Accepted iterations are commits on that branch;\n * rejected ones are reverted.\n *\n * `.mushi-ux/` inside the worktree carries the screenshots and the prompt for\n * the agent. It is never committed.\n */\n\nimport { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { createServer } from 'node:net'\nimport { dirname, isAbsolute, join, relative } from 'node:path'\nimport { appEnv, run, start } from './proc.js'\n\nexport const SCRATCH_DIR = '.mushi-ux'\n\nasync function git(cwd: string, args: string[]): Promise<string> {\n const res = await run('git', args, { cwd, timeoutMs: 120_000 })\n if (res.exitCode !== 0) throw new Error(`git ${args.join(' ')} failed: ${res.tail.trim()}`)\n return res.stdout.trim()\n}\n\nexport async function repoRootOf(cwd: string): Promise<string> {\n return git(cwd, ['rev-parse', '--show-toplevel'])\n}\n\nexport interface Worktree {\n path: string\n branch: string\n baseSha: string\n}\n\n/**\n * Branch `mushi-ux/<runId>` from `baseRef` (default HEAD) in `.worktrees/`.\n * A stale or dirty checkout stays untouched: pass `origin/main` to start from\n * the remote's tip instead of whatever the checkout is on.\n */\nexport async function createWorktree(repoRoot: string, runId: string, baseRef = 'HEAD'): Promise<Worktree> {\n const branch = `mushi-ux/${runId}`\n const path = join(repoRoot, '.worktrees', `mushi-ux-${runId}`)\n if (!/^[\\w./@^~-]{1,200}$/.test(baseRef) || baseRef.startsWith('-')) throw new Error(`Not a git ref: ${baseRef}`)\n const baseSha = await git(repoRoot, ['rev-parse', '--verify', `${baseRef}^{commit}`])\n await ensureLocalExcludes(repoRoot)\n mkdirSync(dirname(path), { recursive: true })\n await git(repoRoot, ['worktree', 'add', '-b', branch, path, baseSha])\n await copyEnvFiles(repoRoot, path)\n return { path, branch, baseSha }\n}\n\n/** Paths the loop writes that must never show up in `git status` or a commit. */\nconst LOCAL_EXCLUDES = ['/.mushi/', '/.worktrees/', `/${SCRATCH_DIR}/`]\n\n/**\n * Add the loop's own directories to `.git/info/exclude` (local to this clone,\n * shared by its worktrees, never committed), so a run leaves the person's\n * `git status` clean without touching their `.gitignore`.\n */\nasync function ensureLocalExcludes(repoRoot: string): Promise<void> {\n let common = await git(repoRoot, ['rev-parse', '--git-common-dir'])\n if (!isAbsolute(common)) common = join(repoRoot, common)\n const file = join(common, 'info', 'exclude')\n mkdirSync(dirname(file), { recursive: true })\n let current = ''\n try {\n current = readFileSync(file, 'utf8')\n } catch {\n // No exclude file yet: append creates it.\n }\n const lines = new Set(current.split(/\\r?\\n/).map((l) => l.trim()))\n const missing = LOCAL_EXCLUDES.filter((p) => !lines.has(p))\n if (missing.length === 0) return\n const lead = current && !current.endsWith('\\n') ? '\\n' : ''\n appendFileSync(file, `${lead}# mushi-ux (local only)\\n${missing.join('\\n')}\\n`)\n}\n\n/**\n * Local `.env*` files are untracked, so a fresh worktree lacks them. Only\n * files git already ignores are copied: an env file the repo does not ignore\n * would otherwise land in the run's commits (`git add -A`) and in the PR.\n */\nasync function copyEnvFiles(from: string, to: string, maxDepth = 4): Promise<string[]> {\n const candidates: string[] = []\n const walk = (dir: string, depth: number) => {\n if (depth > maxDepth) return\n for (const name of readdirSync(dir)) {\n if (name === 'node_modules' || name === '.git' || name === '.worktrees' || name === '.mushi') continue\n const abs = join(dir, name)\n let isDir = false\n try {\n isDir = statSync(abs).isDirectory()\n } catch {\n continue\n }\n if (isDir) walk(abs, depth + 1)\n else if (/^\\.env(\\..+)?$/.test(name) && !name.endsWith('.example')) {\n candidates.push(relative(from, abs).replace(/\\\\/g, '/'))\n }\n }\n }\n walk(from, 0)\n if (candidates.length === 0) return []\n // check-ignore exits 1 when nothing matches; stdout lists the ignored paths.\n const res = await run('git', ['check-ignore', '--', ...candidates], { cwd: from, timeoutMs: 60_000 })\n const ignored = new Set(res.stdout.split(/\\r?\\n/).map((l) => l.trim().replace(/\\\\/g, '/')).filter(Boolean))\n const copied: string[] = []\n for (const rel of candidates) {\n if (!ignored.has(rel)) continue\n const dest = join(to, rel)\n if (existsSync(dest)) continue\n mkdirSync(dirname(dest), { recursive: true })\n copyFileSync(join(from, rel), dest)\n copied.push(rel)\n }\n return copied\n}\n\n/** Files changed by the agent, ignoring the scratch dir. */\nexport async function changedFiles(wt: string): Promise<string[]> {\n // Not git(): its trim() would eat the leading status column of line one.\n const res = await run('git', ['status', '--porcelain', '--untracked-files=all'], {\n cwd: wt,\n timeoutMs: 120_000,\n })\n if (res.exitCode !== 0) throw new Error(`git status failed: ${res.tail.trim()}`)\n return res.stdout\n .split(/\\r?\\n/)\n .filter(Boolean)\n .map((l) => l.slice(3).trim().replace(/^\"|\"$/g, ''))\n}\n\n/**\n * The agent's uncommitted edits as text, for a reviewer: tracked changes from\n * `git diff HEAD` and new files in full, capped. Stages nothing, so\n * revertAll still restores the tree.\n */\nexport async function diffText(wt: string, maxChars = 20_000): Promise<string> {\n const tracked = await run('git', ['diff', 'HEAD', '--', '.', `:(exclude)${SCRATCH_DIR}`], { cwd: wt, timeoutMs: 120_000 })\n let out = tracked.stdout\n const untracked = await run('git', ['ls-files', '--others', '--exclude-standard'], { cwd: wt, timeoutMs: 120_000 })\n for (const f of untracked.stdout.split(/\\r?\\n/).filter((x) => x && !x.startsWith(SCRATCH_DIR))) {\n if (out.length >= maxChars) break\n try {\n out += `\\n--- new file ${f} ---\\n${readFileSync(join(wt, f), 'utf8').slice(0, 4000)}\\n`\n } catch {\n out += `\\n--- new file ${f} (unreadable) ---\\n`\n }\n }\n return out.slice(0, maxChars)\n}\n\nexport async function commitAll(wt: string, message: string): Promise<string> {\n // .mushi-ux/ is in .git/info/exclude (ensureLocalExcludes), so -A skips it.\n await git(wt, ['add', '-A'])\n await git(wt, ['-c', 'user.name=mushi-ux', '-c', 'user.email=mushi-ux@users.noreply.github.com', 'commit', '--no-verify', '-m', message])\n return git(wt, ['rev-parse', 'HEAD'])\n}\n\nexport async function headSha(wt: string): Promise<string> {\n return git(wt, ['rev-parse', 'HEAD'])\n}\n\n/**\n * Move the run's own branch back to a commit it already had (a resume after a\n * crash between an attempt's commit and the state save). Only ever called on\n * the run's worktree, never the person's checkout.\n */\nexport async function resetRunBranch(wt: string, sha: string): Promise<void> {\n await git(wt, ['merge-base', '--is-ancestor', sha, 'HEAD'])\n await git(wt, ['reset', '--hard', sha])\n}\n\n/** Throw away the agent's uncommitted edits; keeps the scratch dir and ignored files (.env). */\nexport async function revertAll(wt: string): Promise<void> {\n await git(wt, ['checkout', '--', '.'])\n await git(wt, ['clean', '-fd', '-e', SCRATCH_DIR])\n}\n\nexport function detectInstallCommand(dir: string): string | null {\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm install --frozen-lockfile --prefer-offline'\n if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun install --frozen-lockfile'\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn install --frozen-lockfile'\n if (existsSync(join(dir, 'package-lock.json'))) return 'npm ci'\n return null\n}\n\nasync function freePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = createServer()\n srv.unref()\n srv.on('error', reject)\n srv.listen(0, '127.0.0.1', () => {\n const addr = srv.address()\n const port = typeof addr === 'object' && addr ? addr.port : 0\n srv.close(() => resolve(port))\n })\n })\n}\n\nexport interface DevServer {\n url: string\n stop(): void\n}\n\n/**\n * Start `command` in the worktree. `{port}` in the command and the PORT env\n * var both carry the chosen port; resolves once `url` answers.\n */\nexport async function startDevServer(\n wt: string,\n command: string,\n opts: { port?: number; path?: string; timeoutMs?: number; onLine?: (l: string) => void } = {},\n): Promise<DevServer> {\n const port = opts.port ?? (await freePort())\n const cmd = command.replace(/\\{port\\}/g, String(port))\n // Keep the last lines, so a failure says why instead of only \"no answer\".\n const recent: string[] = []\n const server = start(cmd, {\n cwd: wt,\n env: { ...appEnv(), PORT: String(port) },\n onLine: (l) => {\n recent.push(l)\n if (recent.length > 40) recent.shift()\n opts.onLine?.(l)\n },\n })\n const url = `http://localhost:${port}`\n const timeoutMs = opts.timeoutMs ?? 180_000\n const deadline = Date.now() + timeoutMs\n const tail = () => {\n // The first error line and what follows is usually the cause; ANSI colours dropped.\n const lines = recent.map((l) => l.replace(/\\u001b\\[[0-9;]*m/g, ''))\n const at = lines.findIndex((l) => /error|⨯|failed|cannot|can't/i.test(l))\n return (at >= 0 ? lines.slice(at, at + 12) : lines.slice(-12)).join('\\n')\n }\n let lastStatus: number | null = null\n while (Date.now() < deadline) {\n if (server.child.exitCode !== null) throw new Error(`Dev server exited with code ${server.child.exitCode}: ${cmd}\\n${tail()}`)\n lastStatus = await fetch(new URL(opts.path ?? '/', url), { redirect: 'manual' })\n .then((r) => r.status)\n .catch(() => lastStatus)\n if (lastStatus !== null && lastStatus < 500) return { url, stop: server.stop }\n await new Promise((r) => setTimeout(r, 1000))\n }\n server.stop()\n const why = lastStatus !== null ? `answered HTTP ${lastStatus} on ${url}${opts.path ?? '/'}` : `did not answer on ${url}`\n throw new Error(`The dev server ${why} for ${Math.round(timeoutMs / 1000)}s: ${cmd}\\n${tail()}`)\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Coding agents the loop can drive, each as a headless subprocess in the\n * worktree. The full instructions live in `.mushi-ux/PROMPT.md`; the agent\n * gets a one-line pointer to it, edits files, and the loop decides what to\n * keep.\n *\n * Credential boundary (ADR 0006 / 0020): the agent never gets the browser\n * profile or the Mushi CLI config. Its environment is scrubbed of every\n * credential except its own model key, and Claude Code runs `--restricted`,\n * which removes shell tools and confines file access to the worktree.\n *\n * `claude-code` is verified on Windows. `cursor` and `codex` follow their\n * documented headless flags and are unverified until the Plan 021 Phase 0\n * probes run (docs/execplans/ux-loop.md §5).\n */\n\nimport { cursorCloudAdapter } from './cursor-cloud.js'\nimport { run, scrubbedEnv, type RunResult } from './proc.js'\n\nexport type AgentName = 'claude-code' | 'cursor' | 'codex' | 'cursor-cloud'\n\nexport interface AgentRunOptions {\n cwd: string\n prompt: string\n model?: string | null\n timeoutMs: number\n onLine?: (line: string) => void\n /** Aborted by the studio's Stop button: the agent's process tree is killed. */\n signal?: AbortSignal\n /** Continue this earlier session (adapters with canResume) instead of starting a new one. */\n resumeSession?: string\n}\n\nexport interface AgentAdapter {\n name: AgentName | (string & {})\n verified: boolean\n /** Can continue a session by id (its stream reports session_id): used for \"time is up, finish now\". */\n canResume?: boolean\n run(opts: AgentRunOptions): Promise<RunResult>\n}\n\nconst claudeCode: AgentAdapter = {\n name: 'claude-code',\n verified: true,\n run: ({ cwd, prompt, model, timeoutMs, onLine, signal }) =>\n run(\n 'claude',\n [\n '-p',\n '--output-format',\n 'stream-json',\n '--verbose',\n '--restricted',\n '--strict-mcp-config',\n '--permission-mode',\n 'acceptEdits',\n '--no-session-persistence',\n ...(model ? ['--model', model] : []),\n ],\n {\n cwd,\n stdin: prompt,\n timeoutMs,\n onLine,\n signal,\n env: scrubbedEnv(['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN']),\n },\n ),\n}\n\nconst cursor: AgentAdapter = {\n name: 'cursor',\n // Verified on Windows 2026-10-06 (2026.10.01, Grok 4.7), launched outside Git Bash.\n verified: true,\n canResume: true,\n // Cursor's CLI takes the prompt as an argument in print mode; whether it\n // reads stdin is a Phase 0 probe. The `.cmd` shim needs a shell on Windows.\n // The loop's prompt is a one-line pointer to .mushi-ux/PROMPT.md, so it\n // stays far below cmd.exe's command-line limit.\n run: ({ cwd, prompt, model, timeoutMs, onLine, signal, resumeSession }) =>\n run(\n 'agent',\n [\n '-p',\n ...(resumeSession ? ['--resume', quoteArg(resumeSession)] : []),\n '--force',\n // Headless runs otherwise stop on the workspace-trust prompt in a fresh worktree.\n '--trust',\n '--output-format',\n 'stream-json',\n '--workspace',\n '.',\n ...(model ? ['--model', quoteArg(cursorCliModel(model))] : []),\n quoteArg(prompt),\n ],\n { cwd, timeoutMs, onLine, signal, shell: true, env: scrubbedEnv(['CURSOR_API_KEY']) },\n ),\n}\n\nconst codex: AgentAdapter = {\n name: 'codex',\n verified: false,\n run: ({ cwd, prompt, model, timeoutMs, onLine, signal }) =>\n run(\n 'codex',\n ['exec', '--json', '--full-auto', '-C', '.', ...(model ? ['-m', quoteArg(model)] : []), '-'],\n { cwd, stdin: prompt, timeoutMs, onLine, signal, shell: true, env: scrubbedEnv(['OPENAI_API_KEY', 'CODEX_API_KEY']) },\n ),\n}\n\n/**\n * The Cursor CLI takes a model's settings in brackets\n * (`claude-opus-4-8[context=1m,effort=high]`); the UI and the Cursor API use\n * `id?context=1m&effort=high`. A bare id passes through.\n * @internal Exported for tests only.\n */\nexport function cursorCliModel(spec: string): string {\n const [id, query] = spec.split('?')\n if (!query) return id\n const params = query.split('&').filter(Boolean)\n return params.length ? `${id}[${params.join(',')}]` : id\n}\n\n/**\n * Quote one argument for the shell `spawn({ shell: true })` uses, so model\n * specs like `grok-4.7?reasoning_effort=xhigh&context=500k` survive.\n * cmd.exe has no escape inside double quotes, so quotes are dropped there.\n */\nexport function quoteArg(s: string, platform: NodeJS.Platform = process.platform): string {\n if (/^[\\w./:=@-]+$/.test(s)) return s\n const flat = s.replace(/\\r?\\n/g, ' ')\n if (platform === 'win32') return `\"${flat.replace(/\"/g, '')}\"`\n return `'${flat.replace(/'/g, `'\\\\''`)}'`\n}\n\nexport const AGENTS: Record<AgentName, AgentAdapter> = {\n 'claude-code': claudeCode,\n cursor,\n codex,\n // Cursor Cloud: the edit runs on Cursor's machines (your plan pays), the\n // measuring stays here. Needs CURSOR_API_KEY and a GitHub origin.\n 'cursor-cloud': cursorCloudAdapter(),\n}\n\nexport function getAgent(name: string): AgentAdapter {\n const adapter = AGENTS[name as AgentName]\n if (!adapter) throw new Error(`Unknown agent \"${name}\". Use one of: ${Object.keys(AGENTS).join(', ')}`)\n return adapter\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Browser sessions and screenshots. Every session goes through the write\n * guard (guard.ts) before any page opens.\n *\n * A session can reuse the persistent profile `mushi-ux login` created, so\n * captures see the signed-in app. The profile lives outside the repo and is\n * never named to the coding agent (ADR 0006).\n */\n\nimport { chromium, type Browser, type BrowserContext, type Page } from 'playwright'\nimport { installGuard, isGuardNoise, type AllowRule, type GuardLog } from './guard.js'\nimport { ignoreList, ignoreStyle } from './ignore.js'\nimport { isFrameworkNoise, runProbes } from './probes.js'\nimport type { ProbeResult, ReplayStep, Surface, Viewport } from './types.js'\n\nexport interface BrowserSession {\n /** Discovery browses here; app state it leaves behind stays here. */\n context: BrowserContext\n /**\n * A clean context for one capture: the cookies and storage the session\n * started with (a saved login included), the same guard and init scripts.\n * Captures share no client state, so a screen looks the same however many\n * other screens were visited before it (glot.it /words lost its empty\n * state after other screens wrote to localStorage, 2026-10-07).\n */\n freshContext(): Promise<BrowserContext>\n /**\n * Visit each path once in the shared context, then seed every later capture\n * from the storage that leaves behind. A first-ever visit can sit on a boot\n * screen past the content wait (glot.it /chat: a skeleton on desktop, blank\n * on the phone, 2026-10-07), so captures start from a visited app, the same\n * one for every screen.\n */\n warmUp(baseUrl: string, paths: readonly string[]): Promise<void>\n guard: GuardLog\n /** Selectors hidden in screenshots and left out of every probe (ignore.ts). */\n ignore: readonly string[]\n close(): Promise<void>\n}\n\nexport interface SessionOptions {\n /** Persistent profile directory from `mushi-ux login`; omit for a clean browser. */\n profileDir?: string\n headless?: boolean\n allow?: readonly AllowRule[]\n /** Extra selectors to ignore on top of DEFAULT_IGNORE. */\n ignore?: readonly string[]\n}\n\n/** Sums layout shifts not caused by input, from page start. */\nconst CLS_SCRIPT = `(() => {\n window.__mushiCls = 0\n try {\n new PerformanceObserver((list) => {\n for (const e of list.getEntries()) if (!e.hadRecentInput) window.__mushiCls += e.value\n }).observe({ type: 'layout-shift', buffered: true })\n } catch {}\n})()`\n\nexport async function openSession(opts: SessionOptions = {}): Promise<BrowserSession> {\n const headless = opts.headless ?? true\n let context: BrowserContext\n let closeBrowser: () => Promise<void>\n let browser: Browser\n // Playwright's docs say requests a Service Worker handles can bypass\n // context.route. Chromium on 1.61 routed them in a probe (Plan 021 §5), but\n // the guard must not depend on that: block Service Workers outright.\n if (opts.profileDir) {\n context = await chromium.launchPersistentContext(opts.profileDir, { headless, serviceWorkers: 'block' })\n // A persistent profile cannot spawn contexts: captures run in a second browser seeded from it.\n browser = await chromium.launch({ headless })\n closeBrowser = async () => {\n await context.close()\n await browser.close()\n }\n } else {\n browser = await chromium.launch({ headless })\n context = await browser.newContext({ serviceWorkers: 'block' })\n closeBrowser = () => browser.close()\n }\n const guard = await installGuard(context, opts.allow ?? [])\n await context.addInitScript({ content: CLS_SCRIPT })\n // The state every capture starts from; warmUp replaces it with a visited app.\n let seed = await context.storageState({ indexedDB: true })\n const warmUp = async (baseUrl: string, paths: readonly string[]) => {\n const page = await context.newPage()\n try {\n for (const p of paths) {\n await gotoPatiently(page, surfaceUrl(baseUrl, p)).catch(() => null)\n await settle(page).catch(() => undefined)\n }\n } finally {\n await page.close()\n }\n seed = await context.storageState({ indexedDB: true })\n }\n const freshContext = async () => {\n const fresh = await browser.newContext({ serviceWorkers: 'block', storageState: seed })\n await installGuard(fresh, opts.allow ?? [], guard)\n await fresh.addInitScript({ content: CLS_SCRIPT })\n return fresh\n }\n return { context, freshContext, warmUp, guard, ignore: ignoreList(opts.ignore), close: closeBrowser }\n}\n\n/**\n * Wait for the network to go quiet and the DOM to stop changing, both\n * bounded. Apps that hold a socket or poll never reach \"network idle\", so\n * that wait is capped short and the DOM-quiet wait does the real work.\n */\nexport async function settle(page: Page, quietMs = 400, maxMs = 5000): Promise<void> {\n await page.waitForLoadState('networkidle', { timeout: Math.min(maxMs, 2500) }).catch(() => {})\n await page\n .evaluate(\n ([quiet, max]) =>\n new Promise<void>((resolve) => {\n let timer = setTimeout(done, quiet)\n const stop = setTimeout(done, max)\n const mo = new MutationObserver(() => {\n clearTimeout(timer)\n timer = setTimeout(done, quiet)\n })\n mo.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true })\n function done() {\n mo.disconnect()\n clearTimeout(timer)\n clearTimeout(stop)\n resolve()\n }\n }),\n [quietMs, maxMs] as const,\n )\n .catch(() => {})\n await page.evaluate(() => document.fonts?.ready).catch(() => {})\n await waitForContent(page)\n}\n\n/**\n * Wait (up to `maxMs`) while the page shows a loading state: aria-busy, a\n * progress bar, or a spinning element covering most of the screen. An app\n * that boots behind a splash spinner was screenshotted as an empty page with\n * a spinner and \"measured\" as fine (glot.it /practice, 2026-10-06).\n * @internal Exported for tests only.\n */\nexport async function waitForContent(page: Page, maxMs = 20_000): Promise<void> {\n await page\n .waitForFunction(\n () => {\n const visible = (el: Element) => {\n const r = (el as HTMLElement).getBoundingClientRect()\n const s = getComputedStyle(el)\n return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'\n }\n const busy = [...document.querySelectorAll('[aria-busy=\"true\"], [role=\"progressbar\"], .animate-spin, .spinner, [class*=\"spinner\" i]')].some(visible)\n // Loading placeholders: skeleton classes, or a running skeleton/shimmer\n // animation (glot.it's Skeleton is marked only by `skeleton-wave`;\n // a regression re-shot of /words caught it mid-load, 2026-10-06).\n const skeleton =\n [...document.querySelectorAll('[class*=\"skeleton\" i], [class*=\"shimmer\" i], .animate-pulse, [data-skeleton]')].some(visible) ||\n (document.getAnimations?.() ?? []).some((a) => {\n const name = (a as CSSAnimation).animationName ?? ''\n const target = (a.effect as KeyframeEffect | null)?.target\n return /skeleton|shimmer|pulse|loading|placeholder/i.test(name) && !!target && visible(target)\n })\n if (skeleton) return false\n // Little text on the page means the real content has not arrived yet.\n const text = (document.body?.innerText ?? '').replace(/\\s+/g, ' ').trim()\n return !busy && text.length > 40\n },\n undefined,\n { timeout: maxMs, polling: 250 },\n )\n .catch(() => {})\n}\n\nexport async function replay(page: Page, steps: readonly ReplayStep[]): Promise<void> {\n for (const step of steps) {\n await page.locator(step.selector).first().click({ timeout: 5000 })\n await settle(page)\n }\n}\n\nexport function surfaceUrl(baseUrl: string, path: string): string {\n return new URL(path, baseUrl).toString()\n}\n\n/** A dev server compiling another route can hold a page for a minute; webpack often longer. */\nconst NAV_TIMEOUT_MS = 90_000\n\n/** A navigation another navigation replaced, or one that ran out of time. */\nconst RETRY_NAV_RE = /timeout|ERR_ABORTED|interrupted by another navigation/i\n\n/**\n * Navigate with a dev-server-sized timeout, and once more when the first try\n * times out (the route was compiling) or is replaced by the page's own reload\n * (a dev server's full reload after a slow compile). Playwright reports the\n * second case as ERR_ABORTED, or resolves to null with no error. Both cost\n * glot.it pages on 2026-10-06: home \"could not load\" under the 30 s default,\n * and /chat dropped with no message.\n */\nexport async function gotoPatiently(page: Page, url: string): Promise<Awaited<ReturnType<Page['goto']>>> {\n const go = () => page.goto(url, { waitUntil: 'domcontentloaded', timeout: NAV_TIMEOUT_MS })\n try {\n return (await go()) ?? (await go())\n } catch (err) {\n if (!RETRY_NAV_RE.test((err as Error).message)) throw err\n return go()\n }\n}\n\nexport interface Capture {\n png: Buffer\n probes: ProbeResult\n}\n\n/** Load one surface at one viewport, screenshot it, and measure it. */\nexport async function captureSurface(\n session: BrowserSession,\n baseUrl: string,\n surface: Pick<Surface, 'path' | 'steps'>,\n viewport: Viewport,\n): Promise<Capture> {\n const ctx = await session.freshContext()\n const page = await ctx.newPage()\n const consoleErrors: string[] = []\n page.on('console', (msg) => {\n if (msg.type() === 'error' && !isGuardNoise(msg.text()) && !isFrameworkNoise(msg.text())) consoleErrors.push(msg.text().slice(0, 300))\n })\n page.on('pageerror', (err) => consoleErrors.push(String(err.message).slice(0, 300)))\n try {\n await page.setViewportSize({ width: viewport.width, height: viewport.height })\n await gotoPatiently(page, surfaceUrl(baseUrl, surface.path))\n await settle(page)\n await replay(page, surface.steps)\n const png = await page.screenshot({\n fullPage: true,\n animations: 'disabled',\n caret: 'hide',\n style: ignoreStyle(session.ignore) || undefined,\n })\n const probes = await runProbes(page, consoleErrors, session.ignore)\n return { png, probes }\n } finally {\n await ctx.close()\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Hard rule of the loop: exploring and screenshotting an app never writes\n * to it. A localhost dev server often talks to a real backend, so one stray\n * \"Delete\" click or form submit during discovery would mutate real data.\n *\n * - Every request that is not GET / HEAD / OPTIONS is aborted unless it\n * matches the per-target allowlist (reads some apps make with POST, such as\n * PostgREST `rpc/` calls or GraphQL queries).\n * - Form submission is cancelled in the page itself.\n * - Discovery never clicks an element whose label reads as destructive.\n * - Service Workers are blocked where the context is created (capture.ts):\n * requests a worker handles never reach `context.route`.\n *\n * WebSockets are not routed: a Supabase Realtime socket only subscribes, and\n * table writes go through REST, which the route sees.\n */\n\nimport type { BrowserContext } from 'playwright'\n\nconst READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])\n\n/** `\"POST /rest/v1/rpc/*\"`, or a bare path glob meaning any method. */\nexport type AllowRule = string\n\nexport interface GuardLog {\n blocked: Array<{ method: string; url: string }>\n}\n\nfunction globToRegExp(glob: string): RegExp {\n const escaped = glob.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*').replace(/\\?/g, '.')\n return new RegExp(`^${escaped}$`)\n}\n\n/** Pure decision, exported for tests: may this request leave the browser? */\nexport function isRequestAllowed(method: string, url: string, allow: readonly AllowRule[]): boolean {\n const m = method.toUpperCase()\n if (READ_METHODS.has(m)) return true\n let path: string\n try {\n const u = new URL(url)\n path = u.pathname + u.search\n } catch {\n return false\n }\n return allow.some((rule) => {\n const space = rule.indexOf(' ')\n const ruleMethod = space > 0 ? rule.slice(0, space).toUpperCase() : null\n const ruleGlob = space > 0 ? rule.slice(space + 1).trim() : rule.trim()\n if (ruleMethod && ruleMethod !== m) return false\n return globToRegExp(ruleGlob).test(path)\n })\n}\n\nconst DESTRUCTIVE_RE =\n /\\b(delete|remove|destroy|erase|discard|revoke|disconnect|uninstall|archive|cancel (?:plan|subscription)|pay|purchase|buy|checkout|charge|send|submit|publish|merge|deploy|log ?out|sign ?out|reset)\\b/i\n\n/** Pure: should discovery refuse to click an element with this label? */\nexport function isDestructiveLabel(label: string): boolean {\n return DESTRUCTIVE_RE.test(label)\n}\n\n/**\n * Cancels form submission inside every page of the context, before any app\n * script runs. Covers submit events, `form.submit()` and `requestSubmit()`.\n */\nconst NO_SUBMIT_SCRIPT = `(() => {\n addEventListener('submit', (e) => { e.preventDefault(); e.stopImmediatePropagation() }, true)\n HTMLFormElement.prototype.submit = function () {}\n HTMLFormElement.prototype.requestSubmit = function () {}\n})()`\n\nexport async function installGuard(context: BrowserContext, allow: readonly AllowRule[], log: GuardLog = { blocked: [] }): Promise<GuardLog> {\n await context.addInitScript({ content: NO_SUBMIT_SCRIPT })\n await context.route('**/*', async (route) => {\n const req = route.request()\n if (isRequestAllowed(req.method(), req.url(), allow)) return route.continue()\n log.blocked.push({ method: req.method(), url: req.url() })\n return route.abort('blockedbyclient')\n })\n return log\n}\n\n/** Console text Chromium prints for a request the guard aborted. */\nexport function isGuardNoise(text: string): boolean {\n return /ERR_BLOCKED_BY_CLIENT/.test(text)\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Elements that are not the app's UI: dev-server overlays, build stamps, and\n * Mushi's own widget. They are hidden in screenshots and left out of every\n * measurement, so the agent is never sent to \"fix\" them. On glot.it the\n * agent spent an attempt raising the contrast of a dev-only build stamp\n * (2026-10-06).\n *\n * Add your own with `--ignore <selector>` (repeatable), or mark an element\n * with `data-mushi-ux-ignore`.\n */\n\nconst DEFAULT_IGNORE: readonly string[] = [\n // Mark anything yourself\n '[data-mushi-ux-ignore]',\n // Next.js dev overlay and indicators\n 'nextjs-portal',\n '[data-nextjs-toast]',\n '[data-nextjs-dev-tools-button]',\n '#__next-build-watcher',\n // Vite / webpack dev overlays\n 'vite-error-overlay',\n '#webpack-dev-server-client-overlay',\n // Build / version stamps shown only in dev or QA builds\n '[data-qa-build-stamp]',\n '[data-build-stamp]',\n // Mushi's own widget, rewards badge and consent banner (not the app's code)\n '#mushi-mushi-widget',\n '#mushi-tier-badge',\n '#mushi-consent-banner',\n]\n\n/**\n * A selector from the command line or the studio form that cannot break out\n * of the injected stylesheet. The browser still validates it: one it cannot\n * parse is skipped there (see probes.ts), never fatal.\n */\nexport function isSafeSelector(s: string): boolean {\n return s.length > 0 && s.length <= 200 && !/[{}<>;\\\\]/.test(s) && !/^[\\s,]|,\\s*$/.test(s)\n}\n\nexport function ignoreList(extra: readonly string[] = []): string[] {\n return [...new Set([...DEFAULT_IGNORE, ...extra.map((s) => s.trim()).filter(isSafeSelector)])]\n}\n\n/** CSS that hides ignored elements in a screenshot without moving anything else. */\nexport function ignoreStyle(selectors: readonly string[]): string {\n return selectors.length ? `${selectors.join(',\\n')} { visibility: hidden !important; }` : ''\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Objective checks run on every capture. A vision model's opinion of a\n * screenshot is unreliable (Baymard: 80% of GPT-4 audit suggestions were\n * wrong or wasted effort; UICrit: 13% of zero-shot critiques valid), so the\n * loop's accept/reject leans on these numbers, not on taste.\n *\n * Contrast comes from axe-core's `color-contrast` rule, which parses modern\n * colour syntax (oklch, color-mix) itself.\n */\n\nimport { AxeBuilder } from '@axe-core/playwright'\nimport type { Page } from 'playwright'\nimport type { AxeViolation, ProbeResult } from './types.js'\n\nconst AXE_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']\nconst MAX_TARGETS = 5\n\n/** The selectors this page's browser can parse; a bad one is dropped, not fatal. */\nasync function usableSelectors(page: Page, selectors: readonly string[]): Promise<string[]> {\n if (!selectors.length) return []\n return page.evaluate((list) => {\n return list.filter((sel) => {\n try {\n document.querySelector(sel)\n return true\n } catch {\n return false\n }\n })\n }, [...selectors])\n}\n\nexport async function runProbes(\n page: Page,\n consoleErrors: readonly string[],\n ignore: readonly string[] = [],\n): Promise<ProbeResult> {\n const skip = await usableSelectors(page, ignore)\n let builder = new AxeBuilder({ page }).withTags(AXE_TAGS)\n for (const sel of skip) builder = builder.exclude(sel)\n const axe = await builder\n .analyze()\n .then((r) =>\n r.violations.map(\n (v): AxeViolation => ({\n id: v.id,\n impact: v.impact ?? null,\n help: v.help,\n count: v.nodes.length,\n targets: v.nodes.slice(0, MAX_TARGETS).map((n) => n.target.join(' ')),\n }),\n ),\n )\n // No catch: an axe failure must fail the capture. Reading it as \"no\n // violations\" would make a broken after-shot look like an improvement.\n\n const layout = await page.evaluate((skipSelectors) => {\n const root = document.documentElement\n const overflowX = root.scrollWidth > root.clientWidth + 1\n const interactive = document.querySelectorAll(\n 'a[href], button, input:not([type=hidden]), select, textarea, [role=button], [role=link], [role=tab], [role=checkbox], [role=switch], [role=menuitem]',\n )\n let smallTargets = 0\n for (const el of Array.from(interactive)) {\n const style = getComputedStyle(el)\n if (style.visibility === 'hidden' || style.display === 'none') continue\n // Not the app's UI (dev overlays, build stamps, the Mushi widget).\n if (skipSelectors.some((sel) => el.closest(sel))) continue\n // Nothing to tap: the element ignores the pointer.\n if (style.pointerEvents === 'none') continue\n // WCAG 2.5.8 exempts links inside running text.\n if (el.tagName === 'A' && style.display === 'inline') continue\n const r = el.getBoundingClientRect()\n if (r.width === 0 || r.height === 0) continue\n // Visually hidden until focused (an sr-only skip link is 1x1 and clipped).\n const clipped = style.clip.startsWith('rect(0') || style.clipPath.startsWith('inset(50%')\n if (clipped || (r.width <= 1 && r.height <= 1)) continue\n if (r.width < 24 || r.height < 24) smallTargets++\n }\n const cls = (window as unknown as { __mushiCls?: number }).__mushiCls ?? 0\n return { overflowX, smallTargets, cls }\n }, skip)\n\n return {\n axe,\n overflowX: layout.overflowX,\n smallTargets: layout.smallTargets,\n consoleErrors: [...consoleErrors],\n cls: Math.round(layout.cls * 1000) / 1000,\n }\n}\n\n/**\n * Console messages the framework's own dev tooling prints, which the app's\n * code cannot fix. On glot.it, React's key warning from Next 16's segment\n * explorer (\"Check the render method of `OuterLayoutRouter`\") sent the agent\n * into node_modules/next for a whole 15-minute attempt (2026-10-06).\n */\nconst FRAMEWORK_NOISE: readonly RegExp[] = [\n /Check the render method of `(OuterLayoutRouter|InnerLayoutRouter|LayoutRouter|SegmentViewNode|SegmentStateProvider|RenderFromTemplateContext|ScrollAndFocusHandler|HTTPAccessFallbackBoundary|RedirectBoundary|ErrorBoundaryHandler|AppRouter|HotReload|ReactDevOverlay)`/,\n /\\[(Fast Refresh|HMR)\\]/,\n /Download the React DevTools/,\n /_next\\/webpack-hmr|__nextjs_original-stack-frame/,\n]\n\nexport function isFrameworkNoise(message: string): boolean {\n return FRAMEWORK_NOISE.some((re) => re.test(message))\n}\n\nconst IMPACT_WEIGHT: Record<string, number> = { critical: 8, serious: 4, moderate: 2, minor: 1 }\n\n/**\n * One number per capture, lower is better. Used only to compare the same\n * surface before and after an agent run, never across surfaces.\n */\nexport function probePenalty(p: ProbeResult): number {\n const axe = p.axe.reduce((sum, v) => sum + (IMPACT_WEIGHT[v.impact ?? ''] ?? 1) * Math.max(1, v.count), 0)\n return axe + (p.overflowX ? 10 : 0) + p.smallTargets + p.consoleErrors.length * 5 + clsPenalty(p.cls)\n}\n\n/**\n * Layout shift up to 0.1 is \"good\" (web.dev/articles/cls), and a dev server\n * that just recompiled shifts a little on its own: glot.it's Home lost two\n * attempts to 0.085 and 0.05 (2026-10-06). Only shift past the threshold\n * counts.\n */\nexport const CLS_GOOD = 0.1\n\nfunction clsPenalty(cls: number): number {\n return cls > CLS_GOOD ? Math.ceil((cls - CLS_GOOD) * 20) : 0\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The local studio: start a run (agent, model, skill, pages) and watch it:\n * phase and progress, the burndown, every attempt's screenshot against the\n * baseline with a slider and a diff overlay, problem scores, and the agent's\n * output as it streams. Served on 127.0.0.1 only, behind a random token,\n * reading nothing but `.mushi/ux/` in the repo.\n *\n * `mushi-ux ui` opens it with the launcher; `mushi-ux run` and `open` open it\n * on one run, read-only.\n */\n\nimport { randomBytes } from 'node:crypto'\nimport type { EventEmitter } from 'node:events'\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport { basename, dirname, join, normalize, sep } from 'node:path'\nimport { z } from 'zod'\nimport { PNG } from 'pngjs'\nimport { attemptLogBase } from './agent-events.js'\nimport { changeRegions } from './image.js'\nimport { isSafeSelector } from './ignore.js'\nimport type { AgentAccount } from './launcher.js'\nimport type { LoopEvent } from './loop.js'\nimport type { ModelList } from './models.js'\nimport type { SkillListItem } from './skills.js'\nimport { loadState, type RunState } from './state.js'\nimport { STUDIO_PAGE } from './studio-page.js'\n\nexport interface Dashboard {\n url: string\n close(): Promise<void>\n}\n\nconst RUN_ID_RE = /^[0-9]{8}-[0-9]{6}-[a-z0-9]{4}$/\n\n/** Pure: resolve a requested shot path inside the run dir, or null if it escapes. */\nexport function safeShotPath(runDirPath: string, requested: string): string | null {\n if (!/^shots\\/[\\w./-]+\\.png$/.test(requested) || requested.includes('..')) return null\n const abs = normalize(join(runDirPath, requested))\n return abs.startsWith(normalize(runDirPath) + sep) ? abs : null\n}\n\n/** What the launcher form sends. Everything is checked here before a run starts. */\nexport const LaunchInput = z\n .object({\n agent: z.string().regex(/^[a-z][a-z-]{1,30}$/),\n model: z.string().max(200).regex(/^[A-Za-z0-9][A-Za-z0-9._:/?=&-]*$/).nullable().default(null),\n skill: z.string().max(300).nullable().default(null),\n devCommand: z.string().min(1).max(500),\n baseRef: z.string().max(200).regex(/^[\\w./@^~-]+$/).default('HEAD'),\n startPaths: z.array(z.string().regex(/^\\/[^\\s]{0,200}$/)).max(20).default([]),\n iterations: z.number().int().min(1).max(5).default(2),\n maxSurfaces: z.number().int().min(1).max(100).default(10),\n timeoutMin: z.number().int().min(1).max(60).default(10),\n judgeModel: z.string().max(120).nullable().default(null),\n /** Follow links from the start pages too; off visits only the pages named. */\n crawl: z.boolean().default(false),\n /** Plan each screen into small steps, then one step per attempt. */\n steps: z.boolean().default(false),\n /** A second model that may roll a kept step back (ADR 0021); null = measurements alone. */\n checkerModel: z.string().max(120).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/).nullable().default(null),\n checkerVia: z.enum(['claude-code', 'anthropic-api']).default('claude-code'),\n /** Keep edits with nothing visible, flagged for review. */\n keepInvisible: z.boolean().default(true),\n /** Selectors that are not the app's UI; added to DEFAULT_IGNORE. */\n ignore: z\n .array(z.string().trim().refine(isSafeSelector, 'Not a usable CSS selector (no { } < > ; or backslash, at most 200 characters).'))\n .max(20)\n .default([]),\n sync: z.boolean().default(false),\n })\n .strict()\nexport type LaunchInput = z.infer<typeof LaunchInput>\n\nexport interface StudioOptions {\n repoRoot: string\n /** Loop events of a run started outside the studio (`mushi-ux run`). */\n events?: EventEmitter\n /** Run to show first. */\n runId?: string\n /** Enables the launcher: starts a run and returns its id and event stream. */\n launch?: (input: LaunchInput) => Promise<{ runId: string; events: EventEmitter }>\n /** Stops a run this studio started; false when it is not running here. */\n stop?: (runId: string) => boolean\n /** Opens the finished run's PR (or adds it to its base branch's PR); rejects with the reason it cannot. */\n openPr?: (runId: string) => Promise<{ url: string; number: number; added: boolean }>\n /** Continues a stopped run with its saved settings; rejects with the reason it cannot. */\n resume?: (runId: string) => Promise<{ runId: string; events: EventEmitter }>\n listModels?: (agent: string) => Promise<ModelList>\n listSkills?: () => Promise<SkillListItem[]>\n /** One skill's hand-offs, for the launcher's \"next skill\" suggestions. */\n skillInfo?: (name: string) => Promise<{ name: string; related: string[] }>\n /** The account an agent would spend (null when the agent does not say). */\n account?: (agent: string) => Promise<AgentAccount | null>\n /** Launcher defaults: agents found, dev command guesses, refs, page suggestions. */\n options?: () => Promise<Record<string, unknown>>\n /** The Mushi console's base URL, for \"Review in console\" on mirrored runs. */\n consoleUrl?: string\n port?: number\n}\n\ninterface RunSummary {\n runId: string\n createdAt: string\n agent: string\n model: string | null\n skill: string | null\n phase: string | null\n total: number\n done: number\n}\n\nfunction summarize(s: RunState): RunSummary {\n const finished = new Set(['accepted', 'reverted', 'skipped', 'regressed', 'blocked'])\n return {\n runId: s.runId,\n createdAt: s.createdAt,\n agent: s.agent,\n model: s.model,\n skill: s.skill?.name ?? null,\n phase: s.phase ?? null,\n total: s.surfaces.length,\n done: s.surfaces.filter((x) => finished.has(x.status)).length,\n }\n}\n\nasync function readBody(req: IncomingMessage, limit = 64_000): Promise<unknown> {\n let size = 0\n const chunks: Buffer[] = []\n for await (const chunk of req) {\n size += (chunk as Buffer).length\n if (size > limit) throw new Error('Request too large')\n chunks.push(chunk as Buffer)\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')\n}\n\nexport async function startStudio(opts: StudioOptions): Promise<Dashboard> {\n const token = randomBytes(16).toString('hex')\n const uxDir = join(opts.repoRoot, '.mushi', 'ux')\n const clients = new Set<ServerResponse>()\n let active: { runId: string; events: EventEmitter } | null = null\n const send = (payload: unknown) => {\n const data = `data: ${JSON.stringify(payload)}\\n\\n`\n for (const res of clients) res.write(data)\n }\n const subscribe = (runId: string, events: EventEmitter) => {\n const onEvent = (e: LoopEvent) => send({ ...e, runId })\n events.on('event', onEvent)\n return () => events.off('event', onEvent)\n }\n const unsubscribers: Array<() => void> = []\n if (opts.events && opts.runId) {\n active = { runId: opts.runId, events: opts.events }\n unsubscribers.push(subscribe(opts.runId, opts.events))\n }\n\n const json = (res: ServerResponse, status: number, body: unknown) => {\n res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n }\n const runDirOf = (runId: string | null) => (runId && RUN_ID_RE.test(runId) ? join(uxDir, runId) : null)\n\n const server: Server = createServer((req, res) => {\n const url = new URL(req.url ?? '/', 'http://127.0.0.1')\n if (url.searchParams.get('t') !== token) {\n res.writeHead(403, { 'content-type': 'text/plain' })\n return res.end('Open the link printed by mushi-ux; it carries the access token.')\n }\n const handle = async () => {\n if (req.method === 'GET' && url.pathname === '/') {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })\n return res.end(STUDIO_PAGE)\n }\n if (req.method === 'GET' && url.pathname === '/api/meta') {\n return json(res, 200, { launcher: Boolean(opts.launch), canStop: Boolean(opts.stop), canResume: Boolean(opts.resume), canOpenPr: Boolean(opts.openPr), consoleUrl: opts.consoleUrl ?? null, active: active?.runId ?? null, initial: opts.runId ?? null, repo: basename(opts.repoRoot) })\n }\n if (req.method === 'GET' && url.pathname === '/api/runs') {\n const ids = existsSync(uxDir) ? readdirSync(uxDir).filter((d) => RUN_ID_RE.test(d)) : []\n const runs = ids\n .map((id) => loadState(join(uxDir, id)))\n .filter((s): s is RunState => s !== null)\n .map(summarize)\n .sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n return json(res, 200, { runs })\n }\n if (req.method === 'GET' && url.pathname === '/api/state') {\n const dir = runDirOf(url.searchParams.get('run'))\n return json(res, 200, dir ? loadState(dir) : null)\n }\n if (req.method === 'GET' && url.pathname === '/api/log') {\n const dir = runDirOf(url.searchParams.get('run'))\n const file = dir ? join(dir, 'run.log') : null\n const lines = file && existsSync(file) ? readFileSync(file, 'utf8').split('\\n').filter(Boolean).slice(-400) : []\n return json(res, 200, { lines })\n }\n if (req.method === 'GET' && url.pathname === '/api/steps') {\n // The agent's readable steps for one screen's attempt (latest when\n // attempt is absent), so a reloaded page still shows what it is doing.\n const dir = runDirOf(url.searchParams.get('run'))\n const key = url.searchParams.get('surface') ?? ''\n const n = url.searchParams.get('attempt')\n if (!dir || !/^[\\w.:-]{1,160}$/.test(key) || (n !== null && !/^[0-9]{1,2}$/.test(n))) return json(res, 400, { error: 'bad request' })\n const agentDir = join(dir, 'agent')\n const prefix = attemptLogBase(key, 0).slice(0, -1)\n const attempts = existsSync(agentDir)\n ? readdirSync(agentDir)\n .map((f) => (f.startsWith(prefix) && f.endsWith('.steps.log') ? Number(f.slice(prefix.length, -'.steps.log'.length)) : NaN))\n .filter((a) => Number.isInteger(a) && a > 0)\n : []\n const attempt = n !== null ? Number(n) : attempts.length ? Math.max(...attempts) : null\n const file = attempt !== null && attempts.includes(attempt) ? join(agentDir, `${prefix}${attempt}.steps.log`) : null\n const lines = file ? readFileSync(file, 'utf8').split('\\n').filter(Boolean).slice(-200) : []\n return json(res, 200, { attempt, lines })\n }\n if (req.method === 'GET' && url.pathname === '/api/events') {\n res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })\n res.write(': connected\\n\\n')\n clients.add(res)\n req.on('close', () => clients.delete(res))\n return\n }\n if (req.method === 'GET' && url.pathname === '/shot') {\n const dir = runDirOf(url.searchParams.get('run'))\n const abs = dir ? safeShotPath(dir, url.searchParams.get('p') ?? '') : null\n if (!abs || !existsSync(abs)) {\n res.writeHead(404)\n return res.end()\n }\n res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'max-age=3600' })\n return res.end(readFileSync(abs))\n }\n // Change areas from a saved diff image, for attempts recorded before they were stored.\n if (req.method === 'GET' && url.pathname === '/api/changes') {\n const dir = runDirOf(url.searchParams.get('run'))\n const abs = dir ? safeShotPath(dir, url.searchParams.get('p') ?? '') : null\n if (!abs || !existsSync(abs)) return json(res, 404, { error: 'No such diff image' })\n const png = PNG.sync.read(readFileSync(abs))\n return json(res, 200, { width: png.width, height: png.height, boxes: changeRegions(png) })\n }\n if (req.method === 'GET' && url.pathname === '/api/options') {\n return json(res, 200, opts.options ? await opts.options() : {})\n }\n if (req.method === 'GET' && url.pathname === '/api/models') {\n const agent = url.searchParams.get('agent') ?? ''\n if (!opts.listModels || !/^[a-z][a-z-]{1,30}$/.test(agent)) return json(res, 400, { error: 'Unknown agent' })\n return json(res, 200, await opts.listModels(agent))\n }\n if (req.method === 'GET' && url.pathname === '/api/skill') {\n const name = url.searchParams.get('name') ?? ''\n if (!/^[a-z0-9][a-z0-9-]{0,80}$/.test(name) || !opts.skillInfo) return json(res, 400, { error: 'Unknown skill' })\n return json(res, 200, await opts.skillInfo(name).catch(() => ({ name, related: [] })))\n }\n if (req.method === 'GET' && url.pathname === '/api/account') {\n const agent = url.searchParams.get('agent') ?? ''\n if (!/^[a-z][a-z-]{1,30}$/.test(agent)) return json(res, 400, { error: 'Unknown agent' })\n return json(res, 200, { account: opts.account ? await opts.account(agent).catch(() => null) : null })\n }\n if (req.method === 'GET' && url.pathname === '/api/skills') {\n if (!opts.listSkills) return json(res, 200, { skills: [] })\n const skills = await opts.listSkills().catch((err: Error) => {\n throw new Error(`Could not list skills: ${err.message}`)\n })\n return json(res, 200, { skills })\n }\n const stopMatch = url.pathname.match(/^\\/api\\/runs\\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\\/stop$/)\n if (req.method === 'POST' && stopMatch) {\n if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 415, { error: 'JSON only' })\n const origin = req.headers.origin\n if (origin && origin !== `http://127.0.0.1:${(server.address() as AddressInfo).port}`) return json(res, 403, { error: 'Wrong origin' })\n if (!opts.stop?.(stopMatch[1])) return json(res, 409, { error: 'That run is not running in this studio.' })\n return json(res, 202, { stopping: true })\n }\n const prMatch = url.pathname.match(/^\\/api\\/runs\\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\\/pr$/)\n if (req.method === 'POST' && prMatch) {\n if (!opts.openPr) return json(res, 404, { error: 'This view is read-only. Start the studio with `mushi-ux ui`.' })\n if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 415, { error: 'JSON only' })\n const origin = req.headers.origin\n if (origin && origin !== `http://127.0.0.1:${(server.address() as AddressInfo).port}`) return json(res, 403, { error: 'Wrong origin' })\n const pr = await opts.openPr(prMatch[1]).catch((err: Error) => err)\n if (pr instanceof Error) return json(res, 409, { error: pr.message })\n return json(res, 201, pr)\n }\n const resumeMatch = url.pathname.match(/^\\/api\\/runs\\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\\/resume$/)\n if (req.method === 'POST' && resumeMatch) {\n if (!opts.resume) return json(res, 404, { error: 'This view is read-only. Start the studio with `mushi-ux ui`.' })\n if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 415, { error: 'JSON only' })\n const origin = req.headers.origin\n if (origin && origin !== `http://127.0.0.1:${(server.address() as AddressInfo).port}`) return json(res, 403, { error: 'Wrong origin' })\n if (active && active.runId !== resumeMatch[1]) {\n const state = loadState(join(uxDir, active.runId))\n if (state && !['done', 'failed'].includes(state.phase ?? '')) return json(res, 409, { error: `Run ${active.runId} is still going. Stop it first.` })\n }\n // Not resumable (still alive elsewhere, finished, from before saved settings): say why, as a 409.\n const started = await opts.resume(resumeMatch[1]).catch((err: Error) => err)\n if (started instanceof Error) return json(res, 409, { error: started.message })\n active = started\n unsubscribers.push(subscribe(started.runId, started.events))\n send({ type: 'started', runId: started.runId })\n return json(res, 202, { runId: started.runId })\n }\n if (req.method === 'POST' && url.pathname === '/api/runs') {\n if (!opts.launch) return json(res, 404, { error: 'This view is read-only. Start the studio with `mushi-ux ui`.' })\n // A form post from another site cannot set this header or read the token.\n if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 415, { error: 'JSON only' })\n const origin = req.headers.origin\n if (origin && origin !== `http://127.0.0.1:${(server.address() as AddressInfo).port}`) return json(res, 403, { error: 'Wrong origin' })\n if (active) {\n const state = loadState(join(uxDir, active.runId))\n if (state && !['done', 'failed'].includes(state.phase ?? '')) return json(res, 409, { error: `Run ${active.runId} is still going.` })\n }\n const parsed = LaunchInput.safeParse(await readBody(req))\n if (!parsed.success) return json(res, 400, { error: parsed.error.issues[0]?.message ?? 'Invalid settings' })\n const started = await opts.launch(parsed.data)\n active = started\n unsubscribers.push(subscribe(started.runId, started.events))\n send({ type: 'started', runId: started.runId })\n return json(res, 201, { runId: started.runId })\n }\n res.writeHead(404)\n res.end()\n }\n handle().catch((err: Error) => {\n if (!res.headersSent) json(res, 500, { error: err.message.slice(0, 500) })\n else res.end()\n })\n })\n await new Promise<void>((r) => server.listen(opts.port ?? 0, '127.0.0.1', r))\n const { port: bound } = server.address() as AddressInfo\n const initial = opts.runId ? `&run=${opts.runId}` : ''\n return {\n url: `http://127.0.0.1:${bound}/?t=${token}${initial}`,\n close: () =>\n new Promise<void>((r) => {\n for (const off of unsubscribers) off()\n for (const res of clients) res.end()\n server.close(() => r())\n }),\n }\n}\n\n/** One run, read-only (used by `mushi-ux run` and `open`). `dir` is `<repo>/.mushi/ux/<runId>`. */\nexport async function startDashboard(dir: string, events?: EventEmitter, port = 0): Promise<Dashboard> {\n const repoRoot = dirname(dirname(dirname(dir)))\n return startStudio({ repoRoot, events, runId: basename(dir), port })\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Turns an agent's stream-json lines into short steps a person can follow:\n * \"Read app/page.tsx\", \"Edit globals.css\", \"Run pnpm lint\", or what the\n * agent said. The raw stream is still saved per attempt for debugging.\n *\n * Formats, as documented on 2026-10-06:\n * - Cursor CLI (cursor.com/docs/cli/reference/output-format): `assistant`\n * messages, `tool_call` started/completed keyed `<name>ToolCall`, a final\n * `result`. Only `started` is shown, so each call appears once.\n * - Claude Code: `assistant` messages whose content holds `text` and\n * `tool_use` blocks; `user` tool results are skipped.\n * - Codex `exec --json`: `item.started` / `item.completed` with\n * `command_execution`, `file_change` and `agent_message` items.\n * Unknown events are dropped; a line that is not JSON (stderr, the cloud\n * adapter's status lines) is shown as is.\n */\n\ntype AgentStepKind = 'say' | 'read' | 'edit' | 'run' | 'search' | 'tool' | 'done' | 'error'\n\nexport interface AgentStep {\n kind: AgentStepKind\n text: string\n /** File the step read or changed, when it names one. */\n path?: string\n}\n\nconst MAX_TEXT = 300\n\nconst clip = (s: string, n = MAX_TEXT) => {\n const one = s.replace(/\\s+/g, ' ').trim()\n return one.length > n ? `${one.slice(0, n - 1)}…` : one\n}\n\ntype Json = Record<string, unknown>\nconst isObj = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)\n\n/**\n * Path relative to the worktree when the agent gave an absolute one.\n * @internal Exported for tests only.\n */\nexport function shortPath(p: string, cwd?: string): string {\n const norm = p.replace(/\\\\/g, '/')\n if (cwd) {\n const base = cwd.replace(/\\\\/g, '/').replace(/\\/$/, '') + '/'\n if (norm.toLowerCase().startsWith(base.toLowerCase())) return norm.slice(base.length)\n }\n return norm\n}\n\nconst EDIT_TOOLS = /^(write|edit|multiedit|strreplace|str_replace|searchreplace|applypatch|apply_patch|delete|notebookedit|create)/i\nconst READ_TOOLS = /^(read|view|ls|list|readfile|readlints)/i\nconst SEARCH_TOOLS = /^(grep|glob|search|find|codebasesearch|semanticsearch|websearch|webfetch)/i\nconst RUN_TOOLS = /^(shell|bash|run|terminal|exec|command)/i\n\n/** One tool call, from its name and arguments, in any of the three formats. */\nfunction describeTool(name: string, args: Json, cwd?: string): AgentStep {\n const path = str(args.path) ?? str(args.file_path) ?? str(args.filePath) ?? str(args.target_file) ?? str(args.notebook_path)\n const command = str(args.command) ?? (Array.isArray(args.command) ? args.command.join(' ') : undefined)\n const pattern = str(args.pattern) ?? str(args.query) ?? str(args.globPattern) ?? str(args.glob_pattern) ?? str(args.url)\n const label = name.replace(/ToolCall$/, '')\n const p = path ? shortPath(path, cwd) : undefined\n // The kind already says what happened (\"[edit] app/page.tsx\"), so the text is just the object.\n if (EDIT_TOOLS.test(label)) return { kind: 'edit', text: `${p ?? '(a file)'}${/^delete/i.test(label) ? ' (deleted)' : ''}`, path: p }\n if (RUN_TOOLS.test(label) && command) return { kind: 'run', text: clip(command, 160) }\n if (SEARCH_TOOLS.test(label)) return { kind: 'search', text: clip(pattern ?? p ?? label, 160) }\n if (READ_TOOLS.test(label)) return { kind: 'read', text: p ?? (clip(pattern ?? '', 160) || '(a file)'), path: p }\n return { kind: 'tool', text: clip(`${label}${p ? ` ${p}` : pattern ? ` ${pattern}` : ''}`, 160) }\n}\n\nfunction textOf(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content\n .filter((c): c is Json => isObj(c) && c.type === 'text')\n .map((c) => str(c.text) ?? '')\n .join(' ')\n}\n\nfunction parseArgs(raw: unknown): Json {\n if (isObj(raw)) return raw\n if (typeof raw === 'string') {\n try {\n const v = JSON.parse(raw) as unknown\n return isObj(v) ? v : {}\n } catch {\n return {}\n }\n }\n return {}\n}\n\n/** The steps one line holds (a Claude Code message can hold several), or none. */\nexport function describeAgentLine(line: string, cwd?: string): AgentStep[] {\n const trimmed = line.trim()\n if (!trimmed) return []\n if (!trimmed.startsWith('{')) return [{ kind: 'say', text: clip(trimmed) }]\n let ev: Json\n try {\n const v = JSON.parse(trimmed) as unknown\n if (!isObj(v)) return []\n ev = v\n } catch {\n return [{ kind: 'say', text: clip(trimmed) }]\n }\n const type = str(ev.type)\n\n if (type === 'system' && ev.subtype === 'init') {\n return [{ kind: 'tool', text: `Started${str(ev.model) ? ` (${ev.model})` : ''}` }]\n }\n if (type === 'assistant' && isObj(ev.message)) {\n // Cursor partial-output flushes repeat text already shown.\n if (ev.model_call_id !== undefined) return []\n const content = ev.message.content\n const steps: AgentStep[] = []\n const said = clip(textOf(content))\n if (said) steps.push({ kind: 'say', text: said })\n if (Array.isArray(content)) {\n for (const c of content) {\n if (isObj(c) && c.type === 'tool_use' && str(c.name)) steps.push(describeTool(c.name as string, parseArgs(c.input), cwd))\n }\n }\n return steps\n }\n if (type === 'tool_call') {\n if (ev.subtype !== 'started' || !isObj(ev.tool_call)) return []\n const [key, body] = Object.entries(ev.tool_call)[0] ?? []\n if (!key || !isObj(body)) return []\n if (key === 'function') return [describeTool(str(body.name) ?? 'tool', parseArgs(body.arguments), cwd)]\n return [describeTool(key, parseArgs(body.args), cwd)]\n }\n if (type === 'result') {\n if (ev.is_error === true || (str(ev.subtype) && ev.subtype !== 'success')) {\n return [{ kind: 'error', text: clip(str(ev.result) ?? str(ev.error) ?? `Finished with ${String(ev.subtype)}`) }]\n }\n return [{ kind: 'done', text: 'Finished' }]\n }\n // Codex exec --json\n if ((type === 'item.started' || type === 'item.completed') && isObj(ev.item)) {\n const item = ev.item\n if (item.type === 'command_execution' && type === 'item.started' && str(item.command)) {\n return [{ kind: 'run', text: clip(item.command as string, 160) }]\n }\n if (item.type === 'file_change' && type === 'item.completed' && Array.isArray(item.changes)) {\n return item.changes\n .filter((c): c is Json => isObj(c) && !!str(c.path))\n .map((c) => {\n const p = shortPath(c.path as string, cwd)\n return { kind: 'edit' as const, text: p, path: p }\n })\n }\n if (item.type === 'agent_message' && type === 'item.completed' && str(item.text)) {\n return [{ kind: 'say', text: clip(item.text as string) }]\n }\n return []\n }\n if (type === 'error') return [{ kind: 'error', text: clip(str(ev.message) ?? 'Error') }]\n return []\n}\n\n/**\n * Per-attempt files under `<run>/agent/`: `<base>.steps.log` gets one\n * readable step per line as the agent works (the studio reads its tail\n * after a reload), `<base>.log` the raw output when the attempt ends.\n */\nexport function attemptLogBase(surfaceKey: string, attempt: number): string {\n return `${surfaceKey.replace(/[^\\w.-]+/g, '_')}-${attempt}`\n}\n\n/** The session id a stream-json run reports (Cursor and Claude Code put it on every event), or null. */\nexport function sessionIdOf(stdout: string): string | null {\n for (const line of stdout.split(/\\r?\\n/)) {\n if (!line.startsWith('{')) continue\n try {\n const id = (JSON.parse(line) as { session_id?: unknown }).session_id\n if (typeof id === 'string' && /^[\\w-]{6,80}$/.test(id)) return id\n } catch {\n /* not JSON */\n }\n }\n return null\n}\n\nconst ICON: Record<AgentStepKind, string> = {\n say: '›',\n read: 'read',\n edit: 'edit',\n run: 'run',\n search: 'find',\n tool: 'tool',\n done: 'done',\n error: 'error',\n}\n\n/** One line for the live log: the kind, then the text. */\nexport function formatStep(step: AgentStep): string {\n return step.kind === 'say' ? `› ${step.text}` : `[${ICON[step.kind]}] ${step.text}`\n}\n","// SPDX-License-Identifier: MIT\n/**\n * PNG helpers: decode, pad two captures to one size, pixel diff, and a\n * difference hash (dHash) for \"is this the same screen\" checks. No native\n * image library, so the package installs anywhere Node does.\n */\n\nimport pixelmatch from 'pixelmatch'\nimport { PNG } from 'pngjs'\n\nfunction decodePng(buf: Buffer): PNG {\n return PNG.sync.read(buf)\n}\n\nfunction encodePng(png: PNG): Buffer {\n return PNG.sync.write(png)\n}\n\n/** Copy `src` onto a white canvas of `width`×`height`. */\nfunction padTo(src: PNG, width: number, height: number): PNG {\n if (src.width === width && src.height === height) return src\n const out = new PNG({ width, height })\n out.data.fill(255)\n PNG.bitblt(src, out, 0, 0, Math.min(src.width, width), Math.min(src.height, height), 0, 0)\n return out\n}\n\nexport interface PixelDiff {\n /** Share of pixels that differ, 0..1, over the larger of the two sizes. */\n ratio: number\n changedPixels: number\n /**\n * Changed pixels over the \"before\" image's content pixels (those unlike\n * its background). A shifted paragraph on a mostly blank page is a small\n * share of the canvas but a large share of what is on it.\n */\n contentRatio: number\n width: number\n height: number\n /** Red-on-grey overlay of the changed pixels. */\n diffPng: Buffer\n /** Where the change is, largest first, so a viewer can zoom to it. */\n regions: ChangeRegion[]\n}\n\nexport interface ChangeRegion {\n x: number\n y: number\n w: number\n h: number\n}\n\n/** pixelmatch paints a real difference pure red (anti-aliasing is yellow, ignored). */\nfunction isDiffPixel(d: Uint8Array | Buffer, i: number): boolean {\n return d[i] === 255 && d[i + 1] === 0 && d[i + 2] === 0\n}\n\n/**\n * Pure: boxes around the changed pixels of a pixelmatch output. Changed pixels\n * are counted on a grid of `cell`-px squares; touching cells form one region;\n * each region is padded so a crop shows context. At most `max`, largest first.\n * A small change (a checkbox, a moved link) on a tall page is a few percent\n * of the pixels, which a full-size side by side hides.\n */\nexport function changeRegions(diff: { width: number; height: number; data: Uint8Array | Buffer }, cell = 16, max = 4, pad = 24): ChangeRegion[] {\n const cols = Math.ceil(diff.width / cell)\n const rows = Math.ceil(diff.height / cell)\n const hit = new Uint8Array(cols * rows)\n for (let y = 0; y < diff.height; y++) {\n for (let x = 0; x < diff.width; x++) {\n if (isDiffPixel(diff.data, (y * diff.width + x) * 4)) hit[Math.floor(y / cell) * cols + Math.floor(x / cell)] = 1\n }\n }\n const seen = new Uint8Array(cols * rows)\n const boxes: Array<ChangeRegion & { cells: number }> = []\n for (let start = 0; start < hit.length; start++) {\n if (!hit[start] || seen[start]) continue\n let minC = cols, minR = rows, maxC = 0, maxR = 0, cells = 0\n const stack = [start]\n seen[start] = 1\n while (stack.length) {\n const i = stack.pop() as number\n const c = i % cols\n const r = Math.floor(i / cols)\n cells++\n minC = Math.min(minC, c); maxC = Math.max(maxC, c); minR = Math.min(minR, r); maxR = Math.max(maxR, r)\n // 8-neighbours, and one empty cell of gap still joins (a line of text with spaces).\n for (let dr = -2; dr <= 2; dr++) {\n for (let dc = -2; dc <= 2; dc++) {\n const rr = r + dr\n const cc = c + dc\n if (rr < 0 || cc < 0 || rr >= rows || cc >= cols) continue\n const j = rr * cols + cc\n if (hit[j] && !seen[j]) {\n seen[j] = 1\n stack.push(j)\n }\n }\n }\n }\n const x = Math.max(0, minC * cell - pad)\n const y = Math.max(0, minR * cell - pad)\n boxes.push({ x, y, w: Math.min(diff.width, (maxC + 1) * cell + pad) - x, h: Math.min(diff.height, (maxR + 1) * cell + pad) - y, cells })\n }\n return boxes\n .sort((a, b) => b.w * b.h - a.w * a.h)\n .slice(0, max)\n .map(({ x, y, w, h }) => ({ x, y, w, h }))\n}\n\nexport function pixelDiff(before: Buffer, after: Buffer, threshold = 0.1): PixelDiff {\n const a = decodePng(before)\n const b = decodePng(after)\n const width = Math.max(a.width, b.width)\n const height = Math.max(a.height, b.height)\n const pa = padTo(a, width, height)\n const pb = padTo(b, width, height)\n const out = new PNG({ width, height })\n const changedPixels = pixelmatch(pa.data, pb.data, out.data, width, height, { threshold })\n const ink = contentPixels(a)\n return {\n ratio: changedPixels / (width * height),\n changedPixels,\n contentRatio: changedPixels / Math.max(ink, 1),\n width,\n height,\n diffPng: encodePng(out),\n regions: changedPixels ? changeRegions(out) : [],\n }\n}\n\n/**\n * Keep the top `maxHeight` px of a capture. Full-page shots of long pages\n * would be downscaled by a vision model until text is unreadable; the top\n * of the page is what the judge can actually see.\n */\nexport function cropTop(buf: Buffer, maxHeight: number): Buffer {\n const src = decodePng(buf)\n if (src.height <= maxHeight) return buf\n const out = new PNG({ width: src.width, height: maxHeight })\n PNG.bitblt(src, out, 0, 0, src.width, maxHeight, 0, 0)\n return encodePng(out)\n}\n\n/** Pixels that differ visibly from the image's top-left (background) colour. */\nfunction contentPixels(png: PNG): number {\n const [r0, g0, b0] = [png.data[0], png.data[1], png.data[2]]\n let n = 0\n for (let i = 0; i < png.data.length; i += 4) {\n if (Math.abs(png.data[i] - r0) + Math.abs(png.data[i + 1] - g0) + Math.abs(png.data[i + 2] - b0) > 24) n++\n }\n return n\n}\n\n/**\n * 64-bit difference hash: shrink to 9×8 greyscale by box averaging, then one\n * bit per \"left pixel brighter than right\". Near-identical screens land\n * within a few bits of each other. Returned as 16 hex chars.\n */\nexport function dHash(buf: Buffer): string {\n const png = decodePng(buf)\n const cols = 9\n const rows = 8\n const grey: number[] = []\n for (let r = 0; r < rows; r++) {\n const y0 = Math.floor((r * png.height) / rows)\n const y1 = Math.max(y0 + 1, Math.floor(((r + 1) * png.height) / rows))\n for (let c = 0; c < cols; c++) {\n const x0 = Math.floor((c * png.width) / cols)\n const x1 = Math.max(x0 + 1, Math.floor(((c + 1) * png.width) / cols))\n let sum = 0\n let n = 0\n for (let y = y0; y < y1; y++) {\n for (let x = x0; x < x1; x++) {\n const i = (y * png.width + x) * 4\n sum += 0.299 * png.data[i] + 0.587 * png.data[i + 1] + 0.114 * png.data[i + 2]\n n++\n }\n }\n grey.push(sum / n)\n }\n }\n let hex = ''\n for (let r = 0; r < rows; r++) {\n let byte = 0\n for (let c = 0; c < cols - 1; c++) {\n byte = (byte << 1) | (grey[r * cols + c] > grey[r * cols + c + 1] ? 1 : 0)\n }\n hex += byte.toString(16).padStart(2, '0')\n }\n return hex\n}\n\nexport function hammingHex(a: string, b: string): number {\n let d = 0\n for (let i = 0; i < Math.min(a.length, b.length); i += 2) {\n let x = parseInt(a.slice(i, i + 2), 16) ^ parseInt(b.slice(i, i + 2), 16)\n while (x) {\n d += x & 1\n x >>= 1\n }\n }\n return d\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Run state on disk: `.mushi/ux/<runId>/state.json` plus the PNGs beside it.\n * Written atomically (temp file + rename) after every step, so a crashed or\n * interrupted run resumes where it stopped.\n */\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { CheckerVerdict } from './checker.js'\nimport type { JudgeVerdict } from './judge.js'\nimport type { RunPullRequest } from './pr.js'\nimport type { ProbeResult, Surface } from './types.js'\n\nexport type SurfaceStatus =\n | 'pending'\n | 'baseline'\n | 'iterating'\n | 'accepted'\n | 'reverted'\n | 'skipped'\n | 'regressed'\n | 'blocked'\n\nexport interface ShotRef {\n /** PNG path relative to the run directory. */\n png: string\n probes: ProbeResult\n penalty: number\n}\n\nexport interface IterationRecord {\n n: number\n agent: string\n model: string | null\n startedAt: string\n durationMs: number\n outcome: 'accepted' | 'rejected' | 'agent_failed' | 'capture_failed' | 'no_change'\n reason: string\n commitSha: string | null\n /** Changed-pixel share per viewport, before vs after. */\n pixelDiff: Record<string, number>\n after: Record<string, ShotRef>\n diffPng: Record<string, string>\n /**\n * Where this attempt changed the screen, per viewport, against the screen\n * before it (the last kept state): image size and up to four boxes.\n */\n changes?: Record<string, { width: number; height: number; boxes: Array<{ x: number; y: number; w: number; h: number }> }>\n logTail: string\n /** agent_failed because the time box ran out (another attempt may still succeed). */\n timedOut?: boolean\n /** Steps mode: the plan step this attempt worked on. */\n step?: string\n /** Kept without a visible change: a person should read the diff (ADR 0021). */\n needsReview?: boolean\n /** The second model's review of a kept step (ADR 0021). */\n checker?: CheckerVerdict\n}\n\n/** One small, separate improvement from a screen's plan; each gets its own attempt. */\nexport interface PlanStep {\n text: string\n status: 'pending' | 'done' | 'skipped' | 'failed'\n /** The attempt that worked on it. */\n attempt?: number\n reason?: string\n}\n\nexport interface SurfaceState {\n /** Steps mode: the screen's plan, made before any edit; null when planning produced none. */\n /** `session`: the agent session that planned, resumed by each step so it keeps what it read. */\n plan?: { steps: PlanStep[]; session?: string | null } | null\n surface: Surface\n status: SurfaceStatus\n /** Why it is blocked / skipped / regressed, in a sentence. */\n note: string | null\n baseline: Record<string, ShotRef>\n iterations: IterationRecord[]\n /** Final pairwise review per viewport; advisory only. */\n judge?: JudgeVerdict[]\n}\n\n/** Where the run is, for the live views. */\nexport type RunPhase = 'starting' | 'worktree' | 'install' | 'dev-server' | 'mapping' | 'working' | 'reviewing' | 'done' | 'failed'\n\n/** Live progress of the attempt in flight, refreshed at least every HEARTBEAT_MS. */\ninterface CurrentAttempt {\n surface: string\n attempt: number\n startedAt: string\n /** The agent is stopped after this long. */\n timeoutMs?: number\n /** Steps the agent took so far (reads, edits, commands, messages). */\n steps?: number\n /** The latest step, one line (\"[edit] app/page.tsx\"). */\n lastStep?: string | null\n /** Files changed in the worktree so far (git status). */\n files?: string[]\n /** When the run last checked in; an old value means the run has stopped. */\n heartbeatAt?: string\n}\n\n/**\n * The settings a run started with, so a resume needs only the run id (from\n * the studio's Resume button or `mushi-ux run --resume <id>`). The signed-in\n * profile is saved as its login URL, never as a path (ADR 0006); the skill's\n * files are kept beside the state in `skill/`.\n */\nexport interface SavedRunOptions {\n agent: string\n model: string | null\n devCommand: string\n /** null = no install; undefined = detect from the lockfile. */\n installCommand?: string | null\n startPaths?: string[]\n crawl?: boolean\n iterations: number\n maxSurfaces: number\n agentTimeoutMs: number\n ignore?: string[]\n allow?: string[]\n judgeModel?: string | null\n loginUrl?: string | null\n /** Mirror to the console again when resumed (needs the login then too). */\n sync?: boolean\n /** Steps mode: plan each screen, then one small change per attempt. */\n steps?: boolean\n /** The reviewing model that may veto a kept step (ADR 0021). */\n checker?: { via: 'claude-code' | 'anthropic-api'; model: string } | null\n /** Keep edits with nothing visible, flagged for review. */\n keepInvisible?: boolean\n}\n\nexport interface RunState {\n version: 1\n runId: string\n baseUrl: string\n createdAt: string\n updatedAt: string\n agent: string\n model: string | null\n /** Skill the agent applies, if any (name and where it came from). */\n skill?: { name: string; source: string } | null\n /** Git ref the worktree branched from (HEAD unless --base). */\n baseRef?: string\n phase?: RunPhase\n /** One line on what the phase is doing (\"npm ci\", \"Home, attempt 2 of 2\"). */\n phaseDetail?: string | null\n /** The screen and attempt the agent is on, while it works. */\n current?: CurrentAttempt | null\n finishedAt?: string | null\n /** Why the run stopped, when it failed. */\n error?: string | null\n /** Stopped from the studio rather than failed. */\n stopped?: boolean\n /** Model of the final review; null when the review is off. */\n judgeModel?: string | null\n /** Settings to resume with; absent on runs from before 2026-10-06. */\n options?: SavedRunOptions\n /** The worktree's install finished; a run killed mid-install installs again. */\n installed?: boolean\n /** Worktree and branch the agent edits; null before the worktree exists. */\n worktree: string | null\n branch: string | null\n baseSha: string | null\n /** The PR the studio opened from the branch, or the existing PR the run was added to. */\n pr?: RunPullRequest | null\n surfaces: SurfaceState[]\n}\n\nexport function runDir(repoRoot: string, runId: string): string {\n return join(repoRoot, '.mushi', 'ux', runId)\n}\n\nexport function newRunId(now = new Date()): string {\n const stamp = now.toISOString().replace(/[-:]/g, '').replace(/\\..+$/, '').replace('T', '-')\n return `${stamp}-${Math.random().toString(36).slice(2, 6)}`\n}\n\nexport function saveState(dir: string, state: RunState): void {\n mkdirSync(dir, { recursive: true })\n state.updatedAt = new Date().toISOString()\n const file = join(dir, 'state.json')\n const tmp = `${file}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(state, null, 2))\n renameSync(tmp, file)\n}\n\nexport function loadState(dir: string): RunState | null {\n const file = join(dir, 'state.json')\n if (!existsSync(file)) return null\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunState\n if (parsed.version !== 1) throw new Error(`Unsupported run state version ${String(parsed.version)} in ${file}`)\n return parsed\n}\n\n/** Write a PNG under the run directory; returns its relative path. */\nexport function savePng(dir: string, rel: string, png: Buffer): string {\n const abs = join(dir, rel)\n mkdirSync(dirname(abs), { recursive: true })\n writeFileSync(abs, png)\n return rel.replace(/\\\\/g, '/')\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The studio's single page (served by dashboard.ts). Plain HTML + a small\n * script: no build step, no network beyond its own 127.0.0.1 server.\n *\n * Launcher: agent → live model list (with the model's own settings, e.g.\n * effort and context) → skill from the skills repo → pages → start.\n * Run view: phase and progress, burndown, every attempt's screenshot against\n * the baseline (slider, changed pixels), problems, and the agent's output.\n */\n\nexport const STUDIO_PAGE = `<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Mushi UX studio</title>\n<style>\n:root{--bg:#f6f6f3;--panel:#fff;--fg:#1c1c1a;--muted:#66665f;--line:#e2e2dc;--accent:#4f7f22;--accentfg:#fff;\n--ok:#2f7d32;--okbg:#e6f3e6;--warn:#8a5a00;--warnbg:#fdf1d8;--bad:#a12a2a;--badbg:#fbe4e4;--info:#2b5c9a;--infobg:#e3edf9;--idle:#55554f;--idlebg:#ecece8}\n@media (prefers-color-scheme:dark){:root{--bg:#141413;--panel:#1d1d1b;--fg:#ececea;--muted:#a3a39c;--line:#2e2e2b;--accent:#9ccf5f;--accentfg:#14200a;\n--ok:#8fd394;--okbg:#1e3320;--warn:#f1c46b;--warnbg:#3a2e14;--bad:#f19a9a;--badbg:#3b1d1d;--info:#9cc2f2;--infobg:#1b2a3d;--idle:#c4c4bd;--idlebg:#2a2a27}}\n*{box-sizing:border-box}body{margin:0;font:14px/1.45 system-ui,-apple-system,Segoe UI,sans-serif;background:var(--bg);color:var(--fg)}\nbutton,select,input,textarea{font:inherit;color:inherit}\nheader{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel)}\nh1{font-size:15px;margin:0;display:flex;gap:6px;align-items:center}h1 small{color:var(--muted);font-weight:400}\n.grow{flex:1}\n.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 12px;cursor:pointer}\n.btn.primary{background:var(--accent);color:var(--accentfg);border-color:transparent;font-weight:600}\n.btn:disabled{opacity:.5;cursor:not-allowed}.btn:focus-visible,select:focus-visible,input:focus-visible,nav button:focus-visible{outline:2px solid var(--accent);outline-offset:1px}\nselect,input[type=text],input[type=number],textarea{border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 8px;min-width:0}\n.status{padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel);display:grid;gap:6px}\n.status .top{display:flex;flex-wrap:wrap;gap:6px 12px;align-items:center}\n.meter{height:8px;background:var(--idlebg);border-radius:4px;overflow:hidden;display:flex}.meter i{display:block;height:100%}\n.chip{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:999px;font-size:12px;font-weight:600;white-space:nowrap}\n.s-accepted,.p-done{background:var(--okbg);color:var(--ok)}.s-reverted,.p-failed{background:var(--badbg);color:var(--bad)}.s-regressed,.s-interrupted{background:var(--warnbg);color:var(--warn)}\n.s-iterating,.s-baseline,.p-working,.p-install,.p-worktree,.p-dev-server,.p-mapping,.p-reviewing,.p-starting{background:var(--infobg);color:var(--info)}.s-pending,.s-skipped,.s-blocked{background:var(--idlebg);color:var(--idle)}\n.dot{width:8px;height:8px;border-radius:50%;background:currentColor;display:inline-block}.live .dot{animation:pulse 1.2s infinite}@keyframes pulse{50%{opacity:.25}}\n@media (prefers-reduced-motion:reduce){.live .dot{animation:none}}\n.sub{color:var(--muted);font-size:12px}.mono{font-family:ui-monospace,monospace;font-size:12px}\nmain{display:grid;grid-template-columns:minmax(240px,320px) 1fr;min-height:calc(100vh - 110px)}\n@media (max-width:860px){main{grid-template-columns:1fr}}\nnav{border-right:1px solid var(--line);overflow:auto;max-height:calc(100vh - 110px)}\n@media (max-width:860px){nav{max-height:260px;border-right:0;border-bottom:1px solid var(--line)}}\nnav button{all:unset;box-sizing:border-box;display:block;width:100%;padding:9px 14px;border-bottom:1px solid var(--line);cursor:pointer}\nnav button[aria-current=true]{background:var(--panel);box-shadow:inset 3px 0 0 var(--accent)}\n.row{display:flex;justify-content:space-between;gap:8px;align-items:center;min-width:0}.row .chip{flex-shrink:0}.label{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\nsection.detail{padding:14px 18px;min-width:0}\n.toolbar{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0}\n.seg{display:inline-flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}.seg button{all:unset;box-sizing:border-box;padding:5px 10px;cursor:pointer;font-size:12px}\n.seg button[aria-pressed=true]{background:var(--fg);color:var(--bg)}\n.compare{position:relative;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--panel)}\n.compare.mobile{max-width:420px}\n.split{display:grid;gap:16px;align-items:start}.split>*{min-width:0}\n.att[aria-busy=true]{grid-column:1/-1;cursor:default}.att[aria-busy=true] .ph{height:36px}.att .mono{overflow-wrap:anywhere}\n@media (min-width:1100px){.split.mobile{grid-template-columns:minmax(0,420px) minmax(0,1fr)}.split.mobile .side h3:first-child{margin-top:0}}\n.compare img{display:block;width:100%;height:auto}.compare .after{position:absolute;inset:0;clip-path:inset(0 0 0 var(--cut,50%))}\n.compare .diff{position:absolute;inset:0;mix-blend-mode:multiply;opacity:.85}\n.pair{display:grid;grid-template-columns:1fr 1fr;gap:8px}.pair figure{margin:0;min-width:0}.pair figcaption{font-size:11px;color:var(--muted);margin-bottom:3px}\n.pair img{display:block;width:100%;height:auto;border:1px solid var(--line);border-radius:8px;background:var(--panel)}\n.crop{border:1px solid var(--line);border-radius:8px;background-repeat:no-repeat;background-color:var(--panel);width:100%}\n.changes{display:grid;gap:12px}.changes h4{margin:0 0 4px;font-size:12px;color:var(--muted);font-weight:600}\n.cap{display:flex;justify-content:space-between;font-size:12px;color:var(--muted);margin-top:4px;gap:8px}\ninput[type=range]{width:100%;max-width:100%}\n.plan{list-style:none;margin:6px 0 4px;padding:0;display:grid;gap:6px}.plan li{display:flex;gap:8px;align-items:flex-start;font-size:13px;border:1px solid var(--line);border-radius:8px;padding:6px 8px;background:var(--panel)}.plan .mark{width:16px;flex:none;text-align:center;font-weight:600}.pl-done .mark{color:var(--ok)}.pl-failed .mark{color:var(--bad)}.pl-skipped .mark,.pl-pending .mark{color:var(--idle)}.pl-now{border-color:var(--info)}.pl-now .mark{color:var(--info)}\n.attempts{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px;margin-top:14px}\n.att{all:unset;box-sizing:border-box;cursor:pointer;border:1px solid var(--line);border-radius:10px;background:var(--panel);overflow:hidden;display:flex;flex-direction:column}\n.att[aria-pressed=true]{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}\n.att img{width:100%;height:120px;object-fit:cover;object-position:top;background:var(--idlebg);display:block}\n.att .body{padding:8px 10px;display:grid;gap:4px}\n.ph{height:120px;display:grid;place-items:center;background:var(--idlebg);color:var(--muted);font-size:12px}\n.problems{margin:8px 0 0;padding-left:18px;font-size:13px}\npre{white-space:pre-wrap;word-break:break-word;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px;max-height:260px;overflow:auto;font-size:12px;margin:0}\nh3{font-size:13px;margin:18px 0 6px}\n.empty{color:var(--muted);padding:24px}\n.form{max-width:860px;margin:0 auto;padding:18px 16px;display:grid;gap:14px}\n.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:14px 16px;display:grid;gap:10px}\n.card h2{font-size:14px;margin:0}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px}\nlabel.f{display:grid;gap:4px;font-size:12px;color:var(--muted)}label.f>span{font-weight:600;color:var(--fg)}\n.params{display:flex;flex-wrap:wrap;gap:10px}\n.pills{display:flex;flex-wrap:wrap;gap:6px}.pill{all:unset;cursor:pointer;border:1px solid var(--line);border-radius:999px;padding:2px 8px;font-size:12px}\n.pill[aria-pressed=true]{background:var(--fg);color:var(--bg)}\n.note{font-size:12px;color:var(--muted)}.warn{color:var(--warn)}.err{color:var(--bad)}\n.card h2 .n{display:inline-grid;place-items:center;width:20px;height:20px;border-radius:999px;background:var(--fg);color:var(--bg);font-size:11px;margin-right:6px}\n.lede{font-size:12px;color:var(--muted);margin:-4px 0 0}\n.choice{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:8px}\n.choice label{display:flex;gap:8px;align-items:flex-start;border:1px solid var(--line);border-radius:10px;padding:10px;cursor:pointer;font-size:12px;color:var(--muted)}\n.choice label b{display:block;color:var(--fg);font-size:13px}\n.choice label:has(input:checked){border-color:var(--fg)}\n.summary{border:1px dashed var(--line);border-radius:10px;padding:10px;font-size:12px;display:grid;gap:4px}\n.summary b{color:var(--fg)}\ndetails.adv summary{cursor:pointer;font-size:12px;color:var(--muted)}\ndetails.log{border-top:1px solid var(--line);background:var(--panel)}details.log summary{padding:8px 16px;cursor:pointer;font-size:12px;color:var(--muted)}details.log pre{border:0;border-radius:0;max-height:220px}details.steps{margin-top:8px}details.steps summary{cursor:pointer;font-size:12px;color:var(--muted)}details.steps pre{max-height:260px}\n[hidden]{display:none!important}\n</style></head><body>\n<header>\n <h1><svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"9\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M8 12l3 3 5-6\" fill=\"none\" stroke=\"var(--accent)\" stroke-width=\"2.4\" stroke-linecap=\"round\"/></svg>Mushi UX <small id=\"repo\"></small></h1>\n <div class=\"grow\"></div>\n <label class=\"sub\" for=\"runPick\">Run</label><select id=\"runPick\" aria-label=\"Run\"></select>\n <button class=\"btn primary\" id=\"newBtn\" hidden>+ New run</button>\n</header>\n<div class=\"status\" id=\"status\" hidden>\n <div class=\"top\"><span id=\"phase\" class=\"chip\"></span><span id=\"phaseDetail\" class=\"sub\"></span><span class=\"grow\"></span><span id=\"clock\" class=\"sub mono\"></span><button class=\"btn\" id=\"stopBtn\" hidden>■ Stop</button><button class=\"btn primary\" id=\"resumeBtn\" hidden>▶ Resume</button><button class=\"btn primary\" id=\"prBtn\" hidden>Open draft PR</button><a class=\"btn\" id=\"prLink\" hidden target=\"_blank\" rel=\"noopener\"></a><a class=\"btn\" id=\"consoleLink\" hidden target=\"_blank\" rel=\"noopener\" title=\"The run, its screens and the merge button in the Mushi console\">Review in console ↗</a></div>\n <div class=\"meter\" id=\"meter\" role=\"img\"></div>\n <div class=\"sub\" id=\"who\"></div>\n</div>\n<div id=\"launcher\" hidden></div>\n<main id=\"runview\" hidden><nav id=\"list\" aria-label=\"Screens\"></nav><section class=\"detail\" id=\"detail\"><p class=\"empty\">Pick a screen.</p></section></main>\n<details class=\"log\" id=\"logbox\" hidden><summary>Run log</summary><pre id=\"runlog\"></pre></details>\n<script>\nconst T = new URLSearchParams(location.search).get('t')\nconst q = (p) => p + (p.includes('?') ? '&' : '?') + 't=' + T\nconst esc = (s) => String(s ?? '').replace(/[&<>\"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' })[c])\nconst api = (p, init) => fetch(q(p), init).then(async (r) => { const b = await r.json().catch(() => ({})); if (!r.ok) throw new Error(b.error || ('HTTP ' + r.status)); return b })\nconst STATUS = { accepted: 'Improved', reverted: 'Rolled back', regressed: 'Moved by another change', iterating: 'Agent working', baseline: 'Measuring', interrupted: 'Stopped mid-attempt', pending: 'Queued', skipped: 'No change needed', blocked: 'Not finished' }\nconst PHASE = { starting: 'Starting', worktree: 'Creating worktree', install: 'Installing', 'dev-server': 'Starting dev server', mapping: 'Mapping screens', working: 'Working', reviewing: 'Reviewing', done: 'Done', failed: 'Failed' }\nconst FINISHED = ['accepted', 'reverted', 'skipped', 'regressed', 'blocked']\nconst store = { get(k) { try { return JSON.parse(localStorage.getItem('mushi-ux:' + k)) } catch { return null } }, set(k, v) { try { localStorage.setItem('mushi-ux:' + k, JSON.stringify(v)) } catch {} } }\nlet meta = null, runs = [], runId = null, state = null, selected = null, vp = 'mobile', diffOn = false, pick = null, view = 'changes'\nconst agentLog = {}, runLog = [], stepsFetched = new Set()\nconst chip = (st) => '<span class=\"chip s-' + st + '\">' + esc(STATUS[st] || st) + '</span>'\nconst shot = (p) => q('/shot?run=' + encodeURIComponent(runId) + '&p=' + encodeURIComponent(p))\nconst dur = (ms) => { const s = Math.max(0, Math.round(ms / 1000)); return s < 60 ? s + 's' : Math.floor(s / 60) + 'm ' + String(s % 60).padStart(2, '0') + 's' }\n\n// ── Run view ───────────────────────────────────────────────────────────────\nfunction renderStatus() {\n const box = document.getElementById('status')\n if (!state) { box.hidden = true; return }\n box.hidden = false\n // A run that stopped mid-phase without saying so (process killed, machine slept) is not live.\n const unfinished = !['done', 'failed'].includes(state.phase || 'starting')\n // A run this studio did not start (another studio, mushi-ux run) is live while it checks in.\n const interrupted = unfinished && !(meta && runId === meta.active) && quietMinutes() > 0\n const ph = interrupted ? 'failed' : (state.phase || 'starting'), live = unfinished && !interrupted\n const el = document.getElementById('phase')\n el.className = 'chip p-' + ph + (live ? ' live' : '')\n el.innerHTML = (live ? '<span class=\"dot\"></span>' : '') + esc(interrupted ? 'Interrupted' : (PHASE[ph] || ph))\n const pd = document.getElementById('phaseDetail')\n pd.textContent = interrupted\n ? 'This run stopped while ' + (PHASE[state.phase] || 'working').toLowerCase() + '. ' + (resumable() ? 'Resume carries on from the first unfinished screen.' : 'Continue it with: mushi-ux run --resume ' + state.runId)\n : state.error ? state.error.split('\\\\n')[0] : (state.phaseDetail || '')\n const quiet = live ? quietMinutes() : 0\n if (quiet) pd.textContent += ' · No check-in for ' + quiet + ' min: the run may have stopped. Check the terminal that started it.'\n // A read-only view (mushi-ux open) has no Resume button: say how to carry on.\n if (state.phase === 'failed' && !resumable()) pd.textContent += ' · Continue it with: mushi-ux run --resume ' + state.runId\n pd.className = state.error || interrupted ? 'sub err' : quiet ? 'sub warn' : 'sub'\n const total = state.surfaces.length, counts = {}\n for (const s of state.surfaces) counts[shownStatus(s)] = (counts[shownStatus(s)] || 0) + 1\n const done = state.surfaces.filter((s) => FINISHED.includes(s.status)).length\n const seg = (k, color) => counts[k] ? '<i style=\"width:' + (counts[k] / Math.max(1, total) * 100) + '%;background:' + color + '\" title=\"' + esc(STATUS[k]) + ' ' + counts[k] + '\"></i>' : ''\n const meter = document.getElementById('meter')\n meter.innerHTML = seg('accepted', 'var(--ok)') + seg('regressed', 'var(--warn)') + seg('reverted', 'var(--bad)') + seg('skipped', 'var(--idle)') + seg('blocked', 'var(--idle)') + seg('iterating', 'var(--info)')\n meter.setAttribute('aria-label', done + ' of ' + total + ' screens finished')\n const parts = [done + ' of ' + total + ' screens done', state.agent + (state.model ? ' · ' + state.model : '')]\n if (state.skill) parts.push('skill ' + state.skill.name)\n if (state.branch) parts.push(state.branch + (state.baseRef ? ' (from ' + state.baseRef + ')' : ''))\n document.getElementById('who').innerHTML = parts.map(esc).join(' · ') + ' ' + Object.entries(counts).map(([k, n]) => chip(k).replace('</span>', ' ' + n + '</span>')).join(' ')\n const stop = document.getElementById('stopBtn')\n stop.hidden = !(meta && meta.canStop && live && runId === meta.active)\n stop.disabled = false\n // Interrupted, failed or stopped: carry on from where it stopped, with the settings it started with.\n const resumeBtn = document.getElementById('resumeBtn')\n resumeBtn.hidden = !((interrupted || state.phase === 'failed') && resumable())\n resumeBtn.disabled = false\n // A finished run with kept changes: open its PR (or add it to the PR its branch came from), then merge from the console.\n const kept = state.surfaces.some((x) => x.iterations.some((it) => it.outcome === 'accepted' && it.commitSha))\n const prBtn = document.getElementById('prBtn'), prLink = document.getElementById('prLink')\n prBtn.hidden = !(meta && meta.canOpenPr && state.phase === 'done' && kept && !state.pr)\n prBtn.textContent = (state.baseRef || '').startsWith('origin/mushi-ux/') ? 'Add to its pull request' : 'Open draft PR'\n prLink.hidden = !state.pr\n if (state.pr) { prLink.href = state.pr.url; prLink.textContent = 'PR #' + state.pr.number + (state.pr.added ? ' (added) ↗' : ' ↗'); prLink.title = 'Merge it from the Mushi console once its checks pass' }\n // A mirrored run is reviewed and merged in the console; link straight to it.\n const consoleLink = document.getElementById('consoleLink')\n consoleLink.hidden = !(meta && meta.consoleUrl && state.options && state.options.sync)\n if (!consoleLink.hidden) consoleLink.href = meta.consoleUrl + '/ux-runs?run=' + encodeURIComponent(state.runId)\n tick()\n}\n/** Minutes since the run last saved its state (it does every 30 s while alive); 0 while it is fresh. */\nfunction quietMinutes() {\n const hb = state && (state.updatedAt || (state.current && state.current.heartbeatAt))\n const gap = hb ? Date.now() - Date.parse(hb) : 0\n return gap > 3 * 60000 ? Math.floor(gap / 60000) : 0\n}\n/** The run is not going anywhere: it failed or stopped, or its process died without saying so. */\nfunction runIsDead() {\n if (!state) return false\n if (state.phase === 'failed') return true\n const unfinished = state.phase !== 'done'\n return unfinished && !(meta && runId === meta.active) && quietMinutes() > 0\n}\n/** A screen the agent was on when the run died shows that, not \"Agent working\". */\nfunction shownStatus(s) { return s.status === 'iterating' && runIsDead() ? 'interrupted' : s.status }\nfunction tick() {\n if (!state) return\n const dead = runIsDead()\n // A dead run's clock stops at its last check-in instead of counting on.\n const end = state.finishedAt ? Date.parse(state.finishedAt) : dead ? Date.parse(state.updatedAt) : Date.now()\n let txt = 'elapsed ' + dur(end - Date.parse(state.createdAt))\n if (state.current && !state.finishedAt && !dead) txt = 'this attempt ' + dur(Date.now() - Date.parse(state.current.startedAt)) + (state.current.timeoutMs ? ' of ' + dur(state.current.timeoutMs) : '') + ' · ' + txt\n document.getElementById('clock').textContent = txt\n}\nsetInterval(tick, 1000)\n// Events can be missing (a run started elsewhere, a dropped stream): re-read an unfinished run's state.\nsetInterval(() => { if (state && !['done', 'failed'].includes(state.phase || 'starting') && !document.hidden) loadState() }, 15000)\n\nfunction workingCard(s) {\n const c = state.current && state.current.surface === s.surface.key ? state.current : null\n const n = c ? c.attempt : s.iterations.length + 1\n if (runIsDead()) {\n return '<div class=\"att\"><div class=\"ph\">Stopped</div><div class=\"body\"><div class=\"row\"><strong>Attempt ' + n + '</strong>' + chip('interrupted') + '</div><div class=\"sub\">The run stopped during this attempt. Its unfinished edits are thrown away and it runs again on Resume.</div></div></div>'\n }\n let body = '<div class=\"row\"><strong>Attempt ' + n + '</strong><span class=\"chip s-iterating\">working</span></div>'\n if (c) {\n body += '<div class=\"sub\">' + (c.steps ? c.steps + ' step' + (c.steps === 1 ? '' : 's') : 'Reading the brief') + (c.lastStep ? ' · ' + esc(c.lastStep) : '') + '</div>'\n if (c.files && c.files.length) body += '<div class=\"sub mono\">Changed so far: ' + c.files.slice(0, 6).map(esc).join(', ') + (c.files.length > 6 ? ' +' + (c.files.length - 6) + ' more' : '') + '</div>'\n }\n return '<div class=\"att\" aria-busy=\"true\"><div class=\"ph live\" style=\"color:var(--info)\"><span><span class=\"dot\"></span> In progress</span></div><div class=\"body\">' + body + '</div></div>'\n}\n/** Steps mode: the screen's plan as a checklist, the step being worked on marked. */\nfunction planHtml(s) {\n if (!s.plan || !s.plan.steps || !s.plan.steps.length) return ''\n const working = shownStatus(s) === 'iterating'\n const now = working ? s.plan.steps.find((p) => p.status === 'pending') : null\n const MARK = { done: '✓', skipped: '–', failed: '✗', pending: '○' }\n const LABEL = { done: 'kept', skipped: 'not needed', failed: 'rolled back', pending: 'to do' }\n return '<h3>Plan: ' + s.plan.steps.filter((p) => p.status === 'done').length + ' of ' + s.plan.steps.length + ' steps kept</h3><ol class=\"plan\">' + s.plan.steps.map((p) => {\n const cur = p === now\n const why = p.reason ? p.reason.replace(/^Step \\\\d+\\\\/\\\\d+: /, '') : ''\n return '<li class=\"pl-' + (cur ? 'now' : p.status) + '\"><span class=\"mark\" aria-hidden=\"true\">' + (cur ? '▶' : MARK[p.status]) + '</span><div><div>' + esc(p.text) + ' <span class=\"sub\">(' + (cur ? 'working now' : LABEL[p.status]) + ')</span></div>' + (why ? '<div class=\"sub\">' + esc(why) + '</div>' : '') + '</div></li>'\n }).join('') + '</ol>'\n}\nfunction attemptsWithShots(s) { return s.iterations.filter((i) => i.after && (i.after.desktop || i.after.mobile)) }\nfunction renderRun() {\n renderStatus()\n const list = document.getElementById('list')\n if (!state) { list.innerHTML = ''; document.getElementById('detail').innerHTML = '<p class=\"empty\">No run selected.</p>'; return }\n const cur = state.current && state.current.surface\n list.innerHTML = state.surfaces.map((s) =>\n '<button data-k=\"' + esc(s.surface.key) + '\" aria-current=\"' + (s.surface.key === selected) + '\"><div class=\"row\"><span class=\"label\">' + (s.surface.key === cur && !runIsDead() ? '<span class=\"live\" style=\"color:var(--info)\"><span class=\"dot\"></span></span> ' : '') + esc(s.surface.label) + '</span>' + chip(shownStatus(s)) + '</div><div class=\"sub mono\">' + esc(s.surface.path) + (s.surface.steps.length ? ' › ' + esc(s.surface.steps.map((x) => x.label).join(' › ')) : '') + (s.iterations.length ? ' · ' + s.iterations.length + ' attempt' + (s.iterations.length === 1 ? '' : 's') : '') + '</div></button>').join('') || '<p class=\"empty\">' + (state.phase === 'mapping' ? 'Mapping screens…' : 'No screens yet.') + '</p>'\n list.querySelectorAll('button').forEach((b) => b.onclick = () => { selected = b.dataset.k; pick = null; renderRun() })\n const s = state.surfaces.find((x) => x.surface.key === selected) || state.surfaces.find((x) => x.surface.key === cur) || state.surfaces[0]\n const box = document.getElementById('detail')\n if (!s) {\n box.innerHTML = state.error\n ? '<h3>The run stopped</h3><pre>' + esc(state.error) + '</pre><p class=\"sub\">The run log below has the full output. Fix the cause, then start a new run.</p>'\n : '<p class=\"empty\">' + esc(PHASE[state.phase] || 'Waiting') + '…</p>'\n if (state.error) document.getElementById('logbox').open = true\n return\n }\n selected = s.surface.key\n const atts = attemptsWithShots(s)\n const chosen = pick == null ? atts[atts.length - 1] : atts.find((a) => a.n === pick)\n const base = s.baseline[vp] || s.baseline.desktop, after = chosen && (chosen.after[vp] || null)\n let html = '<div class=\"row\"><h2 style=\"margin:0;font-size:18px\">' + esc(s.surface.label) + '</h2>' + chip(shownStatus(s)) + '</div>'\n if (s.note) html += '<p class=\"sub\">' + esc(s.note) + '</p>'\n html += '<div class=\"toolbar\"><div class=\"seg\" role=\"group\" aria-label=\"Viewport\">' + ['mobile', 'desktop'].map((v) => '<button data-vp=\"' + v + '\" aria-pressed=\"' + (v === vp) + '\">' + v + '</button>').join('') + '</div>'\n if (after) html += '<div class=\"seg\" role=\"group\" aria-label=\"How to compare\">' + [['changes', 'Changes'], ['side', 'Side by side'], ['slider', 'Slider']].map(([v, l]) => '<button data-view=\"' + v + '\" aria-pressed=\"' + (v === view) + '\">' + l + '</button>').join('') + '</div>'\n if (after && view === 'slider') html += '<label class=\"sub\"><input type=\"checkbox\" id=\"diff\"' + (diffOn ? ' checked' : '') + '> Show changed pixels</label>'\n // Wide screens: the phone screenshot on the left, attempts and the agent's steps beside it.\n html += '</div><div class=\"split ' + vp + '\"><div>'\n let problemsHtml = ''\n if (base) {\n // Before = the screen this attempt started from (the last kept step), so every view shows what THIS attempt changed.\n const prev = after ? startedFrom(s, chosen.n, vp) : null\n if (after && view === 'changes') html += changesHtml(prev, after, chosen, s)\n else if (after && view === 'side') html += '<div class=\"pair\"><figure><figcaption>Before ' + esc(stepName(s, chosen.n, true)) + ' · problem score ' + prev.penalty + '</figcaption><img alt=\"Before\" src=\"' + shot(prev.png) + '\"></figure><figure><figcaption>' + esc(stepName(s, chosen.n)) + ' · problem score ' + after.penalty + '</figcaption><img alt=\"After\" src=\"' + shot(after.png) + '\"></figure></div>'\n else {\n html += '<div class=\"compare ' + vp + '\" id=\"cmp\"><img alt=\"Before\" src=\"' + shot((prev || base).png) + '\">' + (after ? '<img class=\"after\" alt=\"After\" src=\"' + shot(after.png) + '\">' : '') + (after && diffOn && chosen.diffPng[vp] ? '<img class=\"diff\" alt=\"Changed pixels\" src=\"' + shot(chosen.diffPng[vp]) + '\">' : '') + '</div>'\n if (after) html += '<input type=\"range\" id=\"cut\" min=\"0\" max=\"100\" value=\"50\" aria-label=\"Before / after split\"><div class=\"cap\"><span>◀ Before · problem score ' + prev.penalty + '</span><span>' + esc(stepName(s, chosen.n)) + ' · problem score ' + after.penalty + ' ▶</span></div><p class=\"sub\">Drag the handle: left of it is before, right of it is after. One screenshot split in two, not cut off.</p>'\n else html += '<div class=\"cap\"><span>Baseline · problem score ' + base.penalty + '</span><span>' + (shownStatus(s) === 'iterating' ? 'Agent working…' : '') + '</span></div>'\n }\n const probes = (after || base).probes, lines = []\n for (const a of probes.axe || []) lines.push(a.help + ' (' + a.count + ')')\n if (probes.overflowX) lines.push('Scrolls sideways')\n if (probes.smallTargets) lines.push(probes.smallTargets + ' tap target(s) under 24 px')\n for (const e of (probes.consoleErrors || []).slice(0, 3)) lines.push('Console: ' + e)\n if (lines.length) problemsHtml = '<h3>Problems measured on ' + (after ? 'attempt ' + chosen.n : 'the baseline') + ' (' + vp + ')</h3><ul class=\"problems\">' + lines.map((l) => '<li>' + esc(l) + '</li>').join('') + '</ul>'\n } else html += '<p class=\"empty\">No screenshot yet.</p>'\n html += '</div><div class=\"side\">' + planHtml(s) + '<h3>Attempts</h3><div class=\"attempts\">' + s.iterations.map((i) => {\n const a = i.after[vp] || i.after.desktop || i.after.mobile\n const tone = i.outcome === 'accepted' ? 'accepted' : i.outcome === 'rejected' || i.outcome === 'capture_failed' ? 'reverted' : 'skipped'\n return '<button class=\"att\" data-n=\"' + i.n + '\" aria-pressed=\"' + (chosen && chosen.n === i.n) + '\"' + (a ? '' : ' disabled') + '>' + (a ? '<img alt=\"Attempt ' + i.n + '\" loading=\"lazy\" src=\"' + shot(a.png) + '\">' : '<div class=\"ph\">no screenshot</div>') + '<div class=\"body\"><div class=\"row\"><strong>Attempt ' + i.n + '</strong>' + chip(tone).replace(/>[^<]+</, '>' + esc(i.outcome.replace('_', ' ')) + '<') + '</div>' + (i.needsReview ? '<div class=\"sub warn\">Needs your review: nothing visible changed</div>' : '') + (i.checker ? '<div class=\"sub\">' + esc(checkerLine(i.checker)) + '</div>' : '') + '<div class=\"sub\">' + esc(i.reason) + '</div><div class=\"sub mono\">' + dur(i.durationMs) + (i.pixelDiff[vp] != null ? ' · ' + (i.pixelDiff[vp] * 100).toFixed(1) + '% px' : '') + (i.commitSha ? ' · ' + i.commitSha.slice(0, 8) : '') + '</div></div></button>'\n }).join('') + (s.status === 'iterating' ? workingCard(s) : '') + '</div>'\n if (!s.iterations.length && s.status !== 'iterating') html += '<p class=\"sub\">No attempts yet.</p>'\n const mine = (agentLog[selected] || []).slice(-80)\n const stepsTitle = { iterating: 'Agent steps (live)', interrupted: 'Agent steps before the run stopped' }[shownStatus(s)] || 'Agent steps, last attempt'\n if (mine.length) html += '<h3>' + stepsTitle + '</h3><pre id=\"agentout\">' + esc(mine.join('\\\\n')) + '</pre>'\n else if (shownStatus(s) === 'iterating') html += '<h3>' + stepsTitle + '</h3><pre id=\"agentout\" class=\"sub\">Steps appear here as the agent reads and edits files.</pre>'\n html += problemsHtml\n const jv = (s.judge || []).find((v) => v.viewport === vp)\n if (jv) html += '<h3>Review by ' + esc(jv.model) + ' (advisory)</h3><p class=\"sub\">' + esc(jv.error || ('Prefers ' + (jv.preferred === 'tie' ? 'neither' : jv.preferred === 'after' ? 'the new version' : 'the original') + ' (' + jv.confidence + ' confidence). ' + jv.summary)) + '</p>'\n for (const i of s.iterations) if (i.logTail) html += '<details class=\"steps\"><summary>What the agent did in attempt ' + i.n + '</summary><pre>' + esc(i.logTail) + '</pre></details>'\n html += '</div></div>'\n box.innerHTML = html\n // After a reload the live stream has nothing yet: read the saved steps once.\n const stepsKey = runId + ' ' + selected\n if (s.status === 'iterating' && !mine.length && !stepsFetched.has(stepsKey)) {\n stepsFetched.add(stepsKey)\n const forRun = runId, forSurface = selected\n api('/api/steps?run=' + encodeURIComponent(forRun) + '&surface=' + encodeURIComponent(forSurface)).then(({ lines }) => {\n if (runId !== forRun || !lines.length || (agentLog[forSurface] || []).length) return\n agentLog[forSurface] = lines\n if (selected === forSurface) renderRun()\n }).catch(() => {})\n }\n box.querySelectorAll('[data-vp]').forEach((b) => b.onclick = () => { vp = b.dataset.vp; renderRun() })\n box.querySelectorAll('[data-view]').forEach((b) => b.onclick = () => { view = b.dataset.view; renderRun() })\n box.querySelectorAll('.att[data-n]').forEach((b) => b.onclick = () => { pick = Number(b.dataset.n); renderRun() })\n const d = document.getElementById('diff'); if (d) d.onchange = () => { diffOn = d.checked; renderRun() }\n const c = document.getElementById('cut'); if (c) c.oninput = () => document.getElementById('cmp').style.setProperty('--cut', c.value + '%')\n const out = document.getElementById('agentout'); if (out) out.scrollTop = out.scrollHeight\n}\n// ── Before / after ─────────────────────────────────────────────────────────\n/** The screenshot attempt n started from: the last kept attempt before it, else the baseline. */\nconst changeCache = {}\nfunction checkerLine(c) {\n if (c.error) return c.model + ': review failed'\n const votes = (c.votes || []).map((v) => v.preferred).join(' / ')\n return c.model + ': ' + (c.verdict === 'revert' ? 'rolled back' : c.verdict === 'keep' ? 'agrees' : 'unsure') + (votes ? ' (' + votes + ')' : '')\n}\nfunction startedFrom(s, n, v) {\n const kept = s.iterations.filter((i) => i.n < n && i.outcome === 'accepted' && i.after[v]).pop()\n return (kept && kept.after[v]) || s.baseline[v] || s.baseline.desktop\n}\nfunction stepName(s, n, before) {\n const it = s.iterations.find((i) => i.n === n), steps = (s.plan && s.plan.steps) || []\n const k = it && it.step ? steps.findIndex((p) => p.text === it.step) : -1\n return k >= 0 ? (before ? 'step ' : 'Step ') + (k + 1) : (before ? 'attempt ' : 'Attempt ') + n\n}\n/** One changed area as a zoomed crop of a screenshot (CSS sprite maths, no canvas). */\nfunction cropHtml(png, box, size, label) {\n const sx = box.w >= size.width ? 0 : (box.x / (size.width - box.w)) * 100\n const sy = box.h >= size.height ? 0 : (box.y / (size.height - box.h)) * 100\n const style = 'aspect-ratio:' + box.w + '/' + box.h + ';background-image:url("' + shot(png) + '");background-size:' + (size.width / box.w) * 100 + '% auto;background-position:' + sx + '% ' + sy + '%'\n return '<figure><figcaption>' + esc(label) + '</figcaption><div class=\"crop\" role=\"img\" aria-label=\"' + esc(label) + '\" style=\"' + style + '\"></div></figure>'\n}\nfunction changesHtml(prev, after, it, s) {\n let ch = it.changes && it.changes[vp]\n const pct = it.pixelDiff[vp] != null ? (it.pixelDiff[vp] * 100).toFixed(1) + '% of the screen changed' : ''\n if (!ch && it.diffPng && it.diffPng[vp]) {\n // An older attempt: work the areas out from its saved diff image once.\n const key = runId + ' ' + it.diffPng[vp]\n ch = changeCache[key]\n if (!ch) {\n if (!changeCache[key + '?']) {\n changeCache[key + '?'] = true\n api('/api/changes?run=' + encodeURIComponent(runId) + '&p=' + encodeURIComponent(it.diffPng[vp])).then((c) => { changeCache[key] = c; renderRun() }).catch(() => {})\n }\n return '<p class=\"sub\">Finding the changed areas…</p>'\n }\n }\n if (!ch) return '<p class=\"sub\">No change areas for this attempt. Use Side by side.</p>'\n if (!ch.boxes.length) return '<p class=\"sub\">Nothing changed on this screen in this attempt.</p>'\n return '<div class=\"changes\"><p class=\"sub\">' + ch.boxes.length + ' changed area' + (ch.boxes.length === 1 ? '' : 's') + (pct ? ' · ' + pct : '') + '. Each is shown before and after ' + esc(stepName(s, it.n, true)) + ', zoomed in.</p>' + ch.boxes.map((b, i) =>\n '<div><h4>Change ' + (i + 1) + ' · ' + b.w + '×' + b.h + ' px at ' + b.x + ',' + b.y + '</h4><div class=\"pair\">' + cropHtml(prev.png, b, ch, 'Before') + cropHtml(after.png, b, ch, 'After') + '</div></div>').join('') + '</div>'\n}\nasync function loadState() { state = runId ? await api('/api/state?run=' + runId).catch(() => state) : null; renderRun() }\nasync function loadRuns() {\n runs = (await api('/api/runs')).runs\n const sel = document.getElementById('runPick')\n sel.innerHTML = runs.map((r) => '<option value=\"' + esc(r.runId) + '\"' + (r.runId === runId ? ' selected' : '') + '>' + esc(new Date(r.createdAt).toLocaleString()) + ' · ' + esc(r.agent) + (r.model ? ' ' + esc(r.model) : '') + ' · ' + r.done + '/' + r.total + '</option>').join('') || '<option>No runs yet</option>'\n sel.disabled = !runs.length\n}\nfunction showRun(id) {\n runId = id; selected = null; pick = null\n document.getElementById('launcher').hidden = true\n document.getElementById('runview').hidden = false\n document.getElementById('logbox').hidden = false\n const logEl = document.getElementById('runlog')\n logEl.textContent = ''\n history.replaceState(null, '', '?t=' + T + '&run=' + id)\n loadState()\n // The saved log first (past runs, a restarted studio), then live lines arrive over events.\n api('/api/log?run=' + id).then(({ lines }) => {\n if (runId !== id) return\n logEl.textContent = lines.join('\\\\n')\n logEl.scrollTop = logEl.scrollHeight\n }).catch(() => {})\n}\ndocument.getElementById('runPick').onchange = (e) => showRun(e.target.value)\n\n// ── Launcher ───────────────────────────────────────────────────────────────\nlet options = null, models = null\nasync function openLauncher() {\n document.getElementById('runview').hidden = true\n document.getElementById('logbox').hidden = true\n document.getElementById('status').hidden = true\n const box = document.getElementById('launcher')\n box.hidden = false\n box.innerHTML = '<div class=\"form\"><div class=\"card\"><h2>New run</h2><p class=\"note\">Checking which coding agents are installed and signed in, this repo’s branches and its pages. This takes up to 20 seconds.</p></div></div>'\n options = await api('/api/options').catch((e) => ({ error: e.message }))\n const last = store.get('last') || {}\n const agents = options.agents || []\n const agentOpt = (a) => '<option value=\"' + esc(a.name) + '\"' + (a.name === (last.agent || options.defaultAgent) ? ' selected' : '') + (a.installed ? '' : ' disabled') + '>' + esc(a.label) + (a.installed ? '' : ' — ' + esc(a.note || 'not found')) + '</option>'\n const refOpt = (r) => '<option value=\"' + esc(r.ref) + '\"' + (r.ref === (last.baseRef || options.defaultRef) ? ' selected' : '') + '>' + esc(r.label) + '</option>'\n const lastPaths = last.startPaths || (options.lastRun ? options.lastRun.startPaths : [])\n const whole = lastPaths.length === 0\n box.innerHTML = '<form class=\"form\" id=\"lf\" novalidate>' +\n '<div class=\"card\"><h2><span class=\"n\">1</span>What to improve</h2>' +\n '<p class=\"lede\">The agent works one screen at a time on its own branch. Each change is measured (accessibility, layout, console) and kept only if nothing got worse.</p>' +\n '<div class=\"choice\" role=\"radiogroup\" aria-label=\"Which screens\">' +\n '<label><input type=\"radio\" name=\"f-scope\" value=\"whole\"' + (whole ? ' checked' : '') + '><span><b>The whole app</b>Map screens from the home page and the links it opens, up to the screen limit below.</span></label>' +\n '<label><input type=\"radio\" name=\"f-scope\" value=\"pages\"' + (whole ? '' : ' checked') + '><span><b>Pages I pick</b>Only these pages, plus the tabs and dialogs they open.</span></label>' +\n '</div>' +\n '<div id=\"f-pages-box\" class=\"card\" style=\"padding:10px\"' + (whole ? ' hidden' : '') + '>' +\n '<label class=\"f\"><span>Pages (comma-separated, or click below)</span><input type=\"text\" id=\"f-paths\" autocomplete=\"off\" value=\"' + esc(lastPaths.join(', ')) + '\"></label>' +\n '<div class=\"pills\" id=\"f-route-pills\">' + (options.routes || []).slice(0, 40).map((r) => '<button type=\"button\" class=\"pill\" data-r=\"' + esc(r) + '\" aria-pressed=\"false\">' + esc(r) + '</button>').join('') + '</div>' +\n '<label class=\"sub\"><input type=\"checkbox\" id=\"f-crawl\"' + (last.crawl ? ' checked' : '') + '> Also follow links from these pages</label>' +\n '</div>' +\n '<div class=\"grid\">' +\n '<label class=\"f\"><span>Skills: what the agent focuses on, applied in order (' + esc(options.skillsRepo || 'skills package') + ')</span><select id=\"f-skill\"><option value=\"\">Add a skill…</option></select></label>' +\n '<label class=\"f\"><span>…or your own SKILL.md / folder</span><input type=\"text\" id=\"f-skill-path\" placeholder=\"./skills/my-skill\" autocomplete=\"off\"></label>' +\n '</div><div class=\"pills\" id=\"f-chain\" aria-label=\"Skill chain\"></div><div class=\"pills\" id=\"f-next\"></div><div class=\"note\" id=\"f-skill-note\"></div>' +\n '<label class=\"sub\"><input type=\"checkbox\" id=\"f-steps\"' + (last.steps === false ? '' : ' checked') + '> Small steps (recommended): plan each screen first, then one small change per attempt, each kept or rolled back on its own</label>' +\n '</div>' +\n '<div class=\"card\"><h2><span class=\"n\">2</span>Who does the work</h2><div class=\"grid\">' +\n '<label class=\"f\"><span>Coding agent</span><select id=\"f-agent\">' + agents.map(agentOpt).join('') + '</select></label>' +\n '<label class=\"f\"><span>Model</span><select id=\"f-model\"><option>Loading…</option></select></label>' +\n '<label class=\"f\" id=\"f-custom-wrap\" hidden><span>Model id</span><input type=\"text\" id=\"f-custom\" placeholder=\"e.g. grok-4.7\" autocomplete=\"off\"></label>' +\n '</div><div class=\"params\" id=\"f-params\"></div><div class=\"note\" id=\"f-model-note\"></div>' +\n '<div class=\"summary\" id=\"f-account\"><span class=\"note\">Checking the account…</span></div>' +\n '<div class=\"grid\">' +\n '<label class=\"f\"><span>Checker: a second model reviews each kept step and may roll it back</span><select id=\"f-checker\">' + checkerOptions(agents, last) + '</select></label>' +\n '</div>' +\n '<div class=\"note\">The checker sees the changed area before and after, twice with the order swapped, and rolls a step back only when both reviews prefer the original. It never keeps a step the measurements rejected. Each checked step costs about $0.20–0.50 of your Claude usage (two reviews; measured $0.46 on glot.it).</div>' +\n '<label class=\"sub\"><input type=\"checkbox\" id=\"f-invisible\"' + (last.keepInvisible === false ? '' : ' checked') + '> Keep changes that are not visible in a screenshot (motion, haptics, press feedback) and flag them for your review</label>' +\n '<div class=\"row\"><span class=\"sub mono\" id=\"f-spec\"></span><button type=\"button\" class=\"btn\" id=\"f-refresh\">Refresh list</button></div></div>' +\n '<div class=\"card\"><h2><span class=\"n\">3</span>How much</h2><div class=\"grid\">' +\n '<label class=\"f\"><span>Screens at most</span><input type=\"number\" id=\"f-max\" min=\"1\" max=\"100\" value=\"' + (last.maxSurfaces || 8) + '\"></label>' +\n '<label class=\"f\"><span>Attempts (steps) per screen</span><input type=\"number\" id=\"f-iter\" min=\"1\" max=\"5\" value=\"' + (last.iterations || 4) + '\"></label>' +\n '<label class=\"f\"><span>Minutes per attempt</span><input type=\"number\" id=\"f-timeout\" min=\"1\" max=\"60\" value=\"' + (last.timeoutMin || 8) + '\"></label>' +\n '</div><div class=\"summary\" id=\"f-estimate\"></div></div>' +\n '<div class=\"card\"><h2><span class=\"n\">4</span>Your app</h2><div class=\"grid\">' +\n '<label class=\"f\" style=\"grid-column:1/-1\"><span>Dev command ({port} is replaced)</span><input type=\"text\" id=\"f-dev\" list=\"f-devs\" autocomplete=\"off\"><datalist id=\"f-devs\">' + (options.devCommands || []).map((d) => '<option value=\"' + esc(d) + '\">').join('') + '</datalist></label>' +\n '<label class=\"f\"><span>Branch from</span><select id=\"f-base\">' + (options.refs || [{ ref: 'HEAD', label: 'HEAD' }]).map(refOpt).join('') + '</select></label>' +\n '</div>' +\n (options.lastRun ? '<div class=\"note\">Run ' + esc(options.lastRun.runId) + ' mapped screens with <code>' + esc(options.lastRun.devCommand) + '</code>, so it is first in the list.</div>' : '') +\n '<div class=\"note warn\" id=\"f-dev-warn\">' + esc(options.devWarning || '') + '</div>' +\n '<details class=\"adv\"><summary>Advanced: parts of the page to leave out</summary>' +\n '<label class=\"f\"><span>Not part of the app (CSS selectors, one per line): hidden in screenshots and skipped by every check</span><textarea id=\"f-ignore\" rows=\"2\" autocomplete=\"off\" spellcheck=\"false\" placeholder=\".dev-badge\">' + esc((last.ignore || []).join('\\\\n')) + '</textarea></label>' +\n '<div class=\"note\">Dev overlays, build stamps and the Mushi widget are already skipped. Add your own here, or mark an element with <code>data-mushi-ux-ignore</code>.</div></details></div>' +\n '<div class=\"card\"><h2>After the run</h2><div class=\"grid\">' +\n '<label class=\"f\"><span><input type=\"checkbox\" id=\"f-judge\"' + (options.judgeAvailable ? (last.judge === false ? '' : ' checked') : ' disabled') + '> Second-model review</span><input type=\"text\" id=\"f-judge-model\" value=\"' + esc(last.judgeModel || options.judgeModel || '') + '\"' + (options.judgeAvailable ? '' : ' disabled') + '></label>' +\n '<label class=\"f\"><span><input type=\"checkbox\" id=\"f-sync\"' + (options.syncAvailable ? (last.sync ? ' checked' : '') : ' disabled') + '> Mirror to the Mushi console</span><span class=\"note\">' + esc(options.syncNote || '') + '</span></label>' +\n '</div>' + (options.judgeAvailable ? '' : '<div class=\"note\">Review needs ANTHROPIC_API_KEY in this shell.</div>') + '</div>' +\n '<div class=\"row\"><span class=\"note err\" id=\"f-error\"></span><button class=\"btn primary\" id=\"f-start\" type=\"submit\">▶ Start run</button></div></form>'\n document.getElementById('f-dev').value = last.devCommand || (options.devCommands || [])[0] || ''\n syncPills()\n document.getElementById('f-paths').oninput = syncPills\n box.querySelectorAll('input[name=f-scope]').forEach((r) => r.onchange = () => { document.getElementById('f-pages-box').hidden = scope() !== 'pages'; estimate() })\n ;['f-max', 'f-iter', 'f-timeout', 'f-steps'].forEach((id) => document.getElementById(id).addEventListener('input', estimate))\n estimate()\n box.querySelectorAll('.pill').forEach((p) => p.onclick = () => {\n const input = document.getElementById('f-paths'), set = new Set(input.value.split(',').map((x) => x.trim()).filter(Boolean))\n set.has(p.dataset.r) ? set.delete(p.dataset.r) : set.add(p.dataset.r)\n input.value = [...set].join(', '); syncPills()\n })\n document.getElementById('f-agent').onchange = () => loadModels(false)\n document.getElementById('f-refresh').onclick = () => loadModels(true)\n document.getElementById('f-model').onchange = renderParams\n document.getElementById('f-custom').oninput = updateSpec\n document.getElementById('lf').onsubmit = (e) => { e.preventDefault(); start() }\n loadModels(false)\n loadSkills(last.skill)\n}\nfunction checkerOptions(agents, last) {\n const claude = agents.some((a) => a.name === 'claude-code' && a.installed)\n const opts = [['', 'None: measurements alone decide']]\n if (claude) opts.push(['claude-code|claude-opus-5-5', 'Claude Opus 5.5, via Claude Code (your sign-in)'], ['claude-code|claude-sonnet-5-5', 'Claude Sonnet 5.5, via Claude Code (cheaper)'])\n if (options.judgeAvailable) opts.push(['anthropic-api|claude-opus-5-5', 'Claude Opus 5.5, via the Anthropic API key'])\n const want = last.checkerModel ? (last.checkerVia || 'claude-code') + '|' + last.checkerModel : (claude ? 'claude-code|claude-opus-5-5' : '')\n return opts.map(([v, l]) => '<option value=\"' + esc(v) + '\"' + (v === want ? ' selected' : '') + '>' + esc(l) + '</option>').join('') + (claude ? '' : '<option disabled>Claude Code not found: install it to use Claude as the checker</option>')\n}\nfunction checkerPick() {\n const v = document.getElementById('f-checker').value\n if (!v) return { model: null, via: 'claude-code' }\n const [via, model] = v.split('|')\n return { model, via }\n}\nfunction scope() { const r = document.querySelector('input[name=f-scope]:checked'); return r ? r.value : 'whole' }\n// Published per-million-token prices (cursor.com/docs/models-and-pricing, read 2026-10-07).\nconst PRICES = [\n ['grok-4.7', 'Grok 4.7: $2 in / $6 out per million tokens; the Fast tier, the default speed on Pro and above, is $4 / $12. A Cursor model, so it draws on the larger included pool first.'],\n ['opus-5.5', 'Claude Opus 5.5: $4 in / $20 out per million tokens.'],\n ['opus-5-5', 'Claude Opus 5.5: $4 in / $20 out per million tokens.'],\n ['sonnet-5.5', 'Claude Sonnet 5.5: $2 in / $10 out per million tokens.'],\n ['sonnet-5-5', 'Claude Sonnet 5.5: $2 in / $10 out per million tokens.'],\n ['composer', 'A Cursor model: it draws on the larger included pool first.'],\n]\nfunction priceNote() {\n const spec = (modelSpec() || '').toLowerCase()\n const hit = PRICES.find(([k]) => spec.includes(k))\n return hit ? hit[1] : 'Billed at the model’s API rate: first from your plan’s included usage, then on-demand if you allow it.'\n}\nfunction estimate() {\n const num = (id, d) => { const n = parseInt(document.getElementById(id).value, 10); return Number.isFinite(n) && n > 0 ? n : d }\n const screens = num('f-max', 8), tries = num('f-iter', 4), mins = num('f-timeout', 8), steps = document.getElementById('f-steps').checked\n const worst = screens * (tries * mins + (steps ? 4 : 0)) + 5\n const h = Math.floor(worst / 60), m = worst % 60\n document.getElementById('f-estimate').innerHTML =\n '<span><b>Up to ' + screens * tries + ' attempts</b> (' + screens + ' screen' + (screens === 1 ? '' : 's') + ' × ' + tries + (steps ? ' steps, after a planning pass of up to 4 min each' : ' attempts') + ').</span>' +\n '<span>Worst case about <b>' + (h ? h + ' h ' : '') + m + ' min</b> of agent time, since every attempt stops at its time box. Runs usually end sooner: a step that needs no change moves on.</span>' +\n '<span class=\"note\">' + (scope() === 'whole' ? 'Whole app: screens are mapped from the home page until the limit above.' : 'Pages you picked: at most ' + screens + ' of them are worked on.') + '</span>'\n}\nconst accounts = {}\nasync function loadAccount() {\n const agent = document.getElementById('f-agent').value, box = document.getElementById('f-account')\n // The CLI call takes a second or two; a model change only redraws the price.\n accounts[agent] = accounts[agent] || api('/api/account?agent=' + encodeURIComponent(agent)).catch(() => ({ account: null }))\n const r = await accounts[agent]\n const a = r.account\n const who = a ? '<span>Spends <b>' + esc(a.email || 'your account') + '</b>' + (a.plan ? ' · ' + esc(a.plan) + ' plan' : '') + '. To use a different account, sign in with that one in this shell (<code>agent login</code>) and restart the studio.</span>' : '<span>Spends the account this agent is signed in with in this shell.</span>'\n const usage = '<span class=\"note\">No agent reports how much credit is left, so this cannot show a balance. ' + (a && a.usageUrl ? 'Check it on <a href=\"' + esc(a.usageUrl) + '\" target=\"_blank\" rel=\"noopener\">your usage page</a>. ' : '') + 'If the account runs out mid-run, the run stops; resume it later or with another account.</span>'\n box.innerHTML = who + '<span>' + esc(priceNote()) + '</span>' + usage\n}\nfunction syncPills() {\n const set = new Set(document.getElementById('f-paths').value.split(',').map((x) => x.trim()))\n document.querySelectorAll('#f-route-pills .pill').forEach((p) => p.setAttribute('aria-pressed', String(set.has(p.dataset.r))))\n}\nasync function loadModels(force) {\n const agent = document.getElementById('f-agent').value, sel = document.getElementById('f-model'), note = document.getElementById('f-model-note')\n sel.innerHTML = '<option>Loading…</option>'; note.textContent = ''\n models = await api('/api/models?agent=' + encodeURIComponent(agent) + (force ? '&fresh=1' : '')).catch((e) => ({ models: [], note: e.message }))\n const last = store.get('last') || {}, lastModel = (last.agent === agent && last.model) ? last.model.split('?')[0] : null\n const def = models.models.find((m) => m.id === lastModel) || models.models.find((m) => m.isDefault)\n sel.innerHTML = '<option value=\"\">Agent default</option>' + models.models.map((m) => '<option value=\"' + esc(m.id) + '\"' + (def && def.id === m.id ? ' selected' : '') + '>' + esc(m.label === m.id ? m.id : m.label + ' — ' + m.id) + '</option>').join('') + '<option value=\"__custom\">Other model id…</option>'\n note.textContent = (models.source === 'live' ? models.models.length + ' models from your account. ' : '') + (models.note || '')\n note.className = models.source === 'none' && models.note ? 'note warn' : 'note'\n if (lastModel && !def) { sel.value = '__custom'; document.getElementById('f-custom').value = lastModel }\n renderParams()\n}\nfunction renderParams() {\n const id = document.getElementById('f-model').value\n document.getElementById('f-custom-wrap').hidden = id !== '__custom'\n const m = models && models.models.find((x) => x.id === id), last = store.get('last') || {}\n const lastParams = new URLSearchParams((last.model || '').split('?')[1] || '')\n document.getElementById('f-params').innerHTML = (m && m.params ? m.params : []).map((p) => '<label class=\"f\"><span>' + esc(p.label) + '</span><select data-param=\"' + esc(p.id) + '\"><option value=\"\">default</option>' + p.values.map((v) => '<option value=\"' + esc(v.value) + '\"' + (lastParams.get(p.id) === v.value ? ' selected' : '') + '>' + esc(v.label) + '</option>').join('') + '</select></label>').join('')\n document.querySelectorAll('[data-param]').forEach((s) => s.onchange = updateSpec)\n updateSpec()\n}\nfunction modelSpec() {\n const id = document.getElementById('f-model').value\n const base = id === '__custom' ? document.getElementById('f-custom').value.trim() : id\n if (!base) return null\n const params = [...document.querySelectorAll('[data-param]')].filter((s) => s.value).map((s) => s.dataset.param + '=' + s.value)\n return params.length ? base + '?' + params.join('&') : base\n}\nfunction updateSpec() { const s = modelSpec(); document.getElementById('f-spec').textContent = s ? 'model: ' + s : 'model: the agent’s default'; loadAccount() }\nlet chain = [], knownSkills = new Set()\nasync function loadSkills(last) {\n const sel = document.getElementById('f-skill'), note = document.getElementById('f-skill-note')\n try {\n const { skills } = await api('/api/skills')\n knownSkills = new Set(skills.map((s) => s.name))\n const groups = {}\n for (const s of skills) (groups[s.group || 'Skills'] = groups[s.group || 'Skills'] || []).push(s.name)\n sel.innerHTML = '<option value=\"\">Add a skill…</option>' + Object.entries(groups).map(([g, names]) => '<optgroup label=\"' + esc(g) + '\">' + names.map((n) => '<option>' + esc(n) + '</option>').join('') + '</optgroup>').join('')\n note.textContent = skills.length + ' skills. Each skill\\\\'s whole folder (references too) is given to the agent. With several, the agent applies them in this order.'\n } catch (e) { note.textContent = e.message; note.className = 'note warn' }\n if (last && /[\\\\\\\\/.]/.test(last)) document.getElementById('f-skill-path').value = last\n else chain = (last || '').split(',').map((x) => x.trim()).filter((x) => knownSkills.has(x))\n sel.onchange = () => { if (sel.value && !chain.includes(sel.value) && chain.length < 5) chain.push(sel.value); sel.value = ''; renderChain() }\n renderChain()\n}\nconst relatedCache = {}\nasync function renderChain() {\n const box = document.getElementById('f-chain'), next = document.getElementById('f-next')\n box.innerHTML = chain.length\n ? chain.map((n, i) => '<button type=\"button\" class=\"pill\" aria-pressed=\"true\" data-rm=\"' + esc(n) + '\" title=\"Remove\">' + (i + 1) + '. ' + esc(n) + ' ×</button>').join('')\n : '<span class=\"note\">No skill: the agent uses the built-in UX guidance.</span>'\n box.querySelectorAll('[data-rm]').forEach((b) => b.onclick = () => { chain = chain.filter((x) => x !== b.dataset.rm); renderChain() })\n next.innerHTML = ''\n const lastSkill = chain[chain.length - 1]\n if (!lastSkill || chain.length >= 5) return\n relatedCache[lastSkill] = relatedCache[lastSkill] || api('/api/skill?name=' + encodeURIComponent(lastSkill)).catch(() => ({ related: [] }))\n const { related } = await relatedCache[lastSkill]\n const offer = (related || []).filter((n) => knownSkills.has(n) && !chain.includes(n)).slice(0, 6)\n if (chain[chain.length - 1] !== lastSkill) return\n next.innerHTML = offer.length ? '<span class=\"note\">' + esc(lastSkill) + ' hands over to:</span>' + offer.map((n) => '<button type=\"button\" class=\"pill\" data-add=\"' + esc(n) + '\">+ ' + esc(n) + '</button>').join('') : ''\n next.querySelectorAll('[data-add]').forEach((b) => b.onclick = () => { chain.push(b.dataset.add); renderChain() })\n}\nasync function start() {\n const err = document.getElementById('f-error'), btn = document.getElementById('f-start')\n err.textContent = ''\n const num = (id, d) => { const n = parseInt(document.getElementById(id).value, 10); return Number.isFinite(n) ? n : d }\n const judgeOn = document.getElementById('f-judge').checked\n const body = {\n agent: document.getElementById('f-agent').value,\n model: modelSpec(),\n skill: document.getElementById('f-skill-path').value.trim() || chain.join(',') || null,\n devCommand: document.getElementById('f-dev').value.trim(),\n baseRef: document.getElementById('f-base').value,\n startPaths: scope() === 'whole' ? [] : document.getElementById('f-paths').value.split(',').map((x) => x.trim()).filter(Boolean),\n iterations: num('f-iter', 2), maxSurfaces: num('f-max', 8), timeoutMin: num('f-timeout', 15),\n judgeModel: judgeOn ? (document.getElementById('f-judge-model').value.trim() || null) : null,\n sync: document.getElementById('f-sync').checked,\n crawl: scope() === 'pages' && document.getElementById('f-crawl').checked,\n steps: document.getElementById('f-steps').checked,\n checkerModel: checkerPick().model,\n checkerVia: checkerPick().via,\n keepInvisible: document.getElementById('f-invisible').checked,\n ignore: document.getElementById('f-ignore').value.split('\\\\n').map((x) => x.trim()).filter(Boolean),\n }\n if (!body.devCommand) { err.textContent = 'Give the dev command.'; return }\n store.set('last', { ...body, judge: judgeOn })\n btn.disabled = true\n try {\n const { runId: id } = await api('/api/runs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })\n if (meta) meta.active = id\n await loadRuns(); showRun(id)\n } catch (e) { err.textContent = e.message } finally { btn.disabled = false }\n}\nfunction resumable() { return !!(meta && meta.canResume && state && state.options && state.phase !== 'done') }\ndocument.getElementById('resumeBtn').onclick = async () => {\n const b = document.getElementById('resumeBtn'), pd = document.getElementById('phaseDetail')\n b.disabled = true\n b.textContent = 'Resuming…'\n try {\n await api('/api/runs/' + runId + '/resume', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })\n if (meta) meta.active = runId\n await loadRuns(); await loadState()\n } catch (e) { pd.textContent = e.message; pd.className = 'sub err' } finally { b.textContent = '▶ Resume'; b.disabled = false }\n}\ndocument.getElementById('prBtn').onclick = async () => {\n const b = document.getElementById('prBtn'), pd = document.getElementById('phaseDetail'), label = b.textContent\n b.disabled = true\n b.textContent = 'Pushing…'\n try {\n const pr = await api('/api/runs/' + runId + '/pr', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })\n pd.textContent = (pr.added ? 'Added to PR #' : 'Opened draft PR #') + pr.number + '. Merge it from the Mushi console once its checks pass.'\n pd.className = 'sub'\n await loadState()\n } catch (e) { pd.textContent = e.message; pd.className = 'sub err' } finally { b.textContent = label; b.disabled = false }\n}\ndocument.getElementById('newBtn').onclick = openLauncher\ndocument.getElementById('stopBtn').onclick = async () => {\n const b = document.getElementById('stopBtn')\n b.disabled = true\n b.textContent = 'Stopping…'\n await api('/api/runs/' + runId + '/stop', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }).catch((e) => { document.getElementById('phaseDetail').textContent = e.message })\n b.textContent = '■ Stop'\n}\n\n// ── Live events ────────────────────────────────────────────────────────────\nlet stateTimer = null\nconst es = new EventSource(q('/api/events'))\nes.onmessage = (m) => {\n const e = JSON.parse(m.data)\n if (e.type === 'started') { if (meta) meta.active = e.runId; loadRuns(); return }\n if (e.type === 'log') { runLog.push(e); if (e.runId === runId) { const p = document.getElementById('runlog'); p.textContent += (p.textContent ? '\\\\n' : '') + e.message; p.scrollTop = p.scrollHeight } }\n if (e.type === 'agent') { (agentLog[e.surface] = agentLog[e.surface] || []).push(e.line); if (agentLog[e.surface].length > 1500) agentLog[e.surface] = agentLog[e.surface].slice(-800); if (e.runId === runId && e.surface === selected) { const o = document.getElementById('agentout'); if (o) { if (o.classList.contains('sub')) { o.textContent = e.line; o.classList.remove('sub') } else o.textContent += '\\\\n' + e.line; o.scrollTop = o.scrollHeight } else renderRun() } }\n if ((e.type === 'state' || e.type === 'phase') && e.runId === runId) { clearTimeout(stateTimer); stateTimer = setTimeout(() => { loadState(); if (e.type === 'phase') loadRuns() }, 150) }\n}\n\n;(async () => {\n meta = await api('/api/meta')\n document.getElementById('repo').textContent = meta.repo\n document.getElementById('newBtn').hidden = !meta.launcher\n await loadRuns()\n const want = new URLSearchParams(location.search).get('run') || meta.active || meta.initial\n if (want && runs.some((r) => r.runId === want)) showRun(want)\n else if (meta.launcher) openLauncher()\n else if (runs[0]) showRun(runs[0].runId)\n})()\n</script></body></html>`\n","// SPDX-License-Identifier: MIT\n/**\n * Turns a running app into a list of surfaces: every same-origin page\n * reachable from the start paths, plus the tabs, dialogs and menus each page\n * opens. Runs inside a guarded session, so nothing it clicks can write.\n *\n * Pages whose DOM structure matches one already seen (`/reports/1` and\n * `/reports/2`) are kept once.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { Page } from 'playwright'\nimport { gotoPatiently, replay, settle, surfaceUrl, type BrowserSession } from './capture.js'\nimport { isDestructiveLabel } from './guard.js'\nimport { isWorthVisiting, routesFromSource, sitemapPaths } from './routes.js'\nimport type { ReplayStep, Surface, SurfaceKind } from './types.js'\n\nexport interface DiscoverOptions {\n baseUrl: string\n startPaths?: string[]\n /** Repo (or app) directory to read routes from; see routes.ts. */\n sourceDir?: string\n maxPages?: number\n maxStatesPerPage?: number\n /** Paths never visited (globs on pathname), on top of sign-out routes. */\n excludePaths?: string[]\n /**\n * Visit only startPaths (and the tabs, dialogs and menus they open): no\n * routes from the source or sitemap, no following links. Set when the\n * person named the pages.\n */\n onlyStartPaths?: boolean\n onProgress?: (msg: string) => void\n /** Stops discovery between pages (the studio's Stop button). */\n signal?: AbortSignal\n}\n\n/** Redirects to one sign-in path before discovery treats it as an auth wall. */\nconst AUTH_WALL_REDIRECTS = 5\n/** Redirects to one path that are followed; past it the target is a moving one. */\nconst MAX_REDIRECT_FOLLOWS = 3\n/** Page loads one mapping may make, per page it may keep: a hard stop for any loop. */\nconst LOADS_PER_PAGE = 5\nconst SIGN_IN_PATH_RE = /\\/(log-?in|sign-?in|auth)\\b/i\nconst SIGN_OUT_PATH_RE =/\\/(log-?out|sign-?out|logoff)\\b/i\n\n/** Pure: same-origin, normalized path (no hash), or null to skip. */\nexport function normalizeLink(href: string, baseUrl: string): string | null {\n let u: URL\n try {\n u = new URL(href, baseUrl)\n } catch {\n return null\n }\n const base = new URL(baseUrl)\n if (u.origin !== base.origin) return null\n if (!/^https?:$/.test(u.protocol)) return null\n if (SIGN_OUT_PATH_RE.test(u.pathname)) return null\n if (/\\.(png|jpe?g|gif|svg|webp|ico|pdf|zip|csv|json|xml|txt|js|css|map)$/i.test(u.pathname)) return null\n return u.pathname + u.search\n}\n\nexport function surfaceKey(path: string, steps: readonly ReplayStep[]): string {\n const raw = [path, ...steps.map((s) => s.label)].join(' > ')\n const slug = raw.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 80) || 'root'\n return `${slug}-${createHash('sha1').update(raw).digest('hex').slice(0, 6)}`\n}\n\nfunction globMatch(glob: string, path: string): boolean {\n const re = new RegExp(`^${glob.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*')}$`)\n return re.test(path)\n}\n\n/**\n * Structural fingerprint of the visible DOM: tags and roles to depth 8, with\n * runs of identical sibling shapes collapsed so a 3-row and a 30-row table\n * hash the same.\n */\nasync function domHash(page: Page): Promise<string> {\n const shape = await page.evaluate(() => {\n function sig(el: Element, depth: number): string {\n const role = el.getAttribute('role')\n const head = el.tagName.toLowerCase() + (role ? `[${role}]` : '')\n if (depth >= 8 || el.tagName === 'svg') return head\n const kids: string[] = []\n for (const child of Array.from(el.children)) {\n if (['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE'].includes(child.tagName)) continue\n // Hidden panels and closed dialogs are not part of what the user sees.\n if ((child as HTMLElement).hidden || getComputedStyle(child).display === 'none') continue\n const s = sig(child, depth + 1)\n if (kids[kids.length - 1] !== s) kids.push(s)\n }\n return kids.length ? `${head}(${kids.join(',')})` : head\n }\n return sig(document.body, 0)\n })\n return createHash('sha1').update(shape).digest('hex').slice(0, 16)\n}\n\ninterface Trigger {\n selector: string\n label: string\n role: string\n}\n\n/** A quoted attribute value: backslashes escaped before quotes, or a trailing `\\` would eat the closing quote. */\nfunction quoteAttr(value: string): string {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`\n}\n\n/** Pure, for tests: the selector replay uses for a trigger, by test id first, else by role and name. * @internal Exported for tests only.\n */\nexport function triggerSelector(testId: string | null, role: string, label: string): string {\n if (testId) return `[data-testid=${quoteAttr(testId)}]`\n return role ? `role=${role}[name=${quoteAttr(label)}]` : ''\n}\n\n/** Elements that open a state without navigating: tabs, dialog and menu triggers. */\nasync function findTriggers(page: Page): Promise<Trigger[]> {\n const raw = await page.evaluate(() => {\n const found: Array<{ testId: string | null; label: string; role: string }> = []\n const candidates = document.querySelectorAll(\n '[role=\"tab\"]:not([aria-selected=\"true\"]), [aria-haspopup=\"dialog\"], [aria-haspopup=\"menu\"], [aria-haspopup=\"true\"], button[aria-expanded=\"false\"]',\n )\n for (const el of Array.from(candidates)) {\n const r = el.getBoundingClientRect()\n if (r.width === 0 || r.height === 0) continue\n const label = (el.getAttribute('aria-label') || (el as HTMLElement).innerText || '').trim().replace(/\\s+/g, ' ').slice(0, 60)\n if (!label) continue\n const role = el.getAttribute('role') || (el.tagName === 'BUTTON' ? 'button' : el.tagName === 'A' ? 'link' : '')\n found.push({ testId: el.getAttribute('data-testid'), label, role })\n }\n return found\n })\n const triggers: Trigger[] = []\n const seen = new Set<string>()\n for (const { testId, label, role } of raw) {\n const selector = triggerSelector(testId, role, label)\n if (!selector || seen.has(selector)) continue\n seen.add(selector)\n triggers.push({ selector, label, role })\n }\n return triggers\n}\n\nasync function openedKind(page: Page, trigger: Trigger): Promise<SurfaceKind | null> {\n return page.evaluate((role) => {\n const visible = (sel: string) =>\n Array.from(document.querySelectorAll(sel)).some((el) => {\n const r = el.getBoundingClientRect()\n return r.width > 0 && r.height > 0\n })\n if (visible('[role=\"dialog\"], [role=\"alertdialog\"], dialog[open]')) return 'dialog'\n if (visible('[role=\"menu\"], [role=\"listbox\"]')) return 'menu'\n if (role === 'tab') return 'tab'\n return null\n }, trigger.role) as Promise<SurfaceKind | null>\n}\n\n/**\n * Pure: a screen's name. The page title, unless another screen already has\n * that title (an SPA often keeps one <title>), then a name from the path:\n * \"/\" → \"Home\", \"/account/settings/\" → \"Account / Settings\".\n * @internal Exported for tests only.\n */\nexport function pageLabel(title: string, path: string, others: ReadonlyArray<{ label: string }>): string {\n const t = title.trim()\n if (t && !others.some((o) => o.label === t)) return t\n const parts = new URL(path, 'http://x').pathname.split('/').filter(Boolean)\n const fromPath = parts.length\n ? parts.map((p) => decodeURIComponent(p).replace(/[-_]+/g, ' ').replace(/^\\w/, (c) => c.toUpperCase())).join(' / ')\n : 'Home'\n return others.some((o) => o.label === fromPath) ? `${fromPath} (${path})` : fromPath\n}\n\nexport async function discover(session: BrowserSession, opts: DiscoverOptions): Promise<Surface[]> {\n const maxPages = opts.maxPages ?? 40\n const maxStates = opts.maxStatesPerPage ?? 8\n const exclude = opts.excludePaths ?? []\n const progress = opts.onProgress ?? (() => {})\n const only = Boolean(opts.onlyStartPaths && opts.startPaths?.length)\n const seeded = [\n ...(opts.startPaths?.length ? opts.startPaths : ['/']),\n ...(only ? [] : (opts.sourceDir ? routesFromSource(opts.sourceDir) : []).filter(isWorthVisiting)),\n ...(only ? [] : (await sitemapPaths(opts.baseUrl)).filter(isWorthVisiting)),\n ]\n const queue = [...new Set(seeded)]\n progress(only ? `${queue.length} page(s) you named` : `${queue.length} start path(s) from the source, sitemap and options`)\n const visited = new Set<string>()\n const seenShapes = new Set<string>()\n // Many start paths landing on the same sign-in page = an auth wall.\n const redirectsTo = new Map<string, number>()\n const surfaces: Surface[] = []\n let loads = 0\n const page = await session.context.newPage()\n await page.setViewportSize({ width: 1440, height: 900 })\n\n try {\n // Pass 2 only re-tries pages the person named that pass 1 dropped (a slow\n // first compile, a navigation racing a click): glot.it lost /practice\n // inside a run while the same build found it on its own (2026-10-06).\n for (let pass = 1; pass <= 2; pass++) {\n if (pass === 2) {\n if (!only) break\n const strip = (p: string) => p.replace(/\\/(?=\\?|$)/, '')\n const missing = [...new Set(seeded)].filter((p) => !surfaces.some((s) => s.kind === 'page' && strip(s.path) === strip(p)))\n if (missing.length === 0) break\n progress(`retrying ${missing.join(', ')}: not captured on the first pass`)\n for (const p of missing) {\n visited.delete(p)\n visited.delete(strip(p) + '/')\n visited.delete(strip(p))\n }\n queue.push(...missing)\n }\n while (queue.length > 0 && surfaces.filter((s) => s.kind === 'page').length < maxPages) {\n if (opts.signal?.aborted) throw new Error('Stopped.')\n const path = queue.shift() as string\n if (++loads > maxPages * LOADS_PER_PAGE) {\n progress(`stopped mapping after ${loads - 1} page loads; ${queue.length + 1} path(s) not tried`)\n break\n }\n if (visited.has(path)) {\n if (only) progress(`skipped ${path}: already visited`)\n continue\n }\n visited.add(path)\n if (exclude.some((g) => globMatch(g, new URL(path, opts.baseUrl).pathname))) continue\n\n const failed = (err: Error) => {\n progress(`skipped ${path}: it did not load (${err.message.split('\\n')[0].slice(0, 120)})`)\n return undefined\n }\n const res = await gotoPatiently(page, surfaceUrl(opts.baseUrl, path)).catch(failed)\n if (res === undefined) continue\n // null = no response after a retry (the page reloaded itself twice): go\n // on with what is on screen rather than drop the page without a word.\n if (res && res.status() >= 400) {\n progress(`skipped ${path}: HTTP ${res.status()}`)\n continue\n }\n await settle(page)\n const landed = new URL(page.url())\n if (landed.origin !== new URL(opts.baseUrl).origin) {\n progress(`skipped ${path}: it leaves the app for ${landed.origin}`)\n continue\n }\n const landedPath = landed.pathname + landed.search\n // `/practice` → `/practice/` is the same page; loading it again only cost\n // time and, on glot.it, lost /practice and /chat (2026-10-06).\n const sameModuloSlash = (a: string, b: string) => a.replace(/\\/(?=\\?|$)/, '') === b.replace(/\\/(?=\\?|$)/, '')\n if (landedPath !== path && sameModuloSlash(landedPath, path)) {\n visited.add(landedPath)\n if (visited.has(landedPath) && surfaces.some((s) => s.kind === 'page' && s.path === landedPath)) continue\n } else if (landedPath !== path && only) {\n progress(`skipped ${path}: it opens ${landedPath} instead`)\n }\n if (landedPath !== path && !sameModuloSlash(landedPath, path)) {\n // Redirected (sign-in wall, trailing slash): record the target instead.\n const n = (redirectsTo.get(landed.pathname) ?? 0) + 1\n redirectsTo.set(landed.pathname, n)\n // A target that keeps changing (a timestamp in the query) would be\n // followed forever: follow redirects to one path a few times only.\n if (!visited.has(landedPath) && n <= MAX_REDIRECT_FOLLOWS) queue.unshift(landedPath)\n if (n === AUTH_WALL_REDIRECTS && SIGN_IN_PATH_RE.test(landed.pathname)) {\n // Seeded routes behind the wall would each cost a load and redirect; drop them.\n const skipped = queue.filter((p) => p !== landedPath).length\n queue.splice(0, queue.length, ...queue.filter((p) => p === landedPath))\n progress(\n `${n} paths redirect to ${landed.pathname}: the app needs a signed-in session. ` +\n `Skipping the other ${skipped} queued path(s). Run \\`mushi-ux login --url ${opts.baseUrl}\\` and pass --login-url.`,\n )\n }\n continue\n }\n\n const here = landedPath\n // A page that redirects on the client after it loaded (glot.it's\n // /profile → /account when signed out) destroys the page under a read:\n // that skips this page, never the run (it lost 11 minutes of mapping\n // and six found pages, 2026-10-07).\n let shape: string\n let title: string\n let links: Array<{ href: string; label: string }>\n try {\n shape = await domHash(page)\n // A page the person named is always worked on: in an app shell several\n // routes share one structure while loading, and glot.it lost /words,\n // /chat and /account to this check (2026-10-06).\n if (seenShapes.has(shape) && !only) continue\n title = pageLabel(await page.title(), here, surfaces)\n links = await page.$$eval('a[href]', (as) =>\n as.map((a) => ({ href: a.getAttribute('href') ?? '', label: (a as HTMLElement).innerText.trim() })),\n )\n } catch (err) {\n if (opts.signal?.aborted) throw err\n progress(`skipped ${path}: it changed while being read (${(err as Error).message.split('\\n')[0].slice(0, 120)})`)\n continue\n }\n seenShapes.add(shape)\n surfaces.push({ key: surfaceKey(here, []), kind: 'page', path: here, steps: [], label: title, domHash: shape })\n progress(`page ${here}`)\n\n for (const { href, label } of links) {\n if (isDestructiveLabel(label)) continue\n const next = normalizeLink(href, page.url())\n if (!only && next && !visited.has(next) && !queue.includes(next)) queue.push(next)\n }\n\n // Same rule for its tabs and dialogs: a failed read skips that state only.\n const triggers = (await findTriggers(page).catch(() => [] as Trigger[])).filter((t) => !isDestructiveLabel(t.label)).slice(0, maxStates)\n for (const trigger of triggers) {\n const step: ReplayStep = { action: 'click', selector: trigger.selector, label: trigger.label }\n try {\n await gotoPatiently(page, surfaceUrl(opts.baseUrl, here))\n await settle(page)\n await replay(page, [step])\n } catch {\n continue\n }\n const after = new URL(page.url())\n if (after.pathname + after.search !== here) {\n // The \"tab\" was a link in disguise; crawl it as a page.\n const next = normalizeLink(page.url(), opts.baseUrl)\n if (!only && next && !visited.has(next) && !queue.includes(next)) queue.push(next)\n continue\n }\n let kind: SurfaceKind | null\n let stateShape: string\n try {\n kind = await openedKind(page, trigger)\n if (!kind) continue\n stateShape = await domHash(page)\n } catch (err) {\n if (opts.signal?.aborted) throw err\n continue\n }\n if (seenShapes.has(stateShape)) continue\n seenShapes.add(stateShape)\n surfaces.push({\n key: surfaceKey(here, [step]),\n kind,\n path: here,\n steps: [step],\n label: `${title} › ${trigger.label}`,\n domHash: stateShape,\n })\n progress(`${kind} ${here} › ${trigger.label}`)\n }\n }\n }\n } finally {\n await page.close()\n }\n return tidyLabels(surfaces)\n}\n\nconst escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * Drops the site name most page titles repeat (\"Account — glot.it\" →\n * \"Account\"), so the burndown reads as a list of screens. The site name is\n * the first or last title segment shared by at least two pages and half of\n * them. A home page titled \"Site – tagline\" becomes \"Home\". A label that\n * would collide with another keeps its full title.\n * @internal Exported for tests only.\n */\nexport function tidyLabels<T extends { label: string; path: string; kind: string }>(surfaces: T[]): T[] {\n const SEP = /\\s+[|–—·:-]\\s+/\n const pages = surfaces.filter((s) => s.kind === 'page')\n const counts = new Map<string, number>()\n for (const s of pages) {\n const parts = s.label.split(SEP).map((p) => p.trim())\n if (parts.length < 2) continue\n for (const p of new Set([parts[0]!, parts[parts.length - 1]!])) counts.set(p, (counts.get(p) ?? 0) + 1)\n }\n const site = [...counts].filter(([, n]) => n >= 2 && n * 2 >= pages.length).sort((a, b) => b[1] - a[1])[0]?.[0]\n if (!site) return surfaces\n const sep = String.raw`\\s+[|–—·:-]\\s+`\n const trailing = new RegExp(`${sep}${escapeRe(site)}(?=$|\\\\s›)`)\n const leading = new RegExp(`^${escapeRe(site)}${sep}`)\n const renamed = new Map<string, string>()\n for (const s of pages) {\n let next = s.label.replace(trailing, '')\n if (leading.test(next)) next = s.path === '/' ? 'Home' : next.replace(leading, '')\n if (next && next !== s.label) renamed.set(s.label, next)\n }\n const taken = new Set(pages.map((s) => s.label))\n const finalName = new Map<string, string>()\n for (const [from, to] of renamed) {\n if (taken.has(to) || [...finalName.values()].includes(to)) continue\n finalName.set(from, to)\n }\n return surfaces.map((s) => {\n const page = s.label.split(' › ')[0]!\n const to = finalName.get(page)\n return to ? { ...s, label: to + s.label.slice(page.length) } : s\n })\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Start paths read from the source, so discovery reaches pages nothing links\n * to (a settings tab only the sidebar opens, a page behind a button).\n *\n * - React Router: absolute `path=\"/x\"` props and `path: '/x'` route objects.\n * Relative child paths are left to the crawler, which follows the links\n * their layouts render.\n * - Next.js: `app/**\\/page.*` and `pages/**\\/*.*` files.\n * - Anything with a parameter (`:id`, `[id]`, `*`) is skipped: there is no\n * safe value to invent for it.\n */\n\nimport { closeSync, fstatSync, openSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative } from 'node:path'\n\nconst SKIP_DIRS = new Set(['node_modules', '.git', '.next', 'dist', 'build', '.turbo', '.worktrees', '.mushi', '.mushi-ux', 'coverage', '__tests__'])\nconst SOURCE_RE = /\\.(tsx|ts|jsx|js|mjs)$/\nconst MAX_FILES = 4000\n\nfunction isStatic(path: string): boolean {\n return path.startsWith('/') && !/[:*[\\]]/.test(path) && !path.includes('//')\n}\n\n/** Pure, for tests: absolute static paths declared in one React Router source file. */\nexport function reactRouterPaths(source: string): string[] {\n const out: string[] = []\n // `(?:\\{\\s*)?`, not `\\{?\\s*`: two adjacent `\\s*` made a run of spaces with\n // no quote after it quadratic (CodeQL js/polynomial-redos).\n const re = /\\bpath\\s*[=:]\\s*(?:\\{\\s*)?([\"'`])(\\/[^\"'`]*)\\1/g\n for (const m of source.matchAll(re)) if (isStatic(m[2])) out.push(m[2])\n return out\n}\n\n/** Pure, for tests: the URL path a Next.js route file serves, or null. */\nexport function nextRoutePath(relFile: string): string | null {\n const parts = relFile.split(/[\\\\/]/)\n const appAt = parts.lastIndexOf('app')\n const pagesAt = parts.lastIndexOf('pages')\n let segs: string[]\n if (appAt >= 0 && /^page\\.(tsx|jsx|ts|js|mdx)$/.test(parts[parts.length - 1])) {\n segs = parts.slice(appAt + 1, -1).filter((s) => !/^\\(.*\\)$/.test(s) && !s.startsWith('@'))\n } else if (pagesAt >= 0 && SOURCE_RE.test(parts[parts.length - 1])) {\n segs = parts.slice(pagesAt + 1)\n const last = segs.pop()?.replace(SOURCE_RE, '') ?? ''\n if (last.startsWith('_') || segs[0] === 'api') return null\n if (last !== 'index') segs.push(last)\n } else {\n return null\n }\n const path = '/' + segs.join('/')\n return isStatic(path) ? path : null\n}\n\n/**\n * A route worth a screen in the burndown: concrete (no template or dynamic\n * segments) and not an error, auth-callback, API or dev-only page.\n */\nexport function isWorthVisiting(route: string): boolean {\n return route.startsWith('/') && !/[$[{:*]/.test(route) && !/^\\/(api|_|404|500)(\\/|$)|\\/callback(\\/|$)|^\\/dev(\\/|$)/.test(route)\n}\n\nexport function routesFromSource(root: string): string[] {\n const found = new Set<string>()\n let files = 0\n const walk = (dir: string, depth: number) => {\n if (depth > 8 || files > MAX_FILES) return\n let names: string[]\n try {\n names = readdirSync(dir)\n } catch {\n return\n }\n for (const name of names) {\n if (SKIP_DIRS.has(name)) continue\n const abs = join(dir, name)\n // One handle for the stat and the read, so the size checked is the\n // size of the bytes read (CodeQL js/file-system-race).\n let fd: number\n let isDir: boolean\n let text = ''\n try {\n fd = openSync(abs, 'r')\n } catch {\n continue\n }\n try {\n const st = fstatSync(fd)\n isDir = st.isDirectory()\n if (!isDir && st.size < 400_000 && /\\.(tsx|jsx|ts|js)$/.test(name) && !/\\.(test|spec|stories)\\./.test(name)) {\n text = readFileSync(fd, 'utf8')\n }\n } catch {\n continue\n } finally {\n closeSync(fd)\n }\n if (isDir) {\n walk(abs, depth + 1)\n continue\n }\n if (!SOURCE_RE.test(name) && !name.endsWith('.mdx')) continue\n if (/\\.(test|spec|stories)\\./.test(name)) continue\n files++\n const rel = relative(root, abs)\n const next = nextRoutePath(rel)\n if (next) found.add(next)\n if (text.includes('Route') || text.includes('createBrowserRouter') || text.includes('createRoutesFromElements')) {\n for (const p of reactRouterPaths(text)) found.add(p)\n }\n }\n }\n walk(root, 0)\n return [...found].sort()\n}\n\n/** Paths listed in /sitemap.xml on the same origin; empty when there is none. */\nexport async function sitemapPaths(baseUrl: string): Promise<string[]> {\n try {\n const res = await fetch(new URL('/sitemap.xml', baseUrl), { signal: AbortSignal.timeout(10_000) })\n if (!res.ok || !(res.headers.get('content-type') ?? '').includes('xml')) return []\n const xml = await res.text()\n const origin = new URL(baseUrl).origin\n const out = new Set<string>()\n for (const m of xml.matchAll(/<loc>\\s*([^<\\s]+)\\s*<\\/loc>/g)) {\n try {\n const u = new URL(m[1])\n // Production sitemaps list the live domain; map their paths onto this server.\n const path = u.pathname + u.search\n if (u.origin === origin || isStatic(u.pathname)) out.add(path)\n } catch {\n /* not a URL */\n }\n }\n return [...out]\n } catch {\n return []\n }\n}\n\n\nconst COMPONENT_DIRS = ['_components', 'components']\nconst MAX_SCREEN_FILES = 12\n\n/**\n * The source files that render one URL path, so the agent starts editing\n * instead of searching: the Next.js page file, the layout beside it, and\n * the components kept next to it. Empty when the router is not one we read\n * (the agent then finds the files itself). On glot.it an attempt spent its\n * whole 15 minutes searching for /practice's files (2026-10-06).\n */\nexport function screenFiles(root: string, urlPath: string): string[] {\n const want = urlPath.split(/[?#]/)[0]!.replace(/\\/+$/, '') || '/'\n let page: string | null = null\n let files = 0\n const walk = (dir: string, depth: number) => {\n if (page || depth > 8 || files > MAX_FILES) return\n let names: string[]\n try {\n names = readdirSync(dir)\n } catch {\n return\n }\n for (const name of names) {\n if (page) return\n if (SKIP_DIRS.has(name)) continue\n const abs = join(dir, name)\n let st\n try {\n st = statSync(abs)\n } catch {\n continue\n }\n if (st.isDirectory()) {\n walk(abs, depth + 1)\n continue\n }\n files++\n const rel = relative(root, abs).replace(/\\\\/g, '/')\n if (nextRoutePath(rel) === want) page = rel\n }\n }\n walk(root, 0)\n // Set inside walk(), which TypeScript's narrowing does not follow.\n const found = page as string | null\n if (!found) return []\n const dir = found.includes('/') ? found.slice(0, found.lastIndexOf('/')) : ''\n const out: string[] = [found]\n const list = (d: string) => {\n try {\n return readdirSync(join(root, d))\n } catch {\n return []\n }\n }\n for (const name of list(dir)) if (/^layout\\.(tsx|jsx|ts|js)$/.test(name)) out.push(dir ? `${dir}/${name}` : name)\n for (const sub of COMPONENT_DIRS) {\n const d = dir ? `${dir}/${sub}` : sub\n for (const name of list(d)) if (SOURCE_RE.test(name) && !/\\.(test|spec|stories)\\./.test(name)) out.push(`${d}/${name}`)\n }\n return out.slice(0, MAX_SCREEN_FILES)\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Final review by a different model: for each screen the loop changed, one\n * pairwise comparison of the original against the kept version, per\n * viewport, grounded in the repo's design tokens and the measured probe\n * deltas.\n *\n * Why pairwise and evidence-bound: open-ended screenshot critique is mostly\n * wrong (Baymard measured an 80% error rate for GPT-4 UX audits; UICrit found\n * 13% of zero-shot critiques valid). Asking \"which is better, and point at\n * where\" is a narrower question, every claim must carry a bounding box, and\n * the two images are shown in random order so the model cannot learn that\n * \"the second one is the new one\".\n *\n * The judge advises; it never reverts or keeps anything. Runs on the\n * person's own Anthropic credentials.\n */\n\nimport Anthropic from '@anthropic-ai/sdk'\nimport { betaZodOutputFormat } from '@anthropic-ai/sdk/helpers/beta/zod'\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { z } from 'zod'\nimport { cropTop } from './image.js'\nimport type { SurfaceState } from './state.js'\nimport type { ProbeResult } from './types.js'\n\nexport const DEFAULT_JUDGE_MODEL = 'claude-opus-5-5'\nconst MAX_DESIGN_CHARS = 16_000\n\nconst Box = z.object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n})\n\nconst Claim = z.object({\n image: z.enum(['A', 'B']),\n box: Box,\n what: z.string(),\n why: z.string(),\n})\n\nconst JudgeOutput = z.object({\n preferred: z.enum(['A', 'B', 'tie']),\n confidence: z.enum(['low', 'medium', 'high']),\n summary: z.string(),\n better: z.array(Claim),\n worse: z.array(Claim),\n design_system_breaks: z.array(\n Claim.extend({\n token_or_rule: z.string(),\n }),\n ),\n})\ntype JudgeOutputT = z.infer<typeof JudgeOutput>\n\nexport interface JudgeClaim {\n /** Which capture the claim points at, after un-shuffling. */\n image: 'before' | 'after'\n box: { x: number; y: number; width: number; height: number }\n what: string\n why: string\n tokenOrRule?: string\n}\n\nexport interface JudgeVerdict {\n viewport: string\n model: string\n preferred: 'before' | 'after' | 'tie'\n confidence: 'low' | 'medium' | 'high'\n summary: string\n better: JudgeClaim[]\n worse: JudgeClaim[]\n designBreaks: JudgeClaim[]\n /** Claims dropped because their box fell outside the image. */\n droppedClaims: number\n /** Set when the model declined or the call failed; no verdict then. */\n error?: string\n}\n\nconst RUBRIC = `You review UI changes for a solo developer. You will see two screenshots of the same screen, labelled A and B, in random order. One is the original and one was edited by a coding agent. You are not told which is which.\n\nDecide which one is better for the person using this screen, judged on:\n1. Clarity: is the screen's purpose and primary action obvious within a few seconds?\n2. Hierarchy: does visual weight (size, colour, position) match importance?\n3. Density: is there less noise (duplicated info, wordy copy, competing calls to action) without losing needed information?\n4. Consistency with the design system given below (tokens, spacing scale, type scale, components). Ignore taste that the design system does not support.\n5. Accessibility you can see: contrast, text size, target size, focus or state indicators.\n\nMeasured numbers for both images are provided (accessibility violations, sideways scroll, small tap targets, console errors). Treat them as facts; do not contradict them.\n\nRules for claims:\n- Every claim points at a region with a box in that image's pixel coordinates (origin top-left).\n- Only claim what is visible in the screenshots. Do not guess about interactions, data, or other screens.\n- Prefer few, specific claims over many generic ones. Generic advice (\"make it responsive\", \"add more whitespace\") is not a claim.\n- If the two are equally good, or the difference is too small to matter, answer \"tie\".\n- \"design_system_breaks\" lists places in either image that visibly break the given tokens or rules; name the token or rule.`\n\nexport interface JudgeOptions {\n dir: string\n repoRoot: string\n designFiles: string[]\n model?: string\n client?: Anthropic\n /** Deterministic order for tests; defaults to Math.random. */\n random?: () => number\n}\n\nfunction designContext(repoRoot: string, files: string[]): string {\n let out = ''\n for (const f of files) {\n if (out.length >= MAX_DESIGN_CHARS) break\n try {\n const text = readFileSync(join(repoRoot, f), 'utf8')\n out += `\\n--- ${f} ---\\n${text.slice(0, MAX_DESIGN_CHARS - out.length)}\\n`\n } catch {\n /* unreadable file: skip */\n }\n }\n return out || '(No design-system files found. Judge consistency against the rest of the screen.)'\n}\n\nfunction probeLine(label: string, p: ProbeResult): string {\n const axe = p.axe.map((v) => `${v.id}×${v.count}`).join(', ') || 'none'\n return `${label}: accessibility violations ${axe}; sideways scroll ${p.overflowX ? 'yes' : 'no'}; small tap targets ${p.smallTargets}; console errors ${p.consoleErrors.length}; layout shift ${p.cls}`\n}\n\nfunction pngSize(buf: Buffer): { width: number; height: number } {\n return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }\n}\n\n/** Pure: map the shuffled A/B answer back to before/after and drop out-of-image claims. */\nexport function unshuffle(\n out: JudgeOutputT,\n aIsBefore: boolean,\n sizes: { A: { width: number; height: number }; B: { width: number; height: number } },\n viewport: string,\n model: string,\n): JudgeVerdict {\n const side = (img: 'A' | 'B'): 'before' | 'after' => ((img === 'A') === aIsBefore ? 'before' : 'after')\n let dropped = 0\n const keep = (c: z.infer<typeof Claim> & { token_or_rule?: string }): JudgeClaim[] => {\n const size = sizes[c.image]\n const inside =\n c.box.width > 0 &&\n c.box.height > 0 &&\n c.box.x >= 0 &&\n c.box.y >= 0 &&\n c.box.x + c.box.width <= size.width + 2 &&\n c.box.y + c.box.height <= size.height + 2\n if (!inside) {\n dropped++\n return []\n }\n return [{ image: side(c.image), box: c.box, what: c.what, why: c.why, tokenOrRule: c.token_or_rule }]\n }\n return {\n viewport,\n model,\n preferred: out.preferred === 'tie' ? 'tie' : side(out.preferred),\n confidence: out.confidence,\n summary: out.summary,\n better: out.better.flatMap(keep),\n worse: out.worse.flatMap(keep),\n designBreaks: out.design_system_breaks.flatMap(keep),\n droppedClaims: dropped,\n }\n}\n\n/** Judge one screen at one viewport: its baseline against its last kept capture. */\nexport async function judgeSurface(s: SurfaceState, viewport: string, opts: JudgeOptions): Promise<JudgeVerdict | null> {\n const kept = [...s.iterations].reverse().find((i) => i.outcome === 'accepted' && i.after[viewport])\n const before = s.baseline[viewport]\n if (!kept || !before) return null\n const after = kept.after[viewport]\n const model = opts.model ?? DEFAULT_JUDGE_MODEL\n const client = opts.client ?? new Anthropic()\n\n const beforePng = readFileSync(join(opts.dir, before.png))\n const width = pngSize(beforePng).width\n const maxHeight = Math.round(width * (viewport === 'mobile' ? 2.5 : 1.25))\n const bImg = cropTop(beforePng, maxHeight)\n const aImg = cropTop(readFileSync(join(opts.dir, after.png)), maxHeight)\n const aIsBefore = (opts.random ?? Math.random)() < 0.5\n const [imgA, imgB] = aIsBefore ? [bImg, aImg] : [aImg, bImg]\n const [probeA, probeB] = aIsBefore ? [before.probes, after.probes] : [after.probes, before.probes]\n\n const image = (png: Buffer): Anthropic.Beta.BetaImageBlockParam => ({\n type: 'image',\n source: { type: 'base64', media_type: 'image/png', data: png.toString('base64') },\n })\n\n try {\n const response = await client.beta.messages.parse({\n model,\n max_tokens: 16_000,\n betas: ['server-side-fallback-2026-07-01'],\n fallbacks: 'default',\n output_config: { effort: 'high', format: betaZodOutputFormat(JudgeOutput) },\n system: [\n { type: 'text', text: RUBRIC },\n {\n type: 'text',\n text: `Design system of this repository:\\n${designContext(opts.repoRoot, opts.designFiles)}`,\n // Same rubric + tokens for every screen in the run: cache the prefix.\n cache_control: { type: 'ephemeral' },\n },\n ],\n messages: [\n {\n role: 'user',\n content: [\n { type: 'text', text: `Screen: ${s.surface.label} (${s.surface.path}), ${viewport} viewport.` },\n { type: 'text', text: 'Image A:' },\n image(imgA),\n { type: 'text', text: 'Image B:' },\n image(imgB),\n { type: 'text', text: `${probeLine('A', probeA)}\\n${probeLine('B', probeB)}\\n\\nWhich is better, A or B?` },\n ],\n },\n ],\n })\n if (response.stop_reason === 'refusal') {\n return failed(viewport, model, `The model declined (${response.stop_details?.category ?? 'no category'}).`)\n }\n const parsed = response.parsed_output\n if (!parsed) return failed(viewport, model, `No structured answer (stop reason ${response.stop_reason}).`)\n return unshuffle(parsed, aIsBefore, { A: pngSize(imgA), B: pngSize(imgB) }, viewport, response.model)\n } catch (err) {\n if (err instanceof Anthropic.AuthenticationError) {\n return failed(viewport, model, 'No valid Anthropic credentials. Set ANTHROPIC_API_KEY or run `ant auth login`.')\n }\n if (err instanceof Anthropic.RateLimitError) return failed(viewport, model, 'Rate limited by the Anthropic API.')\n if (err instanceof Anthropic.APIError) return failed(viewport, model, `Anthropic API error ${err.status}: ${err.message}`)\n throw err\n }\n}\n\nfunction failed(viewport: string, model: string, error: string): JudgeVerdict {\n return {\n viewport,\n model,\n preferred: 'tie',\n confidence: 'low',\n summary: '',\n better: [],\n worse: [],\n designBreaks: [],\n droppedClaims: 0,\n error,\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The loop. One run:\n *\n * worktree + dev server → discover surfaces → for each surface:\n * baseline (desktop + mobile) → prompt packet → agent edits →\n * recapture → pixel diff + probes → keep (commit) or roll back →\n * re-check a sample of finished screens for collateral changes\n *\n * State is saved after every step, so `--resume <runId>` continues an\n * interrupted run. Events go to the dashboard (dashboard.ts) as they happen.\n */\n\nimport type { EventEmitter } from 'node:events'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { attemptLogBase, describeAgentLine, formatStep, sessionIdOf } from './agent-events.js'\nimport { getAgent, type AgentAdapter, type AgentName, type AgentRunOptions } from './agents.js'\nimport { captureSurface, openSession, type BrowserSession } from './capture.js'\nimport { discover } from './discover.js'\nimport type { AllowRule } from './guard.js'\nimport { checkStep, type CheckerSpec } from './checker.js'\nimport { pixelDiff } from './image.js'\nimport { judgeSurface } from './judge.js'\nimport { buildPacket, buildPlanPacket, findDesignFiles, MAX_PLAN_STEPS, MAX_STEP_FILES, parsePlan, PLAN_POINTER_PROMPT, POINTER_PROMPT } from './packet.js'\nimport { preflightAgent } from './preflight.js'\nimport { screenFiles } from './routes.js'\nimport { isFrameworkNoise, probePenalty } from './probes.js'\nimport { expectedHead, saveSkillFiles } from './resume.js'\nimport { appEnv, run, type RunResult } from './proc.js'\nimport type { ResolvedSkill } from './skills.js'\nimport {\n loadState,\n newRunId,\n runDir,\n saveState,\n savePng,\n type IterationRecord,\n type PlanStep,\n type RunPhase,\n type RunState,\n type ShotRef,\n type SurfaceState,\n} from './state.js'\nimport { VIEWPORTS, type ProbeResult } from './types.js'\nimport { agentFinalMessage, assistantText, clsNeedsSecondLook, decide, explainNoEdit, steadierCls } from './verdict.js'\nimport {\n changedFiles,\n commitAll,\n createWorktree,\n diffText,\n detectInstallCommand,\n headSha,\n resetRunBranch,\n revertAll,\n SCRATCH_DIR,\n startDevServer,\n type DevServer,\n} from './worktree.js'\n\n/** Share of a finished screen's content that must move to count as collateral. */\nconst REGRESSION_CONTENT_RATIO = 0.05\n/** Ignore tiny moves (a clock, a counter) below this many pixels. */\nconst REGRESSION_MIN_PIXELS = 200\n/**\n * The planning pass of steps mode gets at most this long. Grok 4.7 xhigh took\n * 16 steps in 6 minutes on a three-skill chain and wrote no plan with 4 + 2\n * minutes (glot.it tone training, 2026-10-07); a plan that fails costs the\n * screen its small steps.\n */\nconst PLAN_TIMEOUT_MS = 6 * 60_000\n/** \"Time is up\" continuations of the same agent session, when a box ran out with nothing to show. */\nconst PLAN_NUDGE_MS = 3 * 60_000\nconst EDIT_NUDGE_MS = 3 * 60_000\nconst PLAN_NUDGE =\n 'Time is up. Do not read any more files. Write .mushi-ux/PLAN.md now with the improvements you found, one per line starting with \"- \", then stop.'\nconst EDIT_NUDGE =\n 'Time is up. Do not read any more files. Make the one change you have decided on now, touching at most 3 files, then stop.'\n/** How often a working attempt checks in (git status + state save). */\nconst HEARTBEAT_MS = 30_000\n\nexport type LoopEvent =\n | { type: 'log'; message: string }\n | { type: 'agent'; surface: string; line: string; kind?: string }\n | { type: 'state' }\n | { type: 'phase'; phase: RunPhase; detail: string | null }\n\nexport interface LoopOptions {\n repoRoot: string\n devCommand: string\n /** null skips the install; undefined detects it from the lockfile. */\n installCommand?: string | null\n startPaths?: string[]\n agent: AgentName\n /** Overrides `agent` with a custom adapter (tests, other harnesses). */\n agentAdapter?: AgentAdapter\n model?: string | null\n iterations?: number\n maxSurfaces?: number\n agentTimeoutMs?: number\n skillText?: string | null\n /** A skill folder (SKILL.md + references); wins over skillText. */\n skill?: ResolvedSkill | null\n /** Git ref the worktree branches from. Default HEAD. */\n baseRef?: string\n allow?: AllowRule[]\n /** Selectors that are not the app's UI, on top of DEFAULT_IGNORE (ignore.ts). */\n ignore?: string[]\n profileDir?: string\n regressionSample?: number\n /** Model for the final pairwise review; null turns it off. */\n judgeModel?: string | null\n resumeRunId?: string\n /** Follow links from startPaths too. Off: only the named pages and the states they open. */\n crawl?: boolean\n /** Aborting stops the run between steps and kills a running agent. */\n signal?: AbortSignal\n /** Check the agent can read a file before anything slow starts. Default on (off for a custom adapter and the cloud agent). */\n preflight?: boolean\n /** Plan each screen into small steps first, then make one step per attempt (iterations caps the steps). */\n steps?: boolean\n /**\n * A second model that reviews each kept step and may roll it back, never\n * keep a rejected one (ADR 0021). null: measurements alone decide.\n */\n checker?: CheckerSpec | null\n /** Keep an edit with nothing visible, flagged for review (ADR 0021). Default on. */\n keepInvisible?: boolean\n /** Saved with the run for a later resume only: the login URL behind profileDir, and whether it synced. */\n loginUrl?: string | null\n sync?: boolean\n events?: EventEmitter\n}\n\nexport interface LoopHandle {\n runId: string\n dir: string\n done: Promise<RunState>\n}\n\nfunction emit(events: EventEmitter | undefined, e: LoopEvent) {\n events?.emit('event', e)\n}\n\n/** The screenshot a finished screen should still look like. */\nfunction referenceShot(s: SurfaceState, viewport: string): ShotRef | undefined {\n const kept = [...s.iterations].reverse().find((i) => i.outcome === 'accepted')\n return kept?.after[viewport] ?? s.baseline[viewport]\n}\n\n/**\n * Saved probes from before a noise rule existed still carry framework\n * console messages; a resumed run must not score or brief them.\n */\n/** What the next attempt is told after one ran out of time without an edit. */\nfunction timeoutNote(timeoutMs: number): string {\n const minutes = Math.round(timeoutMs / 60_000)\n return `It read for ${minutes} minutes without making any edit and was stopped. Start from the files under \"Start here\", pick one change, and make it within ${Math.max(1, Math.round(minutes / 3))} minutes.`\n}\n\nfunction scrubFrameworkNoise(state: RunState): void {\n const clean = (ref: ShotRef | undefined) => {\n if (!ref) return\n const kept = ref.probes.consoleErrors.filter((e) => !isFrameworkNoise(e))\n if (kept.length === ref.probes.consoleErrors.length) return\n ref.probes = { ...ref.probes, consoleErrors: kept }\n ref.penalty = probePenalty(ref.probes)\n }\n for (const s of state.surfaces) {\n Object.values(s.baseline).forEach(clean)\n for (const it of s.iterations) Object.values(it.after).forEach(clean)\n }\n}\n\n/**\n * Pure: why mapping found no screen, from the \"skipped\" lines and the dev\n * server's first error. Every page failing the same way (all HTTP 500) points\n * at the app, not the pages, so that case leads with the dev server.\n * @internal Exported for tests only.\n */\nexport function noScreensMessage(skipped: string[], devError: string | null): string {\n const reasons = skipped.map((s) => s.replace(/^\\S+:\\s*/, ''))\n const unique = [...new Set(reasons)]\n const lines: string[] = []\n if (skipped.length && unique.length === 1 && /HTTP 5\\d\\d/.test(unique[0])) {\n lines.push(`No screen to work on: every page returned ${unique[0]}, so the app's dev server is failing, not the pages.`)\n } else if (skipped.length) {\n lines.push(`No screen to work on: all ${new Set(skipped.map((s) => s.split(':')[0])).size} page(s) were skipped (${unique.slice(0, 3).join('; ')}).`)\n } else {\n lines.push('No screen to work on: mapping found no page. Name the pages to work on, or check that the home page loads.')\n }\n if (devError) lines.push(`The dev server said: ${devError}`)\n lines.push('Fix the app or the dev command (for example a different bundler flag), then start a new run. The full output is in run.log.')\n return lines.join('\\n')\n}\n\n/** A commit subject's summary stops here, at a whole word. */\nconst SUMMARY_MAX = 72\nconst DANGLING = /[\\s,]+(?:a|an|and|as|at|between|by|for|from|in|into|is|of|on|or|so|that|the|to|while|with)$/i\n\n/**\n * Pure: the commit message for a kept attempt. Host apps lint commits as\n * conventional commits (glot.it allows only the standard types) and turn the\n * subjects into their in-app changelog, so the subject is `fix(ux):` and a\n * plain sentence that ends on a whole word, without file names; the screen,\n * the step and the measurements go in the body.\n * @internal Exported for tests only.\n */\nexport function commitMessage(path: string, screen: string, step: string | null, reason: string): string {\n const name = screen.split(/\\s+[—|–]\\s+/)[0].trim() || path\n const summary = (step ? stepSummary(step) : '') || `improve the ${name} screen`\n const body = [step ? `${name} (${path}): ${step}` : `${name} (${path})`, reason]\n return [`fix(ux): ${lowerFirst(summary)}`, ...body.map((p) => wrapAt(p, BODY_WIDTH))].join('\\n\\n')\n}\n\n/** Conventional-commit lint rejects body lines over 100 characters. */\nconst BODY_WIDTH = 100\n\nfunction wrapAt(text: string, width: number): string {\n const lines: string[] = []\n let line = ''\n for (const word of text.split(/\\s+/).filter(Boolean)) {\n if (line && [...`${line} ${word}`].length > width) {\n lines.push(line)\n line = word\n } else line = line ? `${line} ${word}` : word\n }\n if (line) lines.push(line)\n // A line that starts \"word: \" reads as a commit footer to commitlint, which then wants a blank\n // line before it (\"…screen\\nreader: in x.tsx\" failed glot.it's lint, 2026-10-07). Pull the\n // previous word down so the line starts mid-sentence.\n for (let i = 1; i < lines.length; i++) {\n if (!FOOTER_TOKEN.test(lines[i])) continue\n const prev = lines[i - 1].split(' ')\n if (prev.length < 2) continue\n lines[i] = `${prev.pop()} ${lines[i]}`\n lines[i - 1] = prev.join(' ')\n }\n return lines.join('\\n')\n}\n\n/** What conventional-commit parsers read as a footer token at the start of a line. */\nconst FOOTER_TOKEN = /^(?:[A-Za-z][\\w-]*|BREAKING CHANGE): /\n\n/** \"Fix the caption\" → \"fix the caption\"; \"CTA buttons\" and quoted text stay as they are. */\nconst lowerFirst = (s: string) => (/^[A-Z][a-z]/.test(s) ? s[0].toLowerCase() + s.slice(1) : s)\n\nconst isPath = (code: string) => code.includes('/') || /\\.[a-z]{2,4}$/i.test(code)\n\nfunction stepSummary(step: string): string {\n // Plans lead with a plain summary before a colon (\"Fix the caption contrast: in `x.tsx`, ...\").\n const lead = step.match(/^([^:`]{8,90}):\\s/)?.[1]\n let s = lead ?? step.replace(/^(?:In\\s+)?`[^`]+`(?:\\s*\\([^)]*\\))?\\s*[,:]?\\s*/i, '').split(/(?<=\\.)\\s|;\\s/)[0]\n s = s\n .replace(/\\s*\\(([^()]*)\\)/g, (m, inner: string) => (inner.includes('`') ? '' : m))\n // A file named after \"in\" or \"from\" goes with its preposition.\n .replace(/\\s+(?:in|from|of|on)\\s+`([^`]*)`/gi, (m, inner: string) => (isPath(inner) ? '' : m))\n // Code spans pair left to right: paths go, other code stays as words.\n .replace(/`([^`]*)`/g, (_m, inner: string) => (isPath(inner) ? ' ' : inner.replace(/[\"']/g, '')))\n .replace(/\\s{2,}/g, ' ')\n .trim()\n if (s.length > SUMMARY_MAX) {\n const cut = s.lastIndexOf(' ', SUMMARY_MAX)\n s = s.slice(0, cut > 0 ? cut : SUMMARY_MAX)\n const open = s.lastIndexOf('(')\n if (open > s.lastIndexOf(')')) s = s.slice(0, open)\n // A cut sentence should not end on a word that needs the next one.\n while (DANGLING.test(s)) s = s.replace(DANGLING, '')\n }\n s = s.replace(/^[\\s,;:.—–-]+|[\\s,;:.—–-]+$/g, '')\n return s ? s[0].toUpperCase() + s.slice(1) : ''\n}\n\nexport function startLoop(opts: LoopOptions): LoopHandle {\n const runId = opts.resumeRunId ?? newRunId()\n const dir = runDir(opts.repoRoot, runId)\n const done = runLoop(opts, runId, dir)\n return { runId, dir, done }\n}\n\nasync function runLoop(opts: LoopOptions, runId: string, dir: string): Promise<RunState> {\n const events = opts.events\n // Also kept in run.log, so a past or failed run still shows what happened.\n const log = (message: string) => {\n emit(events, { type: 'log', message })\n try {\n mkdirSync(dir, { recursive: true })\n appendFileSync(join(dir, 'run.log'), `${new Date().toISOString().slice(11, 19)} ${message}\\n`)\n } catch {\n /* the log is a convenience; the run goes on without it */\n }\n }\n const agent = opts.agentAdapter ?? getAgent(opts.agent)\n const iterations = opts.iterations ?? 2\n const timeoutMs = opts.agentTimeoutMs ?? 10 * 60_000\n\n const state: RunState = loadState(dir) ?? {\n version: 1,\n runId,\n baseUrl: '',\n createdAt: new Date().toISOString(),\n updatedAt: '',\n agent: agent.name,\n model: opts.model ?? null,\n skill: opts.skill ? { name: opts.skill.name, source: opts.skill.source } : null,\n baseRef: opts.baseRef ?? 'HEAD',\n phase: 'starting',\n worktree: null,\n branch: null,\n baseSha: null,\n surfaces: [],\n }\n scrubFrameworkNoise(state)\n const resuming = Boolean(state.updatedAt)\n if (resuming) {\n // A resumed run starts clean: the old stop or error is history, kept in run.log.\n state.error = null\n state.finishedAt = null\n state.stopped = false\n state.current = null\n }\n // Everything a later resume needs, so it takes only the run id.\n if (!state.options) {\n state.options = {\n agent: String(opts.agent),\n model: opts.model ?? null,\n devCommand: opts.devCommand,\n installCommand: opts.installCommand,\n startPaths: opts.startPaths,\n crawl: opts.crawl,\n iterations,\n checker: opts.checker ?? null,\n keepInvisible: opts.keepInvisible !== false,\n maxSurfaces: opts.maxSurfaces ?? 10,\n agentTimeoutMs: timeoutMs,\n ignore: opts.ignore,\n allow: opts.allow,\n judgeModel: opts.judgeModel ?? null,\n loginUrl: opts.loginUrl ?? null,\n sync: opts.sync,\n steps: opts.steps,\n }\n }\n if (opts.skill) {\n state.skill = { name: opts.skill.name, source: opts.skill.source }\n try {\n saveSkillFiles(dir, opts.skill)\n } catch {\n // Only a later resume needs the copy; it says so if it is missing.\n }\n }\n const persist = () => {\n saveState(dir, state)\n emit(events, { type: 'state' })\n }\n const phase = (p: RunPhase, detail: string | null = null) => {\n state.phase = p\n state.phaseDetail = detail\n emit(events, { type: 'phase', phase: p, detail })\n persist()\n }\n const skillText = opts.skill?.text ?? opts.skillText ?? null\n\n // The run checks in every 30 s in every phase (a save stamps updatedAt), so\n // the studio and the console can tell a long install from a dead process.\n const beat = setInterval(() => {\n try {\n persist()\n } catch {\n // The next beat, or the next real state change, saves again.\n }\n }, HEARTBEAT_MS)\n try {\n return await runSteps()\n } catch (err) {\n const stopped = Boolean(opts.signal?.aborted)\n state.stopped = stopped\n state.error = stopped ? 'Stopped from the studio.' : (err as Error).message.slice(0, 2000)\n // A stop can land mid-edit: leave the branch at its last kept commit.\n if (stopped && state.worktree) await revertAll(state.worktree).catch(() => undefined)\n state.current = null\n state.finishedAt = new Date().toISOString()\n phase('failed', state.error.split('\\n')[0].slice(0, 200))\n throw err\n } finally {\n clearInterval(beat)\n }\n\n async function runSteps(): Promise<RunState> {\n if (opts.preflight !== false && !opts.agentAdapter && agent.name !== 'cursor-cloud') {\n log(`Checking that ${agent.name} can read files…`)\n phase('starting', 'Checking the agent can read files')\n const problem = await preflightAgent(agent, { model: opts.model, signal: opts.signal })\n if (opts.signal?.aborted) throw new Error('Stopped.')\n if (problem) throw new Error(problem)\n log('Agent check passed.')\n }\n if (!state.worktree) {\n log('Creating a worktree for the agent…')\n phase('worktree', `from ${state.baseRef ?? 'HEAD'}`)\n const wt = await createWorktree(opts.repoRoot, runId, state.baseRef ?? 'HEAD')\n state.worktree = wt.path\n state.branch = wt.branch\n state.baseSha = wt.baseSha\n persist()\n } else if (!existsSync(state.worktree)) {\n throw new Error(`The run's worktree ${state.worktree} is gone, so this run cannot continue. Start a new run.`)\n }\n // Runs from before the flag existed: one that got as far as mapping was installed.\n if (state.installed === undefined && state.surfaces.length > 0) state.installed = true\n if (!state.installed) {\n const install = opts.installCommand === undefined ? detectInstallCommand(state.worktree) : opts.installCommand\n if (install) {\n log(`Installing dependencies: ${install}`)\n phase('install', install)\n const res = await run(install, [], { cwd: state.worktree, shell: true, timeoutMs: 15 * 60_000, env: appEnv() })\n if (res.exitCode !== 0) throw new Error(`Install failed in the worktree:\\n${res.tail}`)\n }\n state.installed = true\n persist()\n }\n const wtPath = state.worktree\n if (resuming) await restoreWorktree(wtPath)\n const designFiles = findDesignFiles(wtPath)\n\n log(`Starting the dev server in the worktree: ${opts.devCommand}`)\n phase('dev-server', opts.devCommand)\n // The dev server's first error line names the cause when every page fails.\n let devError: string | null = null\n const server: DevServer = await startDevServer(wtPath, opts.devCommand, {\n path: opts.startPaths?.[0],\n onLine: (l) => {\n log(`[dev] ${l.slice(0, 200)}`)\n if (!devError && /\\b(error|module not found)\\b/i.test(l)) devError = l.trim().slice(0, 300)\n },\n })\n state.baseUrl = server.url\n persist()\n\n const session: BrowserSession = await openSession({ profileDir: opts.profileDir, allow: opts.allow, ignore: opts.ignore })\n try {\n if (state.surfaces.length === 0) {\n log('Mapping screens…')\n phase('mapping', null)\n // Ask for every named page at once first: the dev server compiles them\n // together instead of one per visit (mapping took 10 min for 8 pages\n // on glot.it's webpack dev server, 2026-10-07). Plain GETs only.\n if (opts.startPaths?.length) {\n const t0 = Date.now()\n await Promise.all(\n // Follow redirects: /chat answers 308 → /chat/ at once, and only the target compiles.\n opts.startPaths.map((p) => fetch(new URL(p, server.url), { signal: AbortSignal.timeout(180_000) }).then((r) => r.arrayBuffer()).catch(() => null)),\n )\n log(`warmed ${opts.startPaths.length} page(s) in ${Math.round((Date.now() - t0) / 1000)} s`)\n }\n const skipped: string[] = []\n const found = await discover(session, {\n baseUrl: server.url,\n startPaths: opts.startPaths,\n onlyStartPaths: Boolean(opts.startPaths?.length) && !opts.crawl,\n sourceDir: wtPath,\n signal: opts.signal,\n onProgress: (m) => {\n log(`found ${m}`)\n if (m.startsWith('skipped ')) skipped.push(m.slice('skipped '.length))\n // The studio shows the latest mapping line under the phase.\n phase('mapping', m.slice(0, 200))\n },\n })\n // Nothing to work on is a failed run, not a finished one: say why.\n if (found.length === 0) throw new Error(noScreensMessage(skipped, devError))\n state.surfaces = found.slice(0, opts.maxSurfaces ?? 10).map((surface) => ({\n surface,\n status: 'pending',\n note: null,\n baseline: {},\n iterations: [],\n }))\n log(`${state.surfaces.length} screen(s) on the burndown (${found.length} found).`)\n persist()\n }\n\n // Captures start from a visited app, the same for every screen (capture.ts warmUp).\n log('Opening every screen once, so each capture starts from a loaded app…')\n await session.warmUp(server.url, [...new Set(state.surfaces.map((x) => x.surface.path))])\n phase('working', null)\n for (const s of state.surfaces) {\n if (opts.signal?.aborted) throw new Error('Stopped.')\n if (!['pending', 'baseline', 'iterating'].includes(s.status)) continue\n if (s.status === 'iterating') await revertAll(wtPath) // interrupted mid-edit\n await processSurface(s)\n }\n state.current = null\n if (opts.judgeModel) {\n phase('reviewing', opts.judgeModel)\n await runJudge(opts.judgeModel)\n }\n state.finishedAt = new Date().toISOString()\n phase('done', null)\n log(`Done. Branch ${state.branch} holds every kept change; open a draft PR from it when you are happy.`)\n return state\n } finally {\n await session.close()\n server.stop()\n persist()\n }\n\n /**\n * Before a resumed run goes on: the branch back on its last saved kept\n * commit (a crash can land between an attempt's commit and the save), and\n * a half-finished attempt's edits thrown away. That attempt runs again.\n */\n async function restoreWorktree(wt: string): Promise<void> {\n const want = expectedHead(state)\n const head = await headSha(wt)\n if (want && head !== want) {\n try {\n await resetRunBranch(wt, want)\n } catch {\n throw new Error(\n `The run branch ${state.branch} no longer holds its last kept commit ${want.slice(0, 8)}: it was changed outside the run. Start a new run.`,\n )\n }\n log(`The run branch was ahead of its last saved attempt (${head.slice(0, 8)}); moved it back to ${want.slice(0, 8)}. That attempt runs again.`)\n }\n await revertAll(wt)\n log('Resumed: unfinished edits cleared; carrying on from the first unfinished screen.')\n }\n\n /**\n * Run the agent; if its time box runs out with nothing to show (no plan,\n * no edit) and it can resume its session, continue that same session once\n * with \"time is up, write it now\" and a short extra box. Grok 4.7 xhigh\n * read for whole attempts and ignored in-prompt deadlines (glot.it,\n * 2026-10-06); the continuation keeps everything it read.\n */\n async function runWithNudge(\n runOpts: AgentRunOptions & { nudge: { prompt: string; ms: number; needed: () => Promise<boolean> } },\n ): Promise<RunResult> {\n const { nudge, ...base } = runOpts\n const first = await agent.run(base)\n if (!first.timedOut || !agent.canResume || opts.signal?.aborted) return first\n const session = sessionIdOf(first.stdout)\n if (!session || !(await nudge.needed())) return first\n log(` time is up: asking the agent to finish now (${Math.round(nudge.ms / 60_000)} more min, same session)`)\n const second = await agent.run({ ...base, prompt: nudge.prompt, timeoutMs: nudge.ms, resumeSession: session })\n return {\n exitCode: second.exitCode,\n timedOut: second.timedOut,\n durationMs: first.durationMs + second.durationMs,\n tail: second.tail,\n stdout: `${first.stdout}\\n${second.stdout}`,\n }\n }\n\n /** Fresh scratch dir for one agent run: the skill, and the screenshots to start from. */\n function prepareScratch(current: Record<string, ShotRef>): { shots: Record<string, string>; probes: Record<string, ProbeResult> } {\n const scratch = join(wtPath, SCRATCH_DIR)\n rmSync(scratch, { recursive: true, force: true })\n mkdirSync(scratch, { recursive: true })\n if (opts.skill) {\n for (const [rel, buf] of Object.entries(opts.skill.files)) {\n const target = join(scratch, 'skill', ...rel.split('/'))\n mkdirSync(dirname(target), { recursive: true })\n writeFileSync(target, buf)\n }\n }\n const shots: Record<string, string> = {}\n for (const [vp, ref] of Object.entries(current)) {\n writeFileSync(join(scratch, `${vp}.png`), readFileSync(join(dir, ref.png)))\n shots[vp] = `${SCRATCH_DIR}/${vp}.png`\n }\n return { shots, probes: Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes])) }\n }\n\n /**\n * Steps mode: one short agent run that lists small, separate improvements\n * for the screen and edits nothing (anything it does edit is thrown\n * away). Null when it produced no usable list: the screen then gets\n * whole-screen attempts instead.\n */\n async function planSurface(s: SurfaceState, current: Record<string, ShotRef>, entryFiles: string[]): Promise<{ steps: PlanStep[]; session?: string | null } | null> {\n const planMs = Math.min(timeoutMs, PLAN_TIMEOUT_MS)\n const { shots, probes } = prepareScratch(current)\n const maxSteps = Math.min(MAX_PLAN_STEPS, iterations)\n writeFileSync(\n join(wtPath, SCRATCH_DIR, 'PROMPT.md'),\n buildPlanPacket({ surface: s.surface, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, timeBudgetMin: Math.round(planMs / 60_000), entryFiles }, maxSteps),\n )\n s.status = 'iterating'\n const startedAt = new Date().toISOString()\n state.current = { surface: s.surface.key, attempt: 1, startedAt, timeoutMs: planMs, steps: 0, lastStep: null, files: [], heartbeatAt: startedAt }\n phase('working', `${s.surface.label}, planning small steps`)\n log(` planning ${s.surface.label} in small steps…`)\n // Its steps go to agent/<screen>-plan.steps.log, so a failed plan can be read.\n const planLog = join(dir, 'agent', `${attemptLogBase(s.surface.key, 0).slice(0, -2)}-plan.steps.log`)\n try {\n mkdirSync(dirname(planLog), { recursive: true })\n writeFileSync(planLog, '')\n } catch {\n // The log is for reading later only.\n }\n const planFile = join(wtPath, SCRATCH_DIR, 'PLAN.md')\n const res = await runWithNudge({\n cwd: wtPath,\n prompt: PLAN_POINTER_PROMPT,\n model: opts.model,\n timeoutMs: planMs,\n signal: opts.signal,\n nudge: {\n prompt: PLAN_NUDGE,\n ms: PLAN_NUDGE_MS,\n needed: async () => !existsSync(planFile) || parsePlan(readFileSync(planFile, 'utf8')).length === 0,\n },\n onLine: (line) => {\n for (const step of describeAgentLine(line, wtPath)) {\n const text = formatStep(step)\n try {\n appendFileSync(planLog, `${text}\\n`)\n } catch {\n // See above.\n }\n emit(events, { type: 'agent', surface: s.surface.key, line: text, kind: step.kind })\n }\n },\n })\n if (opts.signal?.aborted) throw new Error('Stopped.')\n // The file first (written early, refined later); then the reply; then anything the agent said before it was stopped.\n const fromFile = existsSync(planFile) ? readFileSync(planFile, 'utf8') : ''\n const text = parsePlan(fromFile).length ? fromFile : (agentFinalMessage(res.stdout) ?? assistantText(res.stdout))\n await revertAll(wtPath) // planning never edits\n const items = parsePlan(text, maxSteps)\n if (items.length === 0) {\n log(` no plan came back${res.timedOut ? ' (the agent ran out of time)' : ''}; working on the whole screen instead.`)\n return null\n }\n log(` plan: ${items.map((t, i) => `${i + 1}. ${t}`).join(' ')}`)\n return { steps: items.map((t) => ({ text: t, status: 'pending' as const })), session: agent.canResume ? sessionIdOf(res.stdout) : null }\n }\n\n /** Record which plan step an attempt worked on, and how it went. */\n function markStep(\n step: PlanStep | null,\n info: { index: number; total: number } | null,\n record: IterationRecord,\n status: PlanStep['status'],\n ): void {\n if (!step || !info) return\n step.status = status\n step.attempt = record.n\n record.step = step.text\n record.reason = `Step ${info.index}/${info.total}: ${record.reason}`\n step.reason = record.reason\n }\n\n async function capture(s: SurfaceState): Promise<Record<string, { png: Buffer; probes: ProbeResult }>> {\n // Each capture has its own clean browser context, so the viewports run side by side.\n const shots = await Promise.all(VIEWPORTS.map((vp) => captureSurface(session, state.baseUrl, s.surface, vp)))\n return Object.fromEntries(VIEWPORTS.map((vp, i) => [vp.name, shots[i]]))\n }\n\n function shotRefs(s: SurfaceState, label: string, shots: Record<string, { png: Buffer; probes: ProbeResult }>) {\n const refs: Record<string, ShotRef> = {}\n for (const [vp, shot] of Object.entries(shots)) {\n refs[vp] = { png: savePng(dir, `shots/${s.surface.key}/${label}-${vp}.png`, shot.png), probes: shot.probes, penalty: probePenalty(shot.probes) }\n }\n return refs\n }\n\n async function processSurface(s: SurfaceState): Promise<void> {\n log(`▶ ${s.surface.label}`)\n if (Object.keys(s.baseline).length === 0) {\n try {\n s.baseline = shotRefs(s, 'baseline', await capture(s))\n } catch (err) {\n s.status = 'blocked'\n s.note = `Could not capture the screen: ${(err as Error).message.slice(0, 200)}`\n persist()\n return\n }\n }\n s.status = 'baseline'\n persist()\n\n // A resumed screen carries on from what it already has: compare against\n // the last kept version, tell the agent why its last try was rolled\n // back, and stop where a finished attempt would have stopped.\n const entryFiles = screenFiles(wtPath, s.surface.path)\n const lastKept = [...s.iterations].reverse().find((i) => i.outcome === 'accepted')\n let current = lastKept ? lastKept.after : s.baseline\n const last = s.iterations[s.iterations.length - 1]\n let previousRejection: string | null =\n last?.outcome === 'rejected' ? last.reason : last?.outcome === 'agent_failed' && last.timedOut ? timeoutNote(timeoutMs) : null\n // Steps mode: plan once (no edits), then one plan step per attempt.\n // Plan again when planning failed and nothing has come of the screen since (only failed attempts).\n if (opts.steps && (s.plan === undefined || (s.plan === null && s.iterations.every((i) => i.outcome === 'agent_failed')))) {\n s.plan = await planSurface(s, current, entryFiles)\n persist()\n }\n const plan = opts.steps && s.plan?.steps.length ? s.plan : null\n // The session each step resumes, so the agent keeps the files it already read\n // (each fresh step re-read 5-19 files and ran 3-23 searches, glot.it 2026-10-07).\n // Only while the files match its memory: after the plan or a kept step.\n let carrySession: string | null = plan && agent.canResume && !s.iterations.some((i) => i.outcome !== 'accepted') ? plan.session ?? null : null\n const pending = plan ? plan.steps.filter((p) => p.status === 'pending').length : 0\n const settled = last?.outcome === 'no_change' || (last?.outcome === 'agent_failed' && !last.timedOut)\n const first = s.iterations.length + 1\n const lastAttempt = plan ? first + pending - 1 : settled ? 0 : iterations\n for (let n = first; n <= lastAttempt; n++) {\n const step = plan?.steps.find((p) => p.status === 'pending') ?? null\n const stepInfo = step && plan\n ? { text: step.text, index: plan.steps.indexOf(step) + 1, total: plan.steps.length, done: plan.steps.filter((p) => p.status === 'done').map((p) => p.text) }\n : null\n const { shots, probes } = prepareScratch(current)\n writeFileSync(\n join(wtPath, SCRATCH_DIR, 'PROMPT.md'),\n buildPacket({ surface: s.surface, iteration: n, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, previousRejection, timeBudgetMin: Math.round(timeoutMs / 60_000), entryFiles, step: stepInfo }),\n )\n s.status = 'iterating'\n const startedAt = new Date().toISOString()\n const live = { surface: s.surface.key, attempt: n, startedAt, timeoutMs, steps: 0, lastStep: null as string | null, files: [] as string[], heartbeatAt: startedAt }\n state.current = live\n phase('working', stepInfo ? `${s.surface.label}, step ${stepInfo.index} of ${stepInfo.total}` : `${s.surface.label}, attempt ${n} of ${iterations}`)\n\n // Readable steps for the live view and the saved log tail.\n const steps: string[] = []\n const logDir = join(dir, 'agent')\n const logBase = join(logDir, attemptLogBase(s.surface.key, n))\n try {\n mkdirSync(logDir, { recursive: true })\n writeFileSync(`${logBase}.steps.log`, '')\n } catch {\n // Only the reload view of the studio needs the file; the run goes on without it.\n }\n // Check in while the agent works, so a viewer can tell a slow attempt from a dead run.\n const heartbeat = setInterval(() => {\n void changedFiles(wtPath)\n .then((f) => {\n if (state.current !== live) return\n live.files = f.slice(0, 50)\n live.heartbeatAt = new Date().toISOString()\n persist()\n })\n .catch(() => undefined)\n }, HEARTBEAT_MS)\n let res\n try {\n res = await runWithNudge({\n cwd: wtPath,\n prompt: carrySession ? `${POINTER_PROMPT}\\n\\nThis continues your session for this screen: you have already read its files. Do not read them again unless you need a file you have not seen. Make this step's change now.` : POINTER_PROMPT,\n model: opts.model,\n timeoutMs,\n signal: opts.signal,\n resumeSession: carrySession ?? undefined,\n nudge: {\n prompt: EDIT_NUDGE,\n ms: EDIT_NUDGE_MS,\n needed: async () => (await changedFiles(wtPath).catch(() => [])).length === 0,\n },\n onLine: (line) => {\n for (const step of describeAgentLine(line, wtPath)) {\n const text = formatStep(step)\n steps.push(text)\n if (steps.length > 400) steps.splice(0, 200)\n live.steps++\n live.lastStep = text\n try {\n appendFileSync(`${logBase}.steps.log`, `${text}\\n`)\n } catch {\n // See above: never fail an attempt over the step file.\n }\n emit(events, { type: 'agent', surface: s.surface.key, line: text, kind: step.kind })\n }\n },\n })\n } finally {\n clearInterval(heartbeat)\n }\n try {\n mkdirSync(logDir, { recursive: true })\n writeFileSync(`${logBase}.log`, res.stdout)\n } catch {\n // The raw log is for debugging only; never fail an attempt over it.\n }\n if (opts.signal?.aborted) throw new Error('Stopped.')\n const files = await changedFiles(wtPath)\n const record: IterationRecord = {\n n,\n agent: agent.name,\n model: opts.model ?? null,\n startedAt,\n durationMs: res.durationMs,\n outcome: 'no_change',\n reason: '',\n commitSha: null,\n pixelDiff: {},\n after: {},\n diffPng: {},\n logTail: (steps.length ? steps.join('\\n') : res.tail).slice(-2000),\n }\n\n if ((res.exitCode !== 0 || res.timedOut) && files.length === 0) {\n record.outcome = 'agent_failed'\n record.timedOut = res.timedOut\n const minutes = Math.round(timeoutMs / 60_000)\n record.reason = res.timedOut\n ? `The agent ran out of time (${minutes} min) after ${steps.length} steps without editing anything.`\n : `The agent exited with code ${res.exitCode}.`\n markStep(step, stepInfo, record, 'failed')\n s.iterations.push(record)\n persist()\n log(` attempt ${n}: ${record.reason}`)\n // A crash or a blocked agent will fail again: stop. Running out of\n // time is worth one more try with a firmer brief (glot.it /practice,\n // 2026-10-06: 15 minutes of reading, no edit).\n if (!res.timedOut) break\n previousRejection = timeoutNote(timeoutMs)\n continue\n }\n\n let afterShots: Record<string, { png: Buffer; probes: ProbeResult }> | null = null\n if (files.length > 0) {\n await new Promise((r) => setTimeout(r, 2000)) // let the dev server rebuild\n afterShots = await capture(s).catch(() => null)\n const beforeProbes = Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes]))\n const afterProbes = afterShots ? Object.fromEntries(Object.entries(afterShots).map(([vp, r]) => [vp, r.probes])) : null\n if (afterShots && afterProbes && clsNeedsSecondLook(beforeProbes, afterProbes)) {\n // One more shot once the reload has settled; keep the lower layout shift.\n await new Promise((r) => setTimeout(r, 2000))\n const again = await capture(s).catch(() => null)\n if (again) {\n const steady = steadierCls(afterProbes, Object.fromEntries(Object.entries(again).map(([vp, r]) => [vp, r.probes])))\n for (const vp of Object.keys(afterShots)) afterShots[vp] = { ...afterShots[vp]!, probes: steady[vp]! }\n }\n }\n }\n const ratios: Record<string, number> = {}\n if (afterShots) {\n record.after = shotRefs(s, `iter${n}`, afterShots)\n for (const [vp, shot] of Object.entries(afterShots)) {\n const before = readFileSync(join(dir, current[vp].png))\n const d = pixelDiff(before, shot.png)\n ratios[vp] = Math.round(d.ratio * 10_000) / 10_000\n record.diffPng[vp] = savePng(dir, `shots/${s.surface.key}/iter${n}-${vp}-diff.png`, d.diffPng)\n record.changes = { ...record.changes, [vp]: { width: d.width, height: d.height, boxes: d.regions } }\n }\n }\n record.pixelDiff = ratios\n const verdict = decide({\n filesChanged: files.length,\n before: Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes])),\n after: afterShots ? Object.fromEntries(Object.entries(afterShots).map(([vp, r]) => [vp, r.probes])) : null,\n pixelRatios: ratios,\n keepInvisible: opts.keepInvisible !== false,\n })\n record.outcome = verdict.outcome\n record.reason = verdict.reason\n // Only an attempt with no edits is explained by the agent's words; one whose\n // edits changed nothing visible keeps that reason (it said \"made no edits\"\n // for a real edit to flow-layout.ts on glot.it, 2026-10-07).\n if (verdict.outcome === 'no_change' && files.length === 0) {\n const why = explainNoEdit(agentFinalMessage(res.stdout))\n record.outcome = why.outcome\n record.reason = why.reason\n }\n record.timedOut = res.timedOut || undefined\n // A step is one small change: a sprawling edit is rolled back as too big.\n if (step && record.outcome === 'accepted' && files.length > MAX_STEP_FILES) {\n record.outcome = 'rejected'\n record.reason = `Too big for one step: ${files.length} files changed (at most ${MAX_STEP_FILES}). Make a smaller change.`\n }\n if (record.outcome === 'accepted') record.needsReview = verdict.needsReview || undefined\n // The checker only ever vetoes: it reviews what the measurements kept (ADR 0021).\n if (record.outcome === 'accepted' && opts.checker) {\n log(` checking with ${opts.checker.model}…`)\n phase('working', `${s.surface.label}: ${opts.checker.model} reviews the change`)\n const vp = afterShots?.mobile ? 'mobile' : Object.keys(afterShots ?? {})[0]\n const visible = !record.needsReview && vp && afterShots?.[vp]\n const review = await checkStep({\n dir,\n name: `${s.surface.key}-iter${n}`,\n screen: s.surface.label,\n step: step?.text ?? 'Improve this screen for the person using it.',\n visual: visible ? { before: readFileSync(join(dir, current[vp].png)), after: afterShots![vp]!.png, regions: record.changes?.[vp]?.boxes ?? [] } : null,\n diff: await diffText(wtPath).catch(() => ''),\n repoDir: wtPath,\n spec: opts.checker,\n signal: opts.signal,\n })\n record.checker = review\n if (review.verdict === 'revert') {\n record.outcome = 'rejected'\n record.reason = `Rolled back by ${review.model}: ${review.summary}`.slice(0, 600)\n } else if (review.error) {\n log(` ${review.model} review failed: ${review.error}`)\n record.reason += ` The ${review.model} review could not run (${review.error.slice(0, 160)}), so the measurements decided.`\n } else {\n record.reason += ` ${review.model}: ${review.verdict === 'keep' ? 'agrees' : 'unsure, kept on the measurements'}.`\n }\n }\n markStep(step, stepInfo, record, record.outcome === 'accepted' ? 'done' : record.outcome === 'no_change' ? 'skipped' : 'failed')\n log(` attempt ${n}: ${record.reason}`)\n\n if (record.outcome === 'accepted') {\n record.commitSha = await commitAll(wtPath, commitMessage(s.surface.path, s.surface.label, step?.text ?? null, record.reason))\n current = record.after\n s.status = 'accepted'\n s.iterations.push(record)\n persist()\n carrySession = agent.canResume ? sessionIdOf(res.stdout) ?? carrySession : null\n continue\n }\n await revertAll(wtPath)\n s.iterations.push(record)\n persist()\n // Whole-screen mode stops at \"no change\"; steps mode moves to the next\n // step. A blocked agent (it said so) stops either way.\n if (verdict.outcome === 'no_change' && (!step || record.outcome === 'agent_failed')) break\n previousRejection = record.outcome === 'rejected' ? record.reason : null\n // A rolled-back edit is gone from the files but not from the session's memory: start fresh.\n carrySession = null\n }\n\n // Decided from the records: a later no-change attempt must not hide a kept one.\n const kept = s.iterations.filter((i) => i.outcome === 'accepted')\n // Once per screen, not after every kept step: the screens it might have moved\n // are re-shot once for all of this screen's steps.\n if (kept.length > 0) await checkRegressions(s)\n if (kept.length > 0) {\n s.status = 'accepted'\n s.note = kept[kept.length - 1].reason\n } else {\n const rejected = s.iterations.some((i) => i.outcome === 'rejected' || i.outcome === 'capture_failed')\n // Only failed attempts: the agent never finished, which is not \"no change needed\".\n const neverFinished = s.iterations.length > 0 && s.iterations.every((i) => i.outcome === 'agent_failed')\n s.status = rejected ? 'reverted' : neverFinished ? 'blocked' : 'skipped'\n s.note = s.iterations[s.iterations.length - 1]?.reason ?? null\n }\n rmSync(join(wtPath, SCRATCH_DIR), { recursive: true, force: true })\n persist()\n }\n\n /** Second-opinion review of every kept change. Advisory: it never reverts anything. */\n async function runJudge(model: string): Promise<void> {\n state.judgeModel = model\n const changed = state.surfaces.filter((x) => x.iterations.some((i) => i.outcome === 'accepted'))\n if (changed.length === 0) return\n log(`Reviewing ${changed.length} changed screen(s) with ${model}…`)\n for (const s of changed) {\n if (s.judge?.length) continue\n const verdicts = []\n for (const vp of VIEWPORTS) {\n const v = await judgeSurface(s, vp.name, { dir, repoRoot: wtPath, designFiles, model })\n if (v) verdicts.push(v)\n }\n s.judge = verdicts\n const errors = verdicts.filter((v) => v.error)\n if (errors.length) log(` review of ${s.surface.label} failed: ${errors[0].error}`)\n const prefersBefore = verdicts.filter((v) => !v.error && v.preferred === 'before' && v.confidence !== 'low')\n if (prefersBefore.length) {\n log(` ⚠ reviewer prefers the original ${s.surface.label} (${prefersBefore.map((v) => v.viewport).join(', ')}) — check it before merging`)\n }\n persist()\n }\n }\n\n /** After a kept change, re-shoot a sample of finished screens and flag any that moved. */\n async function checkRegressions(changed: SurfaceState): Promise<void> {\n const finished = state.surfaces\n .filter((x) => x !== changed && ['accepted', 'reverted', 'skipped'].includes(x.status))\n .slice(-(opts.regressionSample ?? 5))\n const desktop = VIEWPORTS[0]\n for (const other of finished) {\n const ref = referenceShot(other, desktop.name)\n if (!ref) continue\n const refPng = readFileSync(join(dir, ref.png))\n const moved = (png: Buffer) => {\n const diff = pixelDiff(refPng, png)\n return diff.contentRatio > REGRESSION_CONTENT_RATIO && diff.changedPixels > REGRESSION_MIN_PIXELS ? diff : null\n }\n let now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null)\n if (!now || !moved(now.png)) continue\n // Confirm with a second shot: right after an edit the dev server\n // recompiles, and one shot of a half-loaded page is not a regression\n // (glot.it /words caught as skeletons after Account was kept, 2026-10-06).\n await new Promise((r) => setTimeout(r, 3000))\n now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null)\n const d = now ? moved(now.png) : null\n if (now && d) {\n const pct = (d.contentRatio * 100).toFixed(0)\n other.status = 'regressed'\n other.note = `${pct}% of this screen changed after \"${changed.surface.label}\" was kept. Check whether a shared component or token moved.`\n savePng(dir, `shots/${other.surface.key}/regressed-${desktop.name}.png`, now.png)\n log(` ⚠ ${other.surface.label}: ${pct}% of the screen moved — marked regressed`)\n }\n }\n persist()\n }\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The checker: a second model that reviews each kept step and may roll it\n * back (ADR 0021). It never keeps anything the measurements rejected.\n *\n * - A visible change is judged from crops of the changed area, before and\n * after, shown twice with the order swapped. Vision judges are near random\n * on small UI differences (arxiv 2510.08783) and flip with order (arxiv\n * 2305.17926), so a step is rolled back only when both orders prefer the\n * original with at least medium confidence. Anything else keeps it.\n * - A change with nothing visible (motion, haptics, another screen) is\n * reviewed from its diff and the step it was meant to make.\n *\n * Transports: Claude Code (`claude -p`, the person's own sign-in, read-only\n * tools) or the Anthropic API (ANTHROPIC_API_KEY).\n */\n\nimport Anthropic from '@anthropic-ai/sdk'\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { PNG } from 'pngjs'\nimport type { ChangeRegion } from './image.js'\nimport { run } from './proc.js'\n\ntype CheckerVia = 'claude-code' | 'anthropic-api'\n\nexport interface CheckerSpec {\n via: CheckerVia\n model: string\n}\n\n/** One review's answer. @internal Exported for tests only. */\nexport interface CheckerVote {\n /** Which capture the model preferred, after mapping its A/B answer back. */\n preferred: 'before' | 'after' | 'tie'\n confidence: 'low' | 'medium' | 'high'\n difference: string\n reason: string\n}\n\nexport interface CheckerVerdict {\n model: string\n mode: 'visual' | 'code'\n /** revert = roll the step back; keep = no objection; unsure = keep, the votes disagreed or were weak. */\n verdict: 'keep' | 'revert' | 'unsure'\n summary: string\n votes: CheckerVote[]\n costUsd: number | null\n /** The review could not run; the step is kept on its measurements. */\n error?: string\n}\n\n/** Crop height cap: a vision model shrinks tall images until text is unreadable. */\nconst MAX_CROP_HEIGHT = 1400\nconst MAX_DIFF_CHARS = 20_000\nconst CONTEXT_ROWS = 120\n\n/** Pure: one box around all changed areas, padded, within the image, at most MAX_CROP_HEIGHT tall. @internal Exported for tests only. */\nexport function unionBox(regions: readonly ChangeRegion[], width: number, height: number): ChangeRegion {\n if (!regions.length) return { x: 0, y: 0, w: width, h: Math.min(height, MAX_CROP_HEIGHT) }\n const y0 = Math.min(...regions.map((r) => r.y))\n const y1 = Math.max(...regions.map((r) => r.y + r.h))\n // Full width, plus some rows above and below, keeps the change in its layout context.\n const y = Math.max(0, y0 - CONTEXT_ROWS)\n return { x: 0, y, w: width, h: Math.max(1, Math.min(y1 + CONTEXT_ROWS - y, MAX_CROP_HEIGHT, height - y)) }\n}\n\nfunction crop(png: Buffer, box: ChangeRegion): Buffer {\n const src = PNG.sync.read(png)\n const w = Math.min(box.w, src.width - box.x)\n const h = Math.min(box.h, src.height - box.y)\n const out = new PNG({ width: Math.max(1, w), height: Math.max(1, h) })\n out.data.fill(255)\n if (w > 0 && h > 0) PNG.bitblt(src, out, box.x, box.y, w, h, 0, 0)\n return PNG.sync.write(out)\n}\n\n/** Pure: the first JSON object in a model's text answer, or null. @internal Exported for tests only. */\nexport function firstJson(text: string): Record<string, unknown> | null {\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start < 0 || end <= start) return null\n try {\n return JSON.parse(text.slice(start, end + 1)) as Record<string, unknown>\n } catch {\n return null\n }\n}\n\nconst level = (v: unknown): CheckerVote['confidence'] => (v === 'high' || v === 'medium' ? v : 'low')\n\n/** Pure: map an A/B answer back to before/after. `aIsBefore` is the order shown. @internal Exported for tests only. */\nexport function toVote(answer: Record<string, unknown> | null, aIsBefore: boolean): CheckerVote | null {\n if (!answer) return null\n const v = answer.verdict\n if (v !== 'A' && v !== 'B' && v !== 'tie') return null\n return {\n preferred: v === 'tie' ? 'tie' : (v === 'A') === aIsBefore ? 'before' : 'after',\n confidence: level(answer.confidence),\n difference: String(answer.difference ?? '').slice(0, 400),\n reason: String(answer.reason ?? '').slice(0, 600),\n }\n}\n\n/** Pure: the veto rule. Both orders must prefer the original, each with at least medium confidence. @internal Exported for tests only. */\nexport function combineVotes(votes: CheckerVote[]): { verdict: CheckerVerdict['verdict']; summary: string } {\n const firm = (v: CheckerVote) => v.confidence !== 'low'\n if (votes.length >= 2 && votes.every((v) => v.preferred === 'before' && firm(v))) {\n return { verdict: 'revert', summary: `Both reviews preferred the original: ${votes[0].reason}` }\n }\n if (votes.length >= 2 && votes.every((v) => v.preferred === 'after')) {\n return { verdict: 'keep', summary: `Both reviews preferred the change: ${votes[0].reason}` }\n }\n return { verdict: 'unsure', summary: votes.length ? `The reviews disagreed or were unsure: ${votes.map((v) => v.preferred).join(' / ')}.` : 'No review answered.' }\n}\n\nconst VISUAL_PROMPT = (step: string, screen: string) => `You review one small UI change made by a coding agent to the screen \"${screen}\".\nThe change it was asked to make: ${step}\n\nRead the two images a.png and b.png in the current folder. They show the same area of the screen; one is before the change and one is after, in an order you are not told.\nFirst describe the visible difference in one sentence. Then decide which is better for the person using this screen: clearer purpose and primary action, sensible visual weight, less noise, consistent with the rest of the screen, readable and tappable. If the difference is too small to matter, answer \"tie\".\nAnswer with ONLY this JSON: {\"difference\":\"...\",\"verdict\":\"A\"|\"B\"|\"tie\",\"confidence\":\"low\"|\"medium\"|\"high\",\"reason\":\"...\"} where A is a.png and B is b.png.`\n\nconst CODE_PROMPT = (step: string, screen: string, diff: string) => `You review one small change a coding agent made to the screen \"${screen}\" of a web app. It changed nothing visible in a still screenshot, so judge it from the code.\nThe change it was asked to make: ${step}\n\nThe diff:\n${diff}\n\nYou may open at most 3 files from this repository (for example a class or component the diff uses) to check what it does; then answer. Do not search the repository.\nKeep it when the diff makes that change (or a reasonable part of it) without breaking behaviour, accessibility or the design system. Revert it when it does nothing useful, does something else, or risks breaking the screen.\nAnswer with ONLY this JSON: {\"verdict\":\"keep\"|\"revert\",\"confidence\":\"low\"|\"medium\"|\"high\",\"reason\":\"...\"}`\n\ninterface Ask {\n text: string | null\n costUsd: number | null\n error?: string\n}\n\n/** One question to Claude Code, headless and read-only, in `cwd`. */\nasync function askClaudeCode(prompt: string, cwd: string, model: string, signal?: AbortSignal, maxTurns = 4): Promise<Ask> {\n const args = ['-p', '--model', model, '--tools', 'Read', '--disallowedTools', 'mcp__*', '--permission-mode', 'dontAsk', '--max-turns', String(maxTurns), '--no-session-persistence', '--output-format', 'json']\n let last: Ask = { text: null, costUsd: null, error: 'Claude Code did not run.' }\n // One retry: a call that failed in a second with no output (studio run on\n // glot.it, 2026-10-07) answered normally when repeated.\n for (let attempt = 1; attempt <= 2; attempt++) {\n if (signal?.aborted) break\n const res = await run('claude', args, { cwd, stdin: prompt, shell: process.platform === 'win32', timeoutMs: 240_000, signal })\n if (res.timedOut) return { text: null, costUsd: null, error: 'Claude Code did not answer within 4 minutes.' }\n try {\n const j = JSON.parse(res.stdout) as { result?: unknown; subtype?: unknown; total_cost_usd?: unknown; is_error?: unknown }\n if (!j.is_error) return { text: String(j.result ?? ''), costUsd: typeof j.total_cost_usd === 'number' ? j.total_cost_usd : null }\n // An error result can carry no text, only its kind (error_max_turns, …).\n last = { text: null, costUsd: null, error: `Claude Code: ${String(j.result ?? j.subtype ?? 'error with no message').slice(0, 300)}` }\n if (j.subtype === 'error_max_turns') return last\n } catch {\n const said = `${res.stdout.trim().slice(0, 200)} ${res.tail.trim().slice(-300)}`.trim()\n last = { text: null, costUsd: null, error: `Claude Code exited ${res.exitCode}: ${said || 'no output on stdout or stderr'}` }\n }\n if (attempt === 1) await new Promise((r) => setTimeout(r, 5000))\n }\n return last\n}\n\n/** One question to the Anthropic API, with the images inline. */\nasync function askApi(prompt: string, images: Buffer[], model: string, client: Anthropic): Promise<Ask> {\n try {\n const msg = await client.messages.create({\n model,\n max_tokens: 2000,\n messages: [\n {\n role: 'user',\n content: [\n ...images.flatMap((png, i) => [\n { type: 'text' as const, text: i === 0 ? 'a.png:' : 'b.png:' },\n { type: 'image' as const, source: { type: 'base64' as const, media_type: 'image/png' as const, data: png.toString('base64') } },\n ]),\n { type: 'text', text: prompt },\n ],\n },\n ],\n })\n return { text: msg.content.map((b) => (b.type === 'text' ? b.text : '')).join(''), costUsd: null }\n } catch (err) {\n return { text: null, costUsd: null, error: `Anthropic API: ${(err as Error).message.slice(0, 200)}` }\n }\n}\n\nexport interface CheckStepInput {\n /** Run directory; review files go under checker/. */\n dir: string\n /** A unique name for this step's review files. */\n name: string\n screen: string\n step: string\n /** null: nothing visible changed, review the diff instead. */\n visual: { before: Buffer; after: Buffer; regions: ChangeRegion[] } | null\n diff: string\n /** The worktree: a code review runs there, so the model can read the files the diff touches. */\n repoDir?: string\n spec: CheckerSpec\n signal?: AbortSignal\n client?: Anthropic\n /** Deterministic order for tests. */\n random?: () => number\n}\n\nexport async function checkStep(input: CheckStepInput): Promise<CheckerVerdict> {\n const { spec } = input\n const base = join(input.dir, 'checker', input.name)\n const fail = (mode: CheckerVerdict['mode'], error: string): CheckerVerdict => ({ model: spec.model, mode, verdict: 'unsure', summary: '', votes: [], costUsd: null, error })\n let cost = 0\n const ask = async (prompt: string, cwd: string, images: Buffer[], maxTurns?: number): Promise<Ask> => {\n const a = spec.via === 'claude-code' ? await askClaudeCode(prompt, cwd, spec.model, input.signal, maxTurns) : await askApi(prompt, images, spec.model, input.client ?? new Anthropic())\n if (a.costUsd) cost += a.costUsd\n return a\n }\n\n if (!input.visual) {\n const diff = input.diff.slice(0, MAX_DIFF_CHARS)\n mkdirSync(base, { recursive: true })\n // In the worktree, with room to open the files the diff touches (read-only).\n const a = await ask(CODE_PROMPT(input.step, input.screen, diff), input.repoDir ?? base, [], 20)\n if (a.error || !a.text) return fail('code', a.error ?? 'No answer.')\n const j = firstJson(a.text)\n if (!j || (j.verdict !== 'keep' && j.verdict !== 'revert')) return fail('code', 'The answer was not the expected JSON.')\n const confidence = level(j.confidence)\n const reason = String(j.reason ?? '').slice(0, 600)\n const verdict = j.verdict === 'revert' && confidence !== 'low' ? 'revert' : j.verdict === 'keep' ? 'keep' : 'unsure'\n return { model: spec.model, mode: 'code', verdict, summary: reason, votes: [{ preferred: j.verdict === 'keep' ? 'after' : 'before', confidence, difference: '', reason }], costUsd: cost || null }\n }\n\n const { before, after, regions } = input.visual\n const size = PNG.sync.read(before)\n const box = unionBox(regions, size.width, size.height)\n const b = crop(before, box)\n const a = crop(after, box)\n const firstIsBefore = (input.random ?? Math.random)() < 0.5\n const votes: CheckerVote[] = []\n for (const aIsBefore of [firstIsBefore, !firstIsBefore]) {\n const cwd = join(base, aIsBefore ? 'order-1' : 'order-2')\n mkdirSync(cwd, { recursive: true })\n const [imgA, imgB] = aIsBefore ? [b, a] : [a, b]\n writeFileSync(join(cwd, 'a.png'), imgA)\n writeFileSync(join(cwd, 'b.png'), imgB)\n const res = await ask(VISUAL_PROMPT(input.step, input.screen), cwd, [imgA, imgB])\n if (res.error || !res.text) return fail('visual', res.error ?? 'No answer.')\n const vote = toVote(firstJson(res.text), aIsBefore)\n if (!vote) return fail('visual', 'The answer was not the expected JSON.')\n votes.push(vote)\n }\n const { verdict, summary } = combineVotes(votes)\n return { model: spec.model, mode: 'visual', verdict, summary, votes, costUsd: cost || null }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The instructions one agent run gets, written to `.mushi-ux/PROMPT.md` in\n * the worktree: which screen, its screenshots, the measured problems, where\n * the design system lives, the skill to apply, and what not to touch.\n *\n * File paths only for the design system: the agent reads what it needs, and\n * the packet stays small enough for weaker, short-context models.\n */\n\nimport { closeSync, existsSync, fstatSync, openSync, readdirSync, readFileSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport { CLS_GOOD } from './probes.js'\nimport type { ProbeResult, Surface } from './types.js'\n\nconst MAX_PACKET_CHARS = 24_000\n/** Skill text a prompt carries; a chain splits it between its skills (skills.ts). */\nexport const MAX_SKILL_CHARS = 12_000\n\nconst DEFAULT_GUIDANCE = `Improve this one screen's UI and UX. In order of priority:\n1. Fix every measured problem listed below (accessibility violations, sideways scrolling, tap targets under 24×24 px, console errors).\n2. Make the primary action obvious: one clear call to action, visual hierarchy that matches importance.\n3. Cut noise: shorter copy, group related controls, remove duplicated information, use icons and colour to carry meaning where text is long.\n4. Spacing and alignment on the design system's scale; readable line length; consistent type sizes.\n5. The mobile screenshot must work as well as the desktop one.`\n\nconst GUARDRAILS = `Rules:\n- Change only what this screen needs. Shared components and design tokens affect every other screen; edit them only when the fix truly belongs there, and say so in your final message.\n- Use the existing design tokens, components and icon set. Do not add dependencies.\n- Do not change data fetching, API calls, auth, routing, state management or tests.\n- Do not run the dev server, install packages, or commit. The tool reviews and commits your edits.\n- Do not modify anything under .mushi-ux/. Read only the screenshots and skill files you are pointed to.\n- Do not read or change node_modules or the framework's own code. A problem that comes from there is not yours to fix: say so and move on.\n- If the screen is already good, make no edits and say why.`\n\nexport interface PacketInput {\n surface: Surface\n iteration: number\n /** Screenshot paths relative to the worktree, per viewport name. */\n shots: Record<string, string>\n probes: Record<string, ProbeResult>\n designFiles: string[]\n skillText: string | null\n /** Worktree-relative folder holding the skill's files (SKILL.md, references/). */\n skillDir?: string | null\n /** Why the previous attempt on this screen was rejected, if it was. */\n previousRejection: string | null\n /** Minutes the agent has before it is stopped; shapes the work plan. */\n timeBudgetMin?: number | null\n /** Repo-relative files that render this screen (routes.ts screenFiles); empty when unknown. */\n entryFiles?: string[]\n /** Steps mode: the one plan step this attempt makes. */\n step?: { text: string; index: number; total: number; done: string[] } | null\n}\n\n/** A step should touch this many files at most; more is rolled back as too big. */\nexport const MAX_STEP_FILES = 6\n/** Steps planned per screen at most. */\nexport const MAX_PLAN_STEPS = 5\n/**\n * Source files the planning pass may open besides the entry files. Grok 4.7\n * xhigh opened 12-16 and ran out of its 6 minutes with no plan (glot.it\n * Challenge, 2026-10-07); a read cap took the checker's code review from\n * running out of turns to an answer in 23 s.\n */\nconst PLAN_READ_BUDGET = 6\n\n/**\n * Steps mode, the planning pass: look, list small separate improvements,\n * edit nothing. Small steps measure cleanly and one bad step costs only\n * itself, where a whole-screen pass lost entire 15-minute attempts on\n * glot.it (2026-10-06).\n */\nexport function buildPlanPacket(input: Omit<PacketInput, 'step' | 'iteration' | 'previousRejection'>, maxSteps: number): string {\n const { surface } = input\n const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p))\n const sections = [\n `# UX plan — ${surface.label}`,\n `Screen: \\`${surface.path}\\` (${surface.kind}). Plan only: do not edit any file except \\`.mushi-ux/PLAN.md\\`.`,\n input.timeBudgetMin ? `## Time\\nYou have ${input.timeBudgetMin} minutes. Look, decide, write the list.` : '',\n input.entryFiles?.length ? `## Start here\\nThese files render this screen:\\n${input.entryFiles.map((f) => `- ${f}`).join('\\n')}` : '',\n `## Screenshots (read these images first)\\n${Object.entries(input.shots)\n .map(([vp, p]) => `- ${vp}: ${p}`)\n .join('\\n')}\\nYour read tool opens them as images where they are: do not copy them anywhere.`,\n `## Measured problems\\n${findings.length ? findings.join('\\n') : '- None measured.'}`,\n input.skillText\n ? `## Guidance\\nUse this skill to choose what to improve on this one screen (its supporting files are in \\`${input.skillDir ?? '.mushi-ux/skill'}/\\`):\\n\\n${input.skillText.slice(0, MAX_SKILL_CHARS)}`\n : `## Guidance\\n${DEFAULT_GUIDANCE}`,\n `## What to do\\nList 2 to ${maxSteps} small, separate improvements for this screen, most valuable first. Each must be one focused change a developer could make in a few minutes, touching at most 3 files, that does not depend on the others. Start each item with a short summary a user of the app would understand, without file or code names, then a colon, then the change, naming the component or file it changes (for example \"- Make the caption readable: in \\`x.tsx\\`, ...\"). Open at most ${PLAN_READ_BUDGET} source files besides the \"Start here\" ones; each step's own attempt reads the rest. Write them to \\`.mushi-ux/PLAN.md\\`, one per line starting with \"- \", within your first 2 minutes, from the screenshots and the \"Start here\" files alone; then refine the file if you have time, and reply with the same list. You are stopped when the time is up, and a missing PLAN.md wastes the whole pass. Do not edit any other file: each item gets its own attempt later.`,\n `## Rules\\n- Do not install anything, and do not run scripts on the screenshots: look at them.\\n- Do not read or change node_modules or the framework's own code.\\n- Do not plan changes to data fetching, API calls, auth, routing, state management or tests.\\n- If the screen is already good, write fewer items.`,\n ]\n return sections.filter(Boolean).join('\\n\\n').slice(0, MAX_PACKET_CHARS)\n}\n\n/** Pure: the plan steps in a PLAN.md or a reply (\"- x\", \"* x\", \"1. x\", \"- [ ] x\"), first ones first. */\nexport function parsePlan(text: string, max = MAX_PLAN_STEPS): string[] {\n const out: string[] = []\n for (const line of text.split(/\\r?\\n/)) {\n const m = line.match(/^\\s*(?:[-*•]|\\d+[.)])\\s+(?:\\[[ xX]\\]\\s*)?(.+?)\\s*$/)\n // Agents sometimes write HTML entities (\"School & Study\"); the plan is plain text.\n const item = m?.[1]\n ?.replace(/\\*\\*/g, '')\n .replace(/&(amp|lt|gt|quot|#39);/g, (_, e: string) => ({ amp: '&', lt: '<', gt: '>', quot: '\"', '#39': \"'\" })[e] ?? _)\n .trim()\n if (!item || item.length < 8 || out.includes(item)) continue\n out.push(cutAtWord(item, 280))\n if (out.length >= max) break\n }\n return out\n}\n\n/** Pure: `text` within `max` characters, cut at a word with \"…\" so no word or `code` span ends half-way. * @internal Exported for tests only.\n */\nexport function cutAtWord(text: string, max: number): string {\n if (text.length <= max) return text\n const head = text.slice(0, max - 1)\n const space = head.lastIndexOf(' ')\n let cut = (space > max / 2 ? head.slice(0, space) : head).replace(/[\\s,;:.(-]+$/, '')\n // An odd number of backticks means a code span was opened and not closed.\n if ((cut.match(/`/g)?.length ?? 0) % 2 === 1) cut = cut.slice(0, cut.lastIndexOf('`')).trimEnd()\n return `${cut}…`\n}\n\n/** Steps mode, the planning pass's pointer prompt. */\nexport const PLAN_POINTER_PROMPT =\n 'Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It asks for a plan only: write .mushi-ux/PLAN.md and edit nothing else.'\n\nfunction describeProbes(viewport: string, p: ProbeResult): string[] {\n const lines: string[] = []\n for (const v of p.axe) {\n lines.push(`- [${viewport}] ${v.id} (${v.impact ?? 'n/a'}, ${v.count} node${v.count === 1 ? '' : 's'}): ${v.help} — e.g. ${v.targets.slice(0, 3).join(', ')}`)\n }\n if (p.overflowX) lines.push(`- [${viewport}] The page scrolls sideways at this width.`)\n if (p.smallTargets > 0) lines.push(`- [${viewport}] ${p.smallTargets} tap target(s) smaller than 24×24 px.`)\n for (const e of p.consoleErrors.slice(0, 5)) lines.push(`- [${viewport}] Console error: ${e}`)\n if (p.cls > CLS_GOOD) lines.push(`- [${viewport}] Layout shift ${p.cls} while loading (aim below ${CLS_GOOD}).`)\n return lines\n}\n\nexport function buildPacket(input: PacketInput): string {\n const { surface } = input\n const steps = surface.steps.length ? ` then click ${surface.steps.map((s) => `\"${s.label}\"`).join(' → ')}` : ''\n const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p))\n const skill = input.skillText\n ? [\n `Apply this skill to this one screen only. Skip its whole-app steps (stack detection, scoring every screen, app-wide inventories): another pass handles each other screen. Its supporting files (references, scorecards) are in \\`${input.skillDir ?? '.mushi-ux/skill'}/\\`; read only the ones this screen needs.`,\n input.skillText.slice(0, MAX_SKILL_CHARS),\n ].join('\\n\\n')\n : DEFAULT_GUIDANCE\n const sections = [\n `# UX pass — ${surface.label}`,\n `Screen: \\`${surface.path}\\`${steps} (${surface.kind}). Attempt ${input.iteration}.`,\n input.timeBudgetMin\n ? `## Time\\nYou have ${input.timeBudgetMin} minutes, then you are stopped and unsaved work is lost. Make your first edit within ${Math.max(1, Math.round(input.timeBudgetMin / 3))} minutes: an attempt that ends without an edit counts as a failure. Do not survey the whole design system; read only what the edit needs. A small, finished improvement beats a large unfinished one: make it, then stop.`\n : '',\n input.entryFiles?.length\n ? `## Start here\\nThese files render this screen. Read them first instead of searching the repo:\\n${input.entryFiles.map((f) => `- ${f}`).join('\\n')}`\n : '',\n `## Screenshots (read these images first)\\n${Object.entries(input.shots)\n .map(([vp, p]) => `- ${vp}: ${p}`)\n .join('\\n')}`,\n `## Measured problems\\n${findings.length ? findings.join('\\n') : '- None measured. Focus on hierarchy, clarity and density.'}`,\n input.previousRejection ? `## Your previous attempt was rolled back\\n${input.previousRejection}\\nTry a different, smaller change.` : '',\n `## Design system (read before editing)\\n${input.designFiles.length ? input.designFiles.map((f) => `- ${f}`).join('\\n') : '- No token files found; match the styles already used on this screen.'}`,\n input.step\n ? [\n `## This step (${input.step.index} of ${input.step.total})\\n${input.step.text}`,\n `Make only this change, touching at most 3 files. ${input.step.done.length ? `Already done in earlier steps: ${input.step.done.map((d) => `\"${d}\"`).join('; ')}. ` : ''}Later steps come in their own attempts. If this step turns out to be unnecessary, make no edit and say why.`,\n ].join('\\n')\n : '',\n input.step ? `## Guidance\\n${skill}` : `## What to do\\n${skill}`,\n `## ${GUARDRAILS}`,\n ]\n return sections.filter(Boolean).join('\\n\\n').slice(0, MAX_PACKET_CHARS)\n}\n\n/** One-line instruction handed to the agent on stdin / argv. */\nexport const POINTER_PROMPT =\n 'Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It names the screenshots to look at and the screen to improve.'\n\nconst SKIP_DIRS = new Set(['node_modules', '.git', '.next', 'dist', 'build', '.turbo', '.worktrees', '.mushi', '.mushi-ux', 'coverage'])\n\n/**\n * Likely design-system sources, as repo-relative paths: the recipe manifest,\n * Tailwind configs, DTCG token files, and CSS files that declare theme\n * tokens (`@theme` or many custom properties on :root).\n */\nexport function findDesignFiles(root: string, maxFiles = 12): string[] {\n const found: string[] = []\n const recipe = join(root, 'mushi.recipe.json')\n if (existsSync(recipe)) found.push('mushi.recipe.json')\n const walk = (dir: string, depth: number) => {\n if (depth > 5 || found.length >= maxFiles) return\n let names: string[]\n try {\n names = readdirSync(dir)\n } catch {\n return\n }\n for (const name of names) {\n if (found.length >= maxFiles) return\n if (SKIP_DIRS.has(name)) continue\n const abs = join(dir, name)\n // One handle for the stat and the read, so the size checked is the\n // size of the bytes read (CodeQL js/file-system-race).\n let fd: number\n let isDir: boolean\n let css: string | null = null\n try {\n fd = openSync(abs, 'r')\n } catch {\n continue\n }\n try {\n const st = fstatSync(fd)\n isDir = st.isDirectory()\n if (!isDir && name.endsWith('.css') && st.size < 300_000) css = readFileSync(fd, 'utf8')\n } catch {\n continue\n } finally {\n closeSync(fd)\n }\n if (isDir) {\n walk(abs, depth + 1)\n continue\n }\n const rel = relative(root, abs).replace(/\\\\/g, '/')\n if (/^tailwind\\.config\\.(js|cjs|mjs|ts)$/.test(name) || /\\.tokens\\.json$|^tokens\\.json$/.test(name)) {\n found.push(rel)\n } else if (css !== null) {\n if (/@theme\\b/.test(css) || (css.match(/--[\\w-]+\\s*:/g)?.length ?? 0) > 20) found.push(rel)\n }\n }\n }\n walk(root, 0)\n return found\n}\n","// SPDX-License-Identifier: MIT\n/**\n * A one-minute check that the agent can run and use its file tools, before\n * the worktree, install and dev server spend ten minutes. The agent reads a\n * file holding a random code word; the check passes when the code word comes\n * back in its output (the tool result or the reply).\n *\n * Why (glot.it, 2026-10-06): the Cursor CLI was logged out on the first run,\n * and on a later run every tool call was refused by a Claude Code hook the\n * CLI loads. Both surfaced only after the first attempt's full time box.\n */\n\nimport { randomBytes } from 'node:crypto'\nimport { mkdtempSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport type { AgentAdapter } from './agents.js'\nimport { agentFinalMessage } from './verdict.js'\n\nconst PREFLIGHT_TIMEOUT_MS = 3 * 60_000\n\nconst NOT_LOGGED_IN_RE = /not (logged|signed) in|log ?in required|please (log|sign) ?in|unauthori[sz]ed|invalid api key|authentication/i\nconst HOOK_RE = /\\bhooks?\\b/i\n\n/**\n * Plain-English next step for a failed check, by agent and symptom.\n * @internal Exported for tests only.\n */\nexport function preflightAdvice(agent: string, output: string, platform: NodeJS.Platform = process.platform): string {\n if (NOT_LOGGED_IN_RE.test(output)) {\n const login: Record<string, string> = {\n cursor: 'Run `agent login` (Cursor CLI), then start the run again.',\n 'claude-code': 'Run `claude` once and sign in, or set ANTHROPIC_API_KEY.',\n codex: 'Run `codex login`, or set OPENAI_API_KEY.',\n }\n return `The agent is not signed in. ${login[agent] ?? 'Sign the agent in, then start the run again.'}`\n }\n if (agent === 'cursor' && HOOK_RE.test(output)) {\n return (\n 'A hook refused the agent’s tool calls. The Cursor CLI also runs the hooks in ~/.claude/settings.json; ' +\n (platform === 'win32'\n ? 'on Windows a hook fails when the run is started from Git Bash. Start `mushi ux` from PowerShell or cmd, or fix the hook.'\n : 'fix the failing hook or remove it, then start the run again.')\n )\n }\n return 'Run the agent once by hand in this repo to see what it needs, then start the run again.'\n}\n\n/**\n * Null when the agent read the file; otherwise a message that says what\n * went wrong and what to do. Never throws for an agent failure.\n */\nexport async function preflightAgent(\n agent: AgentAdapter,\n opts: { model?: string | null; signal?: AbortSignal; timeoutMs?: number } = {},\n): Promise<string | null> {\n const dir = mkdtempSync(join(tmpdir(), 'mushi-ux-preflight-'))\n const word = randomBytes(4).toString('hex')\n try {\n writeFileSync(join(dir, 'PREFLIGHT.txt'), `The code word is ${word}.\\n`)\n const timeoutMs = opts.timeoutMs ?? PREFLIGHT_TIMEOUT_MS\n const res = await agent.run({\n cwd: dir,\n prompt: 'Read the file PREFLIGHT.txt in this folder and reply with only the code word it contains. Do not edit anything.',\n model: opts.model,\n timeoutMs,\n signal: opts.signal,\n })\n if (res.stdout.includes(word) || res.tail.includes(word)) return null\n if (opts.signal?.aborted) return 'Stopped.'\n const said = agentFinalMessage(res.stdout) ?? res.tail.trim()\n const output = `${said}\\n${res.tail}`\n const what = res.timedOut\n ? `did not answer within ${Math.round(timeoutMs / 1000)} s`\n : res.exitCode !== 0\n ? `exited with code ${res.exitCode}`\n : 'answered without reading the file'\n const quote = said ? ` It said: “${said.replace(/\\s+/g, ' ').slice(-300)}”` : ''\n return `Agent check failed: ${agent.name}${opts.model ? ` (${opts.model})` : ''} ${what}.${quote} ${preflightAdvice(String(agent.name), output)}`\n } catch (err) {\n return `Agent check failed: could not start ${agent.name}: ${(err as Error).message}. Is it installed and on PATH?`\n } finally {\n rmSync(dir, { recursive: true, force: true })\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The cheap, objective keep-or-revert decision after one agent run. It only\n * uses measurements (probes, pixel diff, files changed), never a model's\n * taste: an edit that makes any measured problem worse is rolled back, and an\n * edit with no visible effect is not worth a commit. Taste is the judge's job\n * (judge.ts), and the judge never auto-accepts.\n */\n\nimport { CLS_GOOD, probePenalty } from './probes.js'\nimport type { ProbeResult } from './types.js'\n\n/** Below this share of changed pixels an edit counts as invisible. */\nconst MIN_VISIBLE_RATIO = 0.0005\n\nexport interface VerdictInput {\n filesChanged: number\n before: Record<string, ProbeResult>\n /** Null when the after-capture failed (page broke, axe failed, timeout). */\n after: Record<string, ProbeResult> | null\n pixelRatios: Record<string, number>\n /**\n * Keep an edit whose effect is not visible in a still screenshot (motion,\n * haptics, another screen) when nothing measured got worse, flagged for a\n * person to read (ADR 0021). Off: such an edit is rolled back.\n */\n keepInvisible?: boolean\n}\n\nexport interface Verdict {\n outcome: 'accepted' | 'rejected' | 'no_change' | 'capture_failed'\n reason: string\n /** Kept without a visible change: a person should read the diff. */\n needsReview?: boolean\n}\n\n/**\n * The agent's own last message, from stream-json / json output (Cursor and\n * Claude Code both end with {\"type\":\"result\",\"result\":\"…\"}), or null.\n */\nexport function agentFinalMessage(stdout: string): string | null {\n let last: string | null = null\n for (const line of stdout.split(/\\r?\\n/)) {\n if (!line.startsWith('{')) continue\n try {\n const j = JSON.parse(line) as { type?: string; result?: unknown }\n if (j.type === 'result' && typeof j.result === 'string' && j.result.trim()) last = j.result.trim()\n } catch {\n /* not JSON */\n }\n }\n return last\n}\n\n/**\n * Everything the agent wrote as messages, newlines kept, in order. For a run\n * stopped before its final result (a planning pass that ran out of time).\n * Reads Cursor and Claude Code stream-json `assistant` events.\n */\nexport function assistantText(stdout: string): string {\n const out: string[] = []\n for (const line of stdout.split(/\\r?\\n/)) {\n if (!line.startsWith('{')) continue\n try {\n const j = JSON.parse(line) as { type?: string; model_call_id?: unknown; message?: { content?: unknown } }\n if (j.type !== 'assistant' || j.model_call_id !== undefined || !Array.isArray(j.message?.content)) continue\n for (const c of j.message.content as Array<{ type?: string; text?: unknown }>) {\n if (c.type === 'text' && typeof c.text === 'string') out.push(c.text)\n }\n } catch {\n /* not JSON */\n }\n }\n return out.join('\\n')\n}\n\n/** The agent said its tools were blocked or it could not read the prompt: it never really ran. */\nconst AGENT_BLOCKED_RE = /\\b(could ?n[o'’]t|can ?not|cannot|unable to) (read|open|access|run|use)\\b|\\bhooks?\\b.*\\b(fail|error|block)|\\b(blocked|stopped) before\\b/i\n\n/**\n * Pure: an edit-less attempt explained by the agent's own words. A blocked\n * agent is a failure, not \"no change needed\" (glot.it, 2026-10-06: Cursor's\n * hooks failed and every file read was refused, yet the screen showed as fine).\n */\nexport function explainNoEdit(final: string | null): { outcome: 'no_change' | 'agent_failed'; reason: string } {\n if (!final) return { outcome: 'no_change', reason: 'The agent made no edits.' }\n const said = final.length > 400 ? `…${final.slice(-400)}` : final\n if (AGENT_BLOCKED_RE.test(final)) return { outcome: 'agent_failed', reason: `The agent could not work on the screen: ${said}` }\n return { outcome: 'no_change', reason: `The agent made no edits: ${said}` }\n}\n\n/**\n * True when an after-shot's layout shift crossed the \"good\" line and rose:\n * worth one more look, because a dev server that just hot-reloaded shifts\n * on its own (glot.it /chat: 0.025 → 0.14 and 0.043 → 0.118, 2026-10-06).\n */\nexport function clsNeedsSecondLook(before: Record<string, ProbeResult>, after: Record<string, ProbeResult>): boolean {\n return Object.entries(after).some(([vp, now]) => now.cls > CLS_GOOD && now.cls > (before[vp]?.cls ?? 0))\n}\n\n/** The steadier of two readings per viewport: a real shift shows up both times. */\nexport function steadierCls(first: Record<string, ProbeResult>, second: Record<string, ProbeResult>): Record<string, ProbeResult> {\n return Object.fromEntries(\n Object.entries(first).map(([vp, p]) => [vp, second[vp] ? { ...p, cls: Math.min(p.cls, second[vp].cls) } : p]),\n )\n}\n\n/** Which measurements got worse, in words, so a rollback says what to fix. */\nfunction whatRose(before: ProbeResult, now: ProbeResult): string[] {\n const out: string[] = []\n if (now.smallTargets > before.smallTargets) out.push(`tap targets under 24 px ${before.smallTargets} → ${now.smallTargets}`)\n if (now.cls > CLS_GOOD && now.cls > before.cls) out.push(`layout shift ${before.cls} → ${now.cls}`)\n const was = new Map(before.axe.map((v) => [v.id, v.count]))\n for (const v of now.axe) {\n if (v.count > (was.get(v.id) ?? 0)) out.push(`${v.id} ${was.get(v.id) ?? 0} → ${v.count} element(s)`)\n }\n return out\n}\n\nexport function decide(input: VerdictInput): Verdict {\n if (input.filesChanged === 0) return { outcome: 'no_change', reason: 'The agent made no edits.' }\n if (!input.after) {\n return { outcome: 'capture_failed', reason: 'The screen could not be captured after the edit (it may no longer render).' }\n }\n const after = input.after\n const worse: string[] = []\n const summary: string[] = []\n for (const [vp, before] of Object.entries(input.before)) {\n const now = after[vp]\n if (!now) {\n worse.push(`${vp}: no capture after the edit`)\n continue\n }\n const pb = probePenalty(before)\n const pa = probePenalty(now)\n summary.push(`${vp} ${pb}→${pa}`)\n if (now.consoleErrors.length > before.consoleErrors.length) {\n worse.push(`${vp}: new console error \"${now.consoleErrors[now.consoleErrors.length - 1]}\"`)\n }\n if (now.overflowX && !before.overflowX) worse.push(`${vp}: the page now scrolls sideways`)\n const beforeIds = new Set(before.axe.map((v) => v.id))\n const newRules = now.axe.filter((v) => !beforeIds.has(v.id)).map((v) => v.id)\n if (newRules.length) worse.push(`${vp}: new accessibility violations ${newRules.join(', ')}`)\n if (pa > pb && worse.length === 0) {\n const rose = whatRose(before, now)\n worse.push(`${vp}: ${rose.length ? rose.join(', ') : 'measured problems rose'} (problem score ${pb} → ${pa})`)\n }\n }\n if (worse.length) return { outcome: 'rejected', reason: `Rolled back: ${worse.join('; ')}.` }\n const maxRatio = Math.max(0, ...Object.values(input.pixelRatios))\n if (maxRatio < MIN_VISIBLE_RATIO) {\n if (input.keepInvisible) {\n return {\n outcome: 'accepted',\n needsReview: true,\n reason: `Kept, needs your review: the edit changed ${input.filesChanged} file(s) but nothing visible in a still screenshot (motion, haptics or another screen). Read the diff.`,\n }\n }\n return { outcome: 'no_change', reason: `The edits changed ${input.filesChanged} file(s) but nothing visible on this screen.` }\n }\n return {\n outcome: 'accepted',\n reason: `Kept: problem score ${summary.join(', ')}; ${(maxRatio * 100).toFixed(1)}% of pixels changed.`,\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Resuming a run that stopped for any reason: the studio or terminal was\n * closed, the machine slept, or the process was killed (on 2026-10-06 the\n * host ran low on memory and took the studio, and its run, with it).\n *\n * A resume needs only the run id. The settings and the skill's files were\n * saved when the run started; the loop then puts the worktree back on the\n * last kept commit, throws away a half-finished attempt and carries on from\n * the first unfinished screen.\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join, relative } from 'node:path'\nimport type { ResolvedSkill } from './skills.js'\nimport { loadState, runDir, type RunState, type SavedRunOptions } from './state.js'\n\n/** A live run saves at least every 30 s; past this it is not running anywhere. */\nconst ALIVE_WITHIN_MS = 90_000\n\n/** Keep the skill beside the run state so a resume does not depend on GitHub or a checkout. */\nexport function saveSkillFiles(dir: string, skill: ResolvedSkill): void {\n const root = join(dir, 'skill')\n rmSync(root, { recursive: true, force: true })\n for (const [rel, buf] of Object.entries(skill.files)) {\n const target = join(root, ...rel.split('/'))\n mkdirSync(dirname(target), { recursive: true })\n writeFileSync(target, buf)\n }\n}\n\nfunction loadSkillFiles(dir: string, meta: { name: string; source: string }): ResolvedSkill | null {\n const root = join(dir, 'skill')\n if (!existsSync(join(root, 'SKILL.md'))) return null\n const files: Record<string, Buffer> = {}\n const walk = (d: string) => {\n // Dirent types, not a stat then a read of the same path (CodeQL js/file-system-race).\n for (const entry of readdirSync(d, { withFileTypes: true })) {\n const abs = join(d, entry.name)\n if (entry.isDirectory()) walk(abs)\n else files[relative(root, abs).replace(/\\\\/g, '/')] = readFileSync(abs)\n }\n }\n walk(root)\n return { name: meta.name, source: meta.source, text: files['SKILL.md']!.toString('utf8'), files }\n}\n\n/**\n * True while the run saved its state recently and has not finished: it is running somewhere.\n * @internal Exported for tests only.\n */\nexport function isRunAlive(state: RunState, now = Date.now()): boolean {\n if (state.phase === 'done' || state.phase === 'failed') return false\n const at = Date.parse(state.updatedAt)\n return Number.isFinite(at) && now - at < ALIVE_WITHIN_MS\n}\n\n/**\n * The commit the run branch should be on: the last kept attempt's commit, or\n * the commit the run branched from. A crash between an attempt's commit and\n * the state save leaves the branch ahead of this; the resume moves it back\n * and the attempt runs again.\n */\nexport function expectedHead(state: RunState): string | null {\n const kept = state.surfaces\n .flatMap((s) => s.iterations)\n .filter((i) => i.outcome === 'accepted' && i.commitSha)\n .sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt))\n return kept.length ? kept[kept.length - 1]!.commitSha : state.baseSha\n}\n\nexport interface ResumeSettings {\n state: RunState\n options: SavedRunOptions\n skill: ResolvedSkill | null\n}\n\n/** Settings to resume a run with, or an error that says why it cannot be resumed and what to do. */\nexport function resumeSettings(repoRoot: string, runId: string, now = Date.now()): ResumeSettings {\n const state = loadState(runDir(repoRoot, runId))\n if (!state) throw new Error(`No run ${runId} in ${join(repoRoot, '.mushi', 'ux')}.`)\n if (state.phase === 'done') throw new Error(`Run ${runId} already finished. Start a new run instead.`)\n if (isRunAlive(state, now)) {\n throw new Error(`Run ${runId} saved its state less than a minute ago, so it is still running somewhere. Stop it there first.`)\n }\n if (!state.options) {\n throw new Error(\n `Run ${runId} started before runs saved their settings. Resume it from the terminal with the same settings: ` +\n `mushi-ux run --resume ${runId} --dev \"<your dev command>\" (plus --agent, --model, --skill and --path as before).`,\n )\n }\n const skill = state.skill ? loadSkillFiles(runDir(repoRoot, runId), state.skill) : null\n if (state.skill && !skill) {\n throw new Error(`Run ${runId} used the skill ${state.skill.name}, but its saved copy is missing. Resume it with --skill ${state.skill.name}.`)\n }\n return { state, options: state.options, skill }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Shared shapes for the UX loop: a surface is one screen state worth\n * reviewing (a page, a tab on it, a dialog it opens), reached by loading a\n * URL path and replaying a few clicks.\n */\n\nexport type SurfaceKind = 'page' | 'tab' | 'dialog' | 'menu'\n\n/** One replayable click. `selector` is a Playwright selector string. */\nexport interface ReplayStep {\n action: 'click'\n selector: string\n label: string\n}\n\nexport interface Surface {\n /** Stable id: path + replay labels, slugged. */\n key: string\n kind: SurfaceKind\n /** Same-origin path with query. Never a full URL, never a token. */\n path: string\n steps: ReplayStep[]\n label: string\n /** Structural hash of the rendered DOM, for dedupe across param routes. */\n domHash: string\n}\n\nexport interface Viewport {\n name: 'desktop' | 'mobile'\n width: number\n height: number\n}\n\nexport const VIEWPORTS: readonly Viewport[] = [\n { name: 'desktop', width: 1440, height: 900 },\n { name: 'mobile', width: 390, height: 844 },\n]\n\nexport interface AxeViolation {\n id: string\n impact: string | null\n help: string\n /** How many nodes fail the rule. */\n count: number\n /** CSS selectors of the offending nodes (first few). */\n targets: string[]\n}\n\n/** Objective, repeatable measurements of one surface at one viewport. */\nexport interface ProbeResult {\n axe: AxeViolation[]\n /** Page scrolls sideways at this width. */\n overflowX: boolean\n /** Interactive elements smaller than 24×24 CSS px (WCAG 2.2 target size). */\n smallTargets: number\n consoleErrors: string[]\n /** Cumulative layout shift observed while the surface settled. */\n cls: number\n}\n","// SPDX-License-Identifier: MIT\n/**\n * `--sync`: mirror a run to the Mushi console while it runs (Plan 021\n * Phase 2). After each state change (debounced) the run snapshot is PUT to\n * the api: phase, the screen and attempt the agent is on, every screen and\n * attempt. Screenshots go up through signed upload URLs as soon as they\n * exist (baseline, then each attempt, mobile and desktop), each one once.\n * A failed sync never stops the loop; the next state change retries, and\n * the final sync is awaited.\n *\n * Agent output stays on this machine: the console gets the files each\n * attempt read and edited (syncableStep), never the agent's words, the\n * commands it ran, or console text.\n *\n * Credentials come from MUSHI_API_KEY / MUSHI_PROJECT_ID / MUSHI_API_ENDPOINT\n * (`mushi ux` passes the CLI's saved login). The coding agent never sees\n * them: its environment drops every MUSHI_* variable (proc.ts).\n */\n\nimport type { EventEmitter } from 'node:events'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { cropTop } from './image.js'\nimport type { LoopEvent } from './loop.js'\nimport { loadState, type RunState, type SurfaceState } from './state.js'\nimport type { ProbeResult } from './types.js'\n\nconst CLOUD_API_ENDPOINT = 'https://dxptnwrhwsqckaftyymj.supabase.co/functions/v1/api'\nconst HOSTED_CONSOLE_URL = 'https://kensaur.us/mushi-mushi/admin'\n\n/** The Mushi console a mirrored run is reviewed and merged in: MUSHI_CONSOLE_URL, else the hosted console. */\nexport function consoleBaseUrl(env: NodeJS.ProcessEnv = process.env): string {\n return trimTrailingSlashes(env.MUSHI_CONSOLE_URL?.trim() || HOSTED_CONSOLE_URL)\n}\nconst VIEWPORT_NAMES = ['desktop', 'mobile'] as const\n/** Screenshots per upload request (the api caps one request at 60 names). */\nconst UPLOAD_BATCH = 40\n\nexport interface SyncConfig {\n apiKey: string\n projectId: string\n endpoint: string\n /** 'cloud' when the run executes on the host's CI rather than a laptop. */\n mode: 'local' | 'cloud'\n}\n\nexport function syncConfigFromEnv(env: NodeJS.ProcessEnv = process.env): SyncConfig | null {\n const apiKey = env.MUSHI_API_KEY?.trim()\n const projectId = env.MUSHI_PROJECT_ID?.trim()\n if (!apiKey || !projectId) return null\n return {\n apiKey,\n projectId,\n endpoint: trimTrailingSlashes(env.MUSHI_API_ENDPOINT?.trim() || CLOUD_API_ENDPOINT),\n mode: env.GITHUB_ACTIONS === 'true' ? 'cloud' : 'local',\n }\n}\n\n/** A loop, not `/\\/+$/`: that regex is quadratic on a long run of '/' that does not end the string. */\nfunction trimTrailingSlashes(s: string): string {\n let end = s.length\n while (end > 0 && s.charCodeAt(end - 1) === 47) end--\n return s.slice(0, end)\n}\n\nconst PROJECT_LINE_RE = /^\\s*(?:NEXT_PUBLIC_|VITE_|EXPO_PUBLIC_|PUBLIC_)?MUSHI_PROJECT_ID\\s*=\\s*[\"']?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[\"']?\\s*$/im\n\n/**\n * The Mushi project this repo's app reports to, from the public SDK variable\n * in its env files (NEXT_PUBLIC_MUSHI_PROJECT_ID and friends). Only that one\n * line is read; nothing else in the file is kept.\n * @internal Exported for tests only.\n */\nexport function repoProjectId(repoRoot: string): string | null {\n for (const name of ['.env.local', '.env.development.local', '.env.development', '.env']) {\n const file = join(repoRoot, name)\n if (!existsSync(file)) continue\n const m = readFileSync(file, 'utf8').match(PROJECT_LINE_RE)\n if (m) return m[1]\n }\n return null\n}\n\n/** Null when syncing to `cfg.projectId` is right for this repo, else why not. */\nexport function syncProjectMismatch(cfg: SyncConfig, repoRoot: string): string | null {\n const repoProject = repoProjectId(repoRoot)\n if (!repoProject || repoProject === cfg.projectId) return null\n return `This repo's app reports to Mushi project ${repoProject}, but your login is for ${cfg.projectId}. Run \\`mushi login\\` and pick this app's project (or set MUSHI_PROJECT_ID), so the run lands on the right project.`\n}\n\nfunction probeSummary(p: ProbeResult | undefined) {\n if (!p) return null\n return {\n axe: p.axe.map((v) => ({ id: v.id, impact: v.impact, help: v.help.slice(0, 300), count: v.count })).slice(0, 60),\n overflowX: p.overflowX,\n smallTargets: p.smallTargets,\n consoleErrors: p.consoleErrors.length,\n cls: p.cls,\n }\n}\n\n/**\n * Pure: the part of an agent step that may leave the machine. Agent output\n * stays local (it can quote file contents, commands and their output), so\n * the console gets only which files were read or edited; a command or a\n * search is counted, never shown. Anything else, raw lines included, is\n * dropped.\n * @internal Exported for tests only.\n */\nexport function syncableStep(line: string): string | null {\n if (/^\\[(read|edit)\\] \\S/.test(line)) return line.slice(0, 300)\n if (line.startsWith('[run] ')) return '[run] a command'\n if (line.startsWith('[find] ')) return '[find] a search'\n if (line === '[done] Finished') return line\n return null\n}\n\nfunction syncableSteps(log: string | undefined): string | null {\n const kept = (log ?? '').split('\\n').map(syncableStep).filter((l): l is string => l !== null)\n return kept.length ? kept.join('\\n').slice(-2000) : null\n}\n\n/** The worse of the phone and desktop scores: a change is judged on both, so one number must not hide the other. */\nfunction worstPenalty(shots: Partial<Record<string, { penalty: number }>>): number | null {\n const scores = Object.values(shots).flatMap((r) => (r && typeof r.penalty === 'number' ? [r.penalty] : []))\n return scores.length ? Math.max(...scores) : null\n}\n\nfunction lastKept(s: SurfaceState) {\n return [...s.iterations].reverse().find((i) => i.outcome === 'accepted') ?? null\n}\n\n/** One screenshot to mirror: its upload name and its file in the run dir. */\ninterface WantedShot {\n /** `<surface>/<slot>.png`, e.g. `home-1a2b3c/iter2-after-mobile.png`. */\n name: string\n /** PNG path relative to the run dir. */\n rel: string\n}\n\n/** Pure: every screenshot the console should have for this state. */\nfunction wantedShots(state: RunState): WantedShot[] {\n const out: WantedShot[] = []\n for (const s of state.surfaces) {\n const key = s.surface.key\n const kept = lastKept(s)\n for (const vp of VIEWPORT_NAMES) {\n const before = s.baseline[vp]?.png\n if (before) out.push({ name: `${key}/before-${vp}.png`, rel: before })\n const after = kept?.after[vp]?.png\n if (after) out.push({ name: `${key}/after-${vp}.png`, rel: after })\n const diff = kept?.diffPng[vp]\n if (diff) out.push({ name: `${key}/diff-${vp}.png`, rel: diff })\n for (const it of s.iterations) {\n if (it.after[vp]?.png) out.push({ name: `${key}/iter${it.n}-after-${vp}.png`, rel: it.after[vp].png })\n if (it.diffPng[vp]) out.push({ name: `${key}/iter${it.n}-diff-${vp}.png`, rel: it.diffPng[vp] })\n }\n }\n }\n return out\n}\n\n/** Pure, for tests: the PUT body for one run state. `uploaded` maps upload name → the file it came from. */\nexport function toSnapshot(state: RunState, finished: boolean, uploaded: ReadonlyMap<string, string>, mode: SyncConfig['mode'] = 'local') {\n const have = (name: string) => (uploaded.has(name) ? name : null)\n const status = state.stopped ? 'stopped' : state.phase === 'failed' ? 'failed' : finished ? 'done' : 'running'\n return {\n mode,\n status,\n agent: state.agent,\n model: state.model,\n judge_model: state.judgeModel ?? null,\n skill: state.skill?.name?.slice(0, 120) ?? null,\n base_ref: state.baseRef?.slice(0, 200) ?? null,\n phase: state.phase ?? null,\n phase_detail: state.phaseDetail?.slice(0, 300) ?? null,\n current_surface: state.current?.surface ?? null,\n current_attempt: state.current?.attempt ?? null,\n current_progress: state.current\n ? {\n steps: state.current.steps ?? 0,\n last_step: state.current.lastStep ? syncableStep(state.current.lastStep) : null,\n files: (state.current.files ?? []).slice(0, 20).map((f) => f.slice(0, 300)),\n started_at: state.current.startedAt,\n timeout_ms: state.current.timeoutMs ?? null,\n }\n : null,\n error: state.error?.slice(0, 1000) ?? null,\n branch: state.branch,\n base_sha: state.baseSha,\n cli_version: null,\n ...(state.pr ? { pr: { url: state.pr.url, number: state.pr.number } } : {}),\n started_at: state.createdAt,\n finished_at: finished || status === 'failed' ? (state.finishedAt ?? new Date().toISOString()) : null,\n surfaces: state.surfaces.map((s) => {\n const kept = lastKept(s)\n const key = s.surface.key\n const shots: Record<string, string> = {}\n for (const vp of VIEWPORT_NAMES) {\n for (const kind of ['before', 'after', 'diff']) {\n const name = have(`${key}/${kind}-${vp}.png`)\n if (name) shots[`${kind}-${vp}`] = name\n }\n }\n return {\n surface_key: key,\n kind: s.surface.kind,\n path: s.surface.path,\n label: s.surface.label.slice(0, 300),\n status: s.status,\n note: s.note?.slice(0, 1000) ?? null,\n // Small-steps mode: the plan as a checklist (the step texts are the agent's own plan, file names included).\n plan: s.plan?.steps.length\n ? s.plan.steps.slice(0, 8).map((p) => ({ text: p.text.slice(0, 300), status: p.status, attempt: p.attempt ?? null }))\n : null,\n penalty_before: worstPenalty(s.baseline),\n penalty_after: kept ? worstPenalty(kept.after) : null,\n probe_before: probeSummary(s.baseline.desktop?.probes),\n probe_after: probeSummary(kept?.after.desktop?.probes),\n judge: s.judge?.length\n ? s.judge.map((j) => ({\n viewport: j.viewport,\n model: j.model,\n preferred: j.preferred,\n confidence: j.confidence,\n summary: j.summary.slice(0, 2000),\n better: j.better.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),\n worse: j.worse.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),\n ...(j.error ? { error: j.error.slice(0, 500) } : {}),\n }))\n : null,\n thumbs: { before: shots['before-desktop'] ?? null, after: shots['after-desktop'] ?? null, diff: shots['diff-desktop'] ?? null },\n shots,\n iterations: s.iterations.map((it) => {\n const itShots: Record<string, string> = {}\n for (const vp of VIEWPORT_NAMES) {\n for (const kind of ['after', 'diff']) {\n const name = have(`${key}/iter${it.n}-${kind}-${vp}.png`)\n if (name) itShots[`${kind}-${vp}`] = name\n }\n }\n return {\n n: it.n,\n agent: it.agent,\n model: it.model,\n duration_ms: it.durationMs,\n outcome: it.outcome,\n reason: it.reason.slice(0, 1000),\n commit_sha: it.commitSha,\n pixel_diff: it.pixelDiff,\n penalty_after: worstPenalty(it.after),\n steps: syncableSteps(it.logTail),\n step: it.step?.slice(0, 300) ?? null,\n shots: itShots,\n }\n }),\n }\n }),\n }\n}\n\nexport interface SyncHandle {\n /** Final sync; resolves with an error message when it did not land. */\n finish(): Promise<string | null>\n}\n\nexport function startSync(dir: string, cfg: SyncConfig, events: EventEmitter, log: (m: string) => void): SyncHandle {\n /** Upload name → the run-dir file last uploaded under it. */\n const uploaded = new Map<string, string>()\n let timer: NodeJS.Timeout | null = null\n let running: Promise<void> = Promise.resolve()\n let lastError: string | null = null\n let warned = false\n\n const headers = {\n Authorization: `Bearer ${cfg.apiKey}`,\n 'X-Mushi-Api-Key': cfg.apiKey,\n 'X-Mushi-Project': cfg.projectId,\n 'Content-Type': 'application/json',\n }\n\n async function api(method: string, path: string, body: unknown): Promise<unknown> {\n const res = await fetch(`${cfg.endpoint}/v1/admin/projects/${cfg.projectId}/ux-runs/${path}`, {\n method,\n headers,\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(30_000),\n })\n const json = (await res.json().catch(() => null)) as { ok?: boolean; data?: unknown; error?: { code?: string; message?: string } } | null\n if (json?.error?.code === 'INSUFFICIENT_SCOPE') {\n // An SDK ingest key (report:write only) cannot sync; a browser login mints mcp:write.\n throw new Error('this Mushi key cannot write to the console. Run `mushi login` (browser sign-in) for a key that can, then retry')\n }\n if (!res.ok || !json?.ok) throw new Error(json?.error?.message ?? `HTTP ${res.status}`)\n return json.data\n }\n\n async function uploadShots(state: RunState): Promise<void> {\n // A later kept attempt replaces after-/diff- under the same name, so compare the source file too.\n const todo = wantedShots(state).filter((w) => uploaded.get(w.name) !== w.rel)\n for (let i = 0; i < todo.length; i += UPLOAD_BATCH) {\n const batch = todo.slice(i, i + UPLOAD_BATCH)\n const data = (await api('POST', `${state.runId}/uploads`, { names: batch.map((w) => w.name) })) as {\n uploads: Array<{ name: string; signedUrl: string }>\n }\n for (const u of data.uploads) {\n const want = batch.find((w) => w.name === u.name)\n if (!want) continue\n const png = cropTop(readFileSync(join(dir, want.rel)), 2400)\n const put = await fetch(u.signedUrl, {\n method: 'PUT',\n headers: { 'Content-Type': 'image/png', 'x-upsert': 'true' },\n body: new Uint8Array(png),\n signal: AbortSignal.timeout(60_000),\n })\n if (!put.ok) throw new Error(`screenshot upload failed (HTTP ${put.status})`)\n uploaded.set(want.name, want.rel)\n }\n }\n }\n\n async function syncOnce(finished: boolean): Promise<void> {\n const state = loadState(dir)\n if (!state) return\n try {\n await api('PUT', state.runId, toSnapshot(state, false, uploaded, cfg.mode))\n await uploadShots(state)\n await api('PUT', state.runId, toSnapshot(state, finished, uploaded, cfg.mode))\n lastError = null\n } catch (err) {\n lastError = (err as Error).message\n if (!warned) {\n log(`Console sync failed (will retry): ${lastError}`)\n warned = true\n }\n }\n }\n\n const schedule = () => {\n if (timer) return\n timer = setTimeout(() => {\n timer = null\n running = running.then(() => syncOnce(false))\n }, 1500)\n }\n events.on('event', (e: LoopEvent) => {\n if (e.type === 'state' || e.type === 'phase') schedule()\n })\n\n return {\n async finish() {\n if (timer) clearTimeout(timer)\n timer = null\n await running\n await syncOnce(true)\n return lastError\n },\n }\n}\n"],"mappings":";AAsBA,SAAS,eAAAA,cAAa,gBAAAC,qBAAoB;AAC1C,SAAS,QAAAC,aAAY;;;AChBrB,SAAS,OAAO,iBAAoC;AAwBpD,SAAS,SAAS,OAA2B;AAC3C,MAAI,MAAM,QAAQ,UAAa,MAAM,aAAa,KAAM;AACxD,MAAI,QAAQ,aAAa,SAAS;AAChC,cAAU,YAAY,CAAC,QAAQ,OAAO,MAAM,GAAG,GAAG,MAAM,IAAI,GAAG,EAAE,OAAO,SAAS,CAAC;AAAA,EACpF,OAAO;AACL,QAAI;AACF,cAAQ,KAAK,CAAC,MAAM,KAAK,SAAS;AAAA,IACpC,QAAQ;AACN,YAAM,KAAK,SAAS;AAAA,IACtB;AAAA,EACF;AACF;AAEO,SAAS,IAAI,KAAa,MAAyB,MAAsC;AAC9F,QAAM,UAAU,KAAK,IAAI;AACzB,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,QAAQ,MAAM,KAAK,MAAM;AAAA,MAC7B,KAAK,KAAK;AAAA,MACV,KAAK,KAAK,OAAO,QAAQ;AAAA,MACzB,OAAO,KAAK,SAAS;AAAA,MACrB,UAAU,QAAQ,aAAa;AAAA,MAC/B,aAAa;AAAA,MACb,OAAO,CAAC,QAAQ,QAAQ,MAAM;AAAA,IAChC,CAAC;AACD,QAAI,OAAO;AACX,Q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M,SAAS,KAAK,CAAC;AAAA,IAC9C,GAAG,IAAI;AAAA,EACT;AACA,SAAO,GAAG,SAAS,CAAC,MAAiB;AACnC,QAAI,EAAE,SAAS,WAAW,EAAE,SAAS,QAAS,UAAS;AAAA,EACzD,CAAC;AAED,SAAO;AAAA,IACL,MAAM,SAAS;AACb,UAAI,MAAO,cAAa,KAAK;AAC7B,cAAQ;AACR,YAAM;AACN,YAAM,SAAS,IAAI;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["readdirSync","readFileSync","join","git","join","readFileSync","readdirSync","existsSync","readdirSync","readFileSync","createServer","dirname","join","PNG","surfaceKey","start","existsSync","mkdirSync","readFileSync","dirname","join","join","createServer","existsSync","readdirSync","readFileSync","PNG","dirname","readdirSync","readFileSync","statSync","join","relative","dir","failed","sep","readFileSync","join","z","z","readFileSync","join","appendFileSync","existsSync","mkdirSync","readFileSync","rmSync","writeFileSync","dirname","join","Anthropic","mkdirSync","writeFileSync","join","PNG","PNG","start","join","a","Anthropic","mkdirSync","verdict","writeFileSync","closeSync","existsSync","fstatSync","openSync","readdirSync","readFileSync","join","relative","SKIP_DIRS","join","existsSync","readdirSync","openSync","fstatSync","readFileSync","closeSync","relative","randomBytes","writeFileSync","join","join","randomBytes","writeFileSync","existsSync","mkdirSync","readdirSync","readFileSync","rmSync","writeFileSync","dirname","join","relative","join","rmSync","mkdirSync","dirname","writeFileSync","mkdirSync","appendFileSync","join","existsSync","session","rmSync","dirname","writeFileSync","readFileSync","text","lastKept","step","existsSync","readFileSync","join","readFileSync","join"]}
|
|
1
|
+
{"version":3,"sources":["../src/cursor-cloud.ts","../src/proc.ts","../src/worktree.ts","../src/agents.ts","../src/capture.ts","../src/guard.ts","../src/ignore.ts","../src/probes.ts","../src/dashboard.ts","../src/agent-events.ts","../src/image.ts","../src/state.ts","../src/studio-page.ts","../src/discover.ts","../src/routes.ts","../src/judge.ts","../src/loop.ts","../src/checker.ts","../src/packet.ts","../src/preflight.ts","../src/verdict.ts","../src/resume.ts","../src/types.ts","../src/sync.ts"],"sourcesContent":["// SPDX-License-Identifier: MIT\n/**\n * `--agent cursor-cloud`: the edit runs in a Cursor Cloud agent (your Cursor\n * plan pays), the measuring stays local. One attempt:\n *\n * push the run branch → POST /v1/agents on it (workOnCurrentBranch, no PR)\n * → poll the run → fetch the branch → apply the agent's commit to the\n * worktree, uncommitted\n *\n * so the loop's own capture, verdict and commit/revert work unchanged. The\n * agent cannot see the local `.mushi-ux/` files, so the prompt text and the\n * screenshots are sent inline.\n *\n * Wire shape: cursor.com/docs/cloud-agent/api/endpoints (read 2026-10-06).\n * `workOnCurrentBranch: true` makes the agent push to the run branch itself\n * instead of a new `cursor/...` branch, so every push of a run is under\n * `mushi-ux/**` and one `branches-ignore` keeps the host's CI quiet. The next\n * attempt's force-with-lease push replaces whatever the loop did not keep.\n * Images are `{ data, mimeType }`, at most 5; if Cursor still refuses them the\n * run goes on text only.\n */\n\nimport { readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { AgentAdapter, AgentRunOptions } from './agents.js'\nimport { run, type RunResult } from './proc.js'\nimport { SCRATCH_DIR } from './worktree.js'\n\nconst API = 'https://api.cursor.com'\nconst POLL_MS = 10_000\nconst MAX_IMAGES = 4 // Cursor allows 5\n\nexport interface CursorCloudDeps {\n fetch?: typeof fetch\n apiKey?: string\n /** Override the repo URL read from `git remote get-url origin` (tests). */\n repoUrl?: string\n sleep?: (ms: number) => Promise<void>\n}\n\nasync function git(cwd: string, args: string[], stdin?: string): Promise<RunResult> {\n return run('git', args, { cwd, stdin, timeoutMs: 120_000 })\n}\n\n/** `git@github.com:o/r.git` / `https://github.com/o/r(.git)` → `https://github.com/o/r`. */\nexport function httpsRepoUrl(remote: string): string | null {\n const s = remote.trim()\n const ssh = s.match(/^git@github\\.com:([\\w.-]+)\\/([\\w.-]+?)(\\.git)?$/)\n if (ssh) return `https://github.com/${ssh[1]}/${ssh[2]}`\n const https = s.match(/^https:\\/\\/(?:[^@/]+@)?github\\.com\\/([\\w.-]+)\\/([\\w.-]+?)(\\.git)?\\/?$/)\n if (https) return `https://github.com/${https[1]}/${https[2]}`\n return null\n}\n\n/** Model spec like `grok-4.7?reasoning_effort=xhigh` → Cursor's `{ id, params }`. */\nexport function cursorModel(spec: string | null | undefined): Record<string, unknown> | undefined {\n if (!spec) return undefined\n const [id, query] = spec.split('?')\n if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/.test(id)) return undefined\n const params = query\n ? query.split('&').filter(Boolean).map((p) => {\n const [k, v] = p.split('=')\n return { id: k, value: v ?? '' }\n })\n : []\n return params.length ? { id, params } : { id }\n}\n\nfunction promptAndImages(cwd: string): { text: string; images: Array<{ data: string; mimeType: 'image/png' }> } {\n const dir = join(cwd, SCRATCH_DIR)\n const text = readFileSync(join(dir, 'PROMPT.md'), 'utf8')\n const images = readdirSync(dir)\n .filter((f) => f.endsWith('.png'))\n .slice(0, MAX_IMAGES)\n .map((f) => ({ data: readFileSync(join(dir, f)).toString('base64'), mimeType: 'image/png' as const }))\n // The cloud agent sees the screenshots inline, not at these paths.\n return { text: text.replace(/\\.mushi-ux\\/(desktop|mobile)\\.png/g, 'the attached $1 screenshot'), images }\n}\n\nexport function cursorCloudAdapter(deps: CursorCloudDeps = {}): AgentAdapter {\n const doFetch = deps.fetch ?? fetch\n const sleep = deps.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)))\n\n return {\n name: 'cursor-cloud',\n verified: false,\n async run({ cwd, model, timeoutMs, onLine }: AgentRunOptions): Promise<RunResult> {\n const started = Date.now()\n const log = (l: string) => onLine?.(l)\n const fail = (tail: string): RunResult => ({ exitCode: 1, timedOut: false, durationMs: Date.now() - started, tail, stdout: '' })\n const apiKey = deps.apiKey ?? process.env.CURSOR_API_KEY\n if (!apiKey) return fail('CURSOR_API_KEY is not set. Create one at cursor.com/settings (Integrations → API keys).')\n\n const branch = (await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim()\n const remote = deps.repoUrl ?? httpsRepoUrl((await git(cwd, ['remote', 'get-url', 'origin'])).stdout)\n if (!remote) return fail('cursor-cloud needs an `origin` remote on GitHub.')\n log(`pushing ${branch} so the cloud agent can start from it`)\n const push = await git(cwd, ['push', '--force-with-lease', 'origin', `HEAD:refs/heads/${branch}`])\n if (push.exitCode !== 0) return fail(`Could not push ${branch}: ${push.tail.trim()}`)\n\n const { text, images } = promptAndImages(cwd)\n const headers = { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' }\n const body = (withImages: boolean) =>\n JSON.stringify({\n prompt: withImages && images.length ? { text, images } : { text },\n repos: [{ url: remote, startingRef: branch }],\n workOnCurrentBranch: true,\n autoCreatePR: false,\n name: `mushi-ux ${branch}`.slice(0, 100),\n ...(cursorModel(model) ? { model: cursorModel(model) } : {}),\n })\n let res = await doFetch(`${API}/v1/agents`, { method: 'POST', headers, body: body(true) })\n if (res.status === 400 && images.length) {\n log('Cursor refused the inline screenshots; retrying with text only')\n res = await doFetch(`${API}/v1/agents`, { method: 'POST', headers, body: body(false) })\n }\n const created = (await res.json().catch(() => null)) as { agent?: { id?: string }; run?: { id?: string }; error?: { message?: string } } | null\n if (!res.ok || !created?.agent?.id || !created.run?.id) {\n return fail(`Cursor did not start the agent (HTTP ${res.status}): ${created?.error?.message ?? 'no agent id'}`)\n }\n const agentId = created.agent.id\n const runId = created.run.id\n log(`cloud agent ${agentId} running`)\n\n let status = 'CREATING'\n let resultBranch: string | null = null\n let result = ''\n while (Date.now() - started < timeoutMs) {\n await sleep(POLL_MS)\n const poll = await doFetch(`${API}/v1/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}`, { headers })\n const r = (await poll.json().catch(() => null)) as { status?: string; result?: string; git?: { branches?: Array<{ branch?: string }> } } | null\n status = r?.status ?? status\n log(`cloud agent ${status.toLowerCase()}`)\n if (status === 'FINISHED' || status === 'ERROR' || status === 'CANCELLED' || status === 'EXPIRED') {\n resultBranch = r?.git?.branches?.find((b) => b.branch)?.branch ?? null\n result = r?.result ?? ''\n break\n }\n }\n if (status !== 'FINISHED') {\n if (Date.now() - started >= timeoutMs) {\n await doFetch(`${API}/v1/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST', headers }).catch(() => undefined)\n return { exitCode: null, timedOut: true, durationMs: Date.now() - started, tail: `Cloud agent still ${status.toLowerCase()} at the time box; cancelled.`, stdout: '' }\n }\n return fail(`Cloud agent ended ${status.toLowerCase()}. ${result}`.trim())\n }\n if (!resultBranch) return { exitCode: 0, timedOut: false, durationMs: Date.now() - started, tail: result || 'Cloud agent made no edits.', stdout: '' }\n\n const fetched = await git(cwd, ['fetch', 'origin', resultBranch])\n if (fetched.exitCode !== 0) return fail(`Could not fetch ${resultBranch}: ${fetched.tail.trim()}`)\n const diff = await git(cwd, ['diff', '--binary', 'HEAD', 'FETCH_HEAD'])\n if (diff.stdout.trim()) {\n const applied = await git(cwd, ['apply', '--whitespace=nowarn'], diff.stdout)\n if (applied.exitCode !== 0) return fail(`The agent's change did not apply: ${applied.tail.trim()}`)\n }\n // The loop commits what it keeps; the next push replaces the agent's commit.\n log(`applied the cloud agent's change from ${resultBranch}`)\n return { exitCode: 0, timedOut: false, durationMs: Date.now() - started, tail: result.slice(-2000), stdout: result }\n },\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Child processes for agents, installs and dev servers. Prompts go on stdin\n * (cmd.exe caps a command line near 8 KB), timeouts kill the whole process\n * tree (`taskkill /T /F` on Windows), and agents get a scrubbed environment.\n */\n\nimport { spawn, spawnSync, type ChildProcess } from 'node:child_process'\n\nexport interface RunResult {\n exitCode: number | null\n timedOut: boolean\n durationMs: number\n /** Last ~4 KB of combined output. */\n tail: string\n /** Full stdout, capped at 1 MB. */\n stdout: string\n}\n\nexport interface RunOptions {\n cwd: string\n env?: NodeJS.ProcessEnv\n stdin?: string\n timeoutMs?: number\n /** Needed for `.cmd` shims and shell syntax in user-given commands. */\n shell?: boolean\n onLine?: (line: string) => void\n /** Stops the process tree when aborted (the studio's Stop button). */\n signal?: AbortSignal\n}\n\nfunction killTree(child: ChildProcess): void {\n if (child.pid === undefined || child.exitCode !== null) return\n if (process.platform === 'win32') {\n spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' })\n } else {\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch {\n child.kill('SIGKILL')\n }\n }\n}\n\nexport function run(cmd: string, args: readonly string[], opts: RunOptions): Promise<RunResult> {\n const started = Date.now()\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: opts.shell ?? false,\n detached: process.platform !== 'win32',\n windowsHide: true,\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n let tail = ''\n let stdout = ''\n let partial = ''\n let timedOut = false\n const onData = (chunk: Buffer) => {\n const text = chunk.toString('utf8')\n tail = (tail + text).slice(-4096)\n if (!opts.onLine) return\n partial += text\n const lines = partial.split(/\\r?\\n/)\n partial = lines.pop() ?? ''\n for (const line of lines) if (line.trim()) opts.onLine(line)\n }\n child.stdout?.on('data', (chunk: Buffer) => {\n if (stdout.length < 1_000_000) stdout += chunk.toString('utf8')\n onData(chunk)\n })\n child.stderr?.on('data', onData)\n child.on('error', reject)\n const timer = opts.timeoutMs\n ? setTimeout(() => {\n timedOut = true\n killTree(child)\n }, opts.timeoutMs)\n : null\n const onAbort = () => killTree(child)\n if (opts.signal?.aborted) onAbort()\n else opts.signal?.addEventListener('abort', onAbort, { once: true })\n child.on('close', (code) => {\n if (timer) clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onAbort)\n if (partial.trim() && opts.onLine) opts.onLine(partial)\n resolve({ exitCode: code, timedOut, durationMs: Date.now() - started, tail, stdout })\n })\n // A child that exits before reading stdin (git, a quick CLI) makes this\n // write fail with EPIPE; without a listener that is an uncaught exception\n // that takes the whole process down (seen in CI, 2026-10-07). The exit\n // code still reports how the child ended.\n child.stdin?.on('error', () => {})\n child.stdin?.end(opts.stdin ?? '')\n })\n}\n\n/** Long-running child (a dev server); the caller stops it with `stop()`. */\nexport function start(command: string, opts: { cwd: string; env?: NodeJS.ProcessEnv; onLine?: (l: string) => void }) {\n const child = spawn(command, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: true,\n detached: process.platform !== 'win32',\n windowsHide: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n const forward = (chunk: Buffer) => {\n for (const line of chunk.toString('utf8').split(/\\r?\\n/)) if (line.trim()) opts.onLine?.(line)\n }\n child.stdout?.on('data', forward)\n child.stderr?.on('data', forward)\n return { child, stop: () => killTree(child) }\n}\n\n/**\n * The tool's own credentials. The dev server and the install run the app's\n * code, which the agent edits, so they get the app's environment without\n * these: on a CI runner that is the Cursor and Anthropic keys and the job's\n * GitHub tokens. App variables (VITE_*_KEY and the like) stay.\n */\nconst TOOL_SECRET_RE = /^(MUSHI_.*|CURSOR_API_KEY|ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN|OPENAI_API_KEY|CODEX_API_KEY|GITHUB_TOKEN|GH_TOKEN|ACTIONS_RUNTIME_TOKEN|ACTIONS_ID_TOKEN_REQUEST_TOKEN|ACTIONS_ID_TOKEN_REQUEST_URL)$/i\n\nexport function appEnv(base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const out: NodeJS.ProcessEnv = {}\n for (const [k, v] of Object.entries(base)) {\n if (v !== undefined && !TOOL_SECRET_RE.test(k)) out[k] = v\n }\n return out\n}\n\nconst SECRET_NAME_RE = /(^MUSHI_|^SUPABASE_|_TOKEN$|_KEY$|_SECRET$|PASSWORD|^GH_|^GITHUB_)/i\n\n/**\n * The environment an agent runs with: everything except credentials, plus\n * the one credential that agent itself needs to talk to its model.\n */\nexport function scrubbedEnv(keep: readonly string[], base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const out: NodeJS.ProcessEnv = {}\n for (const [k, v] of Object.entries(base)) {\n if (v === undefined) continue\n if (SECRET_NAME_RE.test(k) && !keep.includes(k)) continue\n out[k] = v\n }\n return out\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The agent edits a separate git worktree on its own branch, served by its\n * own dev server, so the person's checkout (and any other agent working in\n * it) is never touched. Accepted iterations are commits on that branch;\n * rejected ones are reverted.\n *\n * `.mushi-ux/` inside the worktree carries the screenshots and the prompt for\n * the agent. It is never committed.\n */\n\nimport { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { createServer } from 'node:net'\nimport { dirname, isAbsolute, join, relative } from 'node:path'\nimport { appEnv, run, start } from './proc.js'\n\nexport const SCRATCH_DIR = '.mushi-ux'\n\nasync function git(cwd: string, args: string[]): Promise<string> {\n const res = await run('git', args, { cwd, timeoutMs: 120_000 })\n if (res.exitCode !== 0) throw new Error(`git ${args.join(' ')} failed: ${res.tail.trim()}`)\n return res.stdout.trim()\n}\n\nexport async function repoRootOf(cwd: string): Promise<string> {\n return git(cwd, ['rev-parse', '--show-toplevel'])\n}\n\nexport interface Worktree {\n path: string\n branch: string\n baseSha: string\n}\n\n/**\n * Branch `mushi-ux/<runId>` from `baseRef` (default HEAD) in `.worktrees/`.\n * A stale or dirty checkout stays untouched: pass `origin/main` to start from\n * the remote's tip instead of whatever the checkout is on.\n */\nexport async function createWorktree(repoRoot: string, runId: string, baseRef = 'HEAD'): Promise<Worktree> {\n const branch = `mushi-ux/${runId}`\n const path = join(repoRoot, '.worktrees', `mushi-ux-${runId}`)\n if (!/^[\\w./@^~-]{1,200}$/.test(baseRef) || baseRef.startsWith('-')) throw new Error(`Not a git ref: ${baseRef}`)\n const baseSha = await git(repoRoot, ['rev-parse', '--verify', `${baseRef}^{commit}`])\n await ensureLocalExcludes(repoRoot)\n mkdirSync(dirname(path), { recursive: true })\n await git(repoRoot, ['worktree', 'add', '-b', branch, path, baseSha])\n await copyEnvFiles(repoRoot, path)\n return { path, branch, baseSha }\n}\n\n/** Paths the loop writes that must never show up in `git status` or a commit. */\nconst LOCAL_EXCLUDES = ['/.mushi/', '/.worktrees/', `/${SCRATCH_DIR}/`]\n\n/**\n * Add the loop's own directories to `.git/info/exclude` (local to this clone,\n * shared by its worktrees, never committed), so a run leaves the person's\n * `git status` clean without touching their `.gitignore`.\n */\nasync function ensureLocalExcludes(repoRoot: string): Promise<void> {\n let common = await git(repoRoot, ['rev-parse', '--git-common-dir'])\n if (!isAbsolute(common)) common = join(repoRoot, common)\n const file = join(common, 'info', 'exclude')\n mkdirSync(dirname(file), { recursive: true })\n let current = ''\n try {\n current = readFileSync(file, 'utf8')\n } catch {\n // No exclude file yet: append creates it.\n }\n const lines = new Set(current.split(/\\r?\\n/).map((l) => l.trim()))\n const missing = LOCAL_EXCLUDES.filter((p) => !lines.has(p))\n if (missing.length === 0) return\n const lead = current && !current.endsWith('\\n') ? '\\n' : ''\n appendFileSync(file, `${lead}# mushi-ux (local only)\\n${missing.join('\\n')}\\n`)\n}\n\n/**\n * Local `.env*` files are untracked, so a fresh worktree lacks them. Only\n * files git already ignores are copied: an env file the repo does not ignore\n * would otherwise land in the run's commits (`git add -A`) and in the PR.\n */\nasync function copyEnvFiles(from: string, to: string, maxDepth = 4): Promise<string[]> {\n const candidates: string[] = []\n const walk = (dir: string, depth: number) => {\n if (depth > maxDepth) return\n for (const name of readdirSync(dir)) {\n if (name === 'node_modules' || name === '.git' || name === '.worktrees' || name === '.mushi') continue\n const abs = join(dir, name)\n let isDir = false\n try {\n isDir = statSync(abs).isDirectory()\n } catch {\n continue\n }\n if (isDir) walk(abs, depth + 1)\n else if (/^\\.env(\\..+)?$/.test(name) && !name.endsWith('.example')) {\n candidates.push(relative(from, abs).replace(/\\\\/g, '/'))\n }\n }\n }\n walk(from, 0)\n if (candidates.length === 0) return []\n // check-ignore exits 1 when nothing matches; stdout lists the ignored paths.\n const res = await run('git', ['check-ignore', '--', ...candidates], { cwd: from, timeoutMs: 60_000 })\n const ignored = new Set(res.stdout.split(/\\r?\\n/).map((l) => l.trim().replace(/\\\\/g, '/')).filter(Boolean))\n const copied: string[] = []\n for (const rel of candidates) {\n if (!ignored.has(rel)) continue\n const dest = join(to, rel)\n if (existsSync(dest)) continue\n mkdirSync(dirname(dest), { recursive: true })\n copyFileSync(join(from, rel), dest)\n copied.push(rel)\n }\n return copied\n}\n\n/** Files changed by the agent, ignoring the scratch dir. */\nexport async function changedFiles(wt: string): Promise<string[]> {\n // Not git(): its trim() would eat the leading status column of line one.\n const res = await run('git', ['status', '--porcelain', '--untracked-files=all'], {\n cwd: wt,\n timeoutMs: 120_000,\n })\n if (res.exitCode !== 0) throw new Error(`git status failed: ${res.tail.trim()}`)\n return res.stdout\n .split(/\\r?\\n/)\n .filter(Boolean)\n .map((l) => l.slice(3).trim().replace(/^\"|\"$/g, ''))\n}\n\n/**\n * The agent's uncommitted edits as text, for a reviewer: tracked changes from\n * `git diff HEAD` and new files in full, capped. Stages nothing, so\n * revertAll still restores the tree.\n */\nexport async function diffText(wt: string, maxChars = 20_000): Promise<string> {\n const tracked = await run('git', ['diff', 'HEAD', '--', '.', `:(exclude)${SCRATCH_DIR}`], { cwd: wt, timeoutMs: 120_000 })\n let out = tracked.stdout\n const untracked = await run('git', ['ls-files', '--others', '--exclude-standard'], { cwd: wt, timeoutMs: 120_000 })\n for (const f of untracked.stdout.split(/\\r?\\n/).filter((x) => x && !x.startsWith(SCRATCH_DIR))) {\n if (out.length >= maxChars) break\n try {\n out += `\\n--- new file ${f} ---\\n${readFileSync(join(wt, f), 'utf8').slice(0, 4000)}\\n`\n } catch {\n out += `\\n--- new file ${f} (unreadable) ---\\n`\n }\n }\n return out.slice(0, maxChars)\n}\n\nexport async function commitAll(wt: string, message: string): Promise<string> {\n // .mushi-ux/ is in .git/info/exclude (ensureLocalExcludes), so -A skips it.\n await git(wt, ['add', '-A'])\n await git(wt, ['-c', 'user.name=mushi-ux', '-c', 'user.email=mushi-ux@users.noreply.github.com', 'commit', '--no-verify', '-m', message])\n return git(wt, ['rev-parse', 'HEAD'])\n}\n\nexport async function headSha(wt: string): Promise<string> {\n return git(wt, ['rev-parse', 'HEAD'])\n}\n\n/**\n * Move the run's own branch back to a commit it already had (a resume after a\n * crash between an attempt's commit and the state save). Only ever called on\n * the run's worktree, never the person's checkout.\n */\nexport async function resetRunBranch(wt: string, sha: string): Promise<void> {\n await git(wt, ['merge-base', '--is-ancestor', sha, 'HEAD'])\n await git(wt, ['reset', '--hard', sha])\n}\n\n/** Throw away the agent's uncommitted edits; keeps the scratch dir and ignored files (.env). */\nexport async function revertAll(wt: string): Promise<void> {\n await git(wt, ['checkout', '--', '.'])\n await git(wt, ['clean', '-fd', '-e', SCRATCH_DIR])\n}\n\nexport function detectInstallCommand(dir: string): string | null {\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm install --frozen-lockfile --prefer-offline'\n if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun install --frozen-lockfile'\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn install --frozen-lockfile'\n if (existsSync(join(dir, 'package-lock.json'))) return 'npm ci'\n return null\n}\n\nasync function freePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = createServer()\n srv.unref()\n srv.on('error', reject)\n srv.listen(0, '127.0.0.1', () => {\n const addr = srv.address()\n const port = typeof addr === 'object' && addr ? addr.port : 0\n srv.close(() => resolve(port))\n })\n })\n}\n\nexport interface DevServer {\n url: string\n stop(): void\n}\n\n/**\n * Start `command` in the worktree. `{port}` in the command and the PORT env\n * var both carry the chosen port; resolves once `url` answers.\n */\nexport async function startDevServer(\n wt: string,\n command: string,\n opts: { port?: number; path?: string; timeoutMs?: number; onLine?: (l: string) => void } = {},\n): Promise<DevServer> {\n const port = opts.port ?? (await freePort())\n const cmd = command.replace(/\\{port\\}/g, String(port))\n // Keep the last lines, so a failure says why instead of only \"no answer\".\n const recent: string[] = []\n const server = start(cmd, {\n cwd: wt,\n env: { ...appEnv(), PORT: String(port) },\n onLine: (l) => {\n recent.push(l)\n if (recent.length > 40) recent.shift()\n opts.onLine?.(l)\n },\n })\n const url = `http://localhost:${port}`\n const timeoutMs = opts.timeoutMs ?? 180_000\n const deadline = Date.now() + timeoutMs\n const tail = () => {\n // The first error line and what follows is usually the cause; ANSI colours dropped.\n const lines = recent.map((l) => l.replace(/\\u001b\\[[0-9;]*m/g, ''))\n const at = lines.findIndex((l) => /error|⨯|failed|cannot|can't/i.test(l))\n return (at >= 0 ? lines.slice(at, at + 12) : lines.slice(-12)).join('\\n')\n }\n let lastStatus: number | null = null\n while (Date.now() < deadline) {\n if (server.child.exitCode !== null) throw new Error(`Dev server exited with code ${server.child.exitCode}: ${cmd}\\n${tail()}`)\n lastStatus = await fetch(new URL(opts.path ?? '/', url), { redirect: 'manual' })\n .then((r) => r.status)\n .catch(() => lastStatus)\n if (lastStatus !== null && lastStatus < 500) return { url, stop: server.stop }\n await new Promise((r) => setTimeout(r, 1000))\n }\n server.stop()\n const why = lastStatus !== null ? `answered HTTP ${lastStatus} on ${url}${opts.path ?? '/'}` : `did not answer on ${url}`\n throw new Error(`The dev server ${why} for ${Math.round(timeoutMs / 1000)}s: ${cmd}\\n${tail()}`)\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Coding agents the loop can drive, each as a headless subprocess in the\n * worktree. The full instructions live in `.mushi-ux/PROMPT.md`; the agent\n * gets a one-line pointer to it, edits files, and the loop decides what to\n * keep.\n *\n * Credential boundary (ADR 0006 / 0020): the agent never gets the browser\n * profile or the Mushi CLI config. Its environment is scrubbed of every\n * credential except its own model key, and Claude Code runs `--restricted`,\n * which removes shell tools and confines file access to the worktree.\n *\n * `claude-code` is verified on Windows. `cursor` and `codex` follow their\n * documented headless flags and are unverified until the Plan 021 Phase 0\n * probes run (docs/execplans/ux-loop.md §5).\n */\n\nimport { cursorCloudAdapter } from './cursor-cloud.js'\nimport { run, scrubbedEnv, type RunResult } from './proc.js'\n\nexport type AgentName = 'claude-code' | 'cursor' | 'codex' | 'cursor-cloud'\n\nexport interface AgentRunOptions {\n cwd: string\n prompt: string\n model?: string | null\n timeoutMs: number\n onLine?: (line: string) => void\n /** Aborted by the studio's Stop button: the agent's process tree is killed. */\n signal?: AbortSignal\n /** Continue this earlier session (adapters with canResume) instead of starting a new one. */\n resumeSession?: string\n}\n\nexport interface AgentAdapter {\n name: AgentName | (string & {})\n verified: boolean\n /** Can continue a session by id (its stream reports session_id): used for \"time is up, finish now\". */\n canResume?: boolean\n run(opts: AgentRunOptions): Promise<RunResult>\n}\n\nconst claudeCode: AgentAdapter = {\n name: 'claude-code',\n verified: true,\n run: ({ cwd, prompt, model, timeoutMs, onLine, signal }) =>\n run(\n 'claude',\n [\n '-p',\n '--output-format',\n 'stream-json',\n '--verbose',\n '--restricted',\n '--strict-mcp-config',\n '--permission-mode',\n 'acceptEdits',\n '--no-session-persistence',\n ...(model ? ['--model', model] : []),\n ],\n {\n cwd,\n stdin: prompt,\n timeoutMs,\n onLine,\n signal,\n env: scrubbedEnv(['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN']),\n },\n ),\n}\n\nconst cursor: AgentAdapter = {\n name: 'cursor',\n // Verified on Windows 2026-10-06 (2026.10.01, Grok 4.7), launched outside Git Bash.\n verified: true,\n canResume: true,\n // Cursor's CLI takes the prompt as an argument in print mode; whether it\n // reads stdin is a Phase 0 probe. The `.cmd` shim needs a shell on Windows.\n // The loop's prompt is a one-line pointer to .mushi-ux/PROMPT.md, so it\n // stays far below cmd.exe's command-line limit.\n run: ({ cwd, prompt, model, timeoutMs, onLine, signal, resumeSession }) =>\n run(\n 'agent',\n [\n '-p',\n ...(resumeSession ? ['--resume', quoteArg(resumeSession)] : []),\n '--force',\n // Headless runs otherwise stop on the workspace-trust prompt in a fresh worktree.\n '--trust',\n '--output-format',\n 'stream-json',\n '--workspace',\n '.',\n ...(model ? ['--model', quoteArg(cursorCliModel(model))] : []),\n quoteArg(prompt),\n ],\n { cwd, timeoutMs, onLine, signal, shell: true, env: scrubbedEnv(['CURSOR_API_KEY']) },\n ),\n}\n\nconst codex: AgentAdapter = {\n name: 'codex',\n verified: false,\n run: ({ cwd, prompt, model, timeoutMs, onLine, signal }) =>\n run(\n 'codex',\n ['exec', '--json', '--full-auto', '-C', '.', ...(model ? ['-m', quoteArg(model)] : []), '-'],\n { cwd, stdin: prompt, timeoutMs, onLine, signal, shell: true, env: scrubbedEnv(['OPENAI_API_KEY', 'CODEX_API_KEY']) },\n ),\n}\n\n/**\n * The Cursor CLI takes a model's settings in brackets\n * (`claude-opus-4-8[context=1m,effort=high]`); the UI and the Cursor API use\n * `id?context=1m&effort=high`. A bare id passes through.\n * @internal Exported for tests only.\n */\nexport function cursorCliModel(spec: string): string {\n const [id, query] = spec.split('?')\n if (!query) return id\n const params = query.split('&').filter(Boolean)\n return params.length ? `${id}[${params.join(',')}]` : id\n}\n\n/**\n * Quote one argument for the shell `spawn({ shell: true })` uses, so model\n * specs like `grok-4.7?reasoning_effort=xhigh&context=500k` survive.\n * cmd.exe has no escape inside double quotes, so quotes are dropped there.\n */\nexport function quoteArg(s: string, platform: NodeJS.Platform = process.platform): string {\n if (/^[\\w./:=@-]+$/.test(s)) return s\n const flat = s.replace(/\\r?\\n/g, ' ')\n if (platform === 'win32') return `\"${flat.replace(/\"/g, '')}\"`\n return `'${flat.replace(/'/g, `'\\\\''`)}'`\n}\n\nexport const AGENTS: Record<AgentName, AgentAdapter> = {\n 'claude-code': claudeCode,\n cursor,\n codex,\n // Cursor Cloud: the edit runs on Cursor's machines (your plan pays), the\n // measuring stays here. Needs CURSOR_API_KEY and a GitHub origin.\n 'cursor-cloud': cursorCloudAdapter(),\n}\n\nexport function getAgent(name: string): AgentAdapter {\n const adapter = AGENTS[name as AgentName]\n if (!adapter) throw new Error(`Unknown agent \"${name}\". Use one of: ${Object.keys(AGENTS).join(', ')}`)\n return adapter\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Browser sessions and screenshots. Every session goes through the write\n * guard (guard.ts) before any page opens.\n *\n * A session can reuse the persistent profile `mushi-ux login` created, so\n * captures see the signed-in app. The profile lives outside the repo and is\n * never named to the coding agent (ADR 0006).\n */\n\nimport { chromium, type Browser, type BrowserContext, type Page } from 'playwright'\nimport { installGuard, isGuardNoise, type AllowRule, type GuardLog } from './guard.js'\nimport { ignoreList, ignoreStyle } from './ignore.js'\nimport { isFrameworkNoise, runProbes } from './probes.js'\nimport type { ProbeResult, ReplayStep, Surface, Viewport } from './types.js'\n\nexport interface BrowserSession {\n /** Discovery browses here; app state it leaves behind stays here. */\n context: BrowserContext\n /**\n * A clean context for one capture: the cookies and storage the session\n * started with (a saved login included), the same guard and init scripts.\n * Captures share no client state, so a screen looks the same however many\n * other screens were visited before it (glot.it /words lost its empty\n * state after other screens wrote to localStorage, 2026-10-07).\n */\n freshContext(): Promise<BrowserContext>\n /**\n * Visit each path once in the shared context, then seed every later capture\n * from the storage that leaves behind. A first-ever visit can sit on a boot\n * screen past the content wait (glot.it /chat: a skeleton on desktop, blank\n * on the phone, 2026-10-07), so captures start from a visited app, the same\n * one for every screen.\n */\n warmUp(baseUrl: string, paths: readonly string[]): Promise<void>\n guard: GuardLog\n /** Selectors hidden in screenshots and left out of every probe (ignore.ts). */\n ignore: readonly string[]\n close(): Promise<void>\n}\n\nexport interface SessionOptions {\n /** Persistent profile directory from `mushi-ux login`, or `--profile-dir` (a cached, signed-in profile); omit for a clean browser. */\n profileDir?: string\n /**\n * Browser build to open it with. 'chrome' opens a profile Google Chrome\n * created (playwright-cli's cached profiles) with the installed Chrome; the\n * bundled Chromium is older and may refuse or rewrite such a profile.\n */\n channel?: 'chrome' | 'chromium'\n headless?: boolean\n allow?: readonly AllowRule[]\n /** Extra selectors to ignore on top of DEFAULT_IGNORE. */\n ignore?: readonly string[]\n}\n\n/** Sums layout shifts not caused by input, from page start. */\nconst CLS_SCRIPT = `(() => {\n window.__mushiCls = 0\n try {\n new PerformanceObserver((list) => {\n for (const e of list.getEntries()) if (!e.hadRecentInput) window.__mushiCls += e.value\n }).observe({ type: 'layout-shift', buffered: true })\n } catch {}\n})()`\n\nexport async function openSession(opts: SessionOptions = {}): Promise<BrowserSession> {\n const headless = opts.headless ?? true\n let context: BrowserContext\n let closeBrowser: () => Promise<void>\n let browser: Browser\n // Playwright's docs say requests a Service Worker handles can bypass\n // context.route. Chromium on 1.61 routed them in a probe (Plan 021 §5), but\n // the guard must not depend on that: block Service Workers outright.\n const channel = opts.channel === 'chrome' ? { channel: 'chrome' as const } : {}\n if (opts.profileDir) {\n context = await chromium.launchPersistentContext(opts.profileDir, { headless, serviceWorkers: 'block', ...channel })\n // A persistent profile cannot spawn contexts: captures run in a second browser seeded from it.\n browser = await chromium.launch({ headless, ...channel })\n closeBrowser = async () => {\n await context.close()\n await browser.close()\n }\n } else {\n browser = await chromium.launch({ headless, ...channel })\n context = await browser.newContext({ serviceWorkers: 'block' })\n closeBrowser = () => browser.close()\n }\n const guard = await installGuard(context, opts.allow ?? [])\n await context.addInitScript({ content: CLS_SCRIPT })\n // The state every capture starts from; warmUp replaces it with a visited app.\n let seed = await context.storageState({ indexedDB: true })\n const warmUp = async (baseUrl: string, paths: readonly string[]) => {\n const page = await context.newPage()\n try {\n for (const p of paths) {\n await gotoPatiently(page, surfaceUrl(baseUrl, p)).catch(() => null)\n await settle(page).catch(() => undefined)\n }\n } finally {\n await page.close()\n }\n seed = await context.storageState({ indexedDB: true })\n }\n const freshContext = async () => {\n const fresh = await browser.newContext({ serviceWorkers: 'block', storageState: seed })\n await installGuard(fresh, opts.allow ?? [], guard)\n await fresh.addInitScript({ content: CLS_SCRIPT })\n return fresh\n }\n return { context, freshContext, warmUp, guard, ignore: ignoreList(opts.ignore), close: closeBrowser }\n}\n\n/**\n * Wait for the network to go quiet and the DOM to stop changing, both\n * bounded. Apps that hold a socket or poll never reach \"network idle\", so\n * that wait is capped short and the DOM-quiet wait does the real work.\n */\nexport async function settle(page: Page, quietMs = 400, maxMs = 5000): Promise<void> {\n await page.waitForLoadState('networkidle', { timeout: Math.min(maxMs, 2500) }).catch(() => {})\n await page\n .evaluate(\n ([quiet, max]) =>\n new Promise<void>((resolve) => {\n let timer = setTimeout(done, quiet)\n const stop = setTimeout(done, max)\n const mo = new MutationObserver(() => {\n clearTimeout(timer)\n timer = setTimeout(done, quiet)\n })\n mo.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true })\n function done() {\n mo.disconnect()\n clearTimeout(timer)\n clearTimeout(stop)\n resolve()\n }\n }),\n [quietMs, maxMs] as const,\n )\n .catch(() => {})\n await page.evaluate(() => document.fonts?.ready).catch(() => {})\n await waitForContent(page)\n}\n\n/**\n * Wait (up to `maxMs`) while the page shows a loading state: aria-busy, a\n * progress bar, or a spinning element covering most of the screen. An app\n * that boots behind a splash spinner was screenshotted as an empty page with\n * a spinner and \"measured\" as fine (glot.it /practice, 2026-10-06).\n */\nexport async function waitForContent(page: Page, maxMs = 20_000): Promise<void> {\n await page\n .waitForFunction(\n () => {\n const visible = (el: Element) => {\n const r = (el as HTMLElement).getBoundingClientRect()\n const s = getComputedStyle(el)\n return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'\n }\n const busy = [...document.querySelectorAll('[aria-busy=\"true\"], [role=\"progressbar\"], .animate-spin, .spinner, [class*=\"spinner\" i]')].some(visible)\n // Loading placeholders: skeleton classes, or a running skeleton/shimmer\n // animation (glot.it's Skeleton is marked only by `skeleton-wave`;\n // a regression re-shot of /words caught it mid-load, 2026-10-06).\n const skeleton =\n [...document.querySelectorAll('[class*=\"skeleton\" i], [class*=\"shimmer\" i], .animate-pulse, [data-skeleton]')].some(visible) ||\n (document.getAnimations?.() ?? []).some((a) => {\n const name = (a as CSSAnimation).animationName ?? ''\n const target = (a.effect as KeyframeEffect | null)?.target\n return /skeleton|shimmer|pulse|loading|placeholder/i.test(name) && !!target && visible(target)\n })\n if (skeleton) return false\n // Little text on the page means the real content has not arrived yet.\n const text = (document.body?.innerText ?? '').replace(/\\s+/g, ' ').trim()\n return !busy && text.length > 40\n },\n undefined,\n { timeout: maxMs, polling: 250 },\n )\n .catch(() => {})\n}\n\nexport async function replay(page: Page, steps: readonly ReplayStep[]): Promise<void> {\n for (const step of steps) {\n await page.locator(step.selector).first().click({ timeout: 5000 })\n await settle(page)\n }\n}\n\nexport function surfaceUrl(baseUrl: string, path: string): string {\n return new URL(path, baseUrl).toString()\n}\n\n/** A dev server compiling another route can hold a page for a minute; webpack often longer. */\nconst NAV_TIMEOUT_MS = 90_000\n\n/** A navigation another navigation replaced, or one that ran out of time. */\nconst RETRY_NAV_RE = /timeout|ERR_ABORTED|interrupted by another navigation/i\n\n/**\n * Navigate with a dev-server-sized timeout, and once more when the first try\n * times out (the route was compiling) or is replaced by the page's own reload\n * (a dev server's full reload after a slow compile). Playwright reports the\n * second case as ERR_ABORTED, or resolves to null with no error. Both cost\n * glot.it pages on 2026-10-06: home \"could not load\" under the 30 s default,\n * and /chat dropped with no message.\n */\nexport async function gotoPatiently(page: Page, url: string): Promise<Awaited<ReturnType<Page['goto']>>> {\n const go = () => page.goto(url, { waitUntil: 'domcontentloaded', timeout: NAV_TIMEOUT_MS })\n try {\n return (await go()) ?? (await go())\n } catch (err) {\n if (!RETRY_NAV_RE.test((err as Error).message)) throw err\n return go()\n }\n}\n\nexport interface Capture {\n png: Buffer\n probes: ProbeResult\n}\n\n/** Load one surface at one viewport, screenshot it, and measure it. */\nexport async function captureSurface(\n session: BrowserSession,\n baseUrl: string,\n surface: Pick<Surface, 'path' | 'steps'>,\n viewport: Viewport,\n): Promise<Capture> {\n const ctx = await session.freshContext()\n const page = await ctx.newPage()\n const consoleErrors: string[] = []\n page.on('console', (msg) => {\n if (msg.type() === 'error' && !isGuardNoise(msg.text()) && !isFrameworkNoise(msg.text())) consoleErrors.push(msg.text().slice(0, 300))\n })\n page.on('pageerror', (err) => consoleErrors.push(String(err.message).slice(0, 300)))\n try {\n await page.setViewportSize({ width: viewport.width, height: viewport.height })\n await gotoPatiently(page, surfaceUrl(baseUrl, surface.path))\n await settle(page)\n await replay(page, surface.steps)\n const png = await page.screenshot({\n fullPage: true,\n animations: 'disabled',\n caret: 'hide',\n style: ignoreStyle(session.ignore) || undefined,\n })\n const probes = await runProbes(page, consoleErrors, session.ignore)\n return { png, probes }\n } finally {\n await ctx.close()\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Hard rule of the loop: exploring and screenshotting an app never writes\n * to it. A localhost dev server often talks to a real backend, so one stray\n * \"Delete\" click or form submit during discovery would mutate real data.\n *\n * - Every request that is not GET / HEAD / OPTIONS is aborted unless it\n * matches the per-target allowlist (reads some apps make with POST, such as\n * PostgREST `rpc/` calls or GraphQL queries).\n * - Form submission is cancelled in the page itself.\n * - Discovery never clicks an element whose label reads as destructive.\n * - Service Workers are blocked where the context is created (capture.ts):\n * requests a worker handles never reach `context.route`.\n *\n * WebSockets are not routed: a Supabase Realtime socket only subscribes, and\n * table writes go through REST, which the route sees.\n */\n\nimport type { BrowserContext } from 'playwright'\n\nconst READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])\n\n/** `\"POST /rest/v1/rpc/*\"`, or a bare path glob meaning any method. */\nexport type AllowRule = string\n\nexport interface GuardLog {\n blocked: Array<{ method: string; url: string }>\n}\n\nfunction globToRegExp(glob: string): RegExp {\n const escaped = glob.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*').replace(/\\?/g, '.')\n return new RegExp(`^${escaped}$`)\n}\n\n/** Pure decision, exported for tests: may this request leave the browser? */\nexport function isRequestAllowed(method: string, url: string, allow: readonly AllowRule[]): boolean {\n const m = method.toUpperCase()\n if (READ_METHODS.has(m)) return true\n let path: string\n try {\n const u = new URL(url)\n path = u.pathname + u.search\n } catch {\n return false\n }\n return allow.some((rule) => {\n const space = rule.indexOf(' ')\n const ruleMethod = space > 0 ? rule.slice(0, space).toUpperCase() : null\n const ruleGlob = space > 0 ? rule.slice(space + 1).trim() : rule.trim()\n if (ruleMethod && ruleMethod !== m) return false\n return globToRegExp(ruleGlob).test(path)\n })\n}\n\nconst DESTRUCTIVE_RE =\n /\\b(delete|remove|destroy|erase|discard|revoke|disconnect|uninstall|archive|cancel (?:plan|subscription)|pay|purchase|buy|checkout|charge|send|submit|publish|merge|deploy|log ?out|sign ?out|reset)\\b/i\n\n/** Pure: should discovery refuse to click an element with this label? */\nexport function isDestructiveLabel(label: string): boolean {\n return DESTRUCTIVE_RE.test(label)\n}\n\n/**\n * Cancels form submission inside every page of the context, before any app\n * script runs. Covers submit events, `form.submit()` and `requestSubmit()`.\n */\nconst NO_SUBMIT_SCRIPT = `(() => {\n addEventListener('submit', (e) => { e.preventDefault(); e.stopImmediatePropagation() }, true)\n HTMLFormElement.prototype.submit = function () {}\n HTMLFormElement.prototype.requestSubmit = function () {}\n})()`\n\nexport async function installGuard(context: BrowserContext, allow: readonly AllowRule[], log: GuardLog = { blocked: [] }): Promise<GuardLog> {\n await context.addInitScript({ content: NO_SUBMIT_SCRIPT })\n await context.route('**/*', async (route) => {\n const req = route.request()\n if (isRequestAllowed(req.method(), req.url(), allow)) return route.continue()\n log.blocked.push({ method: req.method(), url: req.url() })\n return route.abort('blockedbyclient')\n })\n return log\n}\n\n/** Console text Chromium prints for a request the guard aborted. */\nexport function isGuardNoise(text: string): boolean {\n return /ERR_BLOCKED_BY_CLIENT/.test(text)\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Elements that are not the app's UI: dev-server overlays, build stamps, and\n * Mushi's own widget. They are hidden in screenshots and left out of every\n * measurement, so the agent is never sent to \"fix\" them. On glot.it the\n * agent spent an attempt raising the contrast of a dev-only build stamp\n * (2026-10-06).\n *\n * Add your own with `--ignore <selector>` (repeatable), or mark an element\n * with `data-mushi-ux-ignore`.\n */\n\nconst DEFAULT_IGNORE: readonly string[] = [\n // Mark anything yourself\n '[data-mushi-ux-ignore]',\n // Next.js dev overlay and indicators\n 'nextjs-portal',\n '[data-nextjs-toast]',\n '[data-nextjs-dev-tools-button]',\n '#__next-build-watcher',\n // Vite / webpack dev overlays\n 'vite-error-overlay',\n '#webpack-dev-server-client-overlay',\n // Build / version stamps shown only in dev or QA builds\n '[data-qa-build-stamp]',\n '[data-build-stamp]',\n // Mushi's own widget, rewards badge and consent banner (not the app's code)\n '#mushi-mushi-widget',\n '#mushi-tier-badge',\n '#mushi-consent-banner',\n]\n\n/**\n * A selector from the command line or the studio form that cannot break out\n * of the injected stylesheet. The browser still validates it: one it cannot\n * parse is skipped there (see probes.ts), never fatal.\n */\nexport function isSafeSelector(s: string): boolean {\n return s.length > 0 && s.length <= 200 && !/[{}<>;\\\\]/.test(s) && !/^[\\s,]|,\\s*$/.test(s)\n}\n\nexport function ignoreList(extra: readonly string[] = []): string[] {\n return [...new Set([...DEFAULT_IGNORE, ...extra.map((s) => s.trim()).filter(isSafeSelector)])]\n}\n\n/** CSS that hides ignored elements in a screenshot without moving anything else. */\nexport function ignoreStyle(selectors: readonly string[]): string {\n return selectors.length ? `${selectors.join(',\\n')} { visibility: hidden !important; }` : ''\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Objective checks run on every capture. A vision model's opinion of a\n * screenshot is unreliable (Baymard: 80% of GPT-4 audit suggestions were\n * wrong or wasted effort; UICrit: 13% of zero-shot critiques valid), so the\n * loop's accept/reject leans on these numbers, not on taste.\n *\n * Contrast comes from axe-core's `color-contrast` rule, which parses modern\n * colour syntax (oklch, color-mix) itself.\n */\n\nimport { AxeBuilder } from '@axe-core/playwright'\nimport type { Page } from 'playwright'\nimport type { AxeViolation, LayoutIssue, ProbeResult } from './types.js'\n\nconst AXE_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']\nconst MAX_TARGETS = 5\n\n/** The selectors this page's browser can parse; a bad one is dropped, not fatal. */\nasync function usableSelectors(page: Page, selectors: readonly string[]): Promise<string[]> {\n if (!selectors.length) return []\n return page.evaluate((list) => {\n return list.filter((sel) => {\n try {\n document.querySelector(sel)\n return true\n } catch {\n return false\n }\n })\n }, [...selectors])\n}\n\nexport async function runProbes(\n page: Page,\n consoleErrors: readonly string[],\n ignore: readonly string[] = [],\n): Promise<ProbeResult> {\n const skip = await usableSelectors(page, ignore)\n let builder = new AxeBuilder({ page }).withTags(AXE_TAGS)\n for (const sel of skip) builder = builder.exclude(sel)\n const axe = await builder\n .analyze()\n .then((r) =>\n r.violations.map(\n (v): AxeViolation => ({\n id: v.id,\n impact: v.impact ?? null,\n help: v.help,\n count: v.nodes.length,\n targets: v.nodes.slice(0, MAX_TARGETS).map((n) => n.target.join(' ')),\n }),\n ),\n )\n // No catch: an axe failure must fail the capture. Reading it as \"no\n // violations\" would make a broken after-shot look like an improvement.\n\n const layout = await page.evaluate((skipSelectors) => {\n const root = document.documentElement\n const overflowX = root.scrollWidth > root.clientWidth + 1\n const interactive = document.querySelectorAll(\n 'a[href], button, input:not([type=hidden]), select, textarea, [role=button], [role=link], [role=tab], [role=checkbox], [role=switch], [role=menuitem]',\n )\n let smallTargets = 0\n for (const el of Array.from(interactive)) {\n const style = getComputedStyle(el)\n if (style.visibility === 'hidden' || style.display === 'none') continue\n // Not the app's UI (dev overlays, build stamps, the Mushi widget).\n if (skipSelectors.some((sel) => el.closest(sel))) continue\n // Nothing to tap: the element ignores the pointer.\n if (style.pointerEvents === 'none') continue\n // WCAG 2.5.8 exempts links inside running text.\n if (el.tagName === 'A' && style.display === 'inline') continue\n const r = el.getBoundingClientRect()\n if (r.width === 0 || r.height === 0) continue\n // Visually hidden until focused (an sr-only skip link is 1x1 and clipped).\n const clipped = style.clip.startsWith('rect(0') || style.clipPath.startsWith('inset(50%')\n if (clipped || (r.width <= 1 && r.height <= 1)) continue\n if (r.width < 24 || r.height < 24) smallTargets++\n }\n const cls = (window as unknown as { __mushiCls?: number }).__mushiCls ?? 0\n return { overflowX, smallTargets, cls }\n }, skip)\n\n return {\n axe,\n overflowX: layout.overflowX,\n smallTargets: layout.smallTargets,\n consoleErrors: [...consoleErrors],\n cls: Math.round(layout.cls * 1000) / 1000,\n layout: await layoutIssues(page, skip),\n }\n}\n\nconst MAX_LAYOUT_ISSUES = 8\n/** A collision or overhang smaller than this is antialiasing or a border, not a bug. */\nconst LAYOUT_SLOP_PX = 4\n\n/**\n * Boxes a person sees collide or stick out, measured, not judged: in-flow\n * siblings drawn over each other, and controls that outgrow their container,\n * wrap past two lines or cut their own label off. The Mushi console's Apps\n * page had oversized, overflowing buttons and overlapping cards that no other\n * probe saw (2026-10-26). Deliberate overlap is skipped: positioned layers,\n * negative margins (avatar stacks), transforms, grid items placed in one cell,\n * scroll containers.\n */\nasync function layoutIssues(page: Page, skipSelectors: readonly string[]): Promise<LayoutIssue[]> {\n return page.evaluate(\n ({ skipSelectors, max, slop }) => {\n type Issue = { kind: 'overlap' | 'outgrows'; selector: string; detail: string }\n const out: Issue[] = []\n const seen = new Set<string>()\n const add = (kind: Issue['kind'], el: Element, detail: string) => {\n const selector = nameOf(el)\n if (seen.has(kind + selector) || out.filter((i) => i.kind === kind).length >= max) return\n seen.add(kind + selector)\n out.push({ kind, selector, detail })\n }\n function nameOf(el: Element): string {\n const id = el.id ? `#${el.id}` : ''\n const cls =\n typeof el.className === 'string'\n ? el.className.trim().split(/\\s+/).filter(Boolean).slice(0, 2).map((c) => `.${c}`).join('')\n : ''\n const text = (el.textContent ?? '').replace(/\\s+/g, ' ').trim().slice(0, 40)\n return `${el.tagName.toLowerCase()}${id}${cls}${text ? ` \"${text}\"` : ''}`\n }\n const px = (v: string) => parseFloat(v) || 0\n const skipped = (el: Element) => skipSelectors.some((sel) => el.closest(sel))\n const visible = (s: CSSStyleDeclaration, r: DOMRect) =>\n s.display !== 'none' && s.visibility !== 'hidden' && Number(s.opacity) > 0.05 && r.width > 0 && r.height > 0\n const placed = (s: CSSStyleDeclaration) =>\n (s.position === 'relative' && ((s.top !== 'auto' && px(s.top) !== 0) || (s.left !== 'auto' && px(s.left) !== 0))) ||\n s.transform !== 'none' ||\n px(s.marginLeft) < 0 ||\n px(s.marginTop) < 0 ||\n px(s.marginRight) < 0 ||\n px(s.marginBottom) < 0\n\n // Overlap: siblings in normal flow whose boxes intersect.\n for (const parent of Array.from(document.querySelectorAll('body *'))) {\n if (parent.childElementCount < 2 || skipped(parent)) continue\n const ps = getComputedStyle(parent)\n const kids = Array.from(parent.children)\n .slice(0, 40)\n .map((el) => ({ el, s: getComputedStyle(el), r: el.getBoundingClientRect() }))\n .filter(\n ({ el, s, r }) =>\n visible(s, r) &&\n (s.position === 'static' || s.position === 'relative') &&\n s.display !== 'inline' &&\n s.display !== 'contents' &&\n s.float === 'none' &&\n !placed(s) &&\n !skipped(el),\n )\n for (let i = 0; i < kids.length; i++) {\n for (let j = i + 1; j < kids.length; j++) {\n const a = kids[i]\n const b = kids[j]\n // Grid items put in one cell on purpose (a stack of layers).\n if (ps.display.includes('grid') && a.s.gridArea === b.s.gridArea && !a.s.gridArea.startsWith('auto')) continue\n const w = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left)\n const h = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top)\n if (w > slop && h > slop) {\n add('overlap', b.el, `overlaps ${nameOf(a.el)} by ${Math.round(w)}×${Math.round(h)}px`)\n }\n }\n }\n }\n\n // Outgrows: controls too big for where they sit.\n const controls = document.querySelectorAll('button, [role=button], a[href], input[type=submit], input[type=button], select')\n for (const el of Array.from(controls)) {\n if (skipped(el)) continue\n const s = getComputedStyle(el)\n const r = el.getBoundingClientRect()\n if (!visible(s, r) || s.position === 'fixed' || s.position === 'absolute' || placed(s)) continue\n if (el.tagName === 'A' && s.display === 'inline') continue\n let box: Element | null = el.parentElement\n while (box && getComputedStyle(box).display === 'contents') box = box.parentElement\n if (box) {\n const bs = getComputedStyle(box)\n const br = box.getBoundingClientRect()\n const scrolls = /auto|scroll/.test(bs.overflowX)\n if (!scrolls && br.width > 0) {\n const right = r.right - br.right\n const left = br.left - r.left\n if (right > slop || left > slop) {\n add('outgrows', el, `sticks ${Math.round(Math.max(right, left))}px out of its container (${Math.round(r.width)}px wide in ${Math.round(br.width)}px)`)\n continue\n }\n }\n }\n // Label-only buttons: everything inside flows inline (text, icons).\n const labelOnly = Array.from(el.querySelectorAll('*')).every(\n (c) => getComputedStyle(c).display.startsWith('inline') || c.closest('svg') !== null,\n )\n const text = (el.textContent ?? '').trim()\n if (!labelOnly || !text || el.tagName === 'A') continue\n if (s.overflow !== 'visible' && el.scrollWidth > el.clientWidth + 1 && s.textOverflow !== 'ellipsis') {\n add('outgrows', el, `label is cut off (needs ${el.scrollWidth}px, has ${el.clientWidth}px)`)\n continue\n }\n const line = px(s.lineHeight) || px(s.fontSize) * 1.2\n const inner = r.height - px(s.paddingTop) - px(s.paddingBottom) - px(s.borderTopWidth) - px(s.borderBottomWidth)\n const lines = line > 0 ? Math.round(inner / line) : 1\n if (lines > 2) add('outgrows', el, `label wraps to ${lines} lines (${Math.round(r.width)}×${Math.round(r.height)}px)`)\n }\n return out\n },\n { skipSelectors: [...skipSelectors], max: MAX_LAYOUT_ISSUES, slop: LAYOUT_SLOP_PX },\n )\n}\n\n/**\n * Console messages the framework's own dev tooling prints, which the app's\n * code cannot fix. On glot.it, React's key warning from Next 16's segment\n * explorer (\"Check the render method of `OuterLayoutRouter`\") sent the agent\n * into node_modules/next for a whole 15-minute attempt (2026-10-06).\n */\nconst FRAMEWORK_NOISE: readonly RegExp[] = [\n /Check the render method of `(OuterLayoutRouter|InnerLayoutRouter|LayoutRouter|SegmentViewNode|SegmentStateProvider|RenderFromTemplateContext|ScrollAndFocusHandler|HTTPAccessFallbackBoundary|RedirectBoundary|ErrorBoundaryHandler|AppRouter|HotReload|ReactDevOverlay)`/,\n /\\[(Fast Refresh|HMR)\\]/,\n /Download the React DevTools/,\n /_next\\/webpack-hmr|__nextjs_original-stack-frame/,\n]\n\nexport function isFrameworkNoise(message: string): boolean {\n return FRAMEWORK_NOISE.some((re) => re.test(message))\n}\n\nconst IMPACT_WEIGHT: Record<string, number> = { critical: 8, serious: 4, moderate: 2, minor: 1 }\n\n/**\n * One number per capture, lower is better. Used only to compare the same\n * surface before and after an agent run, never across surfaces.\n */\nexport function probePenalty(p: ProbeResult): number {\n const axe = p.axe.reduce((sum, v) => sum + (IMPACT_WEIGHT[v.impact ?? ''] ?? 1) * Math.max(1, v.count), 0)\n return axe + (p.overflowX ? 10 : 0) + p.smallTargets + p.consoleErrors.length * 5 + clsPenalty(p.cls) + (p.layout?.length ?? 0) * 3\n}\n\n/**\n * Layout shift up to 0.1 is \"good\" (web.dev/articles/cls), and a dev server\n * that just recompiled shifts a little on its own: glot.it's Home lost two\n * attempts to 0.085 and 0.05 (2026-10-06). Only shift past the threshold\n * counts.\n */\nexport const CLS_GOOD = 0.1\n\nfunction clsPenalty(cls: number): number {\n return cls > CLS_GOOD ? Math.ceil((cls - CLS_GOOD) * 20) : 0\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The local studio: start a run (agent, model, skill, pages) and watch it:\n * phase and progress, the burndown, every attempt's screenshot against the\n * baseline with a slider and a diff overlay, problem scores, and the agent's\n * output as it streams. Served on 127.0.0.1 only, behind a random token,\n * reading nothing but `.mushi/ux/` in the repo.\n *\n * `mushi-ux ui` opens it with the launcher; `mushi-ux run` and `open` open it\n * on one run, read-only.\n */\n\nimport { randomBytes } from 'node:crypto'\nimport type { EventEmitter } from 'node:events'\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport { basename, dirname, join, normalize, sep } from 'node:path'\nimport { z } from 'zod'\nimport { PNG } from 'pngjs'\nimport { attemptLogBase } from './agent-events.js'\nimport { changeRegions } from './image.js'\nimport { isSafeSelector } from './ignore.js'\nimport type { AgentAccount } from './launcher.js'\nimport type { LoopEvent } from './loop.js'\nimport type { ModelList } from './models.js'\nimport type { SkillListItem } from './skills.js'\nimport { loadState, type RunState } from './state.js'\nimport { STUDIO_PAGE } from './studio-page.js'\n\nexport interface Dashboard {\n url: string\n close(): Promise<void>\n}\n\nconst RUN_ID_RE = /^[0-9]{8}-[0-9]{6}-[a-z0-9]{4}$/\n\n/** Pure: resolve a requested shot path inside the run dir, or null if it escapes. */\nexport function safeShotPath(runDirPath: string, requested: string): string | null {\n if (!/^shots\\/[\\w./-]+\\.png$/.test(requested) || requested.includes('..')) return null\n const abs = normalize(join(runDirPath, requested))\n return abs.startsWith(normalize(runDirPath) + sep) ? abs : null\n}\n\n/** What the launcher form sends. Everything is checked here before a run starts. */\nexport const LaunchInput = z\n .object({\n agent: z.string().regex(/^[a-z][a-z-]{1,30}$/),\n model: z.string().max(200).regex(/^[A-Za-z0-9][A-Za-z0-9._:/?=&-]*$/).nullable().default(null),\n skill: z.string().max(300).nullable().default(null),\n devCommand: z.string().min(1).max(500),\n baseRef: z.string().max(200).regex(/^[\\w./@^~-]+$/).default('HEAD'),\n startPaths: z.array(z.string().regex(/^\\/[^\\s]{0,200}$/)).max(20).default([]),\n iterations: z.number().int().min(1).max(5).default(2),\n maxSurfaces: z.number().int().min(1).max(100).default(10),\n timeoutMin: z.number().int().min(1).max(60).default(10),\n judgeModel: z.string().max(120).nullable().default(null),\n /** Follow links from the start pages too; off visits only the pages named. */\n crawl: z.boolean().default(false),\n /** Plan each screen into small steps, then one step per attempt. */\n steps: z.boolean().default(false),\n /** A second model that may roll a kept step back (ADR 0021); null = measurements alone. */\n checkerModel: z.string().max(120).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/).nullable().default(null),\n checkerVia: z.enum(['claude-code', 'anthropic-api', 'cursor']).default('claude-code'),\n /** Keep edits with nothing visible, flagged for review. */\n keepInvisible: z.boolean().default(true),\n /** Selectors that are not the app's UI; added to DEFAULT_IGNORE. */\n ignore: z\n .array(z.string().trim().refine(isSafeSelector, 'Not a usable CSS selector (no { } < > ; or backslash, at most 200 characters).'))\n .max(20)\n .default([]),\n sync: z.boolean().default(false),\n })\n .strict()\nexport type LaunchInput = z.infer<typeof LaunchInput>\n\nexport interface StudioOptions {\n repoRoot: string\n /** Loop events of a run started outside the studio (`mushi-ux run`). */\n events?: EventEmitter\n /** Run to show first. */\n runId?: string\n /** Enables the launcher: starts a run and returns its id and event stream. */\n launch?: (input: LaunchInput) => Promise<{ runId: string; events: EventEmitter }>\n /** Stops a run this studio started; false when it is not running here. */\n stop?: (runId: string) => boolean\n /** Opens the finished run's PR (or adds it to its base branch's PR); rejects with the reason it cannot. */\n openPr?: (runId: string) => Promise<{ url: string; number: number; added: boolean }>\n /** Continues a stopped run with its saved settings; rejects with the reason it cannot. */\n resume?: (runId: string) => Promise<{ runId: string; events: EventEmitter }>\n listModels?: (agent: string) => Promise<ModelList>\n listSkills?: () => Promise<SkillListItem[]>\n /** One skill's hand-offs, for the launcher's \"next skill\" suggestions. */\n skillInfo?: (name: string) => Promise<{ name: string; related: string[] }>\n /** The account an agent would spend (null when the agent does not say). */\n account?: (agent: string) => Promise<AgentAccount | null>\n /** Launcher defaults: agents found, dev command guesses, refs, page suggestions. */\n options?: () => Promise<Record<string, unknown>>\n /** The Mushi console's base URL, for \"Review in console\" on mirrored runs. */\n consoleUrl?: string\n port?: number\n}\n\ninterface RunSummary {\n runId: string\n createdAt: string\n agent: string\n model: string | null\n skill: string | null\n phase: string | null\n total: number\n done: number\n}\n\nfunction summarize(s: RunState): RunSummary {\n const finished = new Set(['accepted', 'reverted', 'skipped', 'regressed', 'blocked'])\n return {\n runId: s.runId,\n createdAt: s.createdAt,\n agent: s.agent,\n model: s.model,\n skill: s.skill?.name ?? null,\n phase: s.phase ?? null,\n total: s.surfaces.length,\n done: s.surfaces.filter((x) => finished.has(x.status)).length,\n }\n}\n\nasync function readBody(req: IncomingMessage, limit = 64_000): Promise<unknown> {\n let size = 0\n const chunks: Buffer[] = []\n for await (const chunk of req) {\n size += (chunk as Buffer).length\n if (size > limit) throw new Error('Request too large')\n chunks.push(chunk as Buffer)\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')\n}\n\nexport async function startStudio(opts: StudioOptions): Promise<Dashboard> {\n const token = randomBytes(16).toString('hex')\n const uxDir = join(opts.repoRoot, '.mushi', 'ux')\n const clients = new Set<ServerResponse>()\n let active: { runId: string; events: EventEmitter } | null = null\n const send = (payload: unknown) => {\n const data = `data: ${JSON.stringify(payload)}\\n\\n`\n for (const res of clients) res.write(data)\n }\n const subscribe = (runId: string, events: EventEmitter) => {\n const onEvent = (e: LoopEvent) => send({ ...e, runId })\n events.on('event', onEvent)\n return () => events.off('event', onEvent)\n }\n const unsubscribers: Array<() => void> = []\n if (opts.events && opts.runId) {\n active = { runId: opts.runId, events: opts.events }\n unsubscribers.push(subscribe(opts.runId, opts.events))\n }\n\n const json = (res: ServerResponse, status: number, body: unknown) => {\n res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n }\n const runDirOf = (runId: string | null) => (runId && RUN_ID_RE.test(runId) ? join(uxDir, runId) : null)\n\n const server: Server = createServer((req, res) => {\n const url = new URL(req.url ?? '/', 'http://127.0.0.1')\n if (url.searchParams.get('t') !== token) {\n res.writeHead(403, { 'content-type': 'text/plain' })\n return res.end('Open the link printed by mushi-ux; it carries the access token.')\n }\n const handle = async () => {\n if (req.method === 'GET' && url.pathname === '/') {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })\n return res.end(STUDIO_PAGE)\n }\n if (req.method === 'GET' && url.pathname === '/api/meta') {\n return json(res, 200, { launcher: Boolean(opts.launch), canStop: Boolean(opts.stop), canResume: Boolean(opts.resume), canOpenPr: Boolean(opts.openPr), consoleUrl: opts.consoleUrl ?? null, active: active?.runId ?? null, initial: opts.runId ?? null, repo: basename(opts.repoRoot) })\n }\n if (req.method === 'GET' && url.pathname === '/api/runs') {\n const ids = existsSync(uxDir) ? readdirSync(uxDir).filter((d) => RUN_ID_RE.test(d)) : []\n const runs = ids\n .map((id) => loadState(join(uxDir, id)))\n .filter((s): s is RunState => s !== null)\n .map(summarize)\n .sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n return json(res, 200, { runs })\n }\n if (req.method === 'GET' && url.pathname === '/api/state') {\n const dir = runDirOf(url.searchParams.get('run'))\n return json(res, 200, dir ? loadState(dir) : null)\n }\n if (req.method === 'GET' && url.pathname === '/api/log') {\n const dir = runDirOf(url.searchParams.get('run'))\n const file = dir ? join(dir, 'run.log') : null\n const lines = file && existsSync(file) ? readFileSync(file, 'utf8').split('\\n').filter(Boolean).slice(-400) : []\n return json(res, 200, { lines })\n }\n if (req.method === 'GET' && url.pathname === '/api/steps') {\n // The agent's readable steps for one screen's attempt (latest when\n // attempt is absent), so a reloaded page still shows what it is doing.\n const dir = runDirOf(url.searchParams.get('run'))\n const key = url.searchParams.get('surface') ?? ''\n const n = url.searchParams.get('attempt')\n if (!dir || !/^[\\w.:-]{1,160}$/.test(key) || (n !== null && !/^[0-9]{1,2}$/.test(n))) return json(res, 400, { error: 'bad request' })\n const agentDir = join(dir, 'agent')\n const prefix = attemptLogBase(key, 0).slice(0, -1)\n const attempts = existsSync(agentDir)\n ? readdirSync(agentDir)\n .map((f) => (f.startsWith(prefix) && f.endsWith('.steps.log') ? Number(f.slice(prefix.length, -'.steps.log'.length)) : NaN))\n .filter((a) => Number.isInteger(a) && a > 0)\n : []\n const attempt = n !== null ? Number(n) : attempts.length ? Math.max(...attempts) : null\n const file = attempt !== null && attempts.includes(attempt) ? join(agentDir, `${prefix}${attempt}.steps.log`) : null\n const lines = file ? readFileSync(file, 'utf8').split('\\n').filter(Boolean).slice(-200) : []\n return json(res, 200, { attempt, lines })\n }\n if (req.method === 'GET' && url.pathname === '/api/events') {\n res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })\n res.write(': connected\\n\\n')\n clients.add(res)\n req.on('close', () => clients.delete(res))\n return\n }\n if (req.method === 'GET' && url.pathname === '/shot') {\n const dir = runDirOf(url.searchParams.get('run'))\n const abs = dir ? safeShotPath(dir, url.searchParams.get('p') ?? '') : null\n if (!abs || !existsSync(abs)) {\n res.writeHead(404)\n return res.end()\n }\n res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'max-age=3600' })\n return res.end(readFileSync(abs))\n }\n // Change areas from a saved diff image, for attempts recorded before they were stored.\n if (req.method === 'GET' && url.pathname === '/api/changes') {\n const dir = runDirOf(url.searchParams.get('run'))\n const abs = dir ? safeShotPath(dir, url.searchParams.get('p') ?? '') : null\n if (!abs || !existsSync(abs)) return json(res, 404, { error: 'No such diff image' })\n const png = PNG.sync.read(readFileSync(abs))\n return json(res, 200, { width: png.width, height: png.height, boxes: changeRegions(png) })\n }\n if (req.method === 'GET' && url.pathname === '/api/options') {\n return json(res, 200, opts.options ? await opts.options() : {})\n }\n if (req.method === 'GET' && url.pathname === '/api/models') {\n const agent = url.searchParams.get('agent') ?? ''\n if (!opts.listModels || !/^[a-z][a-z-]{1,30}$/.test(agent)) return json(res, 400, { error: 'Unknown agent' })\n return json(res, 200, await opts.listModels(agent))\n }\n if (req.method === 'GET' && url.pathname === '/api/skill') {\n const name = url.searchParams.get('name') ?? ''\n if (!/^[a-z0-9][a-z0-9-]{0,80}$/.test(name) || !opts.skillInfo) return json(res, 400, { error: 'Unknown skill' })\n return json(res, 200, await opts.skillInfo(name).catch(() => ({ name, related: [] })))\n }\n if (req.method === 'GET' && url.pathname === '/api/account') {\n const agent = url.searchParams.get('agent') ?? ''\n if (!/^[a-z][a-z-]{1,30}$/.test(agent)) return json(res, 400, { error: 'Unknown agent' })\n return json(res, 200, { account: opts.account ? await opts.account(agent).catch(() => null) : null })\n }\n if (req.method === 'GET' && url.pathname === '/api/skills') {\n if (!opts.listSkills) return json(res, 200, { skills: [] })\n const skills = await opts.listSkills().catch((err: Error) => {\n throw new Error(`Could not list skills: ${err.message}`)\n })\n return json(res, 200, { skills })\n }\n const stopMatch = url.pathname.match(/^\\/api\\/runs\\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\\/stop$/)\n if (req.method === 'POST' && stopMatch) {\n if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 415, { error: 'JSON only' })\n const origin = req.headers.origin\n if (origin && origin !== `http://127.0.0.1:${(server.address() as AddressInfo).port}`) return json(res, 403, { error: 'Wrong origin' })\n if (!opts.stop?.(stopMatch[1])) return json(res, 409, { error: 'That run is not running in this studio.' })\n return json(res, 202, { stopping: true })\n }\n const prMatch = url.pathname.match(/^\\/api\\/runs\\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\\/pr$/)\n if (req.method === 'POST' && prMatch) {\n if (!opts.openPr) return json(res, 404, { error: 'This view is read-only. Start the studio with `mushi-ux ui`.' })\n if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 415, { error: 'JSON only' })\n const origin = req.headers.origin\n if (origin && origin !== `http://127.0.0.1:${(server.address() as AddressInfo).port}`) return json(res, 403, { error: 'Wrong origin' })\n const pr = await opts.openPr(prMatch[1]).catch((err: Error) => err)\n if (pr instanceof Error) return json(res, 409, { error: pr.message })\n return json(res, 201, pr)\n }\n const resumeMatch = url.pathname.match(/^\\/api\\/runs\\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\\/resume$/)\n if (req.method === 'POST' && resumeMatch) {\n if (!opts.resume) return json(res, 404, { error: 'This view is read-only. Start the studio with `mushi-ux ui`.' })\n if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 415, { error: 'JSON only' })\n const origin = req.headers.origin\n if (origin && origin !== `http://127.0.0.1:${(server.address() as AddressInfo).port}`) return json(res, 403, { error: 'Wrong origin' })\n if (active && active.runId !== resumeMatch[1]) {\n const state = loadState(join(uxDir, active.runId))\n if (state && !['done', 'failed'].includes(state.phase ?? '')) return json(res, 409, { error: `Run ${active.runId} is still going. Stop it first.` })\n }\n // Not resumable (still alive elsewhere, finished, from before saved settings): say why, as a 409.\n const started = await opts.resume(resumeMatch[1]).catch((err: Error) => err)\n if (started instanceof Error) return json(res, 409, { error: started.message })\n active = started\n unsubscribers.push(subscribe(started.runId, started.events))\n send({ type: 'started', runId: started.runId })\n return json(res, 202, { runId: started.runId })\n }\n if (req.method === 'POST' && url.pathname === '/api/runs') {\n if (!opts.launch) return json(res, 404, { error: 'This view is read-only. Start the studio with `mushi-ux ui`.' })\n // A form post from another site cannot set this header or read the token.\n if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) return json(res, 415, { error: 'JSON only' })\n const origin = req.headers.origin\n if (origin && origin !== `http://127.0.0.1:${(server.address() as AddressInfo).port}`) return json(res, 403, { error: 'Wrong origin' })\n if (active) {\n const state = loadState(join(uxDir, active.runId))\n if (state && !['done', 'failed'].includes(state.phase ?? '')) return json(res, 409, { error: `Run ${active.runId} is still going.` })\n }\n const parsed = LaunchInput.safeParse(await readBody(req))\n if (!parsed.success) return json(res, 400, { error: parsed.error.issues[0]?.message ?? 'Invalid settings' })\n const started = await opts.launch(parsed.data)\n active = started\n unsubscribers.push(subscribe(started.runId, started.events))\n send({ type: 'started', runId: started.runId })\n return json(res, 201, { runId: started.runId })\n }\n res.writeHead(404)\n res.end()\n }\n handle().catch((err: Error) => {\n if (!res.headersSent) json(res, 500, { error: err.message.slice(0, 500) })\n else res.end()\n })\n })\n await new Promise<void>((r) => server.listen(opts.port ?? 0, '127.0.0.1', r))\n const { port: bound } = server.address() as AddressInfo\n const initial = opts.runId ? `&run=${opts.runId}` : ''\n return {\n url: `http://127.0.0.1:${bound}/?t=${token}${initial}`,\n close: () =>\n new Promise<void>((r) => {\n for (const off of unsubscribers) off()\n for (const res of clients) res.end()\n server.close(() => r())\n }),\n }\n}\n\n/** One run, read-only (used by `mushi-ux run` and `open`). `dir` is `<repo>/.mushi/ux/<runId>`. */\nexport async function startDashboard(dir: string, events?: EventEmitter, port = 0): Promise<Dashboard> {\n const repoRoot = dirname(dirname(dirname(dir)))\n return startStudio({ repoRoot, events, runId: basename(dir), port })\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Turns an agent's stream-json lines into short steps a person can follow:\n * \"Read app/page.tsx\", \"Edit globals.css\", \"Run pnpm lint\", or what the\n * agent said. The raw stream is still saved per attempt for debugging.\n *\n * Formats, as documented on 2026-10-06:\n * - Cursor CLI (cursor.com/docs/cli/reference/output-format): `assistant`\n * messages, `tool_call` started/completed keyed `<name>ToolCall`, a final\n * `result`. Only `started` is shown, so each call appears once.\n * - Claude Code: `assistant` messages whose content holds `text` and\n * `tool_use` blocks; `user` tool results are skipped.\n * - Codex `exec --json`: `item.started` / `item.completed` with\n * `command_execution`, `file_change` and `agent_message` items.\n * Unknown events are dropped; a line that is not JSON (stderr, the cloud\n * adapter's status lines) is shown as is.\n */\n\ntype AgentStepKind = 'say' | 'read' | 'edit' | 'run' | 'search' | 'tool' | 'done' | 'error'\n\nexport interface AgentStep {\n kind: AgentStepKind\n text: string\n /** File the step read or changed, when it names one. */\n path?: string\n}\n\nconst MAX_TEXT = 300\n\nconst clip = (s: string, n = MAX_TEXT) => {\n const one = s.replace(/\\s+/g, ' ').trim()\n return one.length > n ? `${one.slice(0, n - 1)}…` : one\n}\n\ntype Json = Record<string, unknown>\nconst isObj = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)\n\n/**\n * Path relative to the worktree when the agent gave an absolute one.\n * @internal Exported for tests only.\n */\nexport function shortPath(p: string, cwd?: string): string {\n const norm = p.replace(/\\\\/g, '/')\n if (cwd) {\n const base = cwd.replace(/\\\\/g, '/').replace(/\\/$/, '') + '/'\n if (norm.toLowerCase().startsWith(base.toLowerCase())) return norm.slice(base.length)\n }\n return norm\n}\n\nconst EDIT_TOOLS = /^(write|edit|multiedit|strreplace|str_replace|searchreplace|applypatch|apply_patch|delete|notebookedit|create)/i\nconst READ_TOOLS = /^(read|view|ls|list|readfile|readlints)/i\nconst SEARCH_TOOLS = /^(grep|glob|search|find|codebasesearch|semanticsearch|websearch|webfetch)/i\nconst RUN_TOOLS = /^(shell|bash|run|terminal|exec|command)/i\n\n/** One tool call, from its name and arguments, in any of the three formats. */\nfunction describeTool(name: string, args: Json, cwd?: string): AgentStep {\n const path = str(args.path) ?? str(args.file_path) ?? str(args.filePath) ?? str(args.target_file) ?? str(args.notebook_path)\n const command = str(args.command) ?? (Array.isArray(args.command) ? args.command.join(' ') : undefined)\n const pattern = str(args.pattern) ?? str(args.query) ?? str(args.globPattern) ?? str(args.glob_pattern) ?? str(args.url)\n const label = name.replace(/ToolCall$/, '')\n const p = path ? shortPath(path, cwd) : undefined\n // The kind already says what happened (\"[edit] app/page.tsx\"), so the text is just the object.\n if (EDIT_TOOLS.test(label)) return { kind: 'edit', text: `${p ?? '(a file)'}${/^delete/i.test(label) ? ' (deleted)' : ''}`, path: p }\n if (RUN_TOOLS.test(label) && command) return { kind: 'run', text: clip(command, 160) }\n if (SEARCH_TOOLS.test(label)) return { kind: 'search', text: clip(pattern ?? p ?? label, 160) }\n if (READ_TOOLS.test(label)) return { kind: 'read', text: p ?? (clip(pattern ?? '', 160) || '(a file)'), path: p }\n return { kind: 'tool', text: clip(`${label}${p ? ` ${p}` : pattern ? ` ${pattern}` : ''}`, 160) }\n}\n\nfunction textOf(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content\n .filter((c): c is Json => isObj(c) && c.type === 'text')\n .map((c) => str(c.text) ?? '')\n .join(' ')\n}\n\nfunction parseArgs(raw: unknown): Json {\n if (isObj(raw)) return raw\n if (typeof raw === 'string') {\n try {\n const v = JSON.parse(raw) as unknown\n return isObj(v) ? v : {}\n } catch {\n return {}\n }\n }\n return {}\n}\n\n/** The steps one line holds (a Claude Code message can hold several), or none. */\nexport function describeAgentLine(line: string, cwd?: string): AgentStep[] {\n const trimmed = line.trim()\n if (!trimmed) return []\n if (!trimmed.startsWith('{')) return [{ kind: 'say', text: clip(trimmed) }]\n let ev: Json\n try {\n const v = JSON.parse(trimmed) as unknown\n if (!isObj(v)) return []\n ev = v\n } catch {\n return [{ kind: 'say', text: clip(trimmed) }]\n }\n const type = str(ev.type)\n\n if (type === 'system' && ev.subtype === 'init') {\n return [{ kind: 'tool', text: `Started${str(ev.model) ? ` (${ev.model})` : ''}` }]\n }\n if (type === 'assistant' && isObj(ev.message)) {\n // Cursor partial-output flushes repeat text already shown.\n if (ev.model_call_id !== undefined) return []\n const content = ev.message.content\n const steps: AgentStep[] = []\n const said = clip(textOf(content))\n if (said) steps.push({ kind: 'say', text: said })\n if (Array.isArray(content)) {\n for (const c of content) {\n if (isObj(c) && c.type === 'tool_use' && str(c.name)) steps.push(describeTool(c.name as string, parseArgs(c.input), cwd))\n }\n }\n return steps\n }\n if (type === 'tool_call') {\n if (ev.subtype !== 'started' || !isObj(ev.tool_call)) return []\n const [key, body] = Object.entries(ev.tool_call)[0] ?? []\n if (!key || !isObj(body)) return []\n if (key === 'function') return [describeTool(str(body.name) ?? 'tool', parseArgs(body.arguments), cwd)]\n return [describeTool(key, parseArgs(body.args), cwd)]\n }\n if (type === 'result') {\n if (ev.is_error === true || (str(ev.subtype) && ev.subtype !== 'success')) {\n return [{ kind: 'error', text: clip(str(ev.result) ?? str(ev.error) ?? `Finished with ${String(ev.subtype)}`) }]\n }\n return [{ kind: 'done', text: 'Finished' }]\n }\n // Codex exec --json\n if ((type === 'item.started' || type === 'item.completed') && isObj(ev.item)) {\n const item = ev.item\n if (item.type === 'command_execution' && type === 'item.started' && str(item.command)) {\n return [{ kind: 'run', text: clip(item.command as string, 160) }]\n }\n if (item.type === 'file_change' && type === 'item.completed' && Array.isArray(item.changes)) {\n return item.changes\n .filter((c): c is Json => isObj(c) && !!str(c.path))\n .map((c) => {\n const p = shortPath(c.path as string, cwd)\n return { kind: 'edit' as const, text: p, path: p }\n })\n }\n if (item.type === 'agent_message' && type === 'item.completed' && str(item.text)) {\n return [{ kind: 'say', text: clip(item.text as string) }]\n }\n return []\n }\n if (type === 'error') return [{ kind: 'error', text: clip(str(ev.message) ?? 'Error') }]\n return []\n}\n\n/**\n * Per-attempt files under `<run>/agent/`: `<base>.steps.log` gets one\n * readable step per line as the agent works (the studio reads its tail\n * after a reload), `<base>.log` the raw output when the attempt ends.\n */\nexport function attemptLogBase(surfaceKey: string, attempt: number): string {\n return `${surfaceKey.replace(/[^\\w.-]+/g, '_')}-${attempt}`\n}\n\n/** The session id a stream-json run reports (Cursor and Claude Code put it on every event), or null. */\nexport function sessionIdOf(stdout: string): string | null {\n for (const line of stdout.split(/\\r?\\n/)) {\n if (!line.startsWith('{')) continue\n try {\n const id = (JSON.parse(line) as { session_id?: unknown }).session_id\n if (typeof id === 'string' && /^[\\w-]{6,80}$/.test(id)) return id\n } catch {\n /* not JSON */\n }\n }\n return null\n}\n\nconst ICON: Record<AgentStepKind, string> = {\n say: '›',\n read: 'read',\n edit: 'edit',\n run: 'run',\n search: 'find',\n tool: 'tool',\n done: 'done',\n error: 'error',\n}\n\n/** One line for the live log: the kind, then the text. */\nexport function formatStep(step: AgentStep): string {\n return step.kind === 'say' ? `› ${step.text}` : `[${ICON[step.kind]}] ${step.text}`\n}\n","// SPDX-License-Identifier: MIT\n/**\n * PNG helpers: decode, pad two captures to one size, pixel diff, and a\n * difference hash (dHash) for \"is this the same screen\" checks. No native\n * image library, so the package installs anywhere Node does.\n */\n\nimport pixelmatch from 'pixelmatch'\nimport { PNG } from 'pngjs'\n\nfunction decodePng(buf: Buffer): PNG {\n return PNG.sync.read(buf)\n}\n\nfunction encodePng(png: PNG): Buffer {\n return PNG.sync.write(png)\n}\n\n/** Copy `src` onto a white canvas of `width`×`height`. */\nfunction padTo(src: PNG, width: number, height: number): PNG {\n if (src.width === width && src.height === height) return src\n const out = new PNG({ width, height })\n out.data.fill(255)\n PNG.bitblt(src, out, 0, 0, Math.min(src.width, width), Math.min(src.height, height), 0, 0)\n return out\n}\n\nexport interface PixelDiff {\n /** Share of pixels that differ, 0..1, over the larger of the two sizes. */\n ratio: number\n changedPixels: number\n /**\n * Changed pixels over the \"before\" image's content pixels (those unlike\n * its background). A shifted paragraph on a mostly blank page is a small\n * share of the canvas but a large share of what is on it.\n */\n contentRatio: number\n width: number\n height: number\n /** Red-on-grey overlay of the changed pixels. */\n diffPng: Buffer\n /** Where the change is, largest first, so a viewer can zoom to it. */\n regions: ChangeRegion[]\n}\n\nexport interface ChangeRegion {\n x: number\n y: number\n w: number\n h: number\n}\n\n/** pixelmatch paints a real difference pure red (anti-aliasing is yellow, ignored). */\nfunction isDiffPixel(d: Uint8Array | Buffer, i: number): boolean {\n return d[i] === 255 && d[i + 1] === 0 && d[i + 2] === 0\n}\n\n/**\n * Pure: boxes around the changed pixels of a pixelmatch output. Changed pixels\n * are counted on a grid of `cell`-px squares; touching cells form one region;\n * each region is padded so a crop shows context. At most `max`, largest first.\n * A small change (a checkbox, a moved link) on a tall page is a few percent\n * of the pixels, which a full-size side by side hides.\n */\nexport function changeRegions(diff: { width: number; height: number; data: Uint8Array | Buffer }, cell = 16, max = 4, pad = 24): ChangeRegion[] {\n const cols = Math.ceil(diff.width / cell)\n const rows = Math.ceil(diff.height / cell)\n const hit = new Uint8Array(cols * rows)\n for (let y = 0; y < diff.height; y++) {\n for (let x = 0; x < diff.width; x++) {\n if (isDiffPixel(diff.data, (y * diff.width + x) * 4)) hit[Math.floor(y / cell) * cols + Math.floor(x / cell)] = 1\n }\n }\n const seen = new Uint8Array(cols * rows)\n const boxes: Array<ChangeRegion & { cells: number }> = []\n for (let start = 0; start < hit.length; start++) {\n if (!hit[start] || seen[start]) continue\n let minC = cols, minR = rows, maxC = 0, maxR = 0, cells = 0\n const stack = [start]\n seen[start] = 1\n while (stack.length) {\n const i = stack.pop() as number\n const c = i % cols\n const r = Math.floor(i / cols)\n cells++\n minC = Math.min(minC, c); maxC = Math.max(maxC, c); minR = Math.min(minR, r); maxR = Math.max(maxR, r)\n // 8-neighbours, and one empty cell of gap still joins (a line of text with spaces).\n for (let dr = -2; dr <= 2; dr++) {\n for (let dc = -2; dc <= 2; dc++) {\n const rr = r + dr\n const cc = c + dc\n if (rr < 0 || cc < 0 || rr >= rows || cc >= cols) continue\n const j = rr * cols + cc\n if (hit[j] && !seen[j]) {\n seen[j] = 1\n stack.push(j)\n }\n }\n }\n }\n const x = Math.max(0, minC * cell - pad)\n const y = Math.max(0, minR * cell - pad)\n boxes.push({ x, y, w: Math.min(diff.width, (maxC + 1) * cell + pad) - x, h: Math.min(diff.height, (maxR + 1) * cell + pad) - y, cells })\n }\n return boxes\n .sort((a, b) => b.w * b.h - a.w * a.h)\n .slice(0, max)\n .map(({ x, y, w, h }) => ({ x, y, w, h }))\n}\n\nexport function pixelDiff(before: Buffer, after: Buffer, threshold = 0.1): PixelDiff {\n const a = decodePng(before)\n const b = decodePng(after)\n const width = Math.max(a.width, b.width)\n const height = Math.max(a.height, b.height)\n const pa = padTo(a, width, height)\n const pb = padTo(b, width, height)\n const out = new PNG({ width, height })\n const changedPixels = pixelmatch(pa.data, pb.data, out.data, width, height, { threshold })\n const ink = contentPixels(a)\n return {\n ratio: changedPixels / (width * height),\n changedPixels,\n contentRatio: changedPixels / Math.max(ink, 1),\n width,\n height,\n diffPng: encodePng(out),\n regions: changedPixels ? changeRegions(out) : [],\n }\n}\n\n/**\n * Keep the top `maxHeight` px of a capture. Full-page shots of long pages\n * would be downscaled by a vision model until text is unreadable; the top\n * of the page is what the judge can actually see.\n */\nexport function cropTop(buf: Buffer, maxHeight: number): Buffer {\n const src = decodePng(buf)\n if (src.height <= maxHeight) return buf\n const out = new PNG({ width: src.width, height: maxHeight })\n PNG.bitblt(src, out, 0, 0, src.width, maxHeight, 0, 0)\n return encodePng(out)\n}\n\n/** Share of pixels that differ visibly from the background colour: near 0 is a blank screen. */\nexport function contentShare(buf: Buffer): number {\n const png = decodePng(buf)\n const total = png.width * png.height\n return total > 0 ? contentPixels(png) / total : 0\n}\n\n/** Pixels that differ visibly from the image's top-left (background) colour. */\nfunction contentPixels(png: PNG): number {\n const [r0, g0, b0] = [png.data[0], png.data[1], png.data[2]]\n let n = 0\n for (let i = 0; i < png.data.length; i += 4) {\n if (Math.abs(png.data[i] - r0) + Math.abs(png.data[i + 1] - g0) + Math.abs(png.data[i + 2] - b0) > 24) n++\n }\n return n\n}\n\n/**\n * 64-bit difference hash: shrink to 9×8 greyscale by box averaging, then one\n * bit per \"left pixel brighter than right\". Near-identical screens land\n * within a few bits of each other. Returned as 16 hex chars.\n */\nexport function dHash(buf: Buffer): string {\n const png = decodePng(buf)\n const cols = 9\n const rows = 8\n const grey: number[] = []\n for (let r = 0; r < rows; r++) {\n const y0 = Math.floor((r * png.height) / rows)\n const y1 = Math.max(y0 + 1, Math.floor(((r + 1) * png.height) / rows))\n for (let c = 0; c < cols; c++) {\n const x0 = Math.floor((c * png.width) / cols)\n const x1 = Math.max(x0 + 1, Math.floor(((c + 1) * png.width) / cols))\n let sum = 0\n let n = 0\n for (let y = y0; y < y1; y++) {\n for (let x = x0; x < x1; x++) {\n const i = (y * png.width + x) * 4\n sum += 0.299 * png.data[i] + 0.587 * png.data[i + 1] + 0.114 * png.data[i + 2]\n n++\n }\n }\n grey.push(sum / n)\n }\n }\n let hex = ''\n for (let r = 0; r < rows; r++) {\n let byte = 0\n for (let c = 0; c < cols - 1; c++) {\n byte = (byte << 1) | (grey[r * cols + c] > grey[r * cols + c + 1] ? 1 : 0)\n }\n hex += byte.toString(16).padStart(2, '0')\n }\n return hex\n}\n\nexport function hammingHex(a: string, b: string): number {\n let d = 0\n for (let i = 0; i < Math.min(a.length, b.length); i += 2) {\n let x = parseInt(a.slice(i, i + 2), 16) ^ parseInt(b.slice(i, i + 2), 16)\n while (x) {\n d += x & 1\n x >>= 1\n }\n }\n return d\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Run state on disk: `.mushi/ux/<runId>/state.json` plus the PNGs beside it.\n * Written atomically (temp file + rename) after every step, so a crashed or\n * interrupted run resumes where it stopped.\n */\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { CheckerVerdict } from './checker.js'\nimport type { JudgeVerdict } from './judge.js'\nimport type { RunPullRequest } from './pr.js'\nimport type { ProbeResult, Surface } from './types.js'\n\nexport type SurfaceStatus =\n | 'pending'\n | 'baseline'\n | 'iterating'\n | 'accepted'\n | 'reverted'\n | 'skipped'\n | 'regressed'\n | 'blocked'\n\nexport interface ShotRef {\n /** PNG path relative to the run directory. */\n png: string\n probes: ProbeResult\n penalty: number\n}\n\nexport interface IterationRecord {\n n: number\n agent: string\n model: string | null\n startedAt: string\n durationMs: number\n outcome: 'accepted' | 'rejected' | 'agent_failed' | 'capture_failed' | 'no_change'\n reason: string\n commitSha: string | null\n /** Changed-pixel share per viewport, before vs after. */\n pixelDiff: Record<string, number>\n after: Record<string, ShotRef>\n diffPng: Record<string, string>\n /**\n * Where this attempt changed the screen, per viewport, against the screen\n * before it (the last kept state): image size and up to four boxes.\n */\n changes?: Record<string, { width: number; height: number; boxes: Array<{ x: number; y: number; w: number; h: number }> }>\n logTail: string\n /** agent_failed because the time box ran out (another attempt may still succeed). */\n timedOut?: boolean\n /** Steps mode: the plan step this attempt worked on. */\n step?: string\n /** Kept without a visible change: a person should read the diff (ADR 0021). */\n needsReview?: boolean\n /** The second model's review of a kept step (ADR 0021). */\n checker?: CheckerVerdict\n}\n\n/** One small, separate improvement from a screen's plan; each gets its own attempt. */\nexport interface PlanStep {\n text: string\n status: 'pending' | 'done' | 'skipped' | 'failed'\n /** The attempt that worked on it. */\n attempt?: number\n reason?: string\n}\n\nexport interface SurfaceState {\n /** Steps mode: the screen's plan, made before any edit; null when planning produced none. */\n /** `session`: the agent session that planned, resumed by each step so it keeps what it read. */\n plan?: { steps: PlanStep[]; session?: string | null } | null\n surface: Surface\n status: SurfaceStatus\n /** Why it is blocked / skipped / regressed, in a sentence. */\n note: string | null\n baseline: Record<string, ShotRef>\n iterations: IterationRecord[]\n /** Final pairwise review per viewport; advisory only. */\n judge?: JudgeVerdict[]\n}\n\n/** Where the run is, for the live views. */\nexport type RunPhase = 'starting' | 'worktree' | 'install' | 'dev-server' | 'mapping' | 'working' | 'reviewing' | 'done' | 'failed'\n\n/** Live progress of the attempt in flight, refreshed at least every HEARTBEAT_MS. */\ninterface CurrentAttempt {\n surface: string\n attempt: number\n startedAt: string\n /** The agent is stopped after this long. */\n timeoutMs?: number\n /** Steps the agent took so far (reads, edits, commands, messages). */\n steps?: number\n /** The latest step, one line (\"[edit] app/page.tsx\"). */\n lastStep?: string | null\n /** Files changed in the worktree so far (git status). */\n files?: string[]\n /** When the run last checked in; an old value means the run has stopped. */\n heartbeatAt?: string\n}\n\n/**\n * The settings a run started with, so a resume needs only the run id (from\n * the studio's Resume button or `mushi-ux run --resume <id>`). The signed-in\n * profile is saved as its login URL, never as a path (ADR 0006); the skill's\n * files are kept beside the state in `skill/`.\n */\nexport interface SavedRunOptions {\n agent: string\n model: string | null\n devCommand: string\n /** null = no install; undefined = detect from the lockfile. */\n installCommand?: string | null\n startPaths?: string[]\n crawl?: boolean\n iterations: number\n maxSurfaces: number\n agentTimeoutMs: number\n ignore?: string[]\n allow?: string[]\n judgeModel?: string | null\n loginUrl?: string | null\n /** Mirror to the console again when resumed (needs the login then too). */\n sync?: boolean\n /** Steps mode: plan each screen, then one small change per attempt. */\n steps?: boolean\n /** The reviewing model that may veto a kept step (ADR 0021). */\n checker?: { via: 'claude-code' | 'anthropic-api' | 'cursor'; model: string } | null\n /** Keep edits with nothing visible, flagged for review. */\n keepInvisible?: boolean\n}\n\nexport interface RunState {\n version: 1\n runId: string\n baseUrl: string\n createdAt: string\n updatedAt: string\n agent: string\n model: string | null\n /** Skill the agent applies, if any (name and where it came from). */\n skill?: { name: string; source: string } | null\n /** Git ref the worktree branched from (HEAD unless --base). */\n baseRef?: string\n phase?: RunPhase\n /** One line on what the phase is doing (\"npm ci\", \"Home, attempt 2 of 2\"). */\n phaseDetail?: string | null\n /** The screen and attempt the agent is on, while it works. */\n current?: CurrentAttempt | null\n finishedAt?: string | null\n /** Why the run stopped, when it failed. */\n error?: string | null\n /** Stopped from the studio rather than failed. */\n stopped?: boolean\n /** Model of the final review; null when the review is off. */\n judgeModel?: string | null\n /** Settings to resume with; absent on runs from before 2026-10-06. */\n options?: SavedRunOptions\n /** The worktree's install finished; a run killed mid-install installs again. */\n installed?: boolean\n /** Worktree and branch the agent edits; null before the worktree exists. */\n worktree: string | null\n branch: string | null\n baseSha: string | null\n /** The PR the studio opened from the branch, or the existing PR the run was added to. */\n pr?: RunPullRequest | null\n surfaces: SurfaceState[]\n}\n\nexport function runDir(repoRoot: string, runId: string): string {\n return join(repoRoot, '.mushi', 'ux', runId)\n}\n\nexport function newRunId(now = new Date()): string {\n const stamp = now.toISOString().replace(/[-:]/g, '').replace(/\\..+$/, '').replace('T', '-')\n return `${stamp}-${Math.random().toString(36).slice(2, 6)}`\n}\n\nexport function saveState(dir: string, state: RunState): void {\n mkdirSync(dir, { recursive: true })\n state.updatedAt = new Date().toISOString()\n const file = join(dir, 'state.json')\n const tmp = `${file}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(state, null, 2))\n renameSync(tmp, file)\n}\n\nexport function loadState(dir: string): RunState | null {\n const file = join(dir, 'state.json')\n if (!existsSync(file)) return null\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunState\n if (parsed.version !== 1) throw new Error(`Unsupported run state version ${String(parsed.version)} in ${file}`)\n return parsed\n}\n\n/** Write a PNG under the run directory; returns its relative path. */\nexport function savePng(dir: string, rel: string, png: Buffer): string {\n const abs = join(dir, rel)\n mkdirSync(dirname(abs), { recursive: true })\n writeFileSync(abs, png)\n return rel.replace(/\\\\/g, '/')\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The studio's single page (served by dashboard.ts). Plain HTML + a small\n * script: no build step, no network beyond its own 127.0.0.1 server.\n *\n * Launcher: agent → live model list (with the model's own settings, e.g.\n * effort and context) → skill from the skills repo → pages → start.\n * Run view: phase and progress, burndown, every attempt's screenshot against\n * the baseline (slider, changed pixels), problems, and the agent's output.\n */\n\nexport const STUDIO_PAGE = `<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Mushi UX studio</title>\n<style>\n:root{--bg:#f6f6f3;--panel:#fff;--fg:#1c1c1a;--muted:#66665f;--line:#e2e2dc;--accent:#4f7f22;--accentfg:#fff;\n--ok:#2f7d32;--okbg:#e6f3e6;--warn:#8a5a00;--warnbg:#fdf1d8;--bad:#a12a2a;--badbg:#fbe4e4;--info:#2b5c9a;--infobg:#e3edf9;--idle:#55554f;--idlebg:#ecece8}\n@media (prefers-color-scheme:dark){:root{--bg:#141413;--panel:#1d1d1b;--fg:#ececea;--muted:#a3a39c;--line:#2e2e2b;--accent:#9ccf5f;--accentfg:#14200a;\n--ok:#8fd394;--okbg:#1e3320;--warn:#f1c46b;--warnbg:#3a2e14;--bad:#f19a9a;--badbg:#3b1d1d;--info:#9cc2f2;--infobg:#1b2a3d;--idle:#c4c4bd;--idlebg:#2a2a27}}\n*{box-sizing:border-box}body{margin:0;font:14px/1.45 system-ui,-apple-system,Segoe UI,sans-serif;background:var(--bg);color:var(--fg)}\nbutton,select,input,textarea{font:inherit;color:inherit}\nheader{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel)}\nh1{font-size:15px;margin:0;display:flex;gap:6px;align-items:center}h1 small{color:var(--muted);font-weight:400}\n.grow{flex:1}\n.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 12px;cursor:pointer}\n.btn.primary{background:var(--accent);color:var(--accentfg);border-color:transparent;font-weight:600}\n.btn:disabled{opacity:.5;cursor:not-allowed}.btn:focus-visible,select:focus-visible,input:focus-visible,nav button:focus-visible{outline:2px solid var(--accent);outline-offset:1px}\nselect,input[type=text],input[type=number],textarea{border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 8px;min-width:0}\n.status{padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel);display:grid;gap:6px}\n.status .top{display:flex;flex-wrap:wrap;gap:6px 12px;align-items:center}\n.meter{height:8px;background:var(--idlebg);border-radius:4px;overflow:hidden;display:flex}.meter i{display:block;height:100%}\n.chip{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:999px;font-size:12px;font-weight:600;white-space:nowrap}\n.s-accepted,.p-done{background:var(--okbg);color:var(--ok)}.s-reverted,.p-failed{background:var(--badbg);color:var(--bad)}.s-regressed,.s-interrupted{background:var(--warnbg);color:var(--warn)}\n.s-iterating,.s-baseline,.p-working,.p-install,.p-worktree,.p-dev-server,.p-mapping,.p-reviewing,.p-starting{background:var(--infobg);color:var(--info)}.s-pending,.s-skipped,.s-blocked{background:var(--idlebg);color:var(--idle)}\n.dot{width:8px;height:8px;border-radius:50%;background:currentColor;display:inline-block}.live .dot{animation:pulse 1.2s infinite}@keyframes pulse{50%{opacity:.25}}\n@media (prefers-reduced-motion:reduce){.live .dot{animation:none}}\n.sub{color:var(--muted);font-size:12px}.mono{font-family:ui-monospace,monospace;font-size:12px}\nmain{display:grid;grid-template-columns:minmax(240px,320px) 1fr;min-height:calc(100vh - 110px)}\n@media (max-width:860px){main{grid-template-columns:1fr}}\nnav{border-right:1px solid var(--line);overflow:auto;max-height:calc(100vh - 110px)}\n@media (max-width:860px){nav{max-height:260px;border-right:0;border-bottom:1px solid var(--line)}}\nnav button{all:unset;box-sizing:border-box;display:block;width:100%;padding:9px 14px;border-bottom:1px solid var(--line);cursor:pointer}\nnav button[aria-current=true]{background:var(--panel);box-shadow:inset 3px 0 0 var(--accent)}\n.row{display:flex;justify-content:space-between;gap:8px;align-items:center;min-width:0}.row .chip{flex-shrink:0}.label{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\nsection.detail{padding:14px 18px;min-width:0}\n.toolbar{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0}\n.seg{display:inline-flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}.seg button{all:unset;box-sizing:border-box;padding:5px 10px;cursor:pointer;font-size:12px}\n.seg button[aria-pressed=true]{background:var(--fg);color:var(--bg)}\n.compare{position:relative;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--panel)}\n.compare.mobile{max-width:420px}\n.split{display:grid;gap:16px;align-items:start}.split>*{min-width:0}\n.att[aria-busy=true]{grid-column:1/-1;cursor:default}.att[aria-busy=true] .ph{height:36px}.att .mono{overflow-wrap:anywhere}\n@media (min-width:1100px){.split.mobile{grid-template-columns:minmax(0,420px) minmax(0,1fr)}.split.mobile .side h3:first-child{margin-top:0}}\n.compare img{display:block;width:100%;height:auto}.compare .after{position:absolute;inset:0;clip-path:inset(0 0 0 var(--cut,50%))}\n.compare .diff{position:absolute;inset:0;mix-blend-mode:multiply;opacity:.85}\n.pair{display:grid;grid-template-columns:1fr 1fr;gap:8px}.pair figure{margin:0;min-width:0}.pair figcaption{font-size:11px;color:var(--muted);margin-bottom:3px}\n.pair img{display:block;width:100%;height:auto;border:1px solid var(--line);border-radius:8px;background:var(--panel)}\n.crop{border:1px solid var(--line);border-radius:8px;background-repeat:no-repeat;background-color:var(--panel);width:100%}\n.changes{display:grid;gap:12px}.changes h4{margin:0 0 4px;font-size:12px;color:var(--muted);font-weight:600}\n.cap{display:flex;justify-content:space-between;font-size:12px;color:var(--muted);margin-top:4px;gap:8px}\ninput[type=range]{width:100%;max-width:100%}\n.plan{list-style:none;margin:6px 0 4px;padding:0;display:grid;gap:6px}.plan li{display:flex;gap:8px;align-items:flex-start;font-size:13px;border:1px solid var(--line);border-radius:8px;padding:6px 8px;background:var(--panel)}.plan .mark{width:16px;flex:none;text-align:center;font-weight:600}.pl-done .mark{color:var(--ok)}.pl-failed .mark{color:var(--bad)}.pl-skipped .mark,.pl-pending .mark{color:var(--idle)}.pl-now{border-color:var(--info)}.pl-now .mark{color:var(--info)}\n.attempts{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px;margin-top:14px}\n.att{all:unset;box-sizing:border-box;cursor:pointer;border:1px solid var(--line);border-radius:10px;background:var(--panel);overflow:hidden;display:flex;flex-direction:column}\n.att[aria-pressed=true]{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}\n.att img{width:100%;height:120px;object-fit:cover;object-position:top;background:var(--idlebg);display:block}\n.att .body{padding:8px 10px;display:grid;gap:4px}\n.ph{height:120px;display:grid;place-items:center;background:var(--idlebg);color:var(--muted);font-size:12px}\n.problems{margin:8px 0 0;padding-left:18px;font-size:13px}\npre{white-space:pre-wrap;word-break:break-word;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px;max-height:260px;overflow:auto;font-size:12px;margin:0}\nh3{font-size:13px;margin:18px 0 6px}\n.empty{color:var(--muted);padding:24px}\n.form{max-width:860px;margin:0 auto;padding:18px 16px;display:grid;gap:14px}\n.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:14px 16px;display:grid;gap:10px}\n.card h2{font-size:14px;margin:0}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px}\nlabel.f{display:grid;gap:4px;font-size:12px;color:var(--muted)}label.f>span{font-weight:600;color:var(--fg)}\n.params{display:flex;flex-wrap:wrap;gap:10px}\n.pills{display:flex;flex-wrap:wrap;gap:6px}.pill{all:unset;cursor:pointer;border:1px solid var(--line);border-radius:999px;padding:2px 8px;font-size:12px}\n.pill[aria-pressed=true]{background:var(--fg);color:var(--bg)}\n.note{font-size:12px;color:var(--muted)}.warn{color:var(--warn)}.err{color:var(--bad)}\n.card h2 .n{display:inline-grid;place-items:center;width:20px;height:20px;border-radius:999px;background:var(--fg);color:var(--bg);font-size:11px;margin-right:6px}\n.lede{font-size:12px;color:var(--muted);margin:-4px 0 0}\n.choice{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:8px}\n.choice label{display:flex;gap:8px;align-items:flex-start;border:1px solid var(--line);border-radius:10px;padding:10px;cursor:pointer;font-size:12px;color:var(--muted)}\n.choice label b{display:block;color:var(--fg);font-size:13px}\n.choice label:has(input:checked){border-color:var(--fg)}\n.summary{border:1px dashed var(--line);border-radius:10px;padding:10px;font-size:12px;display:grid;gap:4px}\n.summary b{color:var(--fg)}\ndetails.adv summary{cursor:pointer;font-size:12px;color:var(--muted)}\ndetails.log{border-top:1px solid var(--line);background:var(--panel)}details.log summary{padding:8px 16px;cursor:pointer;font-size:12px;color:var(--muted)}details.log pre{border:0;border-radius:0;max-height:220px}details.steps{margin-top:8px}details.steps summary{cursor:pointer;font-size:12px;color:var(--muted)}details.steps pre{max-height:260px}\n[hidden]{display:none!important}\n</style></head><body>\n<header>\n <h1><svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"9\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M8 12l3 3 5-6\" fill=\"none\" stroke=\"var(--accent)\" stroke-width=\"2.4\" stroke-linecap=\"round\"/></svg>Mushi UX <small id=\"repo\"></small></h1>\n <div class=\"grow\"></div>\n <label class=\"sub\" for=\"runPick\">Run</label><select id=\"runPick\" aria-label=\"Run\"></select>\n <button class=\"btn primary\" id=\"newBtn\" hidden>+ New run</button>\n</header>\n<div class=\"status\" id=\"status\" hidden>\n <div class=\"top\"><span id=\"phase\" class=\"chip\"></span><span id=\"phaseDetail\" class=\"sub\"></span><span class=\"grow\"></span><span id=\"clock\" class=\"sub mono\"></span><button class=\"btn\" id=\"stopBtn\" hidden>■ Stop</button><button class=\"btn primary\" id=\"resumeBtn\" hidden>▶ Resume</button><button class=\"btn primary\" id=\"prBtn\" hidden>Open draft PR</button><a class=\"btn\" id=\"prLink\" hidden target=\"_blank\" rel=\"noopener\"></a><a class=\"btn\" id=\"consoleLink\" hidden target=\"_blank\" rel=\"noopener\" title=\"The run, its screens and the merge button in the Mushi console\">Review in console ↗</a></div>\n <div class=\"meter\" id=\"meter\" role=\"img\"></div>\n <div class=\"sub\" id=\"who\"></div>\n</div>\n<div id=\"launcher\" hidden></div>\n<main id=\"runview\" hidden><nav id=\"list\" aria-label=\"Screens\"></nav><section class=\"detail\" id=\"detail\"><p class=\"empty\">Pick a screen.</p></section></main>\n<details class=\"log\" id=\"logbox\" hidden><summary>Run log</summary><pre id=\"runlog\"></pre></details>\n<script>\nconst T = new URLSearchParams(location.search).get('t')\nconst q = (p) => p + (p.includes('?') ? '&' : '?') + 't=' + T\nconst esc = (s) => String(s ?? '').replace(/[&<>\"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' })[c])\nconst api = (p, init) => fetch(q(p), init).then(async (r) => { const b = await r.json().catch(() => ({})); if (!r.ok) throw new Error(b.error || ('HTTP ' + r.status)); return b })\nconst STATUS = { accepted: 'Improved', reverted: 'Rolled back', regressed: 'Moved by another change', iterating: 'Agent working', baseline: 'Measuring', interrupted: 'Stopped mid-attempt', pending: 'Queued', skipped: 'No change needed', blocked: 'Not finished' }\nconst PHASE = { starting: 'Starting', worktree: 'Creating worktree', install: 'Installing', 'dev-server': 'Starting dev server', mapping: 'Mapping screens', working: 'Working', reviewing: 'Reviewing', done: 'Done', failed: 'Failed' }\nconst FINISHED = ['accepted', 'reverted', 'skipped', 'regressed', 'blocked']\nconst store = { get(k) { try { return JSON.parse(localStorage.getItem('mushi-ux:' + k)) } catch { return null } }, set(k, v) { try { localStorage.setItem('mushi-ux:' + k, JSON.stringify(v)) } catch {} } }\nlet meta = null, runs = [], runId = null, state = null, selected = null, vp = 'mobile', diffOn = false, pick = null, view = 'changes'\nconst agentLog = {}, runLog = [], stepsFetched = new Set()\nconst chip = (st) => '<span class=\"chip s-' + st + '\">' + esc(STATUS[st] || st) + '</span>'\nconst shot = (p) => q('/shot?run=' + encodeURIComponent(runId) + '&p=' + encodeURIComponent(p))\nconst dur = (ms) => { const s = Math.max(0, Math.round(ms / 1000)); return s < 60 ? s + 's' : Math.floor(s / 60) + 'm ' + String(s % 60).padStart(2, '0') + 's' }\n\n// ── Run view ───────────────────────────────────────────────────────────────\nfunction renderStatus() {\n const box = document.getElementById('status')\n if (!state) { box.hidden = true; return }\n box.hidden = false\n // A run that stopped mid-phase without saying so (process killed, machine slept) is not live.\n const unfinished = !['done', 'failed'].includes(state.phase || 'starting')\n // A run this studio did not start (another studio, mushi-ux run) is live while it checks in.\n const interrupted = unfinished && !(meta && runId === meta.active) && quietMinutes() > 0\n const ph = interrupted ? 'failed' : (state.phase || 'starting'), live = unfinished && !interrupted\n const el = document.getElementById('phase')\n el.className = 'chip p-' + ph + (live ? ' live' : '')\n el.innerHTML = (live ? '<span class=\"dot\"></span>' : '') + esc(interrupted ? 'Interrupted' : (PHASE[ph] || ph))\n const pd = document.getElementById('phaseDetail')\n pd.textContent = interrupted\n ? 'This run stopped while ' + (PHASE[state.phase] || 'working').toLowerCase() + '. ' + (resumable() ? 'Resume carries on from the first unfinished screen.' : 'Continue it with: mushi-ux run --resume ' + state.runId)\n : state.error ? state.error.split('\\\\n')[0] : (state.phaseDetail || '')\n const quiet = live ? quietMinutes() : 0\n if (quiet) pd.textContent += ' · No check-in for ' + quiet + ' min: the run may have stopped. Check the terminal that started it.'\n // A read-only view (mushi-ux open) has no Resume button: say how to carry on.\n if (state.phase === 'failed' && !resumable()) pd.textContent += ' · Continue it with: mushi-ux run --resume ' + state.runId\n pd.className = state.error || interrupted ? 'sub err' : quiet ? 'sub warn' : 'sub'\n const total = state.surfaces.length, counts = {}\n for (const s of state.surfaces) counts[shownStatus(s)] = (counts[shownStatus(s)] || 0) + 1\n const done = state.surfaces.filter((s) => FINISHED.includes(s.status)).length\n const seg = (k, color) => counts[k] ? '<i style=\"width:' + (counts[k] / Math.max(1, total) * 100) + '%;background:' + color + '\" title=\"' + esc(STATUS[k]) + ' ' + counts[k] + '\"></i>' : ''\n const meter = document.getElementById('meter')\n meter.innerHTML = seg('accepted', 'var(--ok)') + seg('regressed', 'var(--warn)') + seg('reverted', 'var(--bad)') + seg('skipped', 'var(--idle)') + seg('blocked', 'var(--idle)') + seg('iterating', 'var(--info)')\n meter.setAttribute('aria-label', done + ' of ' + total + ' screens finished')\n const parts = [done + ' of ' + total + ' screens done', state.agent + (state.model ? ' · ' + state.model : '')]\n if (state.skill) parts.push('skill ' + state.skill.name)\n if (state.branch) parts.push(state.branch + (state.baseRef ? ' (from ' + state.baseRef + ')' : ''))\n document.getElementById('who').innerHTML = parts.map(esc).join(' · ') + ' ' + Object.entries(counts).map(([k, n]) => chip(k).replace('</span>', ' ' + n + '</span>')).join(' ')\n const stop = document.getElementById('stopBtn')\n stop.hidden = !(meta && meta.canStop && live && runId === meta.active)\n stop.disabled = false\n // Interrupted, failed or stopped: carry on from where it stopped, with the settings it started with.\n const resumeBtn = document.getElementById('resumeBtn')\n resumeBtn.hidden = !((interrupted || state.phase === 'failed') && resumable())\n resumeBtn.disabled = false\n // A finished run with kept changes: open its PR (or add it to the PR its branch came from), then merge from the console.\n const kept = state.surfaces.some((x) => x.iterations.some((it) => it.outcome === 'accepted' && it.commitSha))\n const prBtn = document.getElementById('prBtn'), prLink = document.getElementById('prLink')\n prBtn.hidden = !(meta && meta.canOpenPr && state.phase === 'done' && kept && !state.pr)\n prBtn.textContent = (state.baseRef || '').startsWith('origin/mushi-ux/') ? 'Add to its pull request' : 'Open draft PR'\n prLink.hidden = !state.pr\n if (state.pr) { prLink.href = state.pr.url; prLink.textContent = 'PR #' + state.pr.number + (state.pr.added ? ' (added) ↗' : ' ↗'); prLink.title = 'Merge it from the Mushi console once its checks pass' }\n // A mirrored run is reviewed and merged in the console; link straight to it.\n const consoleLink = document.getElementById('consoleLink')\n consoleLink.hidden = !(meta && meta.consoleUrl && state.options && state.options.sync)\n if (!consoleLink.hidden) consoleLink.href = meta.consoleUrl + '/ux-runs?run=' + encodeURIComponent(state.runId)\n tick()\n}\n/** Minutes since the run last saved its state (it does every 30 s while alive); 0 while it is fresh. */\nfunction quietMinutes() {\n const hb = state && (state.updatedAt || (state.current && state.current.heartbeatAt))\n const gap = hb ? Date.now() - Date.parse(hb) : 0\n return gap > 3 * 60000 ? Math.floor(gap / 60000) : 0\n}\n/** The run is not going anywhere: it failed or stopped, or its process died without saying so. */\nfunction runIsDead() {\n if (!state) return false\n if (state.phase === 'failed') return true\n const unfinished = state.phase !== 'done'\n return unfinished && !(meta && runId === meta.active) && quietMinutes() > 0\n}\n/** A screen the agent was on when the run died shows that, not \"Agent working\". */\nfunction shownStatus(s) { return s.status === 'iterating' && runIsDead() ? 'interrupted' : s.status }\nfunction tick() {\n if (!state) return\n const dead = runIsDead()\n // A dead run's clock stops at its last check-in instead of counting on.\n const end = state.finishedAt ? Date.parse(state.finishedAt) : dead ? Date.parse(state.updatedAt) : Date.now()\n let txt = 'elapsed ' + dur(end - Date.parse(state.createdAt))\n if (state.current && !state.finishedAt && !dead) txt = 'this attempt ' + dur(Date.now() - Date.parse(state.current.startedAt)) + (state.current.timeoutMs ? ' of ' + dur(state.current.timeoutMs) : '') + ' · ' + txt\n document.getElementById('clock').textContent = txt\n}\nsetInterval(tick, 1000)\n// Events can be missing (a run started elsewhere, a dropped stream): re-read an unfinished run's state.\nsetInterval(() => { if (state && !['done', 'failed'].includes(state.phase || 'starting') && !document.hidden) loadState() }, 15000)\n\nfunction workingCard(s) {\n const c = state.current && state.current.surface === s.surface.key ? state.current : null\n const n = c ? c.attempt : s.iterations.length + 1\n if (runIsDead()) {\n return '<div class=\"att\"><div class=\"ph\">Stopped</div><div class=\"body\"><div class=\"row\"><strong>Attempt ' + n + '</strong>' + chip('interrupted') + '</div><div class=\"sub\">The run stopped during this attempt. Its unfinished edits are thrown away and it runs again on Resume.</div></div></div>'\n }\n let body = '<div class=\"row\"><strong>Attempt ' + n + '</strong><span class=\"chip s-iterating\">working</span></div>'\n if (c) {\n body += '<div class=\"sub\">' + (c.steps ? c.steps + ' step' + (c.steps === 1 ? '' : 's') : 'Reading the brief') + (c.lastStep ? ' · ' + esc(c.lastStep) : '') + '</div>'\n if (c.files && c.files.length) body += '<div class=\"sub mono\">Changed so far: ' + c.files.slice(0, 6).map(esc).join(', ') + (c.files.length > 6 ? ' +' + (c.files.length - 6) + ' more' : '') + '</div>'\n }\n return '<div class=\"att\" aria-busy=\"true\"><div class=\"ph live\" style=\"color:var(--info)\"><span><span class=\"dot\"></span> In progress</span></div><div class=\"body\">' + body + '</div></div>'\n}\n/** Steps mode: the screen's plan as a checklist, the step being worked on marked. */\nfunction planHtml(s) {\n if (!s.plan || !s.plan.steps || !s.plan.steps.length) return ''\n const working = shownStatus(s) === 'iterating'\n const now = working ? s.plan.steps.find((p) => p.status === 'pending') : null\n const MARK = { done: '✓', skipped: '–', failed: '✗', pending: '○' }\n const LABEL = { done: 'kept', skipped: 'not needed', failed: 'rolled back', pending: 'to do' }\n return '<h3>Plan: ' + s.plan.steps.filter((p) => p.status === 'done').length + ' of ' + s.plan.steps.length + ' steps kept</h3><ol class=\"plan\">' + s.plan.steps.map((p) => {\n const cur = p === now\n const why = p.reason ? p.reason.replace(/^Step \\\\d+\\\\/\\\\d+: /, '') : ''\n return '<li class=\"pl-' + (cur ? 'now' : p.status) + '\"><span class=\"mark\" aria-hidden=\"true\">' + (cur ? '▶' : MARK[p.status]) + '</span><div><div>' + esc(p.text) + ' <span class=\"sub\">(' + (cur ? 'working now' : LABEL[p.status]) + ')</span></div>' + (why ? '<div class=\"sub\">' + esc(why) + '</div>' : '') + '</div></li>'\n }).join('') + '</ol>'\n}\nfunction attemptsWithShots(s) { return s.iterations.filter((i) => i.after && (i.after.desktop || i.after.mobile)) }\nfunction renderRun() {\n renderStatus()\n const list = document.getElementById('list')\n if (!state) { list.innerHTML = ''; document.getElementById('detail').innerHTML = '<p class=\"empty\">No run selected.</p>'; return }\n const cur = state.current && state.current.surface\n list.innerHTML = state.surfaces.map((s) =>\n '<button data-k=\"' + esc(s.surface.key) + '\" aria-current=\"' + (s.surface.key === selected) + '\"><div class=\"row\"><span class=\"label\">' + (s.surface.key === cur && !runIsDead() ? '<span class=\"live\" style=\"color:var(--info)\"><span class=\"dot\"></span></span> ' : '') + esc(s.surface.label) + '</span>' + chip(shownStatus(s)) + '</div><div class=\"sub mono\">' + esc(s.surface.path) + (s.surface.steps.length ? ' › ' + esc(s.surface.steps.map((x) => x.label).join(' › ')) : '') + (s.iterations.length ? ' · ' + s.iterations.length + ' attempt' + (s.iterations.length === 1 ? '' : 's') : '') + '</div></button>').join('') || '<p class=\"empty\">' + (state.phase === 'mapping' ? 'Mapping screens…' : 'No screens yet.') + '</p>'\n list.querySelectorAll('button').forEach((b) => b.onclick = () => { selected = b.dataset.k; pick = null; renderRun() })\n const s = state.surfaces.find((x) => x.surface.key === selected) || state.surfaces.find((x) => x.surface.key === cur) || state.surfaces[0]\n const box = document.getElementById('detail')\n if (!s) {\n box.innerHTML = state.error\n ? '<h3>The run stopped</h3><pre>' + esc(state.error) + '</pre><p class=\"sub\">The run log below has the full output. Fix the cause, then start a new run.</p>'\n : '<p class=\"empty\">' + esc(PHASE[state.phase] || 'Waiting') + '…</p>'\n if (state.error) document.getElementById('logbox').open = true\n return\n }\n selected = s.surface.key\n const atts = attemptsWithShots(s)\n const chosen = pick == null ? atts[atts.length - 1] : atts.find((a) => a.n === pick)\n const base = s.baseline[vp] || s.baseline.desktop, after = chosen && (chosen.after[vp] || null)\n let html = '<div class=\"row\"><h2 style=\"margin:0;font-size:18px\">' + esc(s.surface.label) + '</h2>' + chip(shownStatus(s)) + '</div>'\n if (s.note) html += '<p class=\"sub\">' + esc(s.note) + '</p>'\n html += '<div class=\"toolbar\"><div class=\"seg\" role=\"group\" aria-label=\"Viewport\">' + ['mobile', 'desktop'].map((v) => '<button data-vp=\"' + v + '\" aria-pressed=\"' + (v === vp) + '\">' + v + '</button>').join('') + '</div>'\n if (after) html += '<div class=\"seg\" role=\"group\" aria-label=\"How to compare\">' + [['changes', 'Changes'], ['side', 'Side by side'], ['slider', 'Slider']].map(([v, l]) => '<button data-view=\"' + v + '\" aria-pressed=\"' + (v === view) + '\">' + l + '</button>').join('') + '</div>'\n if (after && view === 'slider') html += '<label class=\"sub\"><input type=\"checkbox\" id=\"diff\"' + (diffOn ? ' checked' : '') + '> Show changed pixels</label>'\n // Wide screens: the phone screenshot on the left, attempts and the agent's steps beside it.\n html += '</div><div class=\"split ' + vp + '\"><div>'\n let problemsHtml = ''\n if (base) {\n // Before = the screen this attempt started from (the last kept step), so every view shows what THIS attempt changed.\n const prev = after ? startedFrom(s, chosen.n, vp) : null\n if (after && view === 'changes') html += changesHtml(prev, after, chosen, s)\n else if (after && view === 'side') html += '<div class=\"pair\"><figure><figcaption>Before ' + esc(stepName(s, chosen.n, true)) + ' · problem score ' + prev.penalty + '</figcaption><img alt=\"Before\" src=\"' + shot(prev.png) + '\"></figure><figure><figcaption>' + esc(stepName(s, chosen.n)) + ' · problem score ' + after.penalty + '</figcaption><img alt=\"After\" src=\"' + shot(after.png) + '\"></figure></div>'\n else {\n html += '<div class=\"compare ' + vp + '\" id=\"cmp\"><img alt=\"Before\" src=\"' + shot((prev || base).png) + '\">' + (after ? '<img class=\"after\" alt=\"After\" src=\"' + shot(after.png) + '\">' : '') + (after && diffOn && chosen.diffPng[vp] ? '<img class=\"diff\" alt=\"Changed pixels\" src=\"' + shot(chosen.diffPng[vp]) + '\">' : '') + '</div>'\n if (after) html += '<input type=\"range\" id=\"cut\" min=\"0\" max=\"100\" value=\"50\" aria-label=\"Before / after split\"><div class=\"cap\"><span>◀ Before · problem score ' + prev.penalty + '</span><span>' + esc(stepName(s, chosen.n)) + ' · problem score ' + after.penalty + ' ▶</span></div><p class=\"sub\">Drag the handle: left of it is before, right of it is after. One screenshot split in two, not cut off.</p>'\n else html += '<div class=\"cap\"><span>Baseline · problem score ' + base.penalty + '</span><span>' + (shownStatus(s) === 'iterating' ? 'Agent working…' : '') + '</span></div>'\n }\n const probes = (after || base).probes, lines = []\n for (const a of probes.axe || []) lines.push(a.help + ' (' + a.count + ')')\n if (probes.overflowX) lines.push('Scrolls sideways')\n if (probes.smallTargets) lines.push(probes.smallTargets + ' tap target(s) under 24 px')\n for (const l of (probes.layout || []).slice(0, 4)) lines.push((l.kind === 'overlap' ? 'Overlap: ' : 'Too big: ') + l.selector + ' ' + l.detail)\n for (const e of (probes.consoleErrors || []).slice(0, 3)) lines.push('Console: ' + e)\n if (lines.length) problemsHtml = '<h3>Problems measured on ' + (after ? 'attempt ' + chosen.n : 'the baseline') + ' (' + vp + ')</h3><ul class=\"problems\">' + lines.map((l) => '<li>' + esc(l) + '</li>').join('') + '</ul>'\n } else html += '<p class=\"empty\">No screenshot yet.</p>'\n html += '</div><div class=\"side\">' + planHtml(s) + '<h3>Attempts</h3><div class=\"attempts\">' + s.iterations.map((i) => {\n const a = i.after[vp] || i.after.desktop || i.after.mobile\n const tone = i.outcome === 'accepted' ? 'accepted' : i.outcome === 'rejected' || i.outcome === 'capture_failed' ? 'reverted' : 'skipped'\n return '<button class=\"att\" data-n=\"' + i.n + '\" aria-pressed=\"' + (chosen && chosen.n === i.n) + '\"' + (a ? '' : ' disabled') + '>' + (a ? '<img alt=\"Attempt ' + i.n + '\" loading=\"lazy\" src=\"' + shot(a.png) + '\">' : '<div class=\"ph\">no screenshot</div>') + '<div class=\"body\"><div class=\"row\"><strong>Attempt ' + i.n + '</strong>' + chip(tone).replace(/>[^<]+</, '>' + esc(i.outcome.replace('_', ' ')) + '<') + '</div>' + (i.needsReview ? '<div class=\"sub warn\">Needs your review: nothing visible changed</div>' : '') + (i.checker ? '<div class=\"sub\">' + esc(checkerLine(i.checker)) + '</div>' : '') + '<div class=\"sub\">' + esc(i.reason) + '</div><div class=\"sub mono\">' + dur(i.durationMs) + (i.pixelDiff[vp] != null ? ' · ' + (i.pixelDiff[vp] * 100).toFixed(1) + '% px' : '') + (i.commitSha ? ' · ' + i.commitSha.slice(0, 8) : '') + '</div></div></button>'\n }).join('') + (s.status === 'iterating' ? workingCard(s) : '') + '</div>'\n if (!s.iterations.length && s.status !== 'iterating') html += '<p class=\"sub\">No attempts yet.</p>'\n const mine = (agentLog[selected] || []).slice(-80)\n const stepsTitle = { iterating: 'Agent steps (live)', interrupted: 'Agent steps before the run stopped' }[shownStatus(s)] || 'Agent steps, last attempt'\n if (mine.length) html += '<h3>' + stepsTitle + '</h3><pre id=\"agentout\">' + esc(mine.join('\\\\n')) + '</pre>'\n else if (shownStatus(s) === 'iterating') html += '<h3>' + stepsTitle + '</h3><pre id=\"agentout\" class=\"sub\">Steps appear here as the agent reads and edits files.</pre>'\n html += problemsHtml\n const jv = (s.judge || []).find((v) => v.viewport === vp)\n if (jv) html += '<h3>Review by ' + esc(jv.model) + ' (advisory)</h3><p class=\"sub\">' + esc(jv.error || ('Prefers ' + (jv.preferred === 'tie' ? 'neither' : jv.preferred === 'after' ? 'the new version' : 'the original') + ' (' + jv.confidence + ' confidence). ' + jv.summary)) + '</p>'\n for (const i of s.iterations) if (i.logTail) html += '<details class=\"steps\"><summary>What the agent did in attempt ' + i.n + '</summary><pre>' + esc(i.logTail) + '</pre></details>'\n html += '</div></div>'\n box.innerHTML = html\n // After a reload the live stream has nothing yet: read the saved steps once.\n const stepsKey = runId + ' ' + selected\n if (s.status === 'iterating' && !mine.length && !stepsFetched.has(stepsKey)) {\n stepsFetched.add(stepsKey)\n const forRun = runId, forSurface = selected\n api('/api/steps?run=' + encodeURIComponent(forRun) + '&surface=' + encodeURIComponent(forSurface)).then(({ lines }) => {\n if (runId !== forRun || !lines.length || (agentLog[forSurface] || []).length) return\n agentLog[forSurface] = lines\n if (selected === forSurface) renderRun()\n }).catch(() => {})\n }\n box.querySelectorAll('[data-vp]').forEach((b) => b.onclick = () => { vp = b.dataset.vp; renderRun() })\n box.querySelectorAll('[data-view]').forEach((b) => b.onclick = () => { view = b.dataset.view; renderRun() })\n box.querySelectorAll('.att[data-n]').forEach((b) => b.onclick = () => { pick = Number(b.dataset.n); renderRun() })\n const d = document.getElementById('diff'); if (d) d.onchange = () => { diffOn = d.checked; renderRun() }\n const c = document.getElementById('cut'); if (c) c.oninput = () => document.getElementById('cmp').style.setProperty('--cut', c.value + '%')\n const out = document.getElementById('agentout'); if (out) out.scrollTop = out.scrollHeight\n}\n// ── Before / after ─────────────────────────────────────────────────────────\n/** The screenshot attempt n started from: the last kept attempt before it, else the baseline. */\nconst changeCache = {}\nfunction checkerLine(c) {\n if (c.error) return c.model + ': review failed'\n const votes = (c.votes || []).map((v) => v.preferred).join(' / ')\n return c.model + ': ' + (c.verdict === 'revert' ? 'rolled back' : c.verdict === 'keep' ? 'agrees' : 'unsure') + (votes ? ' (' + votes + ')' : '')\n}\nfunction startedFrom(s, n, v) {\n const kept = s.iterations.filter((i) => i.n < n && i.outcome === 'accepted' && i.after[v]).pop()\n return (kept && kept.after[v]) || s.baseline[v] || s.baseline.desktop\n}\nfunction stepName(s, n, before) {\n const it = s.iterations.find((i) => i.n === n), steps = (s.plan && s.plan.steps) || []\n const k = it && it.step ? steps.findIndex((p) => p.text === it.step) : -1\n return k >= 0 ? (before ? 'step ' : 'Step ') + (k + 1) : (before ? 'attempt ' : 'Attempt ') + n\n}\n/** One changed area as a zoomed crop of a screenshot (CSS sprite maths, no canvas). */\nfunction cropHtml(png, box, size, label) {\n const sx = box.w >= size.width ? 0 : (box.x / (size.width - box.w)) * 100\n const sy = box.h >= size.height ? 0 : (box.y / (size.height - box.h)) * 100\n const style = 'aspect-ratio:' + box.w + '/' + box.h + ';background-image:url("' + shot(png) + '");background-size:' + (size.width / box.w) * 100 + '% auto;background-position:' + sx + '% ' + sy + '%'\n return '<figure><figcaption>' + esc(label) + '</figcaption><div class=\"crop\" role=\"img\" aria-label=\"' + esc(label) + '\" style=\"' + style + '\"></div></figure>'\n}\nfunction changesHtml(prev, after, it, s) {\n let ch = it.changes && it.changes[vp]\n const pct = it.pixelDiff[vp] != null ? (it.pixelDiff[vp] * 100).toFixed(1) + '% of the screen changed' : ''\n if (!ch && it.diffPng && it.diffPng[vp]) {\n // An older attempt: work the areas out from its saved diff image once.\n const key = runId + ' ' + it.diffPng[vp]\n ch = changeCache[key]\n if (!ch) {\n if (!changeCache[key + '?']) {\n changeCache[key + '?'] = true\n api('/api/changes?run=' + encodeURIComponent(runId) + '&p=' + encodeURIComponent(it.diffPng[vp])).then((c) => { changeCache[key] = c; renderRun() }).catch(() => {})\n }\n return '<p class=\"sub\">Finding the changed areas…</p>'\n }\n }\n if (!ch) return '<p class=\"sub\">No change areas for this attempt. Use Side by side.</p>'\n if (!ch.boxes.length) return '<p class=\"sub\">Nothing changed on this screen in this attempt.</p>'\n return '<div class=\"changes\"><p class=\"sub\">' + ch.boxes.length + ' changed area' + (ch.boxes.length === 1 ? '' : 's') + (pct ? ' · ' + pct : '') + '. Each is shown before and after ' + esc(stepName(s, it.n, true)) + ', zoomed in.</p>' + ch.boxes.map((b, i) =>\n '<div><h4>Change ' + (i + 1) + ' · ' + b.w + '×' + b.h + ' px at ' + b.x + ',' + b.y + '</h4><div class=\"pair\">' + cropHtml(prev.png, b, ch, 'Before') + cropHtml(after.png, b, ch, 'After') + '</div></div>').join('') + '</div>'\n}\nasync function loadState() { state = runId ? await api('/api/state?run=' + runId).catch(() => state) : null; renderRun() }\nasync function loadRuns() {\n runs = (await api('/api/runs')).runs\n const sel = document.getElementById('runPick')\n sel.innerHTML = runs.map((r) => '<option value=\"' + esc(r.runId) + '\"' + (r.runId === runId ? ' selected' : '') + '>' + esc(new Date(r.createdAt).toLocaleString()) + ' · ' + esc(r.agent) + (r.model ? ' ' + esc(r.model) : '') + ' · ' + r.done + '/' + r.total + '</option>').join('') || '<option>No runs yet</option>'\n sel.disabled = !runs.length\n}\nfunction showRun(id) {\n runId = id; selected = null; pick = null\n document.getElementById('launcher').hidden = true\n document.getElementById('runview').hidden = false\n document.getElementById('logbox').hidden = false\n const logEl = document.getElementById('runlog')\n logEl.textContent = ''\n history.replaceState(null, '', '?t=' + T + '&run=' + id)\n loadState()\n // The saved log first (past runs, a restarted studio), then live lines arrive over events.\n api('/api/log?run=' + id).then(({ lines }) => {\n if (runId !== id) return\n logEl.textContent = lines.join('\\\\n')\n logEl.scrollTop = logEl.scrollHeight\n }).catch(() => {})\n}\ndocument.getElementById('runPick').onchange = (e) => showRun(e.target.value)\n\n// ── Launcher ───────────────────────────────────────────────────────────────\nlet options = null, models = null\nasync function openLauncher() {\n document.getElementById('runview').hidden = true\n document.getElementById('logbox').hidden = true\n document.getElementById('status').hidden = true\n const box = document.getElementById('launcher')\n box.hidden = false\n box.innerHTML = '<div class=\"form\"><div class=\"card\"><h2>New run</h2><p class=\"note\">Checking which coding agents are installed and signed in, this repo’s branches and its pages. This takes up to 20 seconds.</p></div></div>'\n options = await api('/api/options').catch((e) => ({ error: e.message }))\n const last = store.get('last') || {}\n const agents = options.agents || []\n const agentOpt = (a) => '<option value=\"' + esc(a.name) + '\"' + (a.name === (last.agent || options.defaultAgent) ? ' selected' : '') + (a.installed ? '' : ' disabled') + '>' + esc(a.label) + (a.installed ? '' : ' — ' + esc(a.note || 'not found')) + '</option>'\n const refOpt = (r) => '<option value=\"' + esc(r.ref) + '\"' + (r.ref === (last.baseRef || options.defaultRef) ? ' selected' : '') + '>' + esc(r.label) + '</option>'\n const lastPaths = last.startPaths || (options.lastRun ? options.lastRun.startPaths : [])\n const whole = lastPaths.length === 0\n box.innerHTML = '<form class=\"form\" id=\"lf\" novalidate>' +\n '<div class=\"card\"><h2><span class=\"n\">1</span>What to improve</h2>' +\n '<p class=\"lede\">The agent works one screen at a time on its own branch. Each change is measured (accessibility, layout, console) and kept only if nothing got worse.</p>' +\n '<div class=\"choice\" role=\"radiogroup\" aria-label=\"Which screens\">' +\n '<label><input type=\"radio\" name=\"f-scope\" value=\"whole\"' + (whole ? ' checked' : '') + '><span><b>The whole app</b>Map screens from the home page and the links it opens, up to the screen limit below.</span></label>' +\n '<label><input type=\"radio\" name=\"f-scope\" value=\"pages\"' + (whole ? '' : ' checked') + '><span><b>Pages I pick</b>Only these pages, plus the tabs and dialogs they open.</span></label>' +\n '</div>' +\n '<div id=\"f-pages-box\" class=\"card\" style=\"padding:10px\"' + (whole ? ' hidden' : '') + '>' +\n '<label class=\"f\"><span>Pages (comma-separated, or click below)</span><input type=\"text\" id=\"f-paths\" autocomplete=\"off\" value=\"' + esc(lastPaths.join(', ')) + '\"></label>' +\n '<div class=\"pills\" id=\"f-route-pills\">' + (options.routes || []).slice(0, 40).map((r) => '<button type=\"button\" class=\"pill\" data-r=\"' + esc(r) + '\" aria-pressed=\"false\">' + esc(r) + '</button>').join('') + '</div>' +\n '<label class=\"sub\"><input type=\"checkbox\" id=\"f-crawl\"' + (last.crawl ? ' checked' : '') + '> Also follow links from these pages</label>' +\n '</div>' +\n '<div class=\"grid\">' +\n '<label class=\"f\"><span>Skills: what the agent focuses on, applied in order (' + esc(options.skillsRepo || 'skills package') + ')</span><select id=\"f-skill\"><option value=\"\">Add a skill…</option></select></label>' +\n '<label class=\"f\"><span>…or your own SKILL.md / folder</span><input type=\"text\" id=\"f-skill-path\" placeholder=\"./skills/my-skill\" autocomplete=\"off\"></label>' +\n '</div><div class=\"pills\" id=\"f-chain\" aria-label=\"Skill chain\"></div><div class=\"pills\" id=\"f-next\"></div><div class=\"note\" id=\"f-skill-note\"></div>' +\n '<label class=\"sub\"><input type=\"checkbox\" id=\"f-steps\"' + (last.steps === false ? '' : ' checked') + '> Small steps (recommended): plan each screen first, then one small change per attempt, each kept or rolled back on its own</label>' +\n '</div>' +\n '<div class=\"card\"><h2><span class=\"n\">2</span>Who does the work</h2><div class=\"grid\">' +\n '<label class=\"f\"><span>Coding agent</span><select id=\"f-agent\">' + agents.map(agentOpt).join('') + '</select></label>' +\n '<label class=\"f\"><span>Model</span><select id=\"f-model\"><option>Loading…</option></select></label>' +\n '<label class=\"f\" id=\"f-custom-wrap\" hidden><span>Model id</span><input type=\"text\" id=\"f-custom\" placeholder=\"e.g. grok-4.7\" autocomplete=\"off\"></label>' +\n '</div><div class=\"params\" id=\"f-params\"></div><div class=\"note\" id=\"f-model-note\"></div>' +\n '<div class=\"summary\" id=\"f-account\"><span class=\"note\">Checking the account…</span></div>' +\n '<div class=\"grid\">' +\n '<label class=\"f\"><span>Checker: a second model reviews each kept step and may roll it back</span><select id=\"f-checker\">' + checkerOptions(agents, last) + '</select></label>' +\n '</div>' +\n '<div class=\"note\">The checker sees the changed area before and after, twice with the order swapped, and rolls a step back only when both reviews prefer the original. It never keeps a step the measurements rejected. Each checked step costs about $0.20–0.50 of your Claude usage (two reviews; measured $0.46 on glot.it).</div>' +\n '<label class=\"sub\"><input type=\"checkbox\" id=\"f-invisible\"' + (last.keepInvisible === false ? '' : ' checked') + '> Keep changes that are not visible in a screenshot (motion, haptics, press feedback) and flag them for your review</label>' +\n '<div class=\"row\"><span class=\"sub mono\" id=\"f-spec\"></span><button type=\"button\" class=\"btn\" id=\"f-refresh\">Refresh list</button></div></div>' +\n '<div class=\"card\"><h2><span class=\"n\">3</span>How much</h2><div class=\"grid\">' +\n '<label class=\"f\"><span>Screens at most</span><input type=\"number\" id=\"f-max\" min=\"1\" max=\"100\" value=\"' + (last.maxSurfaces || 8) + '\"></label>' +\n '<label class=\"f\"><span>Attempts (steps) per screen</span><input type=\"number\" id=\"f-iter\" min=\"1\" max=\"5\" value=\"' + (last.iterations || 4) + '\"></label>' +\n '<label class=\"f\"><span>Minutes per attempt</span><input type=\"number\" id=\"f-timeout\" min=\"1\" max=\"60\" value=\"' + (last.timeoutMin || 8) + '\"></label>' +\n '</div><div class=\"summary\" id=\"f-estimate\"></div></div>' +\n '<div class=\"card\"><h2><span class=\"n\">4</span>Your app</h2><div class=\"grid\">' +\n '<label class=\"f\" style=\"grid-column:1/-1\"><span>Dev command ({port} is replaced)</span><input type=\"text\" id=\"f-dev\" list=\"f-devs\" autocomplete=\"off\"><datalist id=\"f-devs\">' + (options.devCommands || []).map((d) => '<option value=\"' + esc(d) + '\">').join('') + '</datalist></label>' +\n '<label class=\"f\"><span>Branch from</span><select id=\"f-base\">' + (options.refs || [{ ref: 'HEAD', label: 'HEAD' }]).map(refOpt).join('') + '</select></label>' +\n '</div>' +\n (options.lastRun ? '<div class=\"note\">Run ' + esc(options.lastRun.runId) + ' mapped screens with <code>' + esc(options.lastRun.devCommand) + '</code>, so it is first in the list.</div>' : '') +\n '<div class=\"note warn\" id=\"f-dev-warn\">' + esc(options.devWarning || '') + '</div>' +\n '<details class=\"adv\"><summary>Advanced: parts of the page to leave out</summary>' +\n '<label class=\"f\"><span>Not part of the app (CSS selectors, one per line): hidden in screenshots and skipped by every check</span><textarea id=\"f-ignore\" rows=\"2\" autocomplete=\"off\" spellcheck=\"false\" placeholder=\".dev-badge\">' + esc((last.ignore || []).join('\\\\n')) + '</textarea></label>' +\n '<div class=\"note\">Dev overlays, build stamps and the Mushi widget are already skipped. Add your own here, or mark an element with <code>data-mushi-ux-ignore</code>.</div></details></div>' +\n '<div class=\"card\"><h2>After the run</h2><div class=\"grid\">' +\n '<label class=\"f\"><span><input type=\"checkbox\" id=\"f-judge\"' + (options.judgeAvailable ? (last.judge === false ? '' : ' checked') : ' disabled') + '> Second-model review</span><input type=\"text\" id=\"f-judge-model\" value=\"' + esc(last.judgeModel || options.judgeModel || '') + '\"' + (options.judgeAvailable ? '' : ' disabled') + '></label>' +\n '<label class=\"f\"><span><input type=\"checkbox\" id=\"f-sync\"' + (options.syncAvailable ? (last.sync ? ' checked' : '') : ' disabled') + '> Mirror to the Mushi console</span><span class=\"note\">' + esc(options.syncNote || '') + '</span></label>' +\n '</div>' + (options.judgeAvailable ? '' : '<div class=\"note\">Review needs ANTHROPIC_API_KEY in this shell.</div>') + '</div>' +\n '<div class=\"row\"><span class=\"note err\" id=\"f-error\"></span><button class=\"btn primary\" id=\"f-start\" type=\"submit\">▶ Start run</button></div></form>'\n document.getElementById('f-dev').value = last.devCommand || (options.devCommands || [])[0] || ''\n syncPills()\n document.getElementById('f-paths').oninput = syncPills\n box.querySelectorAll('input[name=f-scope]').forEach((r) => r.onchange = () => { document.getElementById('f-pages-box').hidden = scope() !== 'pages'; estimate() })\n ;['f-max', 'f-iter', 'f-timeout', 'f-steps'].forEach((id) => document.getElementById(id).addEventListener('input', estimate))\n estimate()\n box.querySelectorAll('.pill').forEach((p) => p.onclick = () => {\n const input = document.getElementById('f-paths'), set = new Set(input.value.split(',').map((x) => x.trim()).filter(Boolean))\n set.has(p.dataset.r) ? set.delete(p.dataset.r) : set.add(p.dataset.r)\n input.value = [...set].join(', '); syncPills()\n })\n document.getElementById('f-agent').onchange = () => loadModels(false)\n document.getElementById('f-refresh').onclick = () => loadModels(true)\n document.getElementById('f-model').onchange = renderParams\n document.getElementById('f-custom').oninput = updateSpec\n document.getElementById('lf').onsubmit = (e) => { e.preventDefault(); start() }\n loadModels(false)\n loadSkills(last.skill)\n}\nfunction checkerOptions(agents, last) {\n const claude = agents.some((a) => a.name === 'claude-code' && a.installed)\n const opts = [['', 'None: measurements alone decide']]\n if (claude) opts.push(['claude-code|claude-opus-5-5', 'Claude Opus 5.5, via Claude Code (your sign-in)'], ['claude-code|claude-sonnet-5-5', 'Claude Sonnet 5.5, via Claude Code (cheaper)'])\n if (options.judgeAvailable) opts.push(['anthropic-api|claude-opus-5-5', 'Claude Opus 5.5, via the Anthropic API key'])\n const want = last.checkerModel ? (last.checkerVia || 'claude-code') + '|' + last.checkerModel : (claude ? 'claude-code|claude-opus-5-5' : '')\n return opts.map(([v, l]) => '<option value=\"' + esc(v) + '\"' + (v === want ? ' selected' : '') + '>' + esc(l) + '</option>').join('') + (claude ? '' : '<option disabled>Claude Code not found: install it to use Claude as the checker</option>')\n}\nfunction checkerPick() {\n const v = document.getElementById('f-checker').value\n if (!v) return { model: null, via: 'claude-code' }\n const [via, model] = v.split('|')\n return { model, via }\n}\nfunction scope() { const r = document.querySelector('input[name=f-scope]:checked'); return r ? r.value : 'whole' }\n// Published per-million-token prices (cursor.com/docs/models-and-pricing, read 2026-10-07).\nconst PRICES = [\n ['grok-4.7', 'Grok 4.7: $2 in / $6 out per million tokens; the Fast tier, the default speed on Pro and above, is $4 / $12. A Cursor model, so it draws on the larger included pool first.'],\n ['opus-5.5', 'Claude Opus 5.5: $4 in / $20 out per million tokens.'],\n ['opus-5-5', 'Claude Opus 5.5: $4 in / $20 out per million tokens.'],\n ['sonnet-5.5', 'Claude Sonnet 5.5: $2 in / $10 out per million tokens.'],\n ['sonnet-5-5', 'Claude Sonnet 5.5: $2 in / $10 out per million tokens.'],\n ['composer', 'A Cursor model: it draws on the larger included pool first.'],\n]\nfunction priceNote() {\n const spec = (modelSpec() || '').toLowerCase()\n const hit = PRICES.find(([k]) => spec.includes(k))\n return hit ? hit[1] : 'Billed at the model’s API rate: first from your plan’s included usage, then on-demand if you allow it.'\n}\nfunction estimate() {\n const num = (id, d) => { const n = parseInt(document.getElementById(id).value, 10); return Number.isFinite(n) && n > 0 ? n : d }\n const screens = num('f-max', 8), tries = num('f-iter', 4), mins = num('f-timeout', 8), steps = document.getElementById('f-steps').checked\n const worst = screens * (tries * mins + (steps ? 4 : 0)) + 5\n const h = Math.floor(worst / 60), m = worst % 60\n document.getElementById('f-estimate').innerHTML =\n '<span><b>Up to ' + screens * tries + ' attempts</b> (' + screens + ' screen' + (screens === 1 ? '' : 's') + ' × ' + tries + (steps ? ' steps, after a planning pass of up to 4 min each' : ' attempts') + ').</span>' +\n '<span>Worst case about <b>' + (h ? h + ' h ' : '') + m + ' min</b> of agent time, since every attempt stops at its time box. Runs usually end sooner: a step that needs no change moves on.</span>' +\n '<span class=\"note\">' + (scope() === 'whole' ? 'Whole app: screens are mapped from the home page until the limit above.' : 'Pages you picked: at most ' + screens + ' of them are worked on.') + '</span>'\n}\nconst accounts = {}\nasync function loadAccount() {\n const agent = document.getElementById('f-agent').value, box = document.getElementById('f-account')\n // The CLI call takes a second or two; a model change only redraws the price.\n accounts[agent] = accounts[agent] || api('/api/account?agent=' + encodeURIComponent(agent)).catch(() => ({ account: null }))\n const r = await accounts[agent]\n const a = r.account\n const who = a ? '<span>Spends <b>' + esc(a.email || 'your account') + '</b>' + (a.plan ? ' · ' + esc(a.plan) + ' plan' : '') + '. To use a different account, sign in with that one in this shell (<code>agent login</code>) and restart the studio.</span>' : '<span>Spends the account this agent is signed in with in this shell.</span>'\n const usage = '<span class=\"note\">No agent reports how much credit is left, so this cannot show a balance. ' + (a && a.usageUrl ? 'Check it on <a href=\"' + esc(a.usageUrl) + '\" target=\"_blank\" rel=\"noopener\">your usage page</a>. ' : '') + 'If the account runs out mid-run, the run stops; resume it later or with another account.</span>'\n box.innerHTML = who + '<span>' + esc(priceNote()) + '</span>' + usage\n}\nfunction syncPills() {\n const set = new Set(document.getElementById('f-paths').value.split(',').map((x) => x.trim()))\n document.querySelectorAll('#f-route-pills .pill').forEach((p) => p.setAttribute('aria-pressed', String(set.has(p.dataset.r))))\n}\nasync function loadModels(force) {\n const agent = document.getElementById('f-agent').value, sel = document.getElementById('f-model'), note = document.getElementById('f-model-note')\n sel.innerHTML = '<option>Loading…</option>'; note.textContent = ''\n models = await api('/api/models?agent=' + encodeURIComponent(agent) + (force ? '&fresh=1' : '')).catch((e) => ({ models: [], note: e.message }))\n const last = store.get('last') || {}, lastModel = (last.agent === agent && last.model) ? last.model.split('?')[0] : null\n const def = models.models.find((m) => m.id === lastModel) || models.models.find((m) => m.isDefault)\n sel.innerHTML = '<option value=\"\">Agent default</option>' + models.models.map((m) => '<option value=\"' + esc(m.id) + '\"' + (def && def.id === m.id ? ' selected' : '') + '>' + esc(m.label === m.id ? m.id : m.label + ' — ' + m.id) + '</option>').join('') + '<option value=\"__custom\">Other model id…</option>'\n note.textContent = (models.source === 'live' ? models.models.length + ' models from your account. ' : '') + (models.note || '')\n note.className = models.source === 'none' && models.note ? 'note warn' : 'note'\n if (lastModel && !def) { sel.value = '__custom'; document.getElementById('f-custom').value = lastModel }\n renderParams()\n}\nfunction renderParams() {\n const id = document.getElementById('f-model').value\n document.getElementById('f-custom-wrap').hidden = id !== '__custom'\n const m = models && models.models.find((x) => x.id === id), last = store.get('last') || {}\n const lastParams = new URLSearchParams((last.model || '').split('?')[1] || '')\n document.getElementById('f-params').innerHTML = (m && m.params ? m.params : []).map((p) => '<label class=\"f\"><span>' + esc(p.label) + '</span><select data-param=\"' + esc(p.id) + '\"><option value=\"\">default</option>' + p.values.map((v) => '<option value=\"' + esc(v.value) + '\"' + (lastParams.get(p.id) === v.value ? ' selected' : '') + '>' + esc(v.label) + '</option>').join('') + '</select></label>').join('')\n document.querySelectorAll('[data-param]').forEach((s) => s.onchange = updateSpec)\n updateSpec()\n}\nfunction modelSpec() {\n const id = document.getElementById('f-model').value\n const base = id === '__custom' ? document.getElementById('f-custom').value.trim() : id\n if (!base) return null\n const params = [...document.querySelectorAll('[data-param]')].filter((s) => s.value).map((s) => s.dataset.param + '=' + s.value)\n return params.length ? base + '?' + params.join('&') : base\n}\nfunction updateSpec() { const s = modelSpec(); document.getElementById('f-spec').textContent = s ? 'model: ' + s : 'model: the agent’s default'; loadAccount() }\nlet chain = [], knownSkills = new Set()\nasync function loadSkills(last) {\n const sel = document.getElementById('f-skill'), note = document.getElementById('f-skill-note')\n try {\n const { skills } = await api('/api/skills')\n knownSkills = new Set(skills.map((s) => s.name))\n const groups = {}\n for (const s of skills) (groups[s.group || 'Skills'] = groups[s.group || 'Skills'] || []).push(s.name)\n sel.innerHTML = '<option value=\"\">Add a skill…</option>' + Object.entries(groups).map(([g, names]) => '<optgroup label=\"' + esc(g) + '\">' + names.map((n) => '<option>' + esc(n) + '</option>').join('') + '</optgroup>').join('')\n note.textContent = skills.length + ' skills. Each skill\\\\'s whole folder (references too) is given to the agent. With several, the agent applies them in this order.'\n } catch (e) { note.textContent = e.message; note.className = 'note warn' }\n if (last && /[\\\\\\\\/.]/.test(last)) document.getElementById('f-skill-path').value = last\n else chain = (last || '').split(',').map((x) => x.trim()).filter((x) => knownSkills.has(x))\n sel.onchange = () => { if (sel.value && !chain.includes(sel.value) && chain.length < 5) chain.push(sel.value); sel.value = ''; renderChain() }\n renderChain()\n}\nconst relatedCache = {}\nasync function renderChain() {\n const box = document.getElementById('f-chain'), next = document.getElementById('f-next')\n box.innerHTML = chain.length\n ? chain.map((n, i) => '<button type=\"button\" class=\"pill\" aria-pressed=\"true\" data-rm=\"' + esc(n) + '\" title=\"Remove\">' + (i + 1) + '. ' + esc(n) + ' ×</button>').join('')\n : '<span class=\"note\">No skill: the agent uses the built-in UX guidance.</span>'\n box.querySelectorAll('[data-rm]').forEach((b) => b.onclick = () => { chain = chain.filter((x) => x !== b.dataset.rm); renderChain() })\n next.innerHTML = ''\n const lastSkill = chain[chain.length - 1]\n if (!lastSkill || chain.length >= 5) return\n relatedCache[lastSkill] = relatedCache[lastSkill] || api('/api/skill?name=' + encodeURIComponent(lastSkill)).catch(() => ({ related: [] }))\n const { related } = await relatedCache[lastSkill]\n const offer = (related || []).filter((n) => knownSkills.has(n) && !chain.includes(n)).slice(0, 6)\n if (chain[chain.length - 1] !== lastSkill) return\n next.innerHTML = offer.length ? '<span class=\"note\">' + esc(lastSkill) + ' hands over to:</span>' + offer.map((n) => '<button type=\"button\" class=\"pill\" data-add=\"' + esc(n) + '\">+ ' + esc(n) + '</button>').join('') : ''\n next.querySelectorAll('[data-add]').forEach((b) => b.onclick = () => { chain.push(b.dataset.add); renderChain() })\n}\nasync function start() {\n const err = document.getElementById('f-error'), btn = document.getElementById('f-start')\n err.textContent = ''\n const num = (id, d) => { const n = parseInt(document.getElementById(id).value, 10); return Number.isFinite(n) ? n : d }\n const judgeOn = document.getElementById('f-judge').checked\n const body = {\n agent: document.getElementById('f-agent').value,\n model: modelSpec(),\n skill: document.getElementById('f-skill-path').value.trim() || chain.join(',') || null,\n devCommand: document.getElementById('f-dev').value.trim(),\n baseRef: document.getElementById('f-base').value,\n startPaths: scope() === 'whole' ? [] : document.getElementById('f-paths').value.split(',').map((x) => x.trim()).filter(Boolean),\n iterations: num('f-iter', 2), maxSurfaces: num('f-max', 8), timeoutMin: num('f-timeout', 15),\n judgeModel: judgeOn ? (document.getElementById('f-judge-model').value.trim() || null) : null,\n sync: document.getElementById('f-sync').checked,\n crawl: scope() === 'pages' && document.getElementById('f-crawl').checked,\n steps: document.getElementById('f-steps').checked,\n checkerModel: checkerPick().model,\n checkerVia: checkerPick().via,\n keepInvisible: document.getElementById('f-invisible').checked,\n ignore: document.getElementById('f-ignore').value.split('\\\\n').map((x) => x.trim()).filter(Boolean),\n }\n if (!body.devCommand) { err.textContent = 'Give the dev command.'; return }\n store.set('last', { ...body, judge: judgeOn })\n btn.disabled = true\n try {\n const { runId: id } = await api('/api/runs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })\n if (meta) meta.active = id\n await loadRuns(); showRun(id)\n } catch (e) { err.textContent = e.message } finally { btn.disabled = false }\n}\nfunction resumable() { return !!(meta && meta.canResume && state && state.options && state.phase !== 'done') }\ndocument.getElementById('resumeBtn').onclick = async () => {\n const b = document.getElementById('resumeBtn'), pd = document.getElementById('phaseDetail')\n b.disabled = true\n b.textContent = 'Resuming…'\n try {\n await api('/api/runs/' + runId + '/resume', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })\n if (meta) meta.active = runId\n await loadRuns(); await loadState()\n } catch (e) { pd.textContent = e.message; pd.className = 'sub err' } finally { b.textContent = '▶ Resume'; b.disabled = false }\n}\ndocument.getElementById('prBtn').onclick = async () => {\n const b = document.getElementById('prBtn'), pd = document.getElementById('phaseDetail'), label = b.textContent\n b.disabled = true\n b.textContent = 'Pushing…'\n try {\n const pr = await api('/api/runs/' + runId + '/pr', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })\n pd.textContent = (pr.added ? 'Added to PR #' : 'Opened draft PR #') + pr.number + '. Merge it from the Mushi console once its checks pass.'\n pd.className = 'sub'\n await loadState()\n } catch (e) { pd.textContent = e.message; pd.className = 'sub err' } finally { b.textContent = label; b.disabled = false }\n}\ndocument.getElementById('newBtn').onclick = openLauncher\ndocument.getElementById('stopBtn').onclick = async () => {\n const b = document.getElementById('stopBtn')\n b.disabled = true\n b.textContent = 'Stopping…'\n await api('/api/runs/' + runId + '/stop', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }).catch((e) => { document.getElementById('phaseDetail').textContent = e.message })\n b.textContent = '■ Stop'\n}\n\n// ── Live events ────────────────────────────────────────────────────────────\nlet stateTimer = null\nconst es = new EventSource(q('/api/events'))\nes.onmessage = (m) => {\n const e = JSON.parse(m.data)\n if (e.type === 'started') { if (meta) meta.active = e.runId; loadRuns(); return }\n if (e.type === 'log') { runLog.push(e); if (e.runId === runId) { const p = document.getElementById('runlog'); p.textContent += (p.textContent ? '\\\\n' : '') + e.message; p.scrollTop = p.scrollHeight } }\n if (e.type === 'agent') { (agentLog[e.surface] = agentLog[e.surface] || []).push(e.line); if (agentLog[e.surface].length > 1500) agentLog[e.surface] = agentLog[e.surface].slice(-800); if (e.runId === runId && e.surface === selected) { const o = document.getElementById('agentout'); if (o) { if (o.classList.contains('sub')) { o.textContent = e.line; o.classList.remove('sub') } else o.textContent += '\\\\n' + e.line; o.scrollTop = o.scrollHeight } else renderRun() } }\n if ((e.type === 'state' || e.type === 'phase') && e.runId === runId) { clearTimeout(stateTimer); stateTimer = setTimeout(() => { loadState(); if (e.type === 'phase') loadRuns() }, 150) }\n}\n\n;(async () => {\n meta = await api('/api/meta')\n document.getElementById('repo').textContent = meta.repo\n document.getElementById('newBtn').hidden = !meta.launcher\n await loadRuns()\n const want = new URLSearchParams(location.search).get('run') || meta.active || meta.initial\n if (want && runs.some((r) => r.runId === want)) showRun(want)\n else if (meta.launcher) openLauncher()\n else if (runs[0]) showRun(runs[0].runId)\n})()\n</script></body></html>`\n","// SPDX-License-Identifier: MIT\n/**\n * Turns a running app into a list of surfaces: every same-origin page\n * reachable from the start paths, plus the tabs, dialogs and menus each page\n * opens. Runs inside a guarded session, so nothing it clicks can write.\n *\n * Pages whose DOM structure matches one already seen (`/reports/1` and\n * `/reports/2`) are kept once.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { Page } from 'playwright'\nimport { gotoPatiently, replay, settle, surfaceUrl, type BrowserSession } from './capture.js'\nimport { isDestructiveLabel } from './guard.js'\nimport { isWorthVisiting, routesFromSource, sitemapPaths, trimTrailingSlashes } from './routes.js'\nimport type { ReplayStep, Surface, SurfaceKind } from './types.js'\n\nexport interface DiscoverOptions {\n baseUrl: string\n startPaths?: string[]\n /** Repo (or app) directory to read routes from; see routes.ts. */\n sourceDir?: string\n maxPages?: number\n maxStatesPerPage?: number\n /** Paths never visited (globs on pathname), on top of sign-out routes. */\n excludePaths?: string[]\n /**\n * Only pathnames equal to or under this prefix are visited, e.g.\n * `/mushi-mushi/admin` for a console that shares its origin with docs and\n * a landing site. Omit for the whole origin.\n */\n scopePath?: string\n /**\n * When two pages count as the same: 'shape' (default) by DOM structure, so\n * `/reports/1` and `/reports/2` are worked on once; 'route' by pathname with\n * ids collapsed and the query ignored, for an app shell whose sidebar and\n * header make every page hash alike (the console kept 3 of 75 loads by\n * shape, 2026-10-24).\n */\n dedupe?: 'shape' | 'route'\n /**\n * Visit only startPaths (and the tabs, dialogs and menus they open): no\n * routes from the source or sitemap, no following links. Set when the\n * person named the pages.\n */\n onlyStartPaths?: boolean\n onProgress?: (msg: string) => void\n /** Stops discovery between pages (the studio's Stop button). */\n signal?: AbortSignal\n}\n\n/** Redirects to one sign-in path before discovery treats it as an auth wall. */\nconst AUTH_WALL_REDIRECTS = 5\n/** Redirects to one path that are followed; past it the target is a moving one. */\nconst MAX_REDIRECT_FOLLOWS = 3\n/** Page loads one mapping may make, per page it may keep: a hard stop for any loop. */\nconst LOADS_PER_PAGE = 5\nconst SIGN_IN_PATH_RE = /\\/(log-?in|sign-?in|auth)\\b/i\nconst SIGN_OUT_PATH_RE =/\\/(log-?out|sign-?out|logoff)\\b/i\n\n/** @internal Exported for tests only. Pure: `pathname` is `scope` or under it (`/a/admin` covers `/a/admin/x`, not `/a/administer`). */\nexport function inScope(pathname: string, scope: string | undefined): boolean {\n if (!scope) return true\n const s = trimTrailingSlashes(scope) || '/'\n if (s === '/') return true\n return pathname === s || pathname.startsWith(`${s}/`)\n}\n\n/** @internal Exported for tests only. Pure: a route key: the pathname with ids (numbers, uuids, long hex) collapsed, the query dropped. */\nexport function routeKey(path: string): string {\n const q = path.search(/[?#]/)\n const pathname = q < 0 ? path : path.slice(0, q)\n const collapsed = pathname\n .split('/')\n .map((seg) => (/^(\\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,})$/i.test(seg) ? ':id' : seg))\n .join('/')\n return trimTrailingSlashes(collapsed) || '/'\n}\n\n/** Pure: same-origin, normalized path (no hash), or null to skip. */\nexport function normalizeLink(href: string, baseUrl: string): string | null {\n let u: URL\n try {\n u = new URL(href, baseUrl)\n } catch {\n return null\n }\n const base = new URL(baseUrl)\n if (u.origin !== base.origin) return null\n if (!/^https?:$/.test(u.protocol)) return null\n if (SIGN_OUT_PATH_RE.test(u.pathname)) return null\n if (/\\.(png|jpe?g|gif|svg|webp|ico|pdf|zip|csv|json|xml|txt|js|css|map)$/i.test(u.pathname)) return null\n return u.pathname + u.search\n}\n\nexport function surfaceKey(path: string, steps: readonly ReplayStep[]): string {\n const raw = [path, ...steps.map((s) => s.label)].join(' > ')\n const slug = raw.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 80) || 'root'\n return `${slug}-${createHash('sha1').update(raw).digest('hex').slice(0, 6)}`\n}\n\nfunction globMatch(glob: string, path: string): boolean {\n const re = new RegExp(`^${glob.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*')}$`)\n return re.test(path)\n}\n\n/**\n * Structural fingerprint of the visible DOM: tags and roles to depth 8, with\n * runs of identical sibling shapes collapsed so a 3-row and a 30-row table\n * hash the same.\n */\nasync function domHash(page: Page): Promise<string> {\n const shape = await page.evaluate(() => {\n function sig(el: Element, depth: number): string {\n const role = el.getAttribute('role')\n const head = el.tagName.toLowerCase() + (role ? `[${role}]` : '')\n if (depth >= 8 || el.tagName === 'svg') return head\n const kids: string[] = []\n for (const child of Array.from(el.children)) {\n if (['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE'].includes(child.tagName)) continue\n // Hidden panels and closed dialogs are not part of what the user sees.\n if ((child as HTMLElement).hidden || getComputedStyle(child).display === 'none') continue\n const s = sig(child, depth + 1)\n if (kids[kids.length - 1] !== s) kids.push(s)\n }\n return kids.length ? `${head}(${kids.join(',')})` : head\n }\n return sig(document.body, 0)\n })\n return createHash('sha1').update(shape).digest('hex').slice(0, 16)\n}\n\ninterface Trigger {\n selector: string\n label: string\n role: string\n}\n\n/** A quoted attribute value: backslashes escaped before quotes, or a trailing `\\` would eat the closing quote. */\nfunction quoteAttr(value: string): string {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`\n}\n\n/** Pure, for tests: the selector replay uses for a trigger, by test id first, else by role and name. * @internal Exported for tests only.\n */\nexport function triggerSelector(testId: string | null, role: string, label: string): string {\n if (testId) return `[data-testid=${quoteAttr(testId)}]`\n return role ? `role=${role}[name=${quoteAttr(label)}]` : ''\n}\n\n/** Elements that open a state without navigating: tabs, dialog and menu triggers. */\nasync function findTriggers(page: Page): Promise<Trigger[]> {\n const raw = await page.evaluate(() => {\n const found: Array<{ testId: string | null; label: string; role: string }> = []\n const candidates = document.querySelectorAll(\n '[role=\"tab\"]:not([aria-selected=\"true\"]), [aria-haspopup=\"dialog\"], [aria-haspopup=\"menu\"], [aria-haspopup=\"true\"], button[aria-expanded=\"false\"]',\n )\n for (const el of Array.from(candidates)) {\n const r = el.getBoundingClientRect()\n if (r.width === 0 || r.height === 0) continue\n const label = (el.getAttribute('aria-label') || (el as HTMLElement).innerText || '').trim().replace(/\\s+/g, ' ').slice(0, 60)\n if (!label) continue\n const role = el.getAttribute('role') || (el.tagName === 'BUTTON' ? 'button' : el.tagName === 'A' ? 'link' : '')\n found.push({ testId: el.getAttribute('data-testid'), label, role })\n }\n return found\n })\n const triggers: Trigger[] = []\n const seen = new Set<string>()\n for (const { testId, label, role } of raw) {\n const selector = triggerSelector(testId, role, label)\n if (!selector || seen.has(selector)) continue\n seen.add(selector)\n triggers.push({ selector, label, role })\n }\n return triggers\n}\n\nasync function openedKind(page: Page, trigger: Trigger): Promise<SurfaceKind | null> {\n return page.evaluate((role) => {\n const visible = (sel: string) =>\n Array.from(document.querySelectorAll(sel)).some((el) => {\n const r = el.getBoundingClientRect()\n return r.width > 0 && r.height > 0\n })\n if (visible('[role=\"dialog\"], [role=\"alertdialog\"], dialog[open]')) return 'dialog'\n if (visible('[role=\"menu\"], [role=\"listbox\"]')) return 'menu'\n if (role === 'tab') return 'tab'\n return null\n }, trigger.role) as Promise<SurfaceKind | null>\n}\n\n/**\n * Pure: a screen's name. The page title, unless another screen already has\n * that title (an SPA often keeps one <title>), then a name from the path:\n * \"/\" → \"Home\", \"/account/settings/\" → \"Account / Settings\".\n * @internal Exported for tests only.\n */\nexport function pageLabel(title: string, path: string, others: ReadonlyArray<{ label: string }>): string {\n const t = title.trim()\n if (t && !others.some((o) => o.label === t)) return t\n const parts = new URL(path, 'http://x').pathname.split('/').filter(Boolean)\n const fromPath = parts.length\n ? parts.map((p) => decodeURIComponent(p).replace(/[-_]+/g, ' ').replace(/^\\w/, (c) => c.toUpperCase())).join(' / ')\n : 'Home'\n return others.some((o) => o.label === fromPath) ? `${fromPath} (${path})` : fromPath\n}\n\nexport async function discover(session: BrowserSession, opts: DiscoverOptions): Promise<Surface[]> {\n const maxPages = opts.maxPages ?? 40\n const maxStates = opts.maxStatesPerPage ?? 8\n const exclude = opts.excludePaths ?? []\n const progress = opts.onProgress ?? (() => {})\n const only = Boolean(opts.onlyStartPaths && opts.startPaths?.length)\n const seeded = [\n ...(opts.startPaths?.length ? opts.startPaths : ['/']),\n ...(only ? [] : (opts.sourceDir ? routesFromSource(opts.sourceDir) : []).filter(isWorthVisiting)),\n ...(only ? [] : (await sitemapPaths(opts.baseUrl)).filter(isWorthVisiting)),\n ]\n // Out-of-scope paths never enter the queue: they would spend page loads (a site sitemap lists docs and landing pages).\n const scoped = (p: string) => inScope(new URL(p, opts.baseUrl).pathname, opts.scopePath)\n const queue = [...new Set(seeded)].filter(scoped)\n progress(only ? `${queue.length} page(s) you named` : `${queue.length} start path(s) from the source, sitemap and options`)\n const visited = new Set<string>()\n const seenShapes = new Set<string>()\n // Many start paths landing on the same sign-in page = an auth wall.\n const redirectsTo = new Map<string, number>()\n const surfaces: Surface[] = []\n let loads = 0\n const page = await session.context.newPage()\n await page.setViewportSize({ width: 1440, height: 900 })\n\n try {\n // Pass 2 only re-tries pages the person named that pass 1 dropped (a slow\n // first compile, a navigation racing a click): glot.it lost /practice\n // inside a run while the same build found it on its own (2026-10-06).\n for (let pass = 1; pass <= 2; pass++) {\n if (pass === 2) {\n if (!only) break\n const strip = (p: string) => p.replace(/\\/(?=\\?|$)/, '')\n const missing = [...new Set(seeded)].filter((p) => !surfaces.some((s) => s.kind === 'page' && strip(s.path) === strip(p)))\n if (missing.length === 0) break\n progress(`retrying ${missing.join(', ')}: not captured on the first pass`)\n for (const p of missing) {\n visited.delete(p)\n visited.delete(strip(p) + '/')\n visited.delete(strip(p))\n }\n queue.push(...missing)\n }\n while (queue.length > 0 && surfaces.filter((s) => s.kind === 'page').length < maxPages) {\n if (opts.signal?.aborted) throw new Error('Stopped.')\n const path = queue.shift() as string\n if (++loads > maxPages * LOADS_PER_PAGE) {\n progress(`stopped mapping after ${loads - 1} page loads; ${queue.length + 1} path(s) not tried`)\n break\n }\n if (visited.has(path)) {\n if (only) progress(`skipped ${path}: already visited`)\n continue\n }\n visited.add(path)\n if (exclude.some((g) => globMatch(g, new URL(path, opts.baseUrl).pathname))) continue\n\n const failed = (err: Error) => {\n progress(`skipped ${path}: it did not load (${err.message.split('\\n')[0].slice(0, 120)})`)\n return undefined\n }\n const res = await gotoPatiently(page, surfaceUrl(opts.baseUrl, path)).catch(failed)\n if (res === undefined) continue\n // null = no response after a retry (the page reloaded itself twice): go\n // on with what is on screen rather than drop the page without a word.\n if (res && res.status() >= 400) {\n progress(`skipped ${path}: HTTP ${res.status()}`)\n continue\n }\n await settle(page)\n const landed = new URL(page.url())\n if (landed.origin !== new URL(opts.baseUrl).origin) {\n progress(`skipped ${path}: it leaves the app for ${landed.origin}`)\n continue\n }\n const landedPath = landed.pathname + landed.search\n // `/practice` → `/practice/` is the same page; loading it again only cost\n // time and, on glot.it, lost /practice and /chat (2026-10-06).\n const sameModuloSlash = (a: string, b: string) => a.replace(/\\/(?=\\?|$)/, '') === b.replace(/\\/(?=\\?|$)/, '')\n if (landedPath !== path && sameModuloSlash(landedPath, path)) {\n visited.add(landedPath)\n if (visited.has(landedPath) && surfaces.some((s) => s.kind === 'page' && s.path === landedPath)) continue\n } else if (landedPath !== path && only) {\n progress(`skipped ${path}: it opens ${landedPath} instead`)\n }\n if (landedPath !== path && !sameModuloSlash(landedPath, path)) {\n // Redirected (sign-in wall, trailing slash): record the target instead.\n const n = (redirectsTo.get(landed.pathname) ?? 0) + 1\n redirectsTo.set(landed.pathname, n)\n // A target that keeps changing (a timestamp in the query) would be\n // followed forever: follow redirects to one path a few times only.\n if (!visited.has(landedPath) && n <= MAX_REDIRECT_FOLLOWS) queue.unshift(landedPath)\n if (n === AUTH_WALL_REDIRECTS && SIGN_IN_PATH_RE.test(landed.pathname)) {\n // Seeded routes behind the wall would each cost a load and redirect; drop them.\n const skipped = queue.filter((p) => p !== landedPath).length\n queue.splice(0, queue.length, ...queue.filter((p) => p === landedPath))\n progress(\n `${n} paths redirect to ${landed.pathname}: the app needs a signed-in session. ` +\n `Skipping the other ${skipped} queued path(s). Run \\`mushi-ux login --url ${opts.baseUrl}\\` and pass --login-url.`,\n )\n }\n continue\n }\n\n const here = landedPath\n // A page that redirects on the client after it loaded (glot.it's\n // /profile → /account when signed out) destroys the page under a read:\n // that skips this page, never the run (it lost 11 minutes of mapping\n // and six found pages, 2026-10-07).\n let shape: string\n let title: string\n let links: Array<{ href: string; label: string }>\n try {\n shape = await domHash(page)\n // A page the person named is always worked on: in an app shell several\n // routes share one structure while loading, and glot.it lost /words,\n // /chat and /account to this check (2026-10-06).\n if (opts.dedupe === 'route') {\n if (seenShapes.has(`route:${routeKey(here)}`) && !only) continue\n } else if (seenShapes.has(shape) && !only) continue\n title = pageLabel(await page.title(), here, surfaces)\n links = await page.$$eval('a[href]', (as) =>\n as.map((a) => ({ href: a.getAttribute('href') ?? '', label: (a as HTMLElement).innerText.trim() })),\n )\n } catch (err) {\n if (opts.signal?.aborted) throw err\n progress(`skipped ${path}: it changed while being read (${(err as Error).message.split('\\n')[0].slice(0, 120)})`)\n continue\n }\n seenShapes.add(opts.dedupe === 'route' ? `route:${routeKey(here)}` : shape)\n surfaces.push({ key: surfaceKey(here, []), kind: 'page', path: here, steps: [], label: title, domHash: shape })\n progress(`page ${here}`)\n\n for (const { href, label } of links) {\n if (isDestructiveLabel(label)) continue\n const next = normalizeLink(href, page.url())\n if (!only && next && scoped(next) && !visited.has(next) && !queue.includes(next)) queue.push(next)\n }\n\n // Same rule for its tabs and dialogs: a failed read skips that state only.\n const triggers = (await findTriggers(page).catch(() => [] as Trigger[])).filter((t) => !isDestructiveLabel(t.label)).slice(0, maxStates)\n for (const trigger of triggers) {\n const step: ReplayStep = { action: 'click', selector: trigger.selector, label: trigger.label }\n try {\n await gotoPatiently(page, surfaceUrl(opts.baseUrl, here))\n await settle(page)\n await replay(page, [step])\n } catch {\n continue\n }\n const after = new URL(page.url())\n if (after.pathname + after.search !== here) {\n // The \"tab\" was a link in disguise; crawl it as a page.\n const next = normalizeLink(page.url(), opts.baseUrl)\n if (!only && next && scoped(next) && !visited.has(next) && !queue.includes(next)) queue.push(next)\n continue\n }\n let kind: SurfaceKind | null\n let stateShape: string\n try {\n kind = await openedKind(page, trigger)\n if (!kind) continue\n stateShape = await domHash(page)\n } catch (err) {\n if (opts.signal?.aborted) throw err\n continue\n }\n if (seenShapes.has(stateShape)) continue\n seenShapes.add(stateShape)\n surfaces.push({\n key: surfaceKey(here, [step]),\n kind,\n path: here,\n steps: [step],\n label: `${title} › ${trigger.label}`,\n domHash: stateShape,\n })\n progress(`${kind} ${here} › ${trigger.label}`)\n }\n }\n }\n } finally {\n await page.close()\n }\n return tidyLabels(surfaces)\n}\n\nconst escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * Drops the site name most page titles repeat (\"Account — glot.it\" →\n * \"Account\"), so the burndown reads as a list of screens. The site name is\n * the first or last title segment shared by at least two pages and half of\n * them. A home page titled \"Site – tagline\" becomes \"Home\". A label that\n * would collide with another keeps its full title.\n * @internal Exported for tests only.\n */\nexport function tidyLabels<T extends { label: string; path: string; kind: string }>(surfaces: T[]): T[] {\n const SEP = /\\s+[|–—·:-]\\s+/\n const pages = surfaces.filter((s) => s.kind === 'page')\n const counts = new Map<string, number>()\n for (const s of pages) {\n const parts = s.label.split(SEP).map((p) => p.trim())\n if (parts.length < 2) continue\n for (const p of new Set([parts[0]!, parts[parts.length - 1]!])) counts.set(p, (counts.get(p) ?? 0) + 1)\n }\n const site = [...counts].filter(([, n]) => n >= 2 && n * 2 >= pages.length).sort((a, b) => b[1] - a[1])[0]?.[0]\n if (!site) return surfaces\n const sep = String.raw`\\s+[|–—·:-]\\s+`\n const trailing = new RegExp(`${sep}${escapeRe(site)}(?=$|\\\\s›)`)\n const leading = new RegExp(`^${escapeRe(site)}${sep}`)\n const renamed = new Map<string, string>()\n for (const s of pages) {\n let next = s.label.replace(trailing, '')\n if (leading.test(next)) next = s.path === '/' ? 'Home' : next.replace(leading, '')\n if (next && next !== s.label) renamed.set(s.label, next)\n }\n const taken = new Set(pages.map((s) => s.label))\n const finalName = new Map<string, string>()\n for (const [from, to] of renamed) {\n if (taken.has(to) || [...finalName.values()].includes(to)) continue\n finalName.set(from, to)\n }\n return surfaces.map((s) => {\n const page = s.label.split(' › ')[0]!\n const to = finalName.get(page)\n return to ? { ...s, label: to + s.label.slice(page.length) } : s\n })\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Start paths read from the source, so discovery reaches pages nothing links\n * to (a settings tab only the sidebar opens, a page behind a button).\n *\n * - React Router: absolute `path=\"/x\"` props and `path: '/x'` route objects.\n * Relative child paths are left to the crawler, which follows the links\n * their layouts render.\n * - Next.js: `app/**\\/page.*` and `pages/**\\/*.*` files.\n * - Anything with a parameter (`:id`, `[id]`, `*`) is skipped: there is no\n * safe value to invent for it.\n */\n\nimport { closeSync, fstatSync, openSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative } from 'node:path'\n\nconst SKIP_DIRS = new Set(['node_modules', '.git', '.next', 'dist', 'build', '.turbo', '.worktrees', '.mushi', '.mushi-ux', 'coverage', '__tests__'])\nconst SOURCE_RE = /\\.(tsx|ts|jsx|js|mjs)$/\nconst MAX_FILES = 4000\n\nfunction isStatic(path: string): boolean {\n return path.startsWith('/') && !/[:*[\\]]/.test(path) && !path.includes('//')\n}\n\n/** Pure, for tests: absolute static paths declared in one React Router source file. */\nexport function reactRouterPaths(source: string): string[] {\n const out: string[] = []\n // `(?:\\{\\s*)?`, not `\\{?\\s*`: two adjacent `\\s*` made a run of spaces with\n // no quote after it quadratic (CodeQL js/polynomial-redos).\n const re = /\\bpath\\s*[=:]\\s*(?:\\{\\s*)?([\"'`])(\\/[^\"'`]*)\\1/g\n for (const m of source.matchAll(re)) if (isStatic(m[2])) out.push(m[2])\n return out\n}\n\n/** Pure, for tests: the URL path a Next.js route file serves, or null. */\nexport function nextRoutePath(relFile: string): string | null {\n const parts = relFile.split(/[\\\\/]/)\n const appAt = parts.lastIndexOf('app')\n const pagesAt = parts.lastIndexOf('pages')\n let segs: string[]\n if (appAt >= 0 && /^page\\.(tsx|jsx|ts|js|mdx)$/.test(parts[parts.length - 1])) {\n segs = parts.slice(appAt + 1, -1).filter((s) => !/^\\(.*\\)$/.test(s) && !s.startsWith('@'))\n } else if (pagesAt >= 0 && SOURCE_RE.test(parts[parts.length - 1])) {\n segs = parts.slice(pagesAt + 1)\n const last = segs.pop()?.replace(SOURCE_RE, '') ?? ''\n if (last.startsWith('_') || segs[0] === 'api') return null\n if (last !== 'index') segs.push(last)\n } else {\n return null\n }\n const path = '/' + segs.join('/')\n return isStatic(path) ? path : null\n}\n\n/**\n * A route worth a screen in the burndown: concrete (no template or dynamic\n * segments) and not an error, auth-callback, API or dev-only page.\n */\nexport function isWorthVisiting(route: string): boolean {\n return route.startsWith('/') && !/[$[{:*]/.test(route) && !/^\\/(api|_|404|500)(\\/|$)|\\/callback(\\/|$)|^\\/dev(\\/|$)/.test(route)\n}\n\nexport function routesFromSource(root: string): string[] {\n const found = new Set<string>()\n let files = 0\n const walk = (dir: string, depth: number) => {\n if (depth > 8 || files > MAX_FILES) return\n let names: string[]\n try {\n names = readdirSync(dir)\n } catch {\n return\n }\n for (const name of names) {\n if (SKIP_DIRS.has(name)) continue\n const abs = join(dir, name)\n // One handle for the stat and the read, so the size checked is the\n // size of the bytes read (CodeQL js/file-system-race).\n let fd: number\n let isDir: boolean\n let text = ''\n try {\n fd = openSync(abs, 'r')\n } catch {\n continue\n }\n try {\n const st = fstatSync(fd)\n isDir = st.isDirectory()\n if (!isDir && st.size < 400_000 && /\\.(tsx|jsx|ts|js)$/.test(name) && !/\\.(test|spec|stories)\\./.test(name)) {\n text = readFileSync(fd, 'utf8')\n }\n } catch {\n continue\n } finally {\n closeSync(fd)\n }\n if (isDir) {\n walk(abs, depth + 1)\n continue\n }\n if (!SOURCE_RE.test(name) && !name.endsWith('.mdx')) continue\n if (/\\.(test|spec|stories)\\./.test(name)) continue\n files++\n const rel = relative(root, abs)\n const next = nextRoutePath(rel)\n if (next) found.add(next)\n if (text.includes('Route') || text.includes('createBrowserRouter') || text.includes('createRoutesFromElements')) {\n for (const p of reactRouterPaths(text)) found.add(p)\n }\n }\n }\n walk(root, 0)\n return [...found].sort()\n}\n\n/** Paths listed in /sitemap.xml on the same origin; empty when there is none. */\nexport async function sitemapPaths(baseUrl: string): Promise<string[]> {\n try {\n const res = await fetch(new URL('/sitemap.xml', baseUrl), { signal: AbortSignal.timeout(10_000) })\n if (!res.ok || !(res.headers.get('content-type') ?? '').includes('xml')) return []\n const xml = await res.text()\n const origin = new URL(baseUrl).origin\n const out = new Set<string>()\n for (const m of xml.matchAll(/<loc>\\s*([^<\\s]+)\\s*<\\/loc>/g)) {\n try {\n const u = new URL(m[1])\n // Production sitemaps list the live domain; map their paths onto this server.\n const path = u.pathname + u.search\n if (u.origin === origin || isStatic(u.pathname)) out.add(path)\n } catch {\n /* not a URL */\n }\n }\n return [...out]\n } catch {\n return []\n }\n}\n\n\nconst COMPONENT_DIRS = ['_components', 'components']\nconst MAX_SCREEN_FILES = 12\n\n/** A loop, not `/\\/+$/`: that regex is quadratic on a long run of '/' that does not end the string. */\nexport function trimTrailingSlashes(s: string): string {\n let end = s.length\n while (end > 0 && s.charCodeAt(end - 1) === 47) end--\n return s.slice(0, end)\n}\n\n/**\n * The source files that render one URL path, so the agent starts editing\n * instead of searching: the Next.js page file, the layout beside it, and\n * the components kept next to it. Empty when the router is not one we read\n * (the agent then finds the files itself). On glot.it an attempt spent its\n * whole 15 minutes searching for /practice's files (2026-10-06).\n */\nexport function screenFiles(root: string, urlPath: string): string[] {\n const want = trimTrailingSlashes(urlPath.split(/[?#]/)[0]!) || '/'\n let page: string | null = null\n let files = 0\n const walk = (dir: string, depth: number) => {\n if (page || depth > 8 || files > MAX_FILES) return\n let names: string[]\n try {\n names = readdirSync(dir)\n } catch {\n return\n }\n for (const name of names) {\n if (page) return\n if (SKIP_DIRS.has(name)) continue\n const abs = join(dir, name)\n let st\n try {\n st = statSync(abs)\n } catch {\n continue\n }\n if (st.isDirectory()) {\n walk(abs, depth + 1)\n continue\n }\n files++\n const rel = relative(root, abs).replace(/\\\\/g, '/')\n if (nextRoutePath(rel) === want) page = rel\n }\n }\n walk(root, 0)\n // Set inside walk(), which TypeScript's narrowing does not follow.\n const found = page as string | null\n if (!found) return []\n const dir = found.includes('/') ? found.slice(0, found.lastIndexOf('/')) : ''\n const out: string[] = [found]\n const list = (d: string) => {\n try {\n return readdirSync(join(root, d))\n } catch {\n return []\n }\n }\n for (const name of list(dir)) if (/^layout\\.(tsx|jsx|ts|js)$/.test(name)) out.push(dir ? `${dir}/${name}` : name)\n for (const sub of COMPONENT_DIRS) {\n const d = dir ? `${dir}/${sub}` : sub\n for (const name of list(d)) if (SOURCE_RE.test(name) && !/\\.(test|spec|stories)\\./.test(name)) out.push(`${d}/${name}`)\n }\n return out.slice(0, MAX_SCREEN_FILES)\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Final review by a different model: for each screen the loop changed, one\n * pairwise comparison of the original against the kept version, per\n * viewport, grounded in the repo's design tokens and the measured probe\n * deltas.\n *\n * Why pairwise and evidence-bound: open-ended screenshot critique is mostly\n * wrong (Baymard measured an 80% error rate for GPT-4 UX audits; UICrit found\n * 13% of zero-shot critiques valid). Asking \"which is better, and point at\n * where\" is a narrower question, every claim must carry a bounding box, and\n * the two images are shown in random order so the model cannot learn that\n * \"the second one is the new one\".\n *\n * The judge advises; it never reverts or keeps anything. Runs on the\n * person's own Anthropic credentials.\n */\n\nimport Anthropic from '@anthropic-ai/sdk'\nimport { betaZodOutputFormat } from '@anthropic-ai/sdk/helpers/beta/zod'\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { z } from 'zod'\nimport { cropTop } from './image.js'\nimport type { SurfaceState } from './state.js'\nimport type { ProbeResult } from './types.js'\n\nexport const DEFAULT_JUDGE_MODEL = 'claude-opus-5-5'\nconst MAX_DESIGN_CHARS = 16_000\n\nconst Box = z.object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n})\n\nconst Claim = z.object({\n image: z.enum(['A', 'B']),\n box: Box,\n what: z.string(),\n why: z.string(),\n})\n\nconst JudgeOutput = z.object({\n preferred: z.enum(['A', 'B', 'tie']),\n confidence: z.enum(['low', 'medium', 'high']),\n summary: z.string(),\n better: z.array(Claim),\n worse: z.array(Claim),\n design_system_breaks: z.array(\n Claim.extend({\n token_or_rule: z.string(),\n }),\n ),\n})\ntype JudgeOutputT = z.infer<typeof JudgeOutput>\n\nexport interface JudgeClaim {\n /** Which capture the claim points at, after un-shuffling. */\n image: 'before' | 'after'\n box: { x: number; y: number; width: number; height: number }\n what: string\n why: string\n tokenOrRule?: string\n}\n\nexport interface JudgeVerdict {\n viewport: string\n model: string\n preferred: 'before' | 'after' | 'tie'\n confidence: 'low' | 'medium' | 'high'\n summary: string\n better: JudgeClaim[]\n worse: JudgeClaim[]\n designBreaks: JudgeClaim[]\n /** Claims dropped because their box fell outside the image. */\n droppedClaims: number\n /** Set when the model declined or the call failed; no verdict then. */\n error?: string\n}\n\nconst RUBRIC = `You review UI changes for a solo developer. You will see two screenshots of the same screen, labelled A and B, in random order. One is the original and one was edited by a coding agent. You are not told which is which.\n\nDecide which one is better for the person using this screen, judged on:\n1. Clarity: is the screen's purpose and primary action obvious within a few seconds?\n2. Hierarchy: does visual weight (size, colour, position) match importance?\n3. Density: is there less noise (duplicated info, wordy copy, competing calls to action) without losing needed information?\n4. Consistency with the design system given below (tokens, spacing scale, type scale, components). Ignore taste that the design system does not support.\n5. Accessibility you can see: contrast, text size, target size, focus or state indicators.\n\nMeasured numbers for both images are provided (accessibility violations, sideways scroll, small tap targets, console errors). Treat them as facts; do not contradict them.\n\nRules for claims:\n- Every claim points at a region with a box in that image's pixel coordinates (origin top-left).\n- Only claim what is visible in the screenshots. Do not guess about interactions, data, or other screens.\n- Prefer few, specific claims over many generic ones. Generic advice (\"make it responsive\", \"add more whitespace\") is not a claim.\n- If the two are equally good, or the difference is too small to matter, answer \"tie\".\n- \"design_system_breaks\" lists places in either image that visibly break the given tokens or rules; name the token or rule.`\n\nexport interface JudgeOptions {\n dir: string\n repoRoot: string\n designFiles: string[]\n model?: string\n client?: Anthropic\n /** Deterministic order for tests; defaults to Math.random. */\n random?: () => number\n}\n\nfunction designContext(repoRoot: string, files: string[]): string {\n let out = ''\n for (const f of files) {\n if (out.length >= MAX_DESIGN_CHARS) break\n try {\n const text = readFileSync(join(repoRoot, f), 'utf8')\n out += `\\n--- ${f} ---\\n${text.slice(0, MAX_DESIGN_CHARS - out.length)}\\n`\n } catch {\n /* unreadable file: skip */\n }\n }\n return out || '(No design-system files found. Judge consistency against the rest of the screen.)'\n}\n\nfunction probeLine(label: string, p: ProbeResult): string {\n const axe = p.axe.map((v) => `${v.id}×${v.count}`).join(', ') || 'none'\n return `${label}: accessibility violations ${axe}; sideways scroll ${p.overflowX ? 'yes' : 'no'}; small tap targets ${p.smallTargets}; overlapping or oversized boxes ${p.layout?.length ?? 0}; console errors ${p.consoleErrors.length}; layout shift ${p.cls}`\n}\n\nfunction pngSize(buf: Buffer): { width: number; height: number } {\n return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }\n}\n\n/** Pure: map the shuffled A/B answer back to before/after and drop out-of-image claims. */\nexport function unshuffle(\n out: JudgeOutputT,\n aIsBefore: boolean,\n sizes: { A: { width: number; height: number }; B: { width: number; height: number } },\n viewport: string,\n model: string,\n): JudgeVerdict {\n const side = (img: 'A' | 'B'): 'before' | 'after' => ((img === 'A') === aIsBefore ? 'before' : 'after')\n let dropped = 0\n const keep = (c: z.infer<typeof Claim> & { token_or_rule?: string }): JudgeClaim[] => {\n const size = sizes[c.image]\n const inside =\n c.box.width > 0 &&\n c.box.height > 0 &&\n c.box.x >= 0 &&\n c.box.y >= 0 &&\n c.box.x + c.box.width <= size.width + 2 &&\n c.box.y + c.box.height <= size.height + 2\n if (!inside) {\n dropped++\n return []\n }\n return [{ image: side(c.image), box: c.box, what: c.what, why: c.why, tokenOrRule: c.token_or_rule }]\n }\n return {\n viewport,\n model,\n preferred: out.preferred === 'tie' ? 'tie' : side(out.preferred),\n confidence: out.confidence,\n summary: out.summary,\n better: out.better.flatMap(keep),\n worse: out.worse.flatMap(keep),\n designBreaks: out.design_system_breaks.flatMap(keep),\n droppedClaims: dropped,\n }\n}\n\n/** Judge one screen at one viewport: its baseline against its last kept capture. */\nexport async function judgeSurface(s: SurfaceState, viewport: string, opts: JudgeOptions): Promise<JudgeVerdict | null> {\n const kept = [...s.iterations].reverse().find((i) => i.outcome === 'accepted' && i.after[viewport])\n const before = s.baseline[viewport]\n if (!kept || !before) return null\n const after = kept.after[viewport]\n const model = opts.model ?? DEFAULT_JUDGE_MODEL\n const client = opts.client ?? new Anthropic()\n\n const beforePng = readFileSync(join(opts.dir, before.png))\n const width = pngSize(beforePng).width\n const maxHeight = Math.round(width * (viewport === 'mobile' ? 2.5 : 1.25))\n const bImg = cropTop(beforePng, maxHeight)\n const aImg = cropTop(readFileSync(join(opts.dir, after.png)), maxHeight)\n const aIsBefore = (opts.random ?? Math.random)() < 0.5\n const [imgA, imgB] = aIsBefore ? [bImg, aImg] : [aImg, bImg]\n const [probeA, probeB] = aIsBefore ? [before.probes, after.probes] : [after.probes, before.probes]\n\n const image = (png: Buffer): Anthropic.Beta.BetaImageBlockParam => ({\n type: 'image',\n source: { type: 'base64', media_type: 'image/png', data: png.toString('base64') },\n })\n\n try {\n const response = await client.beta.messages.parse({\n model,\n max_tokens: 16_000,\n betas: ['server-side-fallback-2026-07-01'],\n fallbacks: 'default',\n output_config: { effort: 'high', format: betaZodOutputFormat(JudgeOutput) },\n system: [\n { type: 'text', text: RUBRIC },\n {\n type: 'text',\n text: `Design system of this repository:\\n${designContext(opts.repoRoot, opts.designFiles)}`,\n // Same rubric + tokens for every screen in the run: cache the prefix.\n cache_control: { type: 'ephemeral' },\n },\n ],\n messages: [\n {\n role: 'user',\n content: [\n { type: 'text', text: `Screen: ${s.surface.label} (${s.surface.path}), ${viewport} viewport.` },\n { type: 'text', text: 'Image A:' },\n image(imgA),\n { type: 'text', text: 'Image B:' },\n image(imgB),\n { type: 'text', text: `${probeLine('A', probeA)}\\n${probeLine('B', probeB)}\\n\\nWhich is better, A or B?` },\n ],\n },\n ],\n })\n if (response.stop_reason === 'refusal') {\n return failed(viewport, model, `The model declined (${response.stop_details?.category ?? 'no category'}).`)\n }\n const parsed = response.parsed_output\n if (!parsed) return failed(viewport, model, `No structured answer (stop reason ${response.stop_reason}).`)\n return unshuffle(parsed, aIsBefore, { A: pngSize(imgA), B: pngSize(imgB) }, viewport, response.model)\n } catch (err) {\n if (err instanceof Anthropic.AuthenticationError) {\n return failed(viewport, model, 'No valid Anthropic credentials. Set ANTHROPIC_API_KEY or run `ant auth login`.')\n }\n if (err instanceof Anthropic.RateLimitError) return failed(viewport, model, 'Rate limited by the Anthropic API.')\n if (err instanceof Anthropic.APIError) return failed(viewport, model, `Anthropic API error ${err.status}: ${err.message}`)\n throw err\n }\n}\n\nfunction failed(viewport: string, model: string, error: string): JudgeVerdict {\n return {\n viewport,\n model,\n preferred: 'tie',\n confidence: 'low',\n summary: '',\n better: [],\n worse: [],\n designBreaks: [],\n droppedClaims: 0,\n error,\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The loop. One run:\n *\n * worktree + dev server → discover surfaces → for each surface:\n * baseline (desktop + mobile) → prompt packet → agent edits →\n * recapture → pixel diff + probes → keep (commit) or roll back →\n * re-check a sample of finished screens for collateral changes\n *\n * State is saved after every step, so `--resume <runId>` continues an\n * interrupted run. Events go to the dashboard (dashboard.ts) as they happen.\n */\n\nimport type { EventEmitter } from 'node:events'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { attemptLogBase, describeAgentLine, formatStep, sessionIdOf } from './agent-events.js'\nimport { getAgent, type AgentAdapter, type AgentName, type AgentRunOptions } from './agents.js'\nimport { captureSurface, openSession, type BrowserSession } from './capture.js'\nimport { discover } from './discover.js'\nimport type { AllowRule } from './guard.js'\nimport { checkStep, type CheckerSpec } from './checker.js'\nimport { pixelDiff } from './image.js'\nimport { judgeSurface } from './judge.js'\nimport { buildPacket, buildPlanPacket, findDesignFiles, MAX_PLAN_STEPS, MAX_STEP_FILES, parsePlan, PLAN_POINTER_PROMPT, POINTER_PROMPT } from './packet.js'\nimport { preflightAgent } from './preflight.js'\nimport { screenFiles } from './routes.js'\nimport { isFrameworkNoise, probePenalty } from './probes.js'\nimport { expectedHead, saveSkillFiles } from './resume.js'\nimport { appEnv, run, type RunResult } from './proc.js'\nimport type { ResolvedSkill } from './skills.js'\nimport {\n loadState,\n newRunId,\n runDir,\n saveState,\n savePng,\n type IterationRecord,\n type PlanStep,\n type RunPhase,\n type RunState,\n type ShotRef,\n type SurfaceState,\n} from './state.js'\nimport { VIEWPORTS, type ProbeResult } from './types.js'\nimport { agentFinalMessage, assistantText, clsNeedsSecondLook, decide, explainNoEdit, steadierCls } from './verdict.js'\nimport {\n changedFiles,\n commitAll,\n createWorktree,\n diffText,\n detectInstallCommand,\n headSha,\n resetRunBranch,\n revertAll,\n SCRATCH_DIR,\n startDevServer,\n type DevServer,\n} from './worktree.js'\n\n/** Share of a finished screen's content that must move to count as collateral. */\nconst REGRESSION_CONTENT_RATIO = 0.05\n/** Ignore tiny moves (a clock, a counter) below this many pixels. */\nconst REGRESSION_MIN_PIXELS = 200\n/**\n * The planning pass of steps mode gets at most this long. Grok 4.7 xhigh took\n * 16 steps in 6 minutes on a three-skill chain and wrote no plan with 4 + 2\n * minutes (glot.it tone training, 2026-10-07); a plan that fails costs the\n * screen its small steps.\n */\nconst PLAN_TIMEOUT_MS = 6 * 60_000\n/** \"Time is up\" continuations of the same agent session, when a box ran out with nothing to show. */\nconst PLAN_NUDGE_MS = 3 * 60_000\nconst EDIT_NUDGE_MS = 3 * 60_000\nconst PLAN_NUDGE =\n 'Time is up. Do not read any more files. Write .mushi-ux/PLAN.md now with the improvements you found, one per line starting with \"- \", then stop.'\nconst EDIT_NUDGE =\n 'Time is up. Do not read any more files. Make the one change you have decided on now, touching at most 3 files, then stop.'\n/** How often a working attempt checks in (git status + state save). */\nconst HEARTBEAT_MS = 30_000\n\nexport type LoopEvent =\n | { type: 'log'; message: string }\n | { type: 'agent'; surface: string; line: string; kind?: string }\n | { type: 'state' }\n | { type: 'phase'; phase: RunPhase; detail: string | null }\n\nexport interface LoopOptions {\n repoRoot: string\n devCommand: string\n /** null skips the install; undefined detects it from the lockfile. */\n installCommand?: string | null\n startPaths?: string[]\n agent: AgentName\n /** Overrides `agent` with a custom adapter (tests, other harnesses). */\n agentAdapter?: AgentAdapter\n model?: string | null\n iterations?: number\n maxSurfaces?: number\n agentTimeoutMs?: number\n skillText?: string | null\n /** A skill folder (SKILL.md + references); wins over skillText. */\n skill?: ResolvedSkill | null\n /** Git ref the worktree branches from. Default HEAD. */\n baseRef?: string\n allow?: AllowRule[]\n /** Selectors that are not the app's UI, on top of DEFAULT_IGNORE (ignore.ts). */\n ignore?: string[]\n profileDir?: string\n /** Browser build for profileDir: 'chrome' for a profile Google Chrome made (`--profile-dir`). */\n channel?: 'chrome' | 'chromium'\n regressionSample?: number\n /** Model for the final pairwise review; null turns it off. */\n judgeModel?: string | null\n resumeRunId?: string\n /** Follow links from startPaths too. Off: only the named pages and the states they open. */\n crawl?: boolean\n /** Aborting stops the run between steps and kills a running agent. */\n signal?: AbortSignal\n /** Check the agent can read a file before anything slow starts. Default on (off for a custom adapter and the cloud agent). */\n preflight?: boolean\n /** Plan each screen into small steps first, then make one step per attempt (iterations caps the steps). */\n steps?: boolean\n /**\n * A second model that reviews each kept step and may roll it back, never\n * keep a rejected one (ADR 0021). null: measurements alone decide.\n */\n checker?: CheckerSpec | null\n /** Keep an edit with nothing visible, flagged for review (ADR 0021). Default on. */\n keepInvisible?: boolean\n /** Saved with the run for a later resume only: the login URL behind profileDir, and whether it synced. */\n loginUrl?: string | null\n sync?: boolean\n events?: EventEmitter\n}\n\nexport interface LoopHandle {\n runId: string\n dir: string\n done: Promise<RunState>\n}\n\nfunction emit(events: EventEmitter | undefined, e: LoopEvent) {\n events?.emit('event', e)\n}\n\n/** The screenshot a finished screen should still look like. */\nfunction referenceShot(s: SurfaceState, viewport: string): ShotRef | undefined {\n const kept = [...s.iterations].reverse().find((i) => i.outcome === 'accepted')\n return kept?.after[viewport] ?? s.baseline[viewport]\n}\n\n/**\n * Saved probes from before a noise rule existed still carry framework\n * console messages; a resumed run must not score or brief them.\n */\n/** What the next attempt is told after one ran out of time without an edit. */\nfunction timeoutNote(timeoutMs: number): string {\n const minutes = Math.round(timeoutMs / 60_000)\n return `It read for ${minutes} minutes without making any edit and was stopped. Start from the files under \"Start here\", pick one change, and make it within ${Math.max(1, Math.round(minutes / 3))} minutes.`\n}\n\nfunction scrubFrameworkNoise(state: RunState): void {\n const clean = (ref: ShotRef | undefined) => {\n if (!ref) return\n const kept = ref.probes.consoleErrors.filter((e) => !isFrameworkNoise(e))\n if (kept.length === ref.probes.consoleErrors.length) return\n ref.probes = { ...ref.probes, consoleErrors: kept }\n ref.penalty = probePenalty(ref.probes)\n }\n for (const s of state.surfaces) {\n Object.values(s.baseline).forEach(clean)\n for (const it of s.iterations) Object.values(it.after).forEach(clean)\n }\n}\n\n/**\n * Pure: why mapping found no screen, from the \"skipped\" lines and the dev\n * server's first error. Every page failing the same way (all HTTP 500) points\n * at the app, not the pages, so that case leads with the dev server.\n * @internal Exported for tests only.\n */\nexport function noScreensMessage(skipped: string[], devError: string | null): string {\n const reasons = skipped.map((s) => s.replace(/^\\S+:\\s*/, ''))\n const unique = [...new Set(reasons)]\n const lines: string[] = []\n if (skipped.length && unique.length === 1 && /HTTP 5\\d\\d/.test(unique[0])) {\n lines.push(`No screen to work on: every page returned ${unique[0]}, so the app's dev server is failing, not the pages.`)\n } else if (skipped.length) {\n lines.push(`No screen to work on: all ${new Set(skipped.map((s) => s.split(':')[0])).size} page(s) were skipped (${unique.slice(0, 3).join('; ')}).`)\n } else {\n lines.push('No screen to work on: mapping found no page. Name the pages to work on, or check that the home page loads.')\n }\n if (devError) lines.push(`The dev server said: ${devError}`)\n lines.push('Fix the app or the dev command (for example a different bundler flag), then start a new run. The full output is in run.log.')\n return lines.join('\\n')\n}\n\n/** A commit subject's summary stops here, at a whole word. */\nconst SUMMARY_MAX = 72\nconst DANGLING = /[\\s,]+(?:a|an|and|as|at|between|by|for|from|in|into|is|of|on|or|so|that|the|to|while|with)$/i\n\n/**\n * Pure: the commit message for a kept attempt. Host apps lint commits as\n * conventional commits (glot.it allows only the standard types) and turn the\n * subjects into their in-app changelog, so the subject is `fix(ux):` and a\n * plain sentence that ends on a whole word, without file names; the screen,\n * the step and the measurements go in the body.\n * @internal Exported for tests only.\n */\nexport function commitMessage(path: string, screen: string, step: string | null, reason: string): string {\n const name = screen.split(/\\s+[—|–]\\s+/)[0].trim() || path\n const summary = (step ? stepSummary(step) : '') || `improve the ${name} screen`\n const body = [step ? `${name} (${path}): ${step}` : `${name} (${path})`, reason]\n return [`fix(ux): ${lowerFirst(summary)}`, ...body.map((p) => wrapAt(p, BODY_WIDTH))].join('\\n\\n')\n}\n\n/** Conventional-commit lint rejects body lines over 100 characters. */\nconst BODY_WIDTH = 100\n\nfunction wrapAt(text: string, width: number): string {\n const lines: string[] = []\n let line = ''\n for (const word of text.split(/\\s+/).filter(Boolean)) {\n if (line && [...`${line} ${word}`].length > width) {\n lines.push(line)\n line = word\n } else line = line ? `${line} ${word}` : word\n }\n if (line) lines.push(line)\n // A line that starts \"word: \" reads as a commit footer to commitlint, which then wants a blank\n // line before it (\"…screen\\nreader: in x.tsx\" failed glot.it's lint, 2026-10-07). Pull the\n // previous word down so the line starts mid-sentence.\n for (let i = 1; i < lines.length; i++) {\n if (!FOOTER_TOKEN.test(lines[i])) continue\n const prev = lines[i - 1].split(' ')\n if (prev.length < 2) continue\n lines[i] = `${prev.pop()} ${lines[i]}`\n lines[i - 1] = prev.join(' ')\n }\n return lines.join('\\n')\n}\n\n/** What conventional-commit parsers read as a footer token at the start of a line. */\nconst FOOTER_TOKEN = /^(?:[A-Za-z][\\w-]*|BREAKING CHANGE): /\n\n/** \"Fix the caption\" → \"fix the caption\"; \"CTA buttons\" and quoted text stay as they are. */\nconst lowerFirst = (s: string) => (/^[A-Z][a-z]/.test(s) ? s[0].toLowerCase() + s.slice(1) : s)\n\nconst isPath = (code: string) => code.includes('/') || /\\.[a-z]{2,4}$/i.test(code)\n\nfunction stepSummary(step: string): string {\n // Plans lead with a plain summary before a colon (\"Fix the caption contrast: in `x.tsx`, ...\").\n const lead = step.match(/^([^:`]{8,90}):\\s/)?.[1]\n let s = lead ?? step.replace(/^(?:In\\s+)?`[^`]+`(?:\\s*\\([^)]*\\))?\\s*[,:]?\\s*/i, '').split(/(?<=\\.)\\s|;\\s/)[0]\n s = s\n .replace(/\\s*\\(([^()]*)\\)/g, (m, inner: string) => (inner.includes('`') ? '' : m))\n // A file named after \"in\" or \"from\" goes with its preposition.\n .replace(/\\s+(?:in|from|of|on)\\s+`([^`]*)`/gi, (m, inner: string) => (isPath(inner) ? '' : m))\n // Code spans pair left to right: paths go, other code stays as words.\n .replace(/`([^`]*)`/g, (_m, inner: string) => (isPath(inner) ? ' ' : inner.replace(/[\"']/g, '')))\n .replace(/\\s{2,}/g, ' ')\n .trim()\n if (s.length > SUMMARY_MAX) {\n const cut = s.lastIndexOf(' ', SUMMARY_MAX)\n s = s.slice(0, cut > 0 ? cut : SUMMARY_MAX)\n const open = s.lastIndexOf('(')\n if (open > s.lastIndexOf(')')) s = s.slice(0, open)\n // A cut sentence should not end on a word that needs the next one.\n while (DANGLING.test(s)) s = s.replace(DANGLING, '')\n }\n s = s.replace(/^[\\s,;:.—–-]+|[\\s,;:.—–-]+$/g, '')\n return s ? s[0].toUpperCase() + s.slice(1) : ''\n}\n\nexport function startLoop(opts: LoopOptions): LoopHandle {\n const runId = opts.resumeRunId ?? newRunId()\n const dir = runDir(opts.repoRoot, runId)\n const done = runLoop(opts, runId, dir)\n return { runId, dir, done }\n}\n\nasync function runLoop(opts: LoopOptions, runId: string, dir: string): Promise<RunState> {\n const events = opts.events\n // Also kept in run.log, so a past or failed run still shows what happened.\n const log = (message: string) => {\n emit(events, { type: 'log', message })\n try {\n mkdirSync(dir, { recursive: true })\n appendFileSync(join(dir, 'run.log'), `${new Date().toISOString().slice(11, 19)} ${message}\\n`)\n } catch {\n /* the log is a convenience; the run goes on without it */\n }\n }\n const agent = opts.agentAdapter ?? getAgent(opts.agent)\n const iterations = opts.iterations ?? 2\n const timeoutMs = opts.agentTimeoutMs ?? 10 * 60_000\n\n const state: RunState = loadState(dir) ?? {\n version: 1,\n runId,\n baseUrl: '',\n createdAt: new Date().toISOString(),\n updatedAt: '',\n agent: agent.name,\n model: opts.model ?? null,\n skill: opts.skill ? { name: opts.skill.name, source: opts.skill.source } : null,\n baseRef: opts.baseRef ?? 'HEAD',\n phase: 'starting',\n worktree: null,\n branch: null,\n baseSha: null,\n surfaces: [],\n }\n scrubFrameworkNoise(state)\n const resuming = Boolean(state.updatedAt)\n if (resuming) {\n // A resumed run starts clean: the old stop or error is history, kept in run.log.\n state.error = null\n state.finishedAt = null\n state.stopped = false\n state.current = null\n }\n // Everything a later resume needs, so it takes only the run id.\n if (!state.options) {\n state.options = {\n agent: String(opts.agent),\n model: opts.model ?? null,\n devCommand: opts.devCommand,\n installCommand: opts.installCommand,\n startPaths: opts.startPaths,\n crawl: opts.crawl,\n iterations,\n checker: opts.checker ?? null,\n keepInvisible: opts.keepInvisible !== false,\n maxSurfaces: opts.maxSurfaces ?? 10,\n agentTimeoutMs: timeoutMs,\n ignore: opts.ignore,\n allow: opts.allow,\n judgeModel: opts.judgeModel ?? null,\n loginUrl: opts.loginUrl ?? null,\n sync: opts.sync,\n steps: opts.steps,\n }\n }\n if (opts.skill) {\n state.skill = { name: opts.skill.name, source: opts.skill.source }\n try {\n saveSkillFiles(dir, opts.skill)\n } catch {\n // Only a later resume needs the copy; it says so if it is missing.\n }\n }\n const persist = () => {\n saveState(dir, state)\n emit(events, { type: 'state' })\n }\n const phase = (p: RunPhase, detail: string | null = null) => {\n state.phase = p\n state.phaseDetail = detail\n emit(events, { type: 'phase', phase: p, detail })\n persist()\n }\n const skillText = opts.skill?.text ?? opts.skillText ?? null\n\n // The run checks in every 30 s in every phase (a save stamps updatedAt), so\n // the studio and the console can tell a long install from a dead process.\n const beat = setInterval(() => {\n try {\n persist()\n } catch {\n // The next beat, or the next real state change, saves again.\n }\n }, HEARTBEAT_MS)\n try {\n return await runSteps()\n } catch (err) {\n const stopped = Boolean(opts.signal?.aborted)\n state.stopped = stopped\n state.error = stopped ? 'Stopped from the studio.' : (err as Error).message.slice(0, 2000)\n // A stop can land mid-edit: leave the branch at its last kept commit.\n if (stopped && state.worktree) await revertAll(state.worktree).catch(() => undefined)\n state.current = null\n state.finishedAt = new Date().toISOString()\n phase('failed', state.error.split('\\n')[0].slice(0, 200))\n throw err\n } finally {\n clearInterval(beat)\n }\n\n async function runSteps(): Promise<RunState> {\n if (opts.preflight !== false && !opts.agentAdapter && agent.name !== 'cursor-cloud') {\n log(`Checking that ${agent.name} can read files…`)\n phase('starting', 'Checking the agent can read files')\n const problem = await preflightAgent(agent, { model: opts.model, signal: opts.signal })\n if (opts.signal?.aborted) throw new Error('Stopped.')\n if (problem) throw new Error(problem)\n log('Agent check passed.')\n }\n if (!state.worktree) {\n log('Creating a worktree for the agent…')\n phase('worktree', `from ${state.baseRef ?? 'HEAD'}`)\n const wt = await createWorktree(opts.repoRoot, runId, state.baseRef ?? 'HEAD')\n state.worktree = wt.path\n state.branch = wt.branch\n state.baseSha = wt.baseSha\n persist()\n } else if (!existsSync(state.worktree)) {\n throw new Error(`The run's worktree ${state.worktree} is gone, so this run cannot continue. Start a new run.`)\n }\n // Runs from before the flag existed: one that got as far as mapping was installed.\n if (state.installed === undefined && state.surfaces.length > 0) state.installed = true\n if (!state.installed) {\n const install = opts.installCommand === undefined ? detectInstallCommand(state.worktree) : opts.installCommand\n if (install) {\n log(`Installing dependencies: ${install}`)\n phase('install', install)\n const res = await run(install, [], { cwd: state.worktree, shell: true, timeoutMs: 15 * 60_000, env: appEnv() })\n if (res.exitCode !== 0) throw new Error(`Install failed in the worktree:\\n${res.tail}`)\n }\n state.installed = true\n persist()\n }\n const wtPath = state.worktree\n if (resuming) await restoreWorktree(wtPath)\n const designFiles = findDesignFiles(wtPath)\n\n log(`Starting the dev server in the worktree: ${opts.devCommand}`)\n phase('dev-server', opts.devCommand)\n // The dev server's first error line names the cause when every page fails.\n let devError: string | null = null\n const server: DevServer = await startDevServer(wtPath, opts.devCommand, {\n path: opts.startPaths?.[0],\n onLine: (l) => {\n log(`[dev] ${l.slice(0, 200)}`)\n if (!devError && /\\b(error|module not found)\\b/i.test(l)) devError = l.trim().slice(0, 300)\n },\n })\n state.baseUrl = server.url\n persist()\n\n const session: BrowserSession = await openSession({ profileDir: opts.profileDir, channel: opts.channel, allow: opts.allow, ignore: opts.ignore })\n try {\n if (state.surfaces.length === 0) {\n log('Mapping screens…')\n phase('mapping', null)\n // Ask for every named page at once first: the dev server compiles them\n // together instead of one per visit (mapping took 10 min for 8 pages\n // on glot.it's webpack dev server, 2026-10-07). Plain GETs only.\n if (opts.startPaths?.length) {\n const t0 = Date.now()\n await Promise.all(\n // Follow redirects: /chat answers 308 → /chat/ at once, and only the target compiles.\n opts.startPaths.map((p) => fetch(new URL(p, server.url), { signal: AbortSignal.timeout(180_000) }).then((r) => r.arrayBuffer()).catch(() => null)),\n )\n log(`warmed ${opts.startPaths.length} page(s) in ${Math.round((Date.now() - t0) / 1000)} s`)\n }\n const skipped: string[] = []\n const found = await discover(session, {\n baseUrl: server.url,\n startPaths: opts.startPaths,\n onlyStartPaths: Boolean(opts.startPaths?.length) && !opts.crawl,\n sourceDir: wtPath,\n signal: opts.signal,\n onProgress: (m) => {\n log(`found ${m}`)\n if (m.startsWith('skipped ')) skipped.push(m.slice('skipped '.length))\n // The studio shows the latest mapping line under the phase.\n phase('mapping', m.slice(0, 200))\n },\n })\n // Nothing to work on is a failed run, not a finished one: say why.\n if (found.length === 0) throw new Error(noScreensMessage(skipped, devError))\n state.surfaces = found.slice(0, opts.maxSurfaces ?? 10).map((surface) => ({\n surface,\n status: 'pending',\n note: null,\n baseline: {},\n iterations: [],\n }))\n log(`${state.surfaces.length} screen(s) on the burndown (${found.length} found).`)\n persist()\n }\n\n // Captures start from a visited app, the same for every screen (capture.ts warmUp).\n log('Opening every screen once, so each capture starts from a loaded app…')\n await session.warmUp(server.url, [...new Set(state.surfaces.map((x) => x.surface.path))])\n phase('working', null)\n for (const s of state.surfaces) {\n if (opts.signal?.aborted) throw new Error('Stopped.')\n if (!['pending', 'baseline', 'iterating'].includes(s.status)) continue\n if (s.status === 'iterating') await revertAll(wtPath) // interrupted mid-edit\n await processSurface(s)\n }\n state.current = null\n if (opts.judgeModel) {\n phase('reviewing', opts.judgeModel)\n await runJudge(opts.judgeModel)\n }\n state.finishedAt = new Date().toISOString()\n phase('done', null)\n log(`Done. Branch ${state.branch} holds every kept change; open a draft PR from it when you are happy.`)\n return state\n } finally {\n await session.close()\n server.stop()\n persist()\n }\n\n /**\n * Before a resumed run goes on: the branch back on its last saved kept\n * commit (a crash can land between an attempt's commit and the save), and\n * a half-finished attempt's edits thrown away. That attempt runs again.\n */\n async function restoreWorktree(wt: string): Promise<void> {\n const want = expectedHead(state)\n const head = await headSha(wt)\n if (want && head !== want) {\n try {\n await resetRunBranch(wt, want)\n } catch {\n throw new Error(\n `The run branch ${state.branch} no longer holds its last kept commit ${want.slice(0, 8)}: it was changed outside the run. Start a new run.`,\n )\n }\n log(`The run branch was ahead of its last saved attempt (${head.slice(0, 8)}); moved it back to ${want.slice(0, 8)}. That attempt runs again.`)\n }\n await revertAll(wt)\n log('Resumed: unfinished edits cleared; carrying on from the first unfinished screen.')\n }\n\n /**\n * Run the agent; if its time box runs out with nothing to show (no plan,\n * no edit) and it can resume its session, continue that same session once\n * with \"time is up, write it now\" and a short extra box. Grok 4.7 xhigh\n * read for whole attempts and ignored in-prompt deadlines (glot.it,\n * 2026-10-06); the continuation keeps everything it read.\n */\n async function runWithNudge(\n runOpts: AgentRunOptions & { nudge: { prompt: string; ms: number; needed: () => Promise<boolean> } },\n ): Promise<RunResult> {\n const { nudge, ...base } = runOpts\n const first = await agent.run(base)\n if (!first.timedOut || !agent.canResume || opts.signal?.aborted) return first\n const session = sessionIdOf(first.stdout)\n if (!session || !(await nudge.needed())) return first\n log(` time is up: asking the agent to finish now (${Math.round(nudge.ms / 60_000)} more min, same session)`)\n const second = await agent.run({ ...base, prompt: nudge.prompt, timeoutMs: nudge.ms, resumeSession: session })\n return {\n exitCode: second.exitCode,\n timedOut: second.timedOut,\n durationMs: first.durationMs + second.durationMs,\n tail: second.tail,\n stdout: `${first.stdout}\\n${second.stdout}`,\n }\n }\n\n /** Fresh scratch dir for one agent run: the skill, and the screenshots to start from. */\n function prepareScratch(current: Record<string, ShotRef>): { shots: Record<string, string>; probes: Record<string, ProbeResult> } {\n const scratch = join(wtPath, SCRATCH_DIR)\n rmSync(scratch, { recursive: true, force: true })\n mkdirSync(scratch, { recursive: true })\n if (opts.skill) {\n for (const [rel, buf] of Object.entries(opts.skill.files)) {\n const target = join(scratch, 'skill', ...rel.split('/'))\n mkdirSync(dirname(target), { recursive: true })\n writeFileSync(target, buf)\n }\n }\n const shots: Record<string, string> = {}\n for (const [vp, ref] of Object.entries(current)) {\n writeFileSync(join(scratch, `${vp}.png`), readFileSync(join(dir, ref.png)))\n shots[vp] = `${SCRATCH_DIR}/${vp}.png`\n }\n return { shots, probes: Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes])) }\n }\n\n /**\n * Steps mode: one short agent run that lists small, separate improvements\n * for the screen and edits nothing (anything it does edit is thrown\n * away). Null when it produced no usable list: the screen then gets\n * whole-screen attempts instead.\n */\n async function planSurface(s: SurfaceState, current: Record<string, ShotRef>, entryFiles: string[]): Promise<{ steps: PlanStep[]; session?: string | null } | null> {\n const planMs = Math.min(timeoutMs, PLAN_TIMEOUT_MS)\n const { shots, probes } = prepareScratch(current)\n const maxSteps = Math.min(MAX_PLAN_STEPS, iterations)\n writeFileSync(\n join(wtPath, SCRATCH_DIR, 'PROMPT.md'),\n buildPlanPacket({ surface: s.surface, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, timeBudgetMin: Math.round(planMs / 60_000), entryFiles }, maxSteps),\n )\n s.status = 'iterating'\n const startedAt = new Date().toISOString()\n state.current = { surface: s.surface.key, attempt: 1, startedAt, timeoutMs: planMs, steps: 0, lastStep: null, files: [], heartbeatAt: startedAt }\n phase('working', `${s.surface.label}, planning small steps`)\n log(` planning ${s.surface.label} in small steps…`)\n // Its steps go to agent/<screen>-plan.steps.log, so a failed plan can be read.\n const planLog = join(dir, 'agent', `${attemptLogBase(s.surface.key, 0).slice(0, -2)}-plan.steps.log`)\n try {\n mkdirSync(dirname(planLog), { recursive: true })\n writeFileSync(planLog, '')\n } catch {\n // The log is for reading later only.\n }\n const planFile = join(wtPath, SCRATCH_DIR, 'PLAN.md')\n const res = await runWithNudge({\n cwd: wtPath,\n prompt: PLAN_POINTER_PROMPT,\n model: opts.model,\n timeoutMs: planMs,\n signal: opts.signal,\n nudge: {\n prompt: PLAN_NUDGE,\n ms: PLAN_NUDGE_MS,\n needed: async () => !existsSync(planFile) || parsePlan(readFileSync(planFile, 'utf8')).length === 0,\n },\n onLine: (line) => {\n for (const step of describeAgentLine(line, wtPath)) {\n const text = formatStep(step)\n try {\n appendFileSync(planLog, `${text}\\n`)\n } catch {\n // See above.\n }\n emit(events, { type: 'agent', surface: s.surface.key, line: text, kind: step.kind })\n }\n },\n })\n if (opts.signal?.aborted) throw new Error('Stopped.')\n // The file first (written early, refined later); then the reply; then anything the agent said before it was stopped.\n const fromFile = existsSync(planFile) ? readFileSync(planFile, 'utf8') : ''\n const text = parsePlan(fromFile).length ? fromFile : (agentFinalMessage(res.stdout) ?? assistantText(res.stdout))\n await revertAll(wtPath) // planning never edits\n const items = parsePlan(text, maxSteps)\n if (items.length === 0) {\n log(` no plan came back${res.timedOut ? ' (the agent ran out of time)' : ''}; working on the whole screen instead.`)\n return null\n }\n log(` plan: ${items.map((t, i) => `${i + 1}. ${t}`).join(' ')}`)\n return { steps: items.map((t) => ({ text: t, status: 'pending' as const })), session: agent.canResume ? sessionIdOf(res.stdout) : null }\n }\n\n /** Record which plan step an attempt worked on, and how it went. */\n function markStep(\n step: PlanStep | null,\n info: { index: number; total: number } | null,\n record: IterationRecord,\n status: PlanStep['status'],\n ): void {\n if (!step || !info) return\n step.status = status\n step.attempt = record.n\n record.step = step.text\n record.reason = `Step ${info.index}/${info.total}: ${record.reason}`\n step.reason = record.reason\n }\n\n async function capture(s: SurfaceState): Promise<Record<string, { png: Buffer; probes: ProbeResult }>> {\n // Each capture has its own clean browser context, so the viewports run side by side.\n const shots = await Promise.all(VIEWPORTS.map((vp) => captureSurface(session, state.baseUrl, s.surface, vp)))\n return Object.fromEntries(VIEWPORTS.map((vp, i) => [vp.name, shots[i]]))\n }\n\n function shotRefs(s: SurfaceState, label: string, shots: Record<string, { png: Buffer; probes: ProbeResult }>) {\n const refs: Record<string, ShotRef> = {}\n for (const [vp, shot] of Object.entries(shots)) {\n refs[vp] = { png: savePng(dir, `shots/${s.surface.key}/${label}-${vp}.png`, shot.png), probes: shot.probes, penalty: probePenalty(shot.probes) }\n }\n return refs\n }\n\n async function processSurface(s: SurfaceState): Promise<void> {\n log(`▶ ${s.surface.label}`)\n if (Object.keys(s.baseline).length === 0) {\n try {\n s.baseline = shotRefs(s, 'baseline', await capture(s))\n } catch (err) {\n s.status = 'blocked'\n s.note = `Could not capture the screen: ${(err as Error).message.slice(0, 200)}`\n persist()\n return\n }\n }\n s.status = 'baseline'\n persist()\n\n // A resumed screen carries on from what it already has: compare against\n // the last kept version, tell the agent why its last try was rolled\n // back, and stop where a finished attempt would have stopped.\n const entryFiles = screenFiles(wtPath, s.surface.path)\n const lastKept = [...s.iterations].reverse().find((i) => i.outcome === 'accepted')\n let current = lastKept ? lastKept.after : s.baseline\n const last = s.iterations[s.iterations.length - 1]\n let previousRejection: string | null =\n last?.outcome === 'rejected' ? last.reason : last?.outcome === 'agent_failed' && last.timedOut ? timeoutNote(timeoutMs) : null\n // Steps mode: plan once (no edits), then one plan step per attempt.\n // Plan again when planning failed and nothing has come of the screen since (only failed attempts).\n if (opts.steps && (s.plan === undefined || (s.plan === null && s.iterations.every((i) => i.outcome === 'agent_failed')))) {\n s.plan = await planSurface(s, current, entryFiles)\n persist()\n }\n const plan = opts.steps && s.plan?.steps.length ? s.plan : null\n // The session each step resumes, so the agent keeps the files it already read\n // (each fresh step re-read 5-19 files and ran 3-23 searches, glot.it 2026-10-07).\n // Only while the files match its memory: after the plan or a kept step.\n let carrySession: string | null = plan && agent.canResume && !s.iterations.some((i) => i.outcome !== 'accepted') ? plan.session ?? null : null\n const pending = plan ? plan.steps.filter((p) => p.status === 'pending').length : 0\n const settled = last?.outcome === 'no_change' || (last?.outcome === 'agent_failed' && !last.timedOut)\n const first = s.iterations.length + 1\n const lastAttempt = plan ? first + pending - 1 : settled ? 0 : iterations\n for (let n = first; n <= lastAttempt; n++) {\n const step = plan?.steps.find((p) => p.status === 'pending') ?? null\n const stepInfo = step && plan\n ? { text: step.text, index: plan.steps.indexOf(step) + 1, total: plan.steps.length, done: plan.steps.filter((p) => p.status === 'done').map((p) => p.text) }\n : null\n const { shots, probes } = prepareScratch(current)\n writeFileSync(\n join(wtPath, SCRATCH_DIR, 'PROMPT.md'),\n buildPacket({ surface: s.surface, iteration: n, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, previousRejection, timeBudgetMin: Math.round(timeoutMs / 60_000), entryFiles, step: stepInfo }),\n )\n s.status = 'iterating'\n const startedAt = new Date().toISOString()\n const live = { surface: s.surface.key, attempt: n, startedAt, timeoutMs, steps: 0, lastStep: null as string | null, files: [] as string[], heartbeatAt: startedAt }\n state.current = live\n phase('working', stepInfo ? `${s.surface.label}, step ${stepInfo.index} of ${stepInfo.total}` : `${s.surface.label}, attempt ${n} of ${iterations}`)\n\n // Readable steps for the live view and the saved log tail.\n const steps: string[] = []\n const logDir = join(dir, 'agent')\n const logBase = join(logDir, attemptLogBase(s.surface.key, n))\n try {\n mkdirSync(logDir, { recursive: true })\n writeFileSync(`${logBase}.steps.log`, '')\n } catch {\n // Only the reload view of the studio needs the file; the run goes on without it.\n }\n // Check in while the agent works, so a viewer can tell a slow attempt from a dead run.\n const heartbeat = setInterval(() => {\n void changedFiles(wtPath)\n .then((f) => {\n if (state.current !== live) return\n live.files = f.slice(0, 50)\n live.heartbeatAt = new Date().toISOString()\n persist()\n })\n .catch(() => undefined)\n }, HEARTBEAT_MS)\n let res\n try {\n res = await runWithNudge({\n cwd: wtPath,\n prompt: carrySession ? `${POINTER_PROMPT}\\n\\nThis continues your session for this screen: you have already read its files. Do not read them again unless you need a file you have not seen. Make this step's change now.` : POINTER_PROMPT,\n model: opts.model,\n timeoutMs,\n signal: opts.signal,\n resumeSession: carrySession ?? undefined,\n nudge: {\n prompt: EDIT_NUDGE,\n ms: EDIT_NUDGE_MS,\n needed: async () => (await changedFiles(wtPath).catch(() => [])).length === 0,\n },\n onLine: (line) => {\n for (const step of describeAgentLine(line, wtPath)) {\n const text = formatStep(step)\n steps.push(text)\n if (steps.length > 400) steps.splice(0, 200)\n live.steps++\n live.lastStep = text\n try {\n appendFileSync(`${logBase}.steps.log`, `${text}\\n`)\n } catch {\n // See above: never fail an attempt over the step file.\n }\n emit(events, { type: 'agent', surface: s.surface.key, line: text, kind: step.kind })\n }\n },\n })\n } finally {\n clearInterval(heartbeat)\n }\n try {\n mkdirSync(logDir, { recursive: true })\n writeFileSync(`${logBase}.log`, res.stdout)\n } catch {\n // The raw log is for debugging only; never fail an attempt over it.\n }\n if (opts.signal?.aborted) throw new Error('Stopped.')\n const files = await changedFiles(wtPath)\n const record: IterationRecord = {\n n,\n agent: agent.name,\n model: opts.model ?? null,\n startedAt,\n durationMs: res.durationMs,\n outcome: 'no_change',\n reason: '',\n commitSha: null,\n pixelDiff: {},\n after: {},\n diffPng: {},\n logTail: (steps.length ? steps.join('\\n') : res.tail).slice(-2000),\n }\n\n if ((res.exitCode !== 0 || res.timedOut) && files.length === 0) {\n record.outcome = 'agent_failed'\n record.timedOut = res.timedOut\n const minutes = Math.round(timeoutMs / 60_000)\n record.reason = res.timedOut\n ? `The agent ran out of time (${minutes} min) after ${steps.length} steps without editing anything.`\n : `The agent exited with code ${res.exitCode}.`\n markStep(step, stepInfo, record, 'failed')\n s.iterations.push(record)\n persist()\n log(` attempt ${n}: ${record.reason}`)\n // A crash or a blocked agent will fail again: stop. Running out of\n // time is worth one more try with a firmer brief (glot.it /practice,\n // 2026-10-06: 15 minutes of reading, no edit).\n if (!res.timedOut) break\n previousRejection = timeoutNote(timeoutMs)\n continue\n }\n\n let afterShots: Record<string, { png: Buffer; probes: ProbeResult }> | null = null\n if (files.length > 0) {\n await new Promise((r) => setTimeout(r, 2000)) // let the dev server rebuild\n afterShots = await capture(s).catch(() => null)\n const beforeProbes = Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes]))\n const afterProbes = afterShots ? Object.fromEntries(Object.entries(afterShots).map(([vp, r]) => [vp, r.probes])) : null\n if (afterShots && afterProbes && clsNeedsSecondLook(beforeProbes, afterProbes)) {\n // One more shot once the reload has settled; keep the lower layout shift.\n await new Promise((r) => setTimeout(r, 2000))\n const again = await capture(s).catch(() => null)\n if (again) {\n const steady = steadierCls(afterProbes, Object.fromEntries(Object.entries(again).map(([vp, r]) => [vp, r.probes])))\n for (const vp of Object.keys(afterShots)) afterShots[vp] = { ...afterShots[vp]!, probes: steady[vp]! }\n }\n }\n }\n const ratios: Record<string, number> = {}\n if (afterShots) {\n record.after = shotRefs(s, `iter${n}`, afterShots)\n for (const [vp, shot] of Object.entries(afterShots)) {\n const before = readFileSync(join(dir, current[vp].png))\n const d = pixelDiff(before, shot.png)\n ratios[vp] = Math.round(d.ratio * 10_000) / 10_000\n record.diffPng[vp] = savePng(dir, `shots/${s.surface.key}/iter${n}-${vp}-diff.png`, d.diffPng)\n record.changes = { ...record.changes, [vp]: { width: d.width, height: d.height, boxes: d.regions } }\n }\n }\n record.pixelDiff = ratios\n const verdict = decide({\n filesChanged: files.length,\n before: Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes])),\n after: afterShots ? Object.fromEntries(Object.entries(afterShots).map(([vp, r]) => [vp, r.probes])) : null,\n pixelRatios: ratios,\n keepInvisible: opts.keepInvisible !== false,\n })\n record.outcome = verdict.outcome\n record.reason = verdict.reason\n // Only an attempt with no edits is explained by the agent's words; one whose\n // edits changed nothing visible keeps that reason (it said \"made no edits\"\n // for a real edit to flow-layout.ts on glot.it, 2026-10-07).\n if (verdict.outcome === 'no_change' && files.length === 0) {\n const why = explainNoEdit(agentFinalMessage(res.stdout))\n record.outcome = why.outcome\n record.reason = why.reason\n }\n record.timedOut = res.timedOut || undefined\n // A step is one small change: a sprawling edit is rolled back as too big.\n if (step && record.outcome === 'accepted' && files.length > MAX_STEP_FILES) {\n record.outcome = 'rejected'\n record.reason = `Too big for one step: ${files.length} files changed (at most ${MAX_STEP_FILES}). Make a smaller change.`\n }\n if (record.outcome === 'accepted') record.needsReview = verdict.needsReview || undefined\n // The checker only ever vetoes: it reviews what the measurements kept (ADR 0021).\n if (record.outcome === 'accepted' && opts.checker) {\n log(` checking with ${opts.checker.model}…`)\n phase('working', `${s.surface.label}: ${opts.checker.model} reviews the change`)\n const vp = afterShots?.mobile ? 'mobile' : Object.keys(afterShots ?? {})[0]\n const visible = !record.needsReview && vp && afterShots?.[vp]\n const review = await checkStep({\n dir,\n name: `${s.surface.key}-iter${n}`,\n screen: s.surface.label,\n step: step?.text ?? 'Improve this screen for the person using it.',\n visual: visible ? { before: readFileSync(join(dir, current[vp].png)), after: afterShots![vp]!.png, regions: record.changes?.[vp]?.boxes ?? [] } : null,\n diff: await diffText(wtPath).catch(() => ''),\n repoDir: wtPath,\n spec: opts.checker,\n signal: opts.signal,\n })\n record.checker = review\n if (review.verdict === 'revert') {\n record.outcome = 'rejected'\n record.reason = `Rolled back by ${review.model}: ${review.summary}`.slice(0, 600)\n } else if (review.error) {\n log(` ${review.model} review failed: ${review.error}`)\n record.reason += ` The ${review.model} review could not run (${review.error.slice(0, 160)}), so the measurements decided.`\n } else {\n record.reason += ` ${review.model}: ${review.verdict === 'keep' ? 'agrees' : 'unsure, kept on the measurements'}.`\n }\n }\n markStep(step, stepInfo, record, record.outcome === 'accepted' ? 'done' : record.outcome === 'no_change' ? 'skipped' : 'failed')\n log(` attempt ${n}: ${record.reason}`)\n\n if (record.outcome === 'accepted') {\n record.commitSha = await commitAll(wtPath, commitMessage(s.surface.path, s.surface.label, step?.text ?? null, record.reason))\n current = record.after\n s.status = 'accepted'\n s.iterations.push(record)\n persist()\n carrySession = agent.canResume ? sessionIdOf(res.stdout) ?? carrySession : null\n continue\n }\n await revertAll(wtPath)\n s.iterations.push(record)\n persist()\n // Whole-screen mode stops at \"no change\"; steps mode moves to the next\n // step. A blocked agent (it said so) stops either way.\n if (verdict.outcome === 'no_change' && (!step || record.outcome === 'agent_failed')) break\n previousRejection = record.outcome === 'rejected' ? record.reason : null\n // A rolled-back edit is gone from the files but not from the session's memory: start fresh.\n carrySession = null\n }\n\n // Decided from the records: a later no-change attempt must not hide a kept one.\n const kept = s.iterations.filter((i) => i.outcome === 'accepted')\n // Once per screen, not after every kept step: the screens it might have moved\n // are re-shot once for all of this screen's steps.\n if (kept.length > 0) await checkRegressions(s)\n if (kept.length > 0) {\n s.status = 'accepted'\n s.note = kept[kept.length - 1].reason\n } else {\n const rejected = s.iterations.some((i) => i.outcome === 'rejected' || i.outcome === 'capture_failed')\n // Only failed attempts: the agent never finished, which is not \"no change needed\".\n const neverFinished = s.iterations.length > 0 && s.iterations.every((i) => i.outcome === 'agent_failed')\n s.status = rejected ? 'reverted' : neverFinished ? 'blocked' : 'skipped'\n s.note = s.iterations[s.iterations.length - 1]?.reason ?? null\n }\n rmSync(join(wtPath, SCRATCH_DIR), { recursive: true, force: true })\n persist()\n }\n\n /** Second-opinion review of every kept change. Advisory: it never reverts anything. */\n async function runJudge(model: string): Promise<void> {\n state.judgeModel = model\n const changed = state.surfaces.filter((x) => x.iterations.some((i) => i.outcome === 'accepted'))\n if (changed.length === 0) return\n log(`Reviewing ${changed.length} changed screen(s) with ${model}…`)\n for (const s of changed) {\n if (s.judge?.length) continue\n const verdicts = []\n for (const vp of VIEWPORTS) {\n const v = await judgeSurface(s, vp.name, { dir, repoRoot: wtPath, designFiles, model })\n if (v) verdicts.push(v)\n }\n s.judge = verdicts\n const errors = verdicts.filter((v) => v.error)\n if (errors.length) log(` review of ${s.surface.label} failed: ${errors[0].error}`)\n const prefersBefore = verdicts.filter((v) => !v.error && v.preferred === 'before' && v.confidence !== 'low')\n if (prefersBefore.length) {\n log(` ⚠ reviewer prefers the original ${s.surface.label} (${prefersBefore.map((v) => v.viewport).join(', ')}) — check it before merging`)\n }\n persist()\n }\n }\n\n /** After a kept change, re-shoot a sample of finished screens and flag any that moved. */\n async function checkRegressions(changed: SurfaceState): Promise<void> {\n const finished = state.surfaces\n .filter((x) => x !== changed && ['accepted', 'reverted', 'skipped'].includes(x.status))\n .slice(-(opts.regressionSample ?? 5))\n const desktop = VIEWPORTS[0]\n for (const other of finished) {\n const ref = referenceShot(other, desktop.name)\n if (!ref) continue\n const refPng = readFileSync(join(dir, ref.png))\n const moved = (png: Buffer) => {\n const diff = pixelDiff(refPng, png)\n return diff.contentRatio > REGRESSION_CONTENT_RATIO && diff.changedPixels > REGRESSION_MIN_PIXELS ? diff : null\n }\n let now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null)\n if (!now || !moved(now.png)) continue\n // Confirm with a second shot: right after an edit the dev server\n // recompiles, and one shot of a half-loaded page is not a regression\n // (glot.it /words caught as skeletons after Account was kept, 2026-10-06).\n await new Promise((r) => setTimeout(r, 3000))\n now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null)\n const d = now ? moved(now.png) : null\n if (now && d) {\n const pct = (d.contentRatio * 100).toFixed(0)\n other.status = 'regressed'\n other.note = `${pct}% of this screen changed after \"${changed.surface.label}\" was kept. Check whether a shared component or token moved.`\n savePng(dir, `shots/${other.surface.key}/regressed-${desktop.name}.png`, now.png)\n log(` ⚠ ${other.surface.label}: ${pct}% of the screen moved — marked regressed`)\n }\n }\n persist()\n }\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The checker: a second model that reviews each kept step and may roll it\n * back (ADR 0021). It never keeps anything the measurements rejected.\n *\n * - A visible change is judged from crops of the changed area, before and\n * after, shown twice with the order swapped. Vision judges are near random\n * on small UI differences (arxiv 2510.08783) and flip with order (arxiv\n * 2305.17926), so a step is rolled back only when both orders prefer the\n * original with at least medium confidence. Anything else keeps it.\n * - A change with nothing visible (motion, haptics, another screen) is\n * reviewed from its diff and the step it was meant to make.\n *\n * Transports: Claude Code (`claude -p`, the person's own sign-in, read-only\n * tools), the Anthropic API (ANTHROPIC_API_KEY), or the Cursor CLI\n * (`cursor-agent -p --mode ask`, read-only, any model the Cursor account has,\n * e.g. Grok: a cheaper allowance for screenshot reviews).\n */\n\nimport Anthropic from '@anthropic-ai/sdk'\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { PNG } from 'pngjs'\nimport type { ChangeRegion } from './image.js'\nimport { run } from './proc.js'\n\ntype CheckerVia = 'claude-code' | 'anthropic-api' | 'cursor'\n\nexport interface CheckerSpec {\n via: CheckerVia\n model: string\n}\n\n/** One review's answer. @internal Exported for tests only. */\nexport interface CheckerVote {\n /** Which capture the model preferred, after mapping its A/B answer back. */\n preferred: 'before' | 'after' | 'tie'\n confidence: 'low' | 'medium' | 'high'\n difference: string\n reason: string\n}\n\nexport interface CheckerVerdict {\n model: string\n mode: 'visual' | 'code'\n /** revert = roll the step back; keep = no objection; unsure = keep, the votes disagreed or were weak. */\n verdict: 'keep' | 'revert' | 'unsure'\n summary: string\n votes: CheckerVote[]\n costUsd: number | null\n /** The review could not run; the step is kept on its measurements. */\n error?: string\n}\n\n/** Crop height cap: a vision model shrinks tall images until text is unreadable. */\nconst MAX_CROP_HEIGHT = 1400\nconst MAX_DIFF_CHARS = 20_000\nconst CONTEXT_ROWS = 120\n\n/** Pure: one box around all changed areas, padded, within the image, at most MAX_CROP_HEIGHT tall. @internal Exported for tests only. */\nexport function unionBox(regions: readonly ChangeRegion[], width: number, height: number): ChangeRegion {\n if (!regions.length) return { x: 0, y: 0, w: width, h: Math.min(height, MAX_CROP_HEIGHT) }\n const y0 = Math.min(...regions.map((r) => r.y))\n const y1 = Math.max(...regions.map((r) => r.y + r.h))\n // Full width, plus some rows above and below, keeps the change in its layout context.\n const y = Math.max(0, y0 - CONTEXT_ROWS)\n return { x: 0, y, w: width, h: Math.max(1, Math.min(y1 + CONTEXT_ROWS - y, MAX_CROP_HEIGHT, height - y)) }\n}\n\nfunction crop(png: Buffer, box: ChangeRegion): Buffer {\n const src = PNG.sync.read(png)\n const w = Math.min(box.w, src.width - box.x)\n const h = Math.min(box.h, src.height - box.y)\n const out = new PNG({ width: Math.max(1, w), height: Math.max(1, h) })\n out.data.fill(255)\n if (w > 0 && h > 0) PNG.bitblt(src, out, box.x, box.y, w, h, 0, 0)\n return PNG.sync.write(out)\n}\n\n/** Pure: the first JSON object in a model's text answer, or null. */\nexport function firstJson(text: string): Record<string, unknown> | null {\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start < 0 || end <= start) return null\n try {\n return JSON.parse(text.slice(start, end + 1)) as Record<string, unknown>\n } catch {\n return null\n }\n}\n\nconst level = (v: unknown): CheckerVote['confidence'] => (v === 'high' || v === 'medium' ? v : 'low')\n\n/** Pure: map an A/B answer back to before/after. `aIsBefore` is the order shown. @internal Exported for tests only. */\nexport function toVote(answer: Record<string, unknown> | null, aIsBefore: boolean): CheckerVote | null {\n if (!answer) return null\n const v = answer.verdict\n if (v !== 'A' && v !== 'B' && v !== 'tie') return null\n return {\n preferred: v === 'tie' ? 'tie' : (v === 'A') === aIsBefore ? 'before' : 'after',\n confidence: level(answer.confidence),\n difference: String(answer.difference ?? '').slice(0, 400),\n reason: String(answer.reason ?? '').slice(0, 600),\n }\n}\n\n/** Pure: the veto rule. Both orders must prefer the original, each with at least medium confidence. @internal Exported for tests only. */\nexport function combineVotes(votes: CheckerVote[]): { verdict: CheckerVerdict['verdict']; summary: string } {\n const firm = (v: CheckerVote) => v.confidence !== 'low'\n if (votes.length >= 2 && votes.every((v) => v.preferred === 'before' && firm(v))) {\n return { verdict: 'revert', summary: `Both reviews preferred the original: ${votes[0].reason}` }\n }\n if (votes.length >= 2 && votes.every((v) => v.preferred === 'after')) {\n return { verdict: 'keep', summary: `Both reviews preferred the change: ${votes[0].reason}` }\n }\n return { verdict: 'unsure', summary: votes.length ? `The reviews disagreed or were unsure: ${votes.map((v) => v.preferred).join(' / ')}.` : 'No review answered.' }\n}\n\nconst VISUAL_PROMPT = (step: string, screen: string) => `You review one small UI change made by a coding agent to the screen \"${screen}\".\nThe change it was asked to make: ${step}\n\nRead the two images a.png and b.png in the current folder. They show the same area of the screen; one is before the change and one is after, in an order you are not told.\nFirst describe the visible difference in one sentence. Then decide which is better for the person using this screen: clearer purpose and primary action, sensible visual weight, less noise, consistent with the rest of the screen, readable and tappable. If the difference is too small to matter, answer \"tie\".\nAnswer with ONLY this JSON: {\"difference\":\"...\",\"verdict\":\"A\"|\"B\"|\"tie\",\"confidence\":\"low\"|\"medium\"|\"high\",\"reason\":\"...\"} where A is a.png and B is b.png.`\n\nconst CODE_PROMPT = (step: string, screen: string, diff: string) => `You review one small change a coding agent made to the screen \"${screen}\" of a web app. It changed nothing visible in a still screenshot, so judge it from the code.\nThe change it was asked to make: ${step}\n\nThe diff:\n${diff}\n\nYou may open at most 3 files from this repository (for example a class or component the diff uses) to check what it does; then answer. Do not search the repository.\nKeep it when the diff makes that change (or a reasonable part of it) without breaking behaviour, accessibility or the design system. Revert it when it does nothing useful, does something else, or risks breaking the screen.\nAnswer with ONLY this JSON: {\"verdict\":\"keep\"|\"revert\",\"confidence\":\"low\"|\"medium\"|\"high\",\"reason\":\"...\"}`\n\nexport interface Ask {\n text: string | null\n costUsd: number | null\n error?: string\n}\n\n/** One question to Claude Code, headless and read-only, in `cwd`. */\nexport async function askClaudeCode(prompt: string, cwd: string, model: string, signal?: AbortSignal, maxTurns = 4): Promise<Ask> {\n const args = ['-p', '--model', model, '--tools', 'Read', '--disallowedTools', 'mcp__*', '--permission-mode', 'dontAsk', '--max-turns', String(maxTurns), '--no-session-persistence', '--output-format', 'json']\n let last: Ask = { text: null, costUsd: null, error: 'Claude Code did not run.' }\n // One retry: a call that failed in a second with no output (studio run on\n // glot.it, 2026-10-07) answered normally when repeated.\n for (let attempt = 1; attempt <= 2; attempt++) {\n if (signal?.aborted) break\n const res = await run('claude', args, { cwd, stdin: prompt, shell: process.platform === 'win32', timeoutMs: 240_000, signal })\n if (res.timedOut) return { text: null, costUsd: null, error: 'Claude Code did not answer within 4 minutes.' }\n try {\n const j = JSON.parse(res.stdout) as { result?: unknown; subtype?: unknown; total_cost_usd?: unknown; is_error?: unknown }\n if (!j.is_error) return { text: String(j.result ?? ''), costUsd: typeof j.total_cost_usd === 'number' ? j.total_cost_usd : null }\n // An error result can carry no text, only its kind (error_max_turns, …).\n last = { text: null, costUsd: null, error: `Claude Code: ${String(j.result ?? j.subtype ?? 'error with no message').slice(0, 300)}` }\n if (j.subtype === 'error_max_turns') return last\n } catch {\n const said = `${res.stdout.trim().slice(0, 200)} ${res.tail.trim().slice(-300)}`.trim()\n last = { text: null, costUsd: null, error: `Claude Code exited ${res.exitCode}: ${said || 'no output on stdout or stderr'}` }\n }\n if (attempt === 1) await new Promise((r) => setTimeout(r, 5000))\n }\n return last\n}\n\n/**\n * Default model for the Cursor transport when none is given: cheap and\n * vision-capable. Measured 2026-10-25 on audit screenshots: grok-4.7-high-fast\n * answered in about 2.5 min with concrete defects; grok-4.7-xhigh ran past 4\n * min on 3 pages of 4.\n */\nexport const DEFAULT_CURSOR_REVIEW_MODEL = 'grok-4.7-high-fast'\n\n/**\n * One question to the Cursor CLI in read-only \"ask\" mode: it reads the images\n * from `cwd` itself (verified with Grok 4.7 on an audit screenshot,\n * 2026-10-25). One retry, as for Claude Code.\n */\nexport async function askCursor(prompt: string, cwd: string, model: string, signal?: AbortSignal): Promise<Ask> {\n const args = ['-p', '--trust', '--mode', 'ask', '--output-format', 'text', '--workspace', cwd, '--model', model, prompt]\n let last: Ask = { text: null, costUsd: null, error: 'The Cursor CLI did not run.' }\n for (let attempt = 1; attempt <= 2; attempt++) {\n if (signal?.aborted) break\n const res = await run('cursor-agent', args, { cwd, shell: process.platform === 'win32', timeoutMs: 360_000, signal })\n if (res.timedOut) return { text: null, costUsd: null, error: 'The Cursor CLI did not answer within 6 minutes.' }\n if (res.exitCode === 0 && res.stdout.trim()) return { text: res.stdout, costUsd: null }\n const said = `${res.stdout.trim().slice(0, 200)} ${res.tail.trim().slice(-300)}`.trim()\n last = { text: null, costUsd: null, error: `Cursor CLI exited ${res.exitCode}: ${said || 'no output'}` }\n if (attempt === 1) await new Promise((r) => setTimeout(r, 5000))\n }\n return last\n}\n\n/** One question to the Anthropic API, with the images inline. */\nexport async function askApi(prompt: string, images: Buffer[], model: string, client: Anthropic, labels: readonly string[] = ['a.png', 'b.png']): Promise<Ask> {\n try {\n const msg = await client.messages.create({\n model,\n max_tokens: 2000,\n messages: [\n {\n role: 'user',\n content: [\n ...images.flatMap((png, i) => [\n { type: 'text' as const, text: `${labels[i] ?? `image ${i + 1}`}:` },\n { type: 'image' as const, source: { type: 'base64' as const, media_type: 'image/png' as const, data: png.toString('base64') } },\n ]),\n { type: 'text', text: prompt },\n ],\n },\n ],\n })\n return { text: msg.content.map((b) => (b.type === 'text' ? b.text : '')).join(''), costUsd: null }\n } catch (err) {\n return { text: null, costUsd: null, error: `Anthropic API: ${(err as Error).message.slice(0, 200)}` }\n }\n}\n\nexport interface CheckStepInput {\n /** Run directory; review files go under checker/. */\n dir: string\n /** A unique name for this step's review files. */\n name: string\n screen: string\n step: string\n /** null: nothing visible changed, review the diff instead. */\n visual: { before: Buffer; after: Buffer; regions: ChangeRegion[] } | null\n diff: string\n /** The worktree: a code review runs there, so the model can read the files the diff touches. */\n repoDir?: string\n spec: CheckerSpec\n signal?: AbortSignal\n client?: Anthropic\n /** Deterministic order for tests. */\n random?: () => number\n}\n\nexport async function checkStep(input: CheckStepInput): Promise<CheckerVerdict> {\n const { spec } = input\n const base = join(input.dir, 'checker', input.name)\n const fail = (mode: CheckerVerdict['mode'], error: string): CheckerVerdict => ({ model: spec.model, mode, verdict: 'unsure', summary: '', votes: [], costUsd: null, error })\n let cost = 0\n const ask = async (prompt: string, cwd: string, images: Buffer[], maxTurns?: number): Promise<Ask> => {\n const a =\n spec.via === 'claude-code'\n ? await askClaudeCode(prompt, cwd, spec.model, input.signal, maxTurns)\n : spec.via === 'cursor'\n ? await askCursor(prompt, cwd, spec.model, input.signal)\n : await askApi(prompt, images, spec.model, input.client ?? new Anthropic())\n if (a.costUsd) cost += a.costUsd\n return a\n }\n\n if (!input.visual) {\n const diff = input.diff.slice(0, MAX_DIFF_CHARS)\n mkdirSync(base, { recursive: true })\n // In the worktree, with room to open the files the diff touches (read-only).\n const a = await ask(CODE_PROMPT(input.step, input.screen, diff), input.repoDir ?? base, [], 20)\n if (a.error || !a.text) return fail('code', a.error ?? 'No answer.')\n const j = firstJson(a.text)\n if (!j || (j.verdict !== 'keep' && j.verdict !== 'revert')) return fail('code', 'The answer was not the expected JSON.')\n const confidence = level(j.confidence)\n const reason = String(j.reason ?? '').slice(0, 600)\n const verdict = j.verdict === 'revert' && confidence !== 'low' ? 'revert' : j.verdict === 'keep' ? 'keep' : 'unsure'\n return { model: spec.model, mode: 'code', verdict, summary: reason, votes: [{ preferred: j.verdict === 'keep' ? 'after' : 'before', confidence, difference: '', reason }], costUsd: cost || null }\n }\n\n const { before, after, regions } = input.visual\n const size = PNG.sync.read(before)\n const box = unionBox(regions, size.width, size.height)\n const b = crop(before, box)\n const a = crop(after, box)\n const firstIsBefore = (input.random ?? Math.random)() < 0.5\n const votes: CheckerVote[] = []\n for (const aIsBefore of [firstIsBefore, !firstIsBefore]) {\n const cwd = join(base, aIsBefore ? 'order-1' : 'order-2')\n mkdirSync(cwd, { recursive: true })\n const [imgA, imgB] = aIsBefore ? [b, a] : [a, b]\n writeFileSync(join(cwd, 'a.png'), imgA)\n writeFileSync(join(cwd, 'b.png'), imgB)\n const res = await ask(VISUAL_PROMPT(input.step, input.screen), cwd, [imgA, imgB])\n if (res.error || !res.text) return fail('visual', res.error ?? 'No answer.')\n const vote = toVote(firstJson(res.text), aIsBefore)\n if (!vote) return fail('visual', 'The answer was not the expected JSON.')\n votes.push(vote)\n }\n const { verdict, summary } = combineVotes(votes)\n return { model: spec.model, mode: 'visual', verdict, summary, votes, costUsd: cost || null }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The instructions one agent run gets, written to `.mushi-ux/PROMPT.md` in\n * the worktree: which screen, its screenshots, the measured problems, where\n * the design system lives, the skill to apply, and what not to touch.\n *\n * File paths only for the design system: the agent reads what it needs, and\n * the packet stays small enough for weaker, short-context models.\n */\n\nimport { closeSync, existsSync, fstatSync, openSync, readdirSync, readFileSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport { CLS_GOOD } from './probes.js'\nimport type { ProbeResult, Surface } from './types.js'\n\nconst MAX_PACKET_CHARS = 24_000\n/** Skill text a prompt carries; a chain splits it between its skills (skills.ts). */\nexport const MAX_SKILL_CHARS = 12_000\n\nconst DEFAULT_GUIDANCE = `Improve this one screen's UI and UX. In order of priority:\n1. Fix every measured problem listed below (accessibility violations, sideways scrolling, tap targets under 24×24 px, console errors).\n2. Make the primary action obvious: one clear call to action, visual hierarchy that matches importance.\n3. Cut noise: shorter copy, group related controls, remove duplicated information, use icons and colour to carry meaning where text is long.\n4. Spacing and alignment on the design system's scale; readable line length; consistent type sizes.\n5. The mobile screenshot must work as well as the desktop one.`\n\nconst GUARDRAILS = `Rules:\n- Change only what this screen needs. Shared components and design tokens affect every other screen; edit them only when the fix truly belongs there, and say so in your final message.\n- Use the existing design tokens, components and icon set. Do not add dependencies.\n- Do not change data fetching, API calls, auth, routing, state management or tests.\n- Do not run the dev server, install packages, or commit. The tool reviews and commits your edits.\n- Do not modify anything under .mushi-ux/. Read only the screenshots and skill files you are pointed to.\n- Do not read or change node_modules or the framework's own code. A problem that comes from there is not yours to fix: say so and move on.\n- If the screen is already good, make no edits and say why.`\n\nexport interface PacketInput {\n surface: Surface\n iteration: number\n /** Screenshot paths relative to the worktree, per viewport name. */\n shots: Record<string, string>\n probes: Record<string, ProbeResult>\n designFiles: string[]\n skillText: string | null\n /** Worktree-relative folder holding the skill's files (SKILL.md, references/). */\n skillDir?: string | null\n /** Why the previous attempt on this screen was rejected, if it was. */\n previousRejection: string | null\n /** Minutes the agent has before it is stopped; shapes the work plan. */\n timeBudgetMin?: number | null\n /** Repo-relative files that render this screen (routes.ts screenFiles); empty when unknown. */\n entryFiles?: string[]\n /** Steps mode: the one plan step this attempt makes. */\n step?: { text: string; index: number; total: number; done: string[] } | null\n}\n\n/** A step should touch this many files at most; more is rolled back as too big. */\nexport const MAX_STEP_FILES = 6\n/** Steps planned per screen at most. */\nexport const MAX_PLAN_STEPS = 5\n/**\n * Source files the planning pass may open besides the entry files. Grok 4.7\n * xhigh opened 12-16 and ran out of its 6 minutes with no plan (glot.it\n * Challenge, 2026-10-07); a read cap took the checker's code review from\n * running out of turns to an answer in 23 s.\n */\nconst PLAN_READ_BUDGET = 6\n\n/**\n * Steps mode, the planning pass: look, list small separate improvements,\n * edit nothing. Small steps measure cleanly and one bad step costs only\n * itself, where a whole-screen pass lost entire 15-minute attempts on\n * glot.it (2026-10-06).\n */\nexport function buildPlanPacket(input: Omit<PacketInput, 'step' | 'iteration' | 'previousRejection'>, maxSteps: number): string {\n const { surface } = input\n const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p))\n const sections = [\n `# UX plan — ${surface.label}`,\n `Screen: \\`${surface.path}\\` (${surface.kind}). Plan only: do not edit any file except \\`.mushi-ux/PLAN.md\\`.`,\n input.timeBudgetMin ? `## Time\\nYou have ${input.timeBudgetMin} minutes. Look, decide, write the list.` : '',\n input.entryFiles?.length ? `## Start here\\nThese files render this screen:\\n${input.entryFiles.map((f) => `- ${f}`).join('\\n')}` : '',\n `## Screenshots (read these images first)\\n${Object.entries(input.shots)\n .map(([vp, p]) => `- ${vp}: ${p}`)\n .join('\\n')}\\nYour read tool opens them as images where they are: do not copy them anywhere.`,\n `## Measured problems\\n${findings.length ? findings.join('\\n') : '- None measured.'}`,\n input.skillText\n ? `## Guidance\\nUse this skill to choose what to improve on this one screen (its supporting files are in \\`${input.skillDir ?? '.mushi-ux/skill'}/\\`):\\n\\n${input.skillText.slice(0, MAX_SKILL_CHARS)}`\n : `## Guidance\\n${DEFAULT_GUIDANCE}`,\n `## What to do\\nList 2 to ${maxSteps} small, separate improvements for this screen, most valuable first. Each must be one focused change a developer could make in a few minutes, touching at most 3 files, that does not depend on the others. Start each item with a short summary a user of the app would understand, without file or code names, then a colon, then the change, naming the component or file it changes (for example \"- Make the caption readable: in \\`x.tsx\\`, ...\"). Open at most ${PLAN_READ_BUDGET} source files besides the \"Start here\" ones; each step's own attempt reads the rest. Write them to \\`.mushi-ux/PLAN.md\\`, one per line starting with \"- \", within your first 2 minutes, from the screenshots and the \"Start here\" files alone; then refine the file if you have time, and reply with the same list. You are stopped when the time is up, and a missing PLAN.md wastes the whole pass. Do not edit any other file: each item gets its own attempt later.`,\n `## Rules\\n- Do not install anything, and do not run scripts on the screenshots: look at them.\\n- Do not read or change node_modules or the framework's own code.\\n- Do not plan changes to data fetching, API calls, auth, routing, state management or tests.\\n- If the screen is already good, write fewer items.`,\n ]\n return sections.filter(Boolean).join('\\n\\n').slice(0, MAX_PACKET_CHARS)\n}\n\n/** Pure: the plan steps in a PLAN.md or a reply (\"- x\", \"* x\", \"1. x\", \"- [ ] x\"), first ones first. */\nexport function parsePlan(text: string, max = MAX_PLAN_STEPS): string[] {\n const out: string[] = []\n for (const line of text.split(/\\r?\\n/)) {\n const m = line.match(/^\\s*(?:[-*•]|\\d+[.)])\\s+(?:\\[[ xX]\\]\\s*)?(.+?)\\s*$/)\n // Agents sometimes write HTML entities (\"School & Study\"); the plan is plain text.\n const item = m?.[1]\n ?.replace(/\\*\\*/g, '')\n .replace(/&(amp|lt|gt|quot|#39);/g, (_, e: string) => ({ amp: '&', lt: '<', gt: '>', quot: '\"', '#39': \"'\" })[e] ?? _)\n .trim()\n if (!item || item.length < 8 || out.includes(item)) continue\n out.push(cutAtWord(item, 280))\n if (out.length >= max) break\n }\n return out\n}\n\n/** Pure: `text` within `max` characters, cut at a word with \"…\" so no word or `code` span ends half-way. * @internal Exported for tests only.\n */\nexport function cutAtWord(text: string, max: number): string {\n if (text.length <= max) return text\n const head = text.slice(0, max - 1)\n const space = head.lastIndexOf(' ')\n let cut = (space > max / 2 ? head.slice(0, space) : head).replace(/[\\s,;:.(-]+$/, '')\n // An odd number of backticks means a code span was opened and not closed.\n if ((cut.match(/`/g)?.length ?? 0) % 2 === 1) cut = cut.slice(0, cut.lastIndexOf('`')).trimEnd()\n return `${cut}…`\n}\n\n/** Steps mode, the planning pass's pointer prompt. */\nexport const PLAN_POINTER_PROMPT =\n 'Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It asks for a plan only: write .mushi-ux/PLAN.md and edit nothing else.'\n\nfunction describeProbes(viewport: string, p: ProbeResult): string[] {\n const lines: string[] = []\n for (const v of p.axe) {\n lines.push(`- [${viewport}] ${v.id} (${v.impact ?? 'n/a'}, ${v.count} node${v.count === 1 ? '' : 's'}): ${v.help} — e.g. ${v.targets.slice(0, 3).join(', ')}`)\n }\n if (p.overflowX) lines.push(`- [${viewport}] The page scrolls sideways at this width.`)\n if (p.smallTargets > 0) lines.push(`- [${viewport}] ${p.smallTargets} tap target(s) smaller than 24×24 px.`)\n for (const i of p.layout ?? []) lines.push(`- [${viewport}] ${i.kind === 'overlap' ? 'Overlap' : 'Too big'}: ${i.selector} ${i.detail}.`)\n for (const e of p.consoleErrors.slice(0, 5)) lines.push(`- [${viewport}] Console error: ${e}`)\n if (p.cls > CLS_GOOD) lines.push(`- [${viewport}] Layout shift ${p.cls} while loading (aim below ${CLS_GOOD}).`)\n return lines\n}\n\nexport function buildPacket(input: PacketInput): string {\n const { surface } = input\n const steps = surface.steps.length ? ` then click ${surface.steps.map((s) => `\"${s.label}\"`).join(' → ')}` : ''\n const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p))\n const skill = input.skillText\n ? [\n `Apply this skill to this one screen only. Skip its whole-app steps (stack detection, scoring every screen, app-wide inventories): another pass handles each other screen. Its supporting files (references, scorecards) are in \\`${input.skillDir ?? '.mushi-ux/skill'}/\\`; read only the ones this screen needs.`,\n input.skillText.slice(0, MAX_SKILL_CHARS),\n ].join('\\n\\n')\n : DEFAULT_GUIDANCE\n const sections = [\n `# UX pass — ${surface.label}`,\n `Screen: \\`${surface.path}\\`${steps} (${surface.kind}). Attempt ${input.iteration}.`,\n input.timeBudgetMin\n ? `## Time\\nYou have ${input.timeBudgetMin} minutes, then you are stopped and unsaved work is lost. Make your first edit within ${Math.max(1, Math.round(input.timeBudgetMin / 3))} minutes: an attempt that ends without an edit counts as a failure. Do not survey the whole design system; read only what the edit needs. A small, finished improvement beats a large unfinished one: make it, then stop.`\n : '',\n input.entryFiles?.length\n ? `## Start here\\nThese files render this screen. Read them first instead of searching the repo:\\n${input.entryFiles.map((f) => `- ${f}`).join('\\n')}`\n : '',\n `## Screenshots (read these images first)\\n${Object.entries(input.shots)\n .map(([vp, p]) => `- ${vp}: ${p}`)\n .join('\\n')}`,\n `## Measured problems\\n${findings.length ? findings.join('\\n') : '- None measured. Focus on hierarchy, clarity and density.'}`,\n input.previousRejection ? `## Your previous attempt was rolled back\\n${input.previousRejection}\\nTry a different, smaller change.` : '',\n `## Design system (read before editing)\\n${input.designFiles.length ? input.designFiles.map((f) => `- ${f}`).join('\\n') : '- No token files found; match the styles already used on this screen.'}`,\n input.step\n ? [\n `## This step (${input.step.index} of ${input.step.total})\\n${input.step.text}`,\n `Make only this change, touching at most 3 files. ${input.step.done.length ? `Already done in earlier steps: ${input.step.done.map((d) => `\"${d}\"`).join('; ')}. ` : ''}Later steps come in their own attempts. If this step turns out to be unnecessary, make no edit and say why.`,\n ].join('\\n')\n : '',\n input.step ? `## Guidance\\n${skill}` : `## What to do\\n${skill}`,\n `## ${GUARDRAILS}`,\n ]\n return sections.filter(Boolean).join('\\n\\n').slice(0, MAX_PACKET_CHARS)\n}\n\n/** One-line instruction handed to the agent on stdin / argv. */\nexport const POINTER_PROMPT =\n 'Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It names the screenshots to look at and the screen to improve.'\n\nconst SKIP_DIRS = new Set(['node_modules', '.git', '.next', 'dist', 'build', '.turbo', '.worktrees', '.mushi', '.mushi-ux', 'coverage'])\n\n/**\n * Likely design-system sources, as repo-relative paths: the recipe manifest,\n * Tailwind configs, DTCG token files, and CSS files that declare theme\n * tokens (`@theme` or many custom properties on :root).\n */\nexport function findDesignFiles(root: string, maxFiles = 12): string[] {\n const found: string[] = []\n const recipe = join(root, 'mushi.recipe.json')\n if (existsSync(recipe)) found.push('mushi.recipe.json')\n const walk = (dir: string, depth: number) => {\n if (depth > 5 || found.length >= maxFiles) return\n let names: string[]\n try {\n names = readdirSync(dir)\n } catch {\n return\n }\n for (const name of names) {\n if (found.length >= maxFiles) return\n if (SKIP_DIRS.has(name)) continue\n const abs = join(dir, name)\n // One handle for the stat and the read, so the size checked is the\n // size of the bytes read (CodeQL js/file-system-race).\n let fd: number\n let isDir: boolean\n let css: string | null = null\n try {\n fd = openSync(abs, 'r')\n } catch {\n continue\n }\n try {\n const st = fstatSync(fd)\n isDir = st.isDirectory()\n if (!isDir && name.endsWith('.css') && st.size < 300_000) css = readFileSync(fd, 'utf8')\n } catch {\n continue\n } finally {\n closeSync(fd)\n }\n if (isDir) {\n walk(abs, depth + 1)\n continue\n }\n const rel = relative(root, abs).replace(/\\\\/g, '/')\n if (/^tailwind\\.config\\.(js|cjs|mjs|ts)$/.test(name) || /\\.tokens\\.json$|^tokens\\.json$/.test(name)) {\n found.push(rel)\n } else if (css !== null) {\n if (/@theme\\b/.test(css) || (css.match(/--[\\w-]+\\s*:/g)?.length ?? 0) > 20) found.push(rel)\n }\n }\n }\n walk(root, 0)\n return found\n}\n","// SPDX-License-Identifier: MIT\n/**\n * A one-minute check that the agent can run and use its file tools, before\n * the worktree, install and dev server spend ten minutes. The agent reads a\n * file holding a random code word; the check passes when the code word comes\n * back in its output (the tool result or the reply).\n *\n * Why (glot.it, 2026-10-06): the Cursor CLI was logged out on the first run,\n * and on a later run every tool call was refused by a Claude Code hook the\n * CLI loads. Both surfaced only after the first attempt's full time box.\n */\n\nimport { randomBytes } from 'node:crypto'\nimport { mkdtempSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport type { AgentAdapter } from './agents.js'\nimport { agentFinalMessage } from './verdict.js'\n\nconst PREFLIGHT_TIMEOUT_MS = 3 * 60_000\n\nconst NOT_LOGGED_IN_RE = /not (logged|signed) in|log ?in required|please (log|sign) ?in|unauthori[sz]ed|invalid api key|authentication/i\nconst HOOK_RE = /\\bhooks?\\b/i\n\n/**\n * Plain-English next step for a failed check, by agent and symptom.\n * @internal Exported for tests only.\n */\nexport function preflightAdvice(agent: string, output: string, platform: NodeJS.Platform = process.platform): string {\n if (NOT_LOGGED_IN_RE.test(output)) {\n const login: Record<string, string> = {\n cursor: 'Run `agent login` (Cursor CLI), then start the run again.',\n 'claude-code': 'Run `claude` once and sign in, or set ANTHROPIC_API_KEY.',\n codex: 'Run `codex login`, or set OPENAI_API_KEY.',\n }\n return `The agent is not signed in. ${login[agent] ?? 'Sign the agent in, then start the run again.'}`\n }\n if (agent === 'cursor' && HOOK_RE.test(output)) {\n return (\n 'A hook refused the agent’s tool calls. The Cursor CLI also runs the hooks in ~/.claude/settings.json; ' +\n (platform === 'win32'\n ? 'on Windows a hook fails when the run is started from Git Bash. Start `mushi ux` from PowerShell or cmd, or fix the hook.'\n : 'fix the failing hook or remove it, then start the run again.')\n )\n }\n return 'Run the agent once by hand in this repo to see what it needs, then start the run again.'\n}\n\n/**\n * Null when the agent read the file; otherwise a message that says what\n * went wrong and what to do. Never throws for an agent failure.\n */\nexport async function preflightAgent(\n agent: AgentAdapter,\n opts: { model?: string | null; signal?: AbortSignal; timeoutMs?: number } = {},\n): Promise<string | null> {\n const dir = mkdtempSync(join(tmpdir(), 'mushi-ux-preflight-'))\n const word = randomBytes(4).toString('hex')\n try {\n writeFileSync(join(dir, 'PREFLIGHT.txt'), `The code word is ${word}.\\n`)\n const timeoutMs = opts.timeoutMs ?? PREFLIGHT_TIMEOUT_MS\n const res = await agent.run({\n cwd: dir,\n prompt: 'Read the file PREFLIGHT.txt in this folder and reply with only the code word it contains. Do not edit anything.',\n model: opts.model,\n timeoutMs,\n signal: opts.signal,\n })\n if (res.stdout.includes(word) || res.tail.includes(word)) return null\n if (opts.signal?.aborted) return 'Stopped.'\n const said = agentFinalMessage(res.stdout) ?? res.tail.trim()\n const output = `${said}\\n${res.tail}`\n const what = res.timedOut\n ? `did not answer within ${Math.round(timeoutMs / 1000)} s`\n : res.exitCode !== 0\n ? `exited with code ${res.exitCode}`\n : 'answered without reading the file'\n const quote = said ? ` It said: “${said.replace(/\\s+/g, ' ').slice(-300)}”` : ''\n return `Agent check failed: ${agent.name}${opts.model ? ` (${opts.model})` : ''} ${what}.${quote} ${preflightAdvice(String(agent.name), output)}`\n } catch (err) {\n return `Agent check failed: could not start ${agent.name}: ${(err as Error).message}. Is it installed and on PATH?`\n } finally {\n rmSync(dir, { recursive: true, force: true })\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The cheap, objective keep-or-revert decision after one agent run. It only\n * uses measurements (probes, pixel diff, files changed), never a model's\n * taste: an edit that makes any measured problem worse is rolled back, and an\n * edit with no visible effect is not worth a commit. Taste is the judge's job\n * (judge.ts), and the judge never auto-accepts.\n */\n\nimport { CLS_GOOD, probePenalty } from './probes.js'\nimport type { ProbeResult } from './types.js'\n\n/** Below this share of changed pixels an edit counts as invisible. */\nconst MIN_VISIBLE_RATIO = 0.0005\n\nexport interface VerdictInput {\n filesChanged: number\n before: Record<string, ProbeResult>\n /** Null when the after-capture failed (page broke, axe failed, timeout). */\n after: Record<string, ProbeResult> | null\n pixelRatios: Record<string, number>\n /**\n * Keep an edit whose effect is not visible in a still screenshot (motion,\n * haptics, another screen) when nothing measured got worse, flagged for a\n * person to read (ADR 0021). Off: such an edit is rolled back.\n */\n keepInvisible?: boolean\n}\n\nexport interface Verdict {\n outcome: 'accepted' | 'rejected' | 'no_change' | 'capture_failed'\n reason: string\n /** Kept without a visible change: a person should read the diff. */\n needsReview?: boolean\n}\n\n/**\n * The agent's own last message, from stream-json / json output (Cursor and\n * Claude Code both end with {\"type\":\"result\",\"result\":\"…\"}), or null.\n */\nexport function agentFinalMessage(stdout: string): string | null {\n let last: string | null = null\n for (const line of stdout.split(/\\r?\\n/)) {\n if (!line.startsWith('{')) continue\n try {\n const j = JSON.parse(line) as { type?: string; result?: unknown }\n if (j.type === 'result' && typeof j.result === 'string' && j.result.trim()) last = j.result.trim()\n } catch {\n /* not JSON */\n }\n }\n return last\n}\n\n/**\n * Everything the agent wrote as messages, newlines kept, in order. For a run\n * stopped before its final result (a planning pass that ran out of time).\n * Reads Cursor and Claude Code stream-json `assistant` events.\n */\nexport function assistantText(stdout: string): string {\n const out: string[] = []\n for (const line of stdout.split(/\\r?\\n/)) {\n if (!line.startsWith('{')) continue\n try {\n const j = JSON.parse(line) as { type?: string; model_call_id?: unknown; message?: { content?: unknown } }\n if (j.type !== 'assistant' || j.model_call_id !== undefined || !Array.isArray(j.message?.content)) continue\n for (const c of j.message.content as Array<{ type?: string; text?: unknown }>) {\n if (c.type === 'text' && typeof c.text === 'string') out.push(c.text)\n }\n } catch {\n /* not JSON */\n }\n }\n return out.join('\\n')\n}\n\n/** The agent said its tools were blocked or it could not read the prompt: it never really ran. */\nconst AGENT_BLOCKED_RE = /\\b(could ?n[o'’]t|can ?not|cannot|unable to) (read|open|access|run|use)\\b|\\bhooks?\\b.*\\b(fail|error|block)|\\b(blocked|stopped) before\\b/i\n\n/**\n * Pure: an edit-less attempt explained by the agent's own words. A blocked\n * agent is a failure, not \"no change needed\" (glot.it, 2026-10-06: Cursor's\n * hooks failed and every file read was refused, yet the screen showed as fine).\n */\nexport function explainNoEdit(final: string | null): { outcome: 'no_change' | 'agent_failed'; reason: string } {\n if (!final) return { outcome: 'no_change', reason: 'The agent made no edits.' }\n const said = final.length > 400 ? `…${final.slice(-400)}` : final\n if (AGENT_BLOCKED_RE.test(final)) return { outcome: 'agent_failed', reason: `The agent could not work on the screen: ${said}` }\n return { outcome: 'no_change', reason: `The agent made no edits: ${said}` }\n}\n\n/**\n * True when an after-shot's layout shift crossed the \"good\" line and rose:\n * worth one more look, because a dev server that just hot-reloaded shifts\n * on its own (glot.it /chat: 0.025 → 0.14 and 0.043 → 0.118, 2026-10-06).\n */\nexport function clsNeedsSecondLook(before: Record<string, ProbeResult>, after: Record<string, ProbeResult>): boolean {\n return Object.entries(after).some(([vp, now]) => now.cls > CLS_GOOD && now.cls > (before[vp]?.cls ?? 0))\n}\n\n/** The steadier of two readings per viewport: a real shift shows up both times. */\nexport function steadierCls(first: Record<string, ProbeResult>, second: Record<string, ProbeResult>): Record<string, ProbeResult> {\n return Object.fromEntries(\n Object.entries(first).map(([vp, p]) => [vp, second[vp] ? { ...p, cls: Math.min(p.cls, second[vp].cls) } : p]),\n )\n}\n\n/** Which measurements got worse, in words, so a rollback says what to fix. */\nfunction whatRose(before: ProbeResult, now: ProbeResult): string[] {\n const out: string[] = []\n if (now.smallTargets > before.smallTargets) out.push(`tap targets under 24 px ${before.smallTargets} → ${now.smallTargets}`)\n if (now.cls > CLS_GOOD && now.cls > before.cls) out.push(`layout shift ${before.cls} → ${now.cls}`)\n const boxes = (p: ProbeResult) => p.layout?.length ?? 0\n if (boxes(now) > boxes(before)) out.push(`overlapping or oversized boxes ${boxes(before)} → ${boxes(now)}`)\n const was = new Map(before.axe.map((v) => [v.id, v.count]))\n for (const v of now.axe) {\n if (v.count > (was.get(v.id) ?? 0)) out.push(`${v.id} ${was.get(v.id) ?? 0} → ${v.count} element(s)`)\n }\n return out\n}\n\nexport function decide(input: VerdictInput): Verdict {\n if (input.filesChanged === 0) return { outcome: 'no_change', reason: 'The agent made no edits.' }\n if (!input.after) {\n return { outcome: 'capture_failed', reason: 'The screen could not be captured after the edit (it may no longer render).' }\n }\n const after = input.after\n const worse: string[] = []\n const summary: string[] = []\n for (const [vp, before] of Object.entries(input.before)) {\n const now = after[vp]\n if (!now) {\n worse.push(`${vp}: no capture after the edit`)\n continue\n }\n const pb = probePenalty(before)\n const pa = probePenalty(now)\n summary.push(`${vp} ${pb}→${pa}`)\n if (now.consoleErrors.length > before.consoleErrors.length) {\n worse.push(`${vp}: new console error \"${now.consoleErrors[now.consoleErrors.length - 1]}\"`)\n }\n if (now.overflowX && !before.overflowX) worse.push(`${vp}: the page now scrolls sideways`)\n const beforeIds = new Set(before.axe.map((v) => v.id))\n const newRules = now.axe.filter((v) => !beforeIds.has(v.id)).map((v) => v.id)\n if (newRules.length) worse.push(`${vp}: new accessibility violations ${newRules.join(', ')}`)\n if (pa > pb && worse.length === 0) {\n const rose = whatRose(before, now)\n worse.push(`${vp}: ${rose.length ? rose.join(', ') : 'measured problems rose'} (problem score ${pb} → ${pa})`)\n }\n }\n if (worse.length) return { outcome: 'rejected', reason: `Rolled back: ${worse.join('; ')}.` }\n const maxRatio = Math.max(0, ...Object.values(input.pixelRatios))\n if (maxRatio < MIN_VISIBLE_RATIO) {\n if (input.keepInvisible) {\n return {\n outcome: 'accepted',\n needsReview: true,\n reason: `Kept, needs your review: the edit changed ${input.filesChanged} file(s) but nothing visible in a still screenshot (motion, haptics or another screen). Read the diff.`,\n }\n }\n return { outcome: 'no_change', reason: `The edits changed ${input.filesChanged} file(s) but nothing visible on this screen.` }\n }\n return {\n outcome: 'accepted',\n reason: `Kept: problem score ${summary.join(', ')}; ${(maxRatio * 100).toFixed(1)}% of pixels changed.`,\n }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Resuming a run that stopped for any reason: the studio or terminal was\n * closed, the machine slept, or the process was killed (on 2026-10-06 the\n * host ran low on memory and took the studio, and its run, with it).\n *\n * A resume needs only the run id. The settings and the skill's files were\n * saved when the run started; the loop then puts the worktree back on the\n * last kept commit, throws away a half-finished attempt and carries on from\n * the first unfinished screen.\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join, relative } from 'node:path'\nimport type { ResolvedSkill } from './skills.js'\nimport { loadState, runDir, type RunState, type SavedRunOptions } from './state.js'\n\n/** A live run saves at least every 30 s; past this it is not running anywhere. */\nconst ALIVE_WITHIN_MS = 90_000\n\n/** Keep the skill beside the run state so a resume does not depend on GitHub or a checkout. */\nexport function saveSkillFiles(dir: string, skill: ResolvedSkill): void {\n const root = join(dir, 'skill')\n rmSync(root, { recursive: true, force: true })\n for (const [rel, buf] of Object.entries(skill.files)) {\n const target = join(root, ...rel.split('/'))\n mkdirSync(dirname(target), { recursive: true })\n writeFileSync(target, buf)\n }\n}\n\nfunction loadSkillFiles(dir: string, meta: { name: string; source: string }): ResolvedSkill | null {\n const root = join(dir, 'skill')\n if (!existsSync(join(root, 'SKILL.md'))) return null\n const files: Record<string, Buffer> = {}\n const walk = (d: string) => {\n // Dirent types, not a stat then a read of the same path (CodeQL js/file-system-race).\n for (const entry of readdirSync(d, { withFileTypes: true })) {\n const abs = join(d, entry.name)\n if (entry.isDirectory()) walk(abs)\n else files[relative(root, abs).replace(/\\\\/g, '/')] = readFileSync(abs)\n }\n }\n walk(root)\n return { name: meta.name, source: meta.source, text: files['SKILL.md']!.toString('utf8'), files }\n}\n\n/**\n * True while the run saved its state recently and has not finished: it is running somewhere.\n * @internal Exported for tests only.\n */\nexport function isRunAlive(state: RunState, now = Date.now()): boolean {\n if (state.phase === 'done' || state.phase === 'failed') return false\n const at = Date.parse(state.updatedAt)\n return Number.isFinite(at) && now - at < ALIVE_WITHIN_MS\n}\n\n/**\n * The commit the run branch should be on: the last kept attempt's commit, or\n * the commit the run branched from. A crash between an attempt's commit and\n * the state save leaves the branch ahead of this; the resume moves it back\n * and the attempt runs again.\n */\nexport function expectedHead(state: RunState): string | null {\n const kept = state.surfaces\n .flatMap((s) => s.iterations)\n .filter((i) => i.outcome === 'accepted' && i.commitSha)\n .sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt))\n return kept.length ? kept[kept.length - 1]!.commitSha : state.baseSha\n}\n\nexport interface ResumeSettings {\n state: RunState\n options: SavedRunOptions\n skill: ResolvedSkill | null\n}\n\n/** Settings to resume a run with, or an error that says why it cannot be resumed and what to do. */\nexport function resumeSettings(repoRoot: string, runId: string, now = Date.now()): ResumeSettings {\n const state = loadState(runDir(repoRoot, runId))\n if (!state) throw new Error(`No run ${runId} in ${join(repoRoot, '.mushi', 'ux')}.`)\n if (state.phase === 'done') throw new Error(`Run ${runId} already finished. Start a new run instead.`)\n if (isRunAlive(state, now)) {\n throw new Error(`Run ${runId} saved its state less than a minute ago, so it is still running somewhere. Stop it there first.`)\n }\n if (!state.options) {\n throw new Error(\n `Run ${runId} started before runs saved their settings. Resume it from the terminal with the same settings: ` +\n `mushi-ux run --resume ${runId} --dev \"<your dev command>\" (plus --agent, --model, --skill and --path as before).`,\n )\n }\n const skill = state.skill ? loadSkillFiles(runDir(repoRoot, runId), state.skill) : null\n if (state.skill && !skill) {\n throw new Error(`Run ${runId} used the skill ${state.skill.name}, but its saved copy is missing. Resume it with --skill ${state.skill.name}.`)\n }\n return { state, options: state.options, skill }\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Shared shapes for the UX loop: a surface is one screen state worth\n * reviewing (a page, a tab on it, a dialog it opens), reached by loading a\n * URL path and replaying a few clicks.\n */\n\nexport type SurfaceKind = 'page' | 'tab' | 'dialog' | 'menu'\n\n/** One replayable click. `selector` is a Playwright selector string. */\nexport interface ReplayStep {\n action: 'click'\n selector: string\n label: string\n}\n\nexport interface Surface {\n /** Stable id: path + replay labels, slugged. */\n key: string\n kind: SurfaceKind\n /** Same-origin path with query. Never a full URL, never a token. */\n path: string\n steps: ReplayStep[]\n label: string\n /** Structural hash of the rendered DOM, for dedupe across param routes. */\n domHash: string\n}\n\nexport interface Viewport {\n name: 'desktop' | 'mobile'\n width: number\n height: number\n}\n\nexport const VIEWPORTS: readonly Viewport[] = [\n { name: 'desktop', width: 1440, height: 900 },\n { name: 'mobile', width: 390, height: 844 },\n]\n\nexport interface AxeViolation {\n id: string\n impact: string | null\n help: string\n /** How many nodes fail the rule. */\n count: number\n /** CSS selectors of the offending nodes (first few). */\n targets: string[]\n}\n\n/** Objective, repeatable measurements of one surface at one viewport. */\nexport interface ProbeResult {\n axe: AxeViolation[]\n /** Page scrolls sideways at this width. */\n overflowX: boolean\n /** Interactive elements smaller than 24×24 CSS px (WCAG 2.2 target size). */\n smallTargets: number\n consoleErrors: string[]\n /** Cumulative layout shift observed while the surface settled. */\n cls: number\n /**\n * Boxes that collide or stick out of their container. Absent in runs\n * captured before 2026-10-26.\n */\n layout?: LayoutIssue[]\n}\n\nexport interface LayoutIssue {\n /**\n * `overlap`: two in-flow siblings drawn on top of each other.\n * `outgrows`: a control wider than its container, sticking past its edge,\n * wrapping past two lines or cutting its own label off.\n */\n kind: 'overlap' | 'outgrows'\n /** Short CSS-ish name of the element, with its text. */\n selector: string\n /** What was measured, in px. */\n detail: string\n}\n","// SPDX-License-Identifier: MIT\n/**\n * `--sync`: mirror a run to the Mushi console while it runs (Plan 021\n * Phase 2). After each state change (debounced) the run snapshot is PUT to\n * the api: phase, the screen and attempt the agent is on, every screen and\n * attempt. Screenshots go up through signed upload URLs as soon as they\n * exist (baseline, then each attempt, mobile and desktop), each one once.\n * A failed sync never stops the loop; the next state change retries, and\n * the final sync is awaited.\n *\n * Agent output stays on this machine: the console gets the files each\n * attempt read and edited (syncableStep), never the agent's words, the\n * commands it ran, or console text.\n *\n * Credentials come from MUSHI_API_KEY / MUSHI_PROJECT_ID / MUSHI_API_ENDPOINT\n * (`mushi ux` passes the CLI's saved login). The coding agent never sees\n * them: its environment drops every MUSHI_* variable (proc.ts).\n */\n\nimport type { EventEmitter } from 'node:events'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { cropTop } from './image.js'\nimport { trimTrailingSlashes } from './routes.js'\nimport type { LoopEvent } from './loop.js'\nimport { loadState, type RunState, type SurfaceState } from './state.js'\nimport type { ProbeResult } from './types.js'\n\nconst CLOUD_API_ENDPOINT = 'https://dxptnwrhwsqckaftyymj.supabase.co/functions/v1/api'\nconst HOSTED_CONSOLE_URL = 'https://kensaur.us/mushi-mushi/admin'\n\n/** The Mushi console a mirrored run is reviewed and merged in: MUSHI_CONSOLE_URL, else the hosted console. */\nexport function consoleBaseUrl(env: NodeJS.ProcessEnv = process.env): string {\n return trimTrailingSlashes(env.MUSHI_CONSOLE_URL?.trim() || HOSTED_CONSOLE_URL)\n}\nconst VIEWPORT_NAMES = ['desktop', 'mobile'] as const\n/** Screenshots per upload request (the api caps one request at 60 names). */\nconst UPLOAD_BATCH = 40\n\nexport interface SyncConfig {\n apiKey: string\n projectId: string\n endpoint: string\n /** 'cloud' when the run executes on the host's CI rather than a laptop. */\n mode: 'local' | 'cloud'\n}\n\nexport function syncConfigFromEnv(env: NodeJS.ProcessEnv = process.env): SyncConfig | null {\n const apiKey = env.MUSHI_API_KEY?.trim()\n const projectId = env.MUSHI_PROJECT_ID?.trim()\n if (!apiKey || !projectId) return null\n return {\n apiKey,\n projectId,\n endpoint: trimTrailingSlashes(env.MUSHI_API_ENDPOINT?.trim() || CLOUD_API_ENDPOINT),\n mode: env.GITHUB_ACTIONS === 'true' ? 'cloud' : 'local',\n }\n}\n\nconst PROJECT_LINE_RE = /^\\s*(?:NEXT_PUBLIC_|VITE_|EXPO_PUBLIC_|PUBLIC_)?MUSHI_PROJECT_ID\\s*=\\s*[\"']?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[\"']?\\s*$/im\n\n/**\n * The Mushi project this repo's app reports to, from the public SDK variable\n * in its env files (NEXT_PUBLIC_MUSHI_PROJECT_ID and friends). Only that one\n * line is read; nothing else in the file is kept.\n * @internal Exported for tests only.\n */\nexport function repoProjectId(repoRoot: string): string | null {\n for (const name of ['.env.local', '.env.development.local', '.env.development', '.env']) {\n const file = join(repoRoot, name)\n if (!existsSync(file)) continue\n const m = readFileSync(file, 'utf8').match(PROJECT_LINE_RE)\n if (m) return m[1]\n }\n return null\n}\n\n/** Null when syncing to `cfg.projectId` is right for this repo, else why not. */\nexport function syncProjectMismatch(cfg: SyncConfig, repoRoot: string): string | null {\n const repoProject = repoProjectId(repoRoot)\n if (!repoProject || repoProject === cfg.projectId) return null\n return `This repo's app reports to Mushi project ${repoProject}, but your login is for ${cfg.projectId}. Run \\`mushi login\\` and pick this app's project (or set MUSHI_PROJECT_ID), so the run lands on the right project.`\n}\n\nfunction probeSummary(p: ProbeResult | undefined) {\n if (!p) return null\n return {\n axe: p.axe.map((v) => ({ id: v.id, impact: v.impact, help: v.help.slice(0, 300), count: v.count })).slice(0, 60),\n overflowX: p.overflowX,\n smallTargets: p.smallTargets,\n consoleErrors: p.consoleErrors.length,\n cls: p.cls,\n }\n}\n\n/**\n * Pure: the part of an agent step that may leave the machine. Agent output\n * stays local (it can quote file contents, commands and their output), so\n * the console gets only which files were read or edited; a command or a\n * search is counted, never shown. Anything else, raw lines included, is\n * dropped.\n * @internal Exported for tests only.\n */\nexport function syncableStep(line: string): string | null {\n if (/^\\[(read|edit)\\] \\S/.test(line)) return line.slice(0, 300)\n if (line.startsWith('[run] ')) return '[run] a command'\n if (line.startsWith('[find] ')) return '[find] a search'\n if (line === '[done] Finished') return line\n return null\n}\n\nfunction syncableSteps(log: string | undefined): string | null {\n const kept = (log ?? '').split('\\n').map(syncableStep).filter((l): l is string => l !== null)\n return kept.length ? kept.join('\\n').slice(-2000) : null\n}\n\n/** The worse of the phone and desktop scores: a change is judged on both, so one number must not hide the other. */\nfunction worstPenalty(shots: Partial<Record<string, { penalty: number }>>): number | null {\n const scores = Object.values(shots).flatMap((r) => (r && typeof r.penalty === 'number' ? [r.penalty] : []))\n return scores.length ? Math.max(...scores) : null\n}\n\nfunction lastKept(s: SurfaceState) {\n return [...s.iterations].reverse().find((i) => i.outcome === 'accepted') ?? null\n}\n\n/** One screenshot to mirror: its upload name and its file in the run dir. */\ninterface WantedShot {\n /** `<surface>/<slot>.png`, e.g. `home-1a2b3c/iter2-after-mobile.png`. */\n name: string\n /** PNG path relative to the run dir. */\n rel: string\n}\n\n/** Pure: every screenshot the console should have for this state. */\nfunction wantedShots(state: RunState): WantedShot[] {\n const out: WantedShot[] = []\n for (const s of state.surfaces) {\n const key = s.surface.key\n const kept = lastKept(s)\n for (const vp of VIEWPORT_NAMES) {\n const before = s.baseline[vp]?.png\n if (before) out.push({ name: `${key}/before-${vp}.png`, rel: before })\n const after = kept?.after[vp]?.png\n if (after) out.push({ name: `${key}/after-${vp}.png`, rel: after })\n const diff = kept?.diffPng[vp]\n if (diff) out.push({ name: `${key}/diff-${vp}.png`, rel: diff })\n for (const it of s.iterations) {\n if (it.after[vp]?.png) out.push({ name: `${key}/iter${it.n}-after-${vp}.png`, rel: it.after[vp].png })\n if (it.diffPng[vp]) out.push({ name: `${key}/iter${it.n}-diff-${vp}.png`, rel: it.diffPng[vp] })\n }\n }\n }\n return out\n}\n\n/** Pure, for tests: the PUT body for one run state. `uploaded` maps upload name → the file it came from. */\nexport function toSnapshot(state: RunState, finished: boolean, uploaded: ReadonlyMap<string, string>, mode: SyncConfig['mode'] = 'local') {\n const have = (name: string) => (uploaded.has(name) ? name : null)\n const status = state.stopped ? 'stopped' : state.phase === 'failed' ? 'failed' : finished ? 'done' : 'running'\n return {\n mode,\n status,\n agent: state.agent,\n model: state.model,\n judge_model: state.judgeModel ?? null,\n skill: state.skill?.name?.slice(0, 120) ?? null,\n base_ref: state.baseRef?.slice(0, 200) ?? null,\n phase: state.phase ?? null,\n phase_detail: state.phaseDetail?.slice(0, 300) ?? null,\n current_surface: state.current?.surface ?? null,\n current_attempt: state.current?.attempt ?? null,\n current_progress: state.current\n ? {\n steps: state.current.steps ?? 0,\n last_step: state.current.lastStep ? syncableStep(state.current.lastStep) : null,\n files: (state.current.files ?? []).slice(0, 20).map((f) => f.slice(0, 300)),\n started_at: state.current.startedAt,\n timeout_ms: state.current.timeoutMs ?? null,\n }\n : null,\n error: state.error?.slice(0, 1000) ?? null,\n branch: state.branch,\n base_sha: state.baseSha,\n cli_version: null,\n ...(state.pr ? { pr: { url: state.pr.url, number: state.pr.number } } : {}),\n started_at: state.createdAt,\n finished_at: finished || status === 'failed' ? (state.finishedAt ?? new Date().toISOString()) : null,\n surfaces: state.surfaces.map((s) => {\n const kept = lastKept(s)\n const key = s.surface.key\n const shots: Record<string, string> = {}\n for (const vp of VIEWPORT_NAMES) {\n for (const kind of ['before', 'after', 'diff']) {\n const name = have(`${key}/${kind}-${vp}.png`)\n if (name) shots[`${kind}-${vp}`] = name\n }\n }\n return {\n surface_key: key,\n kind: s.surface.kind,\n path: s.surface.path,\n label: s.surface.label.slice(0, 300),\n status: s.status,\n note: s.note?.slice(0, 1000) ?? null,\n // Small-steps mode: the plan as a checklist (the step texts are the agent's own plan, file names included).\n plan: s.plan?.steps.length\n ? s.plan.steps.slice(0, 8).map((p) => ({ text: p.text.slice(0, 300), status: p.status, attempt: p.attempt ?? null }))\n : null,\n penalty_before: worstPenalty(s.baseline),\n penalty_after: kept ? worstPenalty(kept.after) : null,\n probe_before: probeSummary(s.baseline.desktop?.probes),\n probe_after: probeSummary(kept?.after.desktop?.probes),\n judge: s.judge?.length\n ? s.judge.map((j) => ({\n viewport: j.viewport,\n model: j.model,\n preferred: j.preferred,\n confidence: j.confidence,\n summary: j.summary.slice(0, 2000),\n better: j.better.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),\n worse: j.worse.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),\n ...(j.error ? { error: j.error.slice(0, 500) } : {}),\n }))\n : null,\n thumbs: { before: shots['before-desktop'] ?? null, after: shots['after-desktop'] ?? null, diff: shots['diff-desktop'] ?? null },\n shots,\n iterations: s.iterations.map((it) => {\n const itShots: Record<string, string> = {}\n for (const vp of VIEWPORT_NAMES) {\n for (const kind of ['after', 'diff']) {\n const name = have(`${key}/iter${it.n}-${kind}-${vp}.png`)\n if (name) itShots[`${kind}-${vp}`] = name\n }\n }\n return {\n n: it.n,\n agent: it.agent,\n model: it.model,\n duration_ms: it.durationMs,\n outcome: it.outcome,\n reason: it.reason.slice(0, 1000),\n commit_sha: it.commitSha,\n pixel_diff: it.pixelDiff,\n penalty_after: worstPenalty(it.after),\n steps: syncableSteps(it.logTail),\n step: it.step?.slice(0, 300) ?? null,\n shots: itShots,\n }\n }),\n }\n }),\n }\n}\n\nexport interface SyncHandle {\n /** Final sync; resolves with an error message when it did not land. */\n finish(): Promise<string | null>\n}\n\nexport function startSync(dir: string, cfg: SyncConfig, events: EventEmitter, log: (m: string) => void): SyncHandle {\n /** Upload name → the run-dir file last uploaded under it. */\n const uploaded = new Map<string, string>()\n let timer: NodeJS.Timeout | null = null\n let running: Promise<void> = Promise.resolve()\n let lastError: string | null = null\n let warned = false\n\n const headers = {\n Authorization: `Bearer ${cfg.apiKey}`,\n 'X-Mushi-Api-Key': cfg.apiKey,\n 'X-Mushi-Project': cfg.projectId,\n 'Content-Type': 'application/json',\n }\n\n async function api(method: string, path: string, body: unknown): Promise<unknown> {\n const res = await fetch(`${cfg.endpoint}/v1/admin/projects/${cfg.projectId}/ux-runs/${path}`, {\n method,\n headers,\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(30_000),\n })\n const json = (await res.json().catch(() => null)) as { ok?: boolean; data?: unknown; error?: { code?: string; message?: string } } | null\n if (json?.error?.code === 'INSUFFICIENT_SCOPE') {\n // An SDK ingest key (report:write only) cannot sync; a browser login mints mcp:write.\n throw new Error('this Mushi key cannot write to the console. Run `mushi login` (browser sign-in) for a key that can, then retry')\n }\n if (!res.ok || !json?.ok) throw new Error(json?.error?.message ?? `HTTP ${res.status}`)\n return json.data\n }\n\n async function uploadShots(state: RunState): Promise<void> {\n // A later kept attempt replaces after-/diff- under the same name, so compare the source file too.\n const todo = wantedShots(state).filter((w) => uploaded.get(w.name) !== w.rel)\n for (let i = 0; i < todo.length; i += UPLOAD_BATCH) {\n const batch = todo.slice(i, i + UPLOAD_BATCH)\n const data = (await api('POST', `${state.runId}/uploads`, { names: batch.map((w) => w.name) })) as {\n uploads: Array<{ name: string; signedUrl: string }>\n }\n for (const u of data.uploads) {\n const want = batch.find((w) => w.name === u.name)\n if (!want) continue\n const png = cropTop(readFileSync(join(dir, want.rel)), 2400)\n const put = await fetch(u.signedUrl, {\n method: 'PUT',\n headers: { 'Content-Type': 'image/png', 'x-upsert': 'true' },\n body: new Uint8Array(png),\n signal: AbortSignal.timeout(60_000),\n })\n if (!put.ok) throw new Error(`screenshot upload failed (HTTP ${put.status})`)\n uploaded.set(want.name, want.rel)\n }\n }\n }\n\n async function syncOnce(finished: boolean): Promise<void> {\n const state = loadState(dir)\n if (!state) return\n try {\n await api('PUT', state.runId, toSnapshot(state, false, uploaded, cfg.mode))\n await uploadShots(state)\n await api('PUT', state.runId, toSnapshot(state, finished, uploaded, cfg.mode))\n lastError = null\n } catch (err) {\n lastError = (err as Error).message\n if (!warned) {\n log(`Console sync failed (will retry): ${lastError}`)\n warned = true\n }\n }\n }\n\n const schedule = () => {\n if (timer) return\n timer = setTimeout(() => {\n timer = null\n running = running.then(() => syncOnce(false))\n }, 1500)\n }\n events.on('event', (e: LoopEvent) => {\n if (e.type === 'state' || e.type === 'phase') schedule()\n })\n\n return {\n async finish() {\n if (timer) clearTimeout(timer)\n timer = null\n await running\n await syncOnce(true)\n return lastError\n },\n }\n}\n"],"mappings":";AAsBA,SAAS,eAAAA,cAAa,gBAAAC,qBA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UAAU,IAAI,IAAI,CAAC;AAC1E,YAAM,YAAY,KAAK;AACvB,YAAM,IAAI,OAAO,MAAM,OAAO,WAAW,OAAO,UAAU,UAAU,IAAI,IAAI,CAAC;AAC7E,kBAAY;AAAA,IACd,SAAS,KAAK;AACZ,kBAAa,IAAc;AAC3B,UAAI,CAAC,QAAQ;AACX,YAAI,qCAAqC,SAAS,EAAE;AACpD,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;AAEA,QAAM,WAAW,MAAM;AACrB,QAAI,MAAO;AACX,YAAQ,WAAW,MAAM;AACvB,cAAQ;AACR,gBAAU,QAAQ,KAAK,MAAM,SAAS,KAAK,CAAC;AAAA,IAC9C,GAAG,IAAI;AAAA,EACT;AACA,SAAO,GAAG,SAAS,CAAC,MAAiB;AACnC,QAAI,EAAE,SAAS,WAAW,EAAE,SAAS,QAAS,UAAS;AAAA,EACzD,CAAC;AAED,SAAO;AAAA,IACL,MAAM,SAAS;AACb,UAAI,MAAO,cAAa,KAAK;AAC7B,cAAQ;AACR,YAAM;AACN,YAAM,SAAS,IAAI;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["readdirSync","readFileSync","join","git","join","readFileSync","readdirSync","skipSelectors","existsSync","readdirSync","readFileSync","createServer","dirname","join","PNG","surfaceKey","start","existsSync","mkdirSync","readFileSync","dirname","join","join","createServer","existsSync","readdirSync","readFileSync","PNG","dirname","readdirSync","readFileSync","statSync","join","relative","dir","failed","sep","readFileSync","join","z","z","readFileSync","join","appendFileSync","existsSync","mkdirSync","readFileSync","rmSync","writeFileSync","dirname","join","Anthropic","mkdirSync","writeFileSync","join","PNG","PNG","start","join","a","Anthropic","mkdirSync","verdict","PNG","writeFileSync","closeSync","existsSync","fstatSync","openSync","readdirSync","readFileSync","join","relative","SKIP_DIRS","join","existsSync","readdirSync","openSync","fstatSync","readFileSync","closeSync","relative","randomBytes","writeFileSync","join","join","randomBytes","writeFileSync","existsSync","mkdirSync","readdirSync","readFileSync","rmSync","writeFileSync","dirname","join","relative","join","rmSync","mkdirSync","dirname","writeFileSync","mkdirSync","appendFileSync","join","existsSync","session","rmSync","dirname","writeFileSync","readFileSync","text","lastKept","step","existsSync","readFileSync","join","readFileSync","join"]}
|