@mushi-mushi/ux 0.4.0 → 0.5.1

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/dist/index.js CHANGED
@@ -797,8 +797,8 @@ async function openSession(opts = {}) {
797
797
  }
798
798
  seed = await context.storageState({ indexedDB: true });
799
799
  };
800
- const freshContext = async () => {
801
- const fresh = await browser.newContext({ serviceWorkers: "block", storageState: seed });
800
+ const freshContext = async (extra = {}) => {
801
+ const fresh = await browser.newContext({ ...extra, serviceWorkers: "block", storageState: seed });
802
802
  await installGuard(fresh, opts.allow ?? [], guard, opts.policy);
803
803
  await fresh.addInitScript({ content: CLS_SCRIPT });
804
804
  return fresh;
@@ -924,11 +924,232 @@ async function captureSurface(session, baseUrl, surface, viewport) {
924
924
  }
925
925
  }
926
926
 
927
+ // src/clips.ts
928
+ import { createHash } from "crypto";
929
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, statSync as statSync2 } from "fs";
930
+ import { join as join3 } from "path";
931
+ import { chromium as chromium2 } from "playwright";
932
+ var CLIP_LIMITS = {
933
+ maxFlows: 5,
934
+ maxPathsPerFlow: 6,
935
+ defaultSeconds: 30,
936
+ maxSeconds: 60,
937
+ minSeconds: 5,
938
+ defaultBytes: 25 * 1024 * 1024,
939
+ maxBytes: 100 * 1024 * 1024,
940
+ /** How long each screen stays on camera after it settles. */
941
+ dwellMs: 1500
942
+ };
943
+ var DEFAULT_CLIP_VIEWPORT = { width: 390, height: 844 };
944
+ var SLUG_RE = /[^a-z0-9]+/g;
945
+ function clipSlug(name) {
946
+ const s = name.toLowerCase().replace(SLUG_RE, "-");
947
+ let a = 0;
948
+ let b = s.length;
949
+ while (a < b && s[a] === "-") a++;
950
+ while (b > a && s[b - 1] === "-") b--;
951
+ return s.slice(a, b).slice(0, 60) || "flow";
952
+ }
953
+ function parseFlow(value) {
954
+ const raw = value.trim();
955
+ const colon = raw.indexOf(":");
956
+ const hasName = colon > 0 && !raw.slice(0, colon).includes("/");
957
+ const name = hasName ? raw.slice(0, colon).trim() : "";
958
+ const paths = (hasName ? raw.slice(colon + 1) : raw).split(",").map((p) => p.trim()).filter(Boolean);
959
+ if (!paths.length) throw new Error(`--flow "${value}" names no paths; use name:/a,/b`);
960
+ for (const p of paths) if (!p.startsWith("/") || p.startsWith("//")) throw new Error(`--flow path "${p}" must start with a single /`);
961
+ return { name: (name || paths[0]).slice(0, 80), paths };
962
+ }
963
+ function capFlows(flows) {
964
+ const notes = [];
965
+ if (flows.length > CLIP_LIMITS.maxFlows) notes.push(`Only the first ${CLIP_LIMITS.maxFlows} of ${flows.length} flows are recorded.`);
966
+ const seen = /* @__PURE__ */ new Set();
967
+ const out = [];
968
+ for (const f of flows.slice(0, CLIP_LIMITS.maxFlows)) {
969
+ let slug = clipSlug(f.name);
970
+ for (let i = 2; seen.has(slug); i++) slug = `${clipSlug(f.name)}-${i}`;
971
+ seen.add(slug);
972
+ if (f.paths.length > CLIP_LIMITS.maxPathsPerFlow) notes.push(`"${f.name}": only the first ${CLIP_LIMITS.maxPathsPerFlow} of ${f.paths.length} screens.`);
973
+ out.push({ name: f.name, paths: f.paths.slice(0, CLIP_LIMITS.maxPathsPerFlow) });
974
+ }
975
+ return { flows: out, notes };
976
+ }
977
+ function clampCaps(input) {
978
+ const secs = Number.isFinite(input.maxSeconds) ? Number(input.maxSeconds) : CLIP_LIMITS.defaultSeconds;
979
+ const bytes = Number.isFinite(input.maxBytes) ? Number(input.maxBytes) : CLIP_LIMITS.defaultBytes;
980
+ return {
981
+ maxSeconds: Math.min(CLIP_LIMITS.maxSeconds, Math.max(CLIP_LIMITS.minSeconds, Math.floor(secs))),
982
+ maxBytes: Math.min(CLIP_LIMITS.maxBytes, Math.max(1024 * 1024, Math.floor(bytes)))
983
+ };
984
+ }
985
+ function hasTimeForScreen(elapsedMs, slowestScreenMs, maxSeconds) {
986
+ const next = Math.max(3e3, slowestScreenMs) + CLIP_LIMITS.dwellMs;
987
+ return elapsedMs + next <= maxSeconds * 1e3;
988
+ }
989
+ async function recordClips(opts) {
990
+ const log = opts.log ?? (() => {
991
+ });
992
+ const { flows, notes } = capFlows(opts.flows);
993
+ const { maxSeconds, maxBytes } = clampCaps({ maxSeconds: opts.maxSeconds, maxBytes: opts.maxBytes });
994
+ const viewport = opts.viewport ?? DEFAULT_CLIP_VIEWPORT;
995
+ const headless = opts.headless ?? true;
996
+ const channel = opts.channel === "chrome" ? { channel: "chrome" } : {};
997
+ mkdirSync2(opts.outDir, { recursive: true });
998
+ const guard = { blocked: [] };
999
+ const clips = [];
1000
+ const skipped = [];
1001
+ let storageState;
1002
+ if (opts.profileDir) {
1003
+ const persistent = await chromium2.launchPersistentContext(opts.profileDir, { headless, serviceWorkers: "block", ...channel });
1004
+ try {
1005
+ storageState = await persistent.storageState();
1006
+ } finally {
1007
+ await persistent.close();
1008
+ }
1009
+ }
1010
+ const browser = await chromium2.launch({ headless, ...channel });
1011
+ try {
1012
+ for (const flow of flows) {
1013
+ const slug = clipSlug(flow.name);
1014
+ const rawDir = join3(opts.outDir, `.raw-${slug}`);
1015
+ const context = await browser.newContext({
1016
+ serviceWorkers: "block",
1017
+ viewport,
1018
+ recordVideo: { dir: rawDir, size: viewport },
1019
+ ...storageState ? { storageState } : {}
1020
+ });
1021
+ await installGuard(context, opts.allow ?? [], guard);
1022
+ const page = await context.newPage();
1023
+ const started = Date.now();
1024
+ const shown = [];
1025
+ let slowest = 0;
1026
+ let failure = null;
1027
+ try {
1028
+ for (const p of flow.paths) {
1029
+ if (!hasTimeForScreen(Date.now() - started, slowest, maxSeconds)) {
1030
+ notes.push(`"${flow.name}": stopped after ${shown.length} screen(s) to stay under ${maxSeconds} s.`);
1031
+ break;
1032
+ }
1033
+ const t0 = Date.now();
1034
+ await gotoPatiently(page, surfaceUrl(opts.baseUrl, p));
1035
+ await settle(page);
1036
+ slowest = Math.max(slowest, Date.now() - t0);
1037
+ await page.waitForTimeout(CLIP_LIMITS.dwellMs);
1038
+ shown.push(p);
1039
+ }
1040
+ } catch (err) {
1041
+ failure = err.message.split("\n")[0].slice(0, 200);
1042
+ }
1043
+ const durationMs = Date.now() - started;
1044
+ const video = page.video();
1045
+ await context.close();
1046
+ const rawPath = await video?.path().catch(() => null);
1047
+ const file = join3(opts.outDir, `${slug}.webm`);
1048
+ if (!rawPath || shown.length === 0) {
1049
+ skipped.push({ name: flow.name, reason: failure ?? "No screen loaded." });
1050
+ rmSync(rawDir, { recursive: true, force: true });
1051
+ continue;
1052
+ }
1053
+ renameSync(rawPath, file);
1054
+ rmSync(rawDir, { recursive: true, force: true });
1055
+ const bytes = statSync2(file).size;
1056
+ if (bytes > maxBytes) {
1057
+ rmSync(file, { force: true });
1058
+ skipped.push({ name: flow.name, reason: `${(bytes / 1048576).toFixed(1)} MB is over the ${(maxBytes / 1048576).toFixed(0)} MB cap.` });
1059
+ continue;
1060
+ }
1061
+ if (failure) notes.push(`"${flow.name}": stopped at an error after ${shown.length} screen(s): ${failure}`);
1062
+ clips.push({ name: flow.name, file, bytes, durationMs, width: viewport.width, height: viewport.height, paths: shown });
1063
+ log(`Recorded "${flow.name}" (${shown.length} screen(s), ${(durationMs / 1e3).toFixed(1)} s, ${(bytes / 1048576).toFixed(1)} MB)`);
1064
+ }
1065
+ } finally {
1066
+ await browser.close();
1067
+ }
1068
+ return { clips, skipped, notes, guard };
1069
+ }
1070
+ function clipUploadBody(clips) {
1071
+ return {
1072
+ files: clips.map((c) => ({
1073
+ name: `${clipSlug(c.name)}.webm`,
1074
+ kind: "clip",
1075
+ mime: "video/webm",
1076
+ bytes: c.bytes,
1077
+ source: "playwright",
1078
+ platform: "web",
1079
+ durationMs: Math.max(1, Math.round(c.durationMs)),
1080
+ width: c.width,
1081
+ height: c.height,
1082
+ surfacePath: c.paths[0] ?? null,
1083
+ label: c.name.slice(0, 200)
1084
+ }))
1085
+ };
1086
+ }
1087
+ async function call(fetchImpl, cfg, path, init = {}) {
1088
+ const res = await fetchImpl(`${cfg.endpoint}${path}`, {
1089
+ ...init,
1090
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${cfg.apiKey}`, "X-Mushi-Api-Key": cfg.apiKey, "X-Mushi-Project": cfg.projectId, ...init.headers ?? {} }
1091
+ });
1092
+ const body = await res.json().catch(() => null);
1093
+ return { ok: res.ok, status: res.status, body };
1094
+ }
1095
+ function apiMessage(r) {
1096
+ const e = r.body?.error;
1097
+ return e?.message ? e.message.slice(0, 300) : `the API answered ${r.status}`;
1098
+ }
1099
+ async function fetchClipCaps(cfg, releaseId, fetchImpl = fetch) {
1100
+ try {
1101
+ const r = await call(fetchImpl, cfg, `/v1/admin/projects/${encodeURIComponent(cfg.projectId)}/releases/${encodeURIComponent(releaseId)}/kit`);
1102
+ if (!r.ok) return null;
1103
+ const s = r.body?.data?.settings;
1104
+ if (!s || typeof s.clipsEnabled !== "boolean" || typeof s.clipMaxSeconds !== "number" || typeof s.clipMaxMb !== "number") return null;
1105
+ return { clipsEnabled: s.clipsEnabled, maxSeconds: s.clipMaxSeconds, maxBytes: s.clipMaxMb * 1024 * 1024 };
1106
+ } catch {
1107
+ return null;
1108
+ }
1109
+ }
1110
+ function effectiveClipCaps(requested, server) {
1111
+ const asked = clampCaps(requested);
1112
+ if (!server) {
1113
+ return { ...asked, blocked: null, notes: ["Could not read this app's clip settings; using the local caps (the server still checks them on upload)."] };
1114
+ }
1115
+ if (!server.clipsEnabled) {
1116
+ return { ...asked, notes: [], blocked: `Recording clips is off for this app. Turn on "Record clips for release kits" in the release's kit (Releases \u2192 the release \u2192 Ship it), then run this again.` };
1117
+ }
1118
+ const capped = clampCaps({ maxSeconds: Math.min(asked.maxSeconds, server.maxSeconds), maxBytes: Math.min(asked.maxBytes, server.maxBytes) });
1119
+ const notes = [];
1120
+ if (capped.maxSeconds < asked.maxSeconds) notes.push(`This app caps clips at ${capped.maxSeconds} s; recording up to that.`);
1121
+ if (capped.maxBytes < asked.maxBytes) notes.push(`This app caps clips at ${Math.round(capped.maxBytes / 1048576)} MB; larger ones are dropped before upload.`);
1122
+ return { ...capped, notes, blocked: null };
1123
+ }
1124
+ async function uploadClips(cfg, releaseId, clips, fetchImpl = fetch) {
1125
+ const base = `/v1/admin/projects/${encodeURIComponent(cfg.projectId)}/releases/${encodeURIComponent(releaseId)}/kit`;
1126
+ const out = { uploaded: [], failed: [] };
1127
+ if (!clips.length) return out;
1128
+ const r = await call(fetchImpl, cfg, `${base}/uploads`, { method: "POST", body: JSON.stringify(clipUploadBody(clips)) });
1129
+ if (!r.ok) throw new Error(`Clips not uploaded: ${apiMessage(r)}`);
1130
+ const uploads = r.body?.data?.uploads ?? [];
1131
+ for (let i = 0; i < uploads.length; i++) {
1132
+ const u = uploads[i];
1133
+ const clip3 = clips[i];
1134
+ const bytes = readFileSync3(clip3.file);
1135
+ const put = await fetchImpl(u.signedUrl, { method: "PUT", headers: { "Content-Type": "video/webm" }, body: new Uint8Array(bytes) });
1136
+ if (!put.ok) {
1137
+ out.failed.push({ name: clip3.name, reason: `storage answered ${put.status}` });
1138
+ continue;
1139
+ }
1140
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
1141
+ const fin = await call(fetchImpl, cfg, `${base}/assets/${encodeURIComponent(u.assetId)}/finalize`, { method: "POST", body: JSON.stringify({ sha256 }) });
1142
+ if (!fin.ok) out.failed.push({ name: clip3.name, reason: apiMessage(fin) });
1143
+ else out.uploaded.push({ name: clip3.name, assetId: u.assetId });
1144
+ }
1145
+ return out;
1146
+ }
1147
+
927
1148
  // src/dashboard.ts
928
1149
  import { randomBytes } from "crypto";
929
- import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync4 } from "fs";
1150
+ import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync5 } from "fs";
930
1151
  import { createServer as createServer2 } from "http";
931
- import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
1152
+ import { basename, dirname as dirname3, join as join5, normalize, sep } from "path";
932
1153
  import { z } from "zod";
933
1154
  import { PNG as PNG2 } from "pngjs";
934
1155
 
@@ -1214,33 +1435,47 @@ function hammingHex(a, b) {
1214
1435
  }
1215
1436
 
1216
1437
  // src/state.ts
1217
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, writeFileSync } from "fs";
1218
- import { dirname as dirname2, join as join3 } from "path";
1438
+ import { existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync } from "fs";
1439
+ import { dirname as dirname2, join as join4 } from "path";
1440
+ function addJudgeUsage(state, model, v) {
1441
+ const t = state.judgeUsage ??= { model, judged: 0, reused: 0, input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
1442
+ t.model = model;
1443
+ if (v.reused) {
1444
+ t.reused++;
1445
+ return;
1446
+ }
1447
+ t.judged++;
1448
+ if (!v.usage) return;
1449
+ t.input_tokens += v.usage.input_tokens;
1450
+ t.output_tokens += v.usage.output_tokens;
1451
+ t.cache_read_input_tokens += v.usage.cache_read_input_tokens;
1452
+ t.cache_creation_input_tokens += v.usage.cache_creation_input_tokens;
1453
+ }
1219
1454
  function runDir(repoRoot, runId) {
1220
- return join3(repoRoot, ".mushi", "ux", runId);
1455
+ return join4(repoRoot, ".mushi", "ux", runId);
1221
1456
  }
1222
1457
  function newRunId(now = /* @__PURE__ */ new Date()) {
1223
1458
  const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-");
1224
1459
  return `${stamp}-${Math.random().toString(36).slice(2, 6)}`;
1225
1460
  }
1226
1461
  function saveState(dir, state) {
1227
- mkdirSync2(dir, { recursive: true });
1462
+ mkdirSync3(dir, { recursive: true });
1228
1463
  state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1229
- const file = join3(dir, "state.json");
1464
+ const file = join4(dir, "state.json");
1230
1465
  const tmp = `${file}.${process.pid}.tmp`;
1231
1466
  writeFileSync(tmp, JSON.stringify(state, null, 2));
1232
- renameSync(tmp, file);
1467
+ renameSync2(tmp, file);
1233
1468
  }
1234
1469
  function loadState(dir) {
1235
- const file = join3(dir, "state.json");
1470
+ const file = join4(dir, "state.json");
1236
1471
  if (!existsSync2(file)) return null;
1237
- const parsed = JSON.parse(readFileSync3(file, "utf8"));
1472
+ const parsed = JSON.parse(readFileSync4(file, "utf8"));
1238
1473
  if (parsed.version !== 1) throw new Error(`Unsupported run state version ${String(parsed.version)} in ${file}`);
1239
1474
  return parsed;
1240
1475
  }
1241
1476
  function savePng(dir, rel, png) {
1242
- const abs = join3(dir, rel);
1243
- mkdirSync2(dirname2(abs), { recursive: true });
1477
+ const abs = join4(dir, rel);
1478
+ mkdirSync3(dirname2(abs), { recursive: true });
1244
1479
  writeFileSync(abs, png);
1245
1480
  return rel.replace(/\\/g, "/");
1246
1481
  }
@@ -1658,7 +1893,7 @@ async function openLauncher() {
1658
1893
  '<div class="grid">' +
1659
1894
  '<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>' +
1660
1895
  '</div>' +
1661
- '<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\u20130.50 of your Claude usage (two reviews; measured $0.46 on glot.it).</div>' +
1896
+ '<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\u20130.50 of your Claude usage (two reviews; measured $0.46 on one real app).</div>' +
1662
1897
  '<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>' +
1663
1898
  '<div class="row"><span class="sub mono" id="f-spec"></span><button type="button" class="btn" id="f-refresh">Refresh list</button></div></div>' +
1664
1899
  '<div class="card"><h2><span class="n">3</span>How much</h2><div class="grid">' +
@@ -1904,7 +2139,7 @@ es.onmessage = (m) => {
1904
2139
  var RUN_ID_RE = /^[0-9]{8}-[0-9]{6}-[a-z0-9]{4}$/;
1905
2140
  function safeShotPath(runDirPath, requested) {
1906
2141
  if (!/^shots\/[\w./-]+\.png$/.test(requested) || requested.includes("..")) return null;
1907
- const abs = normalize(join4(runDirPath, requested));
2142
+ const abs = normalize(join5(runDirPath, requested));
1908
2143
  return abs.startsWith(normalize(runDirPath) + sep) ? abs : null;
1909
2144
  }
1910
2145
  var LaunchInput = z.object({
@@ -1956,7 +2191,7 @@ async function readBody(req, limit = 64e3) {
1956
2191
  }
1957
2192
  async function startStudio(opts) {
1958
2193
  const token = randomBytes(16).toString("hex");
1959
- const uxDir = join4(opts.repoRoot, ".mushi", "ux");
2194
+ const uxDir = join5(opts.repoRoot, ".mushi", "ux");
1960
2195
  const clients = /* @__PURE__ */ new Set();
1961
2196
  let active = null;
1962
2197
  const send = (payload) => {
@@ -1979,7 +2214,7 @@ async function startStudio(opts) {
1979
2214
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
1980
2215
  res.end(JSON.stringify(body));
1981
2216
  };
1982
- const runDirOf = (runId) => runId && RUN_ID_RE.test(runId) ? join4(uxDir, runId) : null;
2217
+ const runDirOf = (runId) => runId && RUN_ID_RE.test(runId) ? join5(uxDir, runId) : null;
1983
2218
  const server = createServer2((req, res) => {
1984
2219
  const url = new URL(req.url ?? "/", "http://127.0.0.1");
1985
2220
  if (url.searchParams.get("t") !== token) {
@@ -1996,7 +2231,7 @@ async function startStudio(opts) {
1996
2231
  }
1997
2232
  if (req.method === "GET" && url.pathname === "/api/runs") {
1998
2233
  const ids = existsSync3(uxDir) ? readdirSync3(uxDir).filter((d) => RUN_ID_RE.test(d)) : [];
1999
- const runs = ids.map((id) => loadState(join4(uxDir, id))).filter((s) => s !== null).map(summarize).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2234
+ const runs = ids.map((id) => loadState(join5(uxDir, id))).filter((s) => s !== null).map(summarize).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2000
2235
  return json(res, 200, { runs });
2001
2236
  }
2002
2237
  if (req.method === "GET" && url.pathname === "/api/state") {
@@ -2005,8 +2240,8 @@ async function startStudio(opts) {
2005
2240
  }
2006
2241
  if (req.method === "GET" && url.pathname === "/api/log") {
2007
2242
  const dir = runDirOf(url.searchParams.get("run"));
2008
- const file = dir ? join4(dir, "run.log") : null;
2009
- const lines = file && existsSync3(file) ? readFileSync4(file, "utf8").split("\n").filter(Boolean).slice(-400) : [];
2243
+ const file = dir ? join5(dir, "run.log") : null;
2244
+ const lines = file && existsSync3(file) ? readFileSync5(file, "utf8").split("\n").filter(Boolean).slice(-400) : [];
2010
2245
  return json(res, 200, { lines });
2011
2246
  }
2012
2247
  if (req.method === "GET" && url.pathname === "/api/steps") {
@@ -2014,12 +2249,12 @@ async function startStudio(opts) {
2014
2249
  const key = url.searchParams.get("surface") ?? "";
2015
2250
  const n = url.searchParams.get("attempt");
2016
2251
  if (!dir || !/^[\w.:-]{1,160}$/.test(key) || n !== null && !/^[0-9]{1,2}$/.test(n)) return json(res, 400, { error: "bad request" });
2017
- const agentDir = join4(dir, "agent");
2252
+ const agentDir = join5(dir, "agent");
2018
2253
  const prefix = attemptLogBase(key, 0).slice(0, -1);
2019
2254
  const attempts = existsSync3(agentDir) ? readdirSync3(agentDir).map((f) => f.startsWith(prefix) && f.endsWith(".steps.log") ? Number(f.slice(prefix.length, -".steps.log".length)) : NaN).filter((a) => Number.isInteger(a) && a > 0) : [];
2020
2255
  const attempt = n !== null ? Number(n) : attempts.length ? Math.max(...attempts) : null;
2021
- const file = attempt !== null && attempts.includes(attempt) ? join4(agentDir, `${prefix}${attempt}.steps.log`) : null;
2022
- const lines = file ? readFileSync4(file, "utf8").split("\n").filter(Boolean).slice(-200) : [];
2256
+ const file = attempt !== null && attempts.includes(attempt) ? join5(agentDir, `${prefix}${attempt}.steps.log`) : null;
2257
+ const lines = file ? readFileSync5(file, "utf8").split("\n").filter(Boolean).slice(-200) : [];
2023
2258
  return json(res, 200, { attempt, lines });
2024
2259
  }
2025
2260
  if (req.method === "GET" && url.pathname === "/api/events") {
@@ -2037,13 +2272,13 @@ async function startStudio(opts) {
2037
2272
  return res.end();
2038
2273
  }
2039
2274
  res.writeHead(200, { "content-type": "image/png", "cache-control": "max-age=3600" });
2040
- return res.end(readFileSync4(abs));
2275
+ return res.end(readFileSync5(abs));
2041
2276
  }
2042
2277
  if (req.method === "GET" && url.pathname === "/api/changes") {
2043
2278
  const dir = runDirOf(url.searchParams.get("run"));
2044
2279
  const abs = dir ? safeShotPath(dir, url.searchParams.get("p") ?? "") : null;
2045
2280
  if (!abs || !existsSync3(abs)) return json(res, 404, { error: "No such diff image" });
2046
- const png = PNG2.sync.read(readFileSync4(abs));
2281
+ const png = PNG2.sync.read(readFileSync5(abs));
2047
2282
  return json(res, 200, { width: png.width, height: png.height, boxes: changeRegions(png) });
2048
2283
  }
2049
2284
  if (req.method === "GET" && url.pathname === "/api/options") {
@@ -2096,7 +2331,7 @@ async function startStudio(opts) {
2096
2331
  const origin = req.headers.origin;
2097
2332
  if (origin && origin !== `http://127.0.0.1:${server.address().port}`) return json(res, 403, { error: "Wrong origin" });
2098
2333
  if (active && active.runId !== resumeMatch[1]) {
2099
- const state = loadState(join4(uxDir, active.runId));
2334
+ const state = loadState(join5(uxDir, active.runId));
2100
2335
  if (state && !["done", "failed"].includes(state.phase ?? "")) return json(res, 409, { error: `Run ${active.runId} is still going. Stop it first.` });
2101
2336
  }
2102
2337
  const started = await opts.resume(resumeMatch[1]).catch((err) => err);
@@ -2112,7 +2347,7 @@ async function startStudio(opts) {
2112
2347
  const origin = req.headers.origin;
2113
2348
  if (origin && origin !== `http://127.0.0.1:${server.address().port}`) return json(res, 403, { error: "Wrong origin" });
2114
2349
  if (active) {
2115
- const state = loadState(join4(uxDir, active.runId));
2350
+ const state = loadState(join5(uxDir, active.runId));
2116
2351
  if (state && !["done", "failed"].includes(state.phase ?? "")) return json(res, 409, { error: `Run ${active.runId} is still going.` });
2117
2352
  }
2118
2353
  const parsed = LaunchInput.safeParse(await readBody(req));
@@ -2149,11 +2384,11 @@ async function startDashboard(dir, events, port = 0) {
2149
2384
  }
2150
2385
 
2151
2386
  // src/discover.ts
2152
- import { createHash } from "crypto";
2387
+ import { createHash as createHash2 } from "crypto";
2153
2388
 
2154
2389
  // src/routes.ts
2155
- import { closeSync, fstatSync, openSync, readdirSync as readdirSync4, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
2156
- import { join as join5, relative as relative2 } from "path";
2390
+ import { closeSync, fstatSync, openSync, readdirSync as readdirSync4, readFileSync as readFileSync6, statSync as statSync3 } from "fs";
2391
+ import { join as join6, relative as relative2 } from "path";
2157
2392
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".turbo", ".worktrees", ".mushi", ".mushi-ux", "coverage", "__tests__"]);
2158
2393
  var SOURCE_RE = /\.(tsx|ts|jsx|js|mjs)$/;
2159
2394
  var MAX_FILES = 4e3;
@@ -2200,7 +2435,7 @@ function routesFromSource(root) {
2200
2435
  }
2201
2436
  for (const name of names) {
2202
2437
  if (SKIP_DIRS.has(name)) continue;
2203
- const abs = join5(dir, name);
2438
+ const abs = join6(dir, name);
2204
2439
  let fd;
2205
2440
  let isDir;
2206
2441
  let text = "";
@@ -2213,7 +2448,7 @@ function routesFromSource(root) {
2213
2448
  const st = fstatSync(fd);
2214
2449
  isDir = st.isDirectory();
2215
2450
  if (!isDir && st.size < 4e5 && /\.(tsx|jsx|ts|js)$/.test(name) && !/\.(test|spec|stories)\./.test(name)) {
2216
- text = readFileSync5(fd, "utf8");
2451
+ text = readFileSync6(fd, "utf8");
2217
2452
  }
2218
2453
  } catch {
2219
2454
  continue;
@@ -2280,10 +2515,10 @@ function screenFiles(root, urlPath) {
2280
2515
  for (const name of names) {
2281
2516
  if (page) return;
2282
2517
  if (SKIP_DIRS.has(name)) continue;
2283
- const abs = join5(dir2, name);
2518
+ const abs = join6(dir2, name);
2284
2519
  let st;
2285
2520
  try {
2286
- st = statSync2(abs);
2521
+ st = statSync3(abs);
2287
2522
  } catch {
2288
2523
  continue;
2289
2524
  }
@@ -2303,7 +2538,7 @@ function screenFiles(root, urlPath) {
2303
2538
  const out = [found];
2304
2539
  const list = (d) => {
2305
2540
  try {
2306
- return readdirSync4(join5(root, d));
2541
+ return readdirSync4(join6(root, d));
2307
2542
  } catch {
2308
2543
  return [];
2309
2544
  }
@@ -2351,7 +2586,7 @@ function normalizeLink(href, baseUrl) {
2351
2586
  function surfaceKey(path, steps) {
2352
2587
  const raw = [path, ...steps.map((s) => s.label)].join(" > ");
2353
2588
  const slug = raw.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 80) || "root";
2354
- return `${slug}-${createHash("sha1").update(raw).digest("hex").slice(0, 6)}`;
2589
+ return `${slug}-${createHash2("sha1").update(raw).digest("hex").slice(0, 6)}`;
2355
2590
  }
2356
2591
  function globMatch(glob, path) {
2357
2592
  const re = new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
@@ -2374,7 +2609,7 @@ async function domHash(page) {
2374
2609
  }
2375
2610
  return sig(document.body, 0);
2376
2611
  });
2377
- return createHash("sha1").update(shape).digest("hex").slice(0, 16);
2612
+ return createHash2("sha1").update(shape).digest("hex").slice(0, 16);
2378
2613
  }
2379
2614
  function quoteAttr(value) {
2380
2615
  return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
@@ -2622,14 +2857,14 @@ function tidyLabels(surfaces) {
2622
2857
  }
2623
2858
 
2624
2859
  // src/fresh-eyes.ts
2625
- import { createHash as createHash4 } from "crypto";
2626
- import { mkdirSync as mkdirSync6, writeFileSync as writeFileSync4 } from "fs";
2627
- import { join as join9, resolve } from "path";
2860
+ import { createHash as createHash5 } from "crypto";
2861
+ import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync4 } from "fs";
2862
+ import { join as join10, resolve } from "path";
2628
2863
 
2629
2864
  // src/checker.ts
2630
2865
  import Anthropic from "@anthropic-ai/sdk";
2631
- import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "fs";
2632
- import { join as join6 } from "path";
2866
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync2 } from "fs";
2867
+ import { join as join7 } from "path";
2633
2868
  import { PNG as PNG3 } from "pngjs";
2634
2869
  var MAX_CROP_HEIGHT = 1400;
2635
2870
  var MAX_DIFF_CHARS = 2e4;
@@ -2757,7 +2992,7 @@ async function askApi(prompt, images, model, client, labels = ["a.png", "b.png"]
2757
2992
  }
2758
2993
  async function checkStep(input) {
2759
2994
  const { spec } = input;
2760
- const base = join6(input.dir, "checker", input.name);
2995
+ const base = join7(input.dir, "checker", input.name);
2761
2996
  const fail = (mode, error) => ({ model: spec.model, mode, verdict: "unsure", summary: "", votes: [], costUsd: null, error });
2762
2997
  let cost = 0;
2763
2998
  const ask = async (prompt, cwd, images, maxTurns) => {
@@ -2767,7 +3002,7 @@ async function checkStep(input) {
2767
3002
  };
2768
3003
  if (!input.visual) {
2769
3004
  const diff = input.diff.slice(0, MAX_DIFF_CHARS);
2770
- mkdirSync3(base, { recursive: true });
3005
+ mkdirSync4(base, { recursive: true });
2771
3006
  const a2 = await ask(CODE_PROMPT(input.step, input.screen, diff), input.repoDir ?? base, [], 20);
2772
3007
  if (a2.error || !a2.text) return fail("code", a2.error ?? "No answer.");
2773
3008
  const j = firstJson(a2.text);
@@ -2785,11 +3020,11 @@ async function checkStep(input) {
2785
3020
  const firstIsBefore = (input.random ?? Math.random)() < 0.5;
2786
3021
  const votes = [];
2787
3022
  for (const aIsBefore of [firstIsBefore, !firstIsBefore]) {
2788
- const cwd = join6(base, aIsBefore ? "order-1" : "order-2");
2789
- mkdirSync3(cwd, { recursive: true });
3023
+ const cwd = join7(base, aIsBefore ? "order-1" : "order-2");
3024
+ mkdirSync4(cwd, { recursive: true });
2790
3025
  const [imgA, imgB] = aIsBefore ? [b, a] : [a, b];
2791
- writeFileSync2(join6(cwd, "a.png"), imgA);
2792
- writeFileSync2(join6(cwd, "b.png"), imgB);
3026
+ writeFileSync2(join7(cwd, "a.png"), imgA);
3027
+ writeFileSync2(join7(cwd, "b.png"), imgB);
2793
3028
  const res = await ask(VISUAL_PROMPT(input.step, input.screen), cwd, [imgA, imgB]);
2794
3029
  if (res.error || !res.text) return fail("visual", res.error ?? "No answer.");
2795
3030
  const vote = toVote(firstJson(res.text), aIsBefore);
@@ -2801,16 +3036,16 @@ async function checkStep(input) {
2801
3036
  }
2802
3037
 
2803
3038
  // src/explore.ts
2804
- import { mkdirSync as mkdirSync5 } from "fs";
2805
- import { createHash as createHash3 } from "crypto";
2806
- import { join as join8 } from "path";
3039
+ import { mkdirSync as mkdirSync6 } from "fs";
3040
+ import { createHash as createHash4 } from "crypto";
3041
+ import { join as join9 } from "path";
2807
3042
 
2808
3043
  // src/audit.ts
2809
3044
  import Anthropic2 from "@anthropic-ai/sdk";
2810
- import { createHash as createHash2 } from "crypto";
2811
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
3045
+ import { createHash as createHash3 } from "crypto";
3046
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
2812
3047
  import { homedir } from "os";
2813
- import { join as join7 } from "path";
3048
+ import { join as join8 } from "path";
2814
3049
 
2815
3050
  // src/types.ts
2816
3051
  var VIEWPORTS = [
@@ -2824,7 +3059,7 @@ function pagePath(path) {
2824
3059
  return q < 0 ? path : path.slice(0, q);
2825
3060
  }
2826
3061
  function auditHome() {
2827
- return join7(process.env.LOCALAPPDATA ?? join7(homedir(), ".cache"), "mushi", "ux-audits");
3062
+ return join8(process.env.LOCALAPPDATA ?? join8(homedir(), ".cache"), "mushi", "ux-audits");
2828
3063
  }
2829
3064
  var AUDIT_DEFAULT_ALLOW = ["POST /auth/v1/token?grant_type=refresh_token"];
2830
3065
 
@@ -3223,14 +3458,14 @@ function dropSnapshotNodes(snapshot, drop) {
3223
3458
  var SNAPSHOT_NAME_RE = /^\s*- [a-z]+ "((?:[^"\\]|\\.)*)"/;
3224
3459
  function composeSnapshot(parts, budget = MAX_SNAPSHOT_CHARS2) {
3225
3460
  const hidden = new Set(parts.hidden);
3226
- const clean = (snap) => hidden.size ? dropSnapshotNodes(snap, (line) => {
3461
+ const clean2 = (snap) => hidden.size ? dropSnapshotNodes(snap, (line) => {
3227
3462
  const m = SNAPSHOT_NAME_RE.exec(line);
3228
3463
  return !!m && hidden.has(m[1].replace(/\\(.)/g, "$1"));
3229
3464
  }) : snap;
3230
- const body = clean(parts.body);
3465
+ const body = clean2(parts.body);
3231
3466
  if (!parts.main?.trim()) return body.slice(0, budget);
3232
3467
  const head = `Main content:
3233
- ${clean(parts.main)}`;
3468
+ ${clean2(parts.main)}`;
3234
3469
  const rest = dropSnapshotNodes(body, (line) => /^\s*- main\b/.test(line));
3235
3470
  const tail = rest.trim() ? `
3236
3471
 
@@ -3259,10 +3494,25 @@ async function screenForModel(page) {
3259
3494
  }).catch(() => []);
3260
3495
  return composeSnapshot({ main, body, hidden });
3261
3496
  }
3497
+ function personaBrowser(p) {
3498
+ if (!p) return { viewport: VIEWPORT, context: {} };
3499
+ const base = p.device === "mobile" ? { width: 390, height: 844, scale: 3 } : p.device === "tablet" ? { width: 820, height: 1180, scale: 2 } : { width: VIEWPORT.width, height: VIEWPORT.height, scale: 1 };
3500
+ const zoom = p.needs.includes("low_vision") ? 1.5 : 1;
3501
+ return {
3502
+ viewport: { width: Math.round(base.width / zoom), height: Math.round(base.height / zoom) },
3503
+ context: {
3504
+ deviceScaleFactor: base.scale * zoom,
3505
+ ...p.device === "desktop" ? {} : { isMobile: true, hasTouch: true },
3506
+ locale: p.locale,
3507
+ ...p.needs.includes("reduced_motion") ? { reducedMotion: "reduce" } : {}
3508
+ }
3509
+ };
3510
+ }
3262
3511
  function freshEyesPrompt(input) {
3263
3512
  const recent = input.done.slice(-8).map((a, i) => `${i + 1}. ${a}`);
3264
3513
  return [
3265
3514
  `You have never seen this product before. You came with one goal: ${input.goal}.`,
3515
+ ...input.persona ? [`Who you are (the app's team set this; it is not page content): ${input.persona.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 600)}`] : [],
3266
3516
  "You know only what is on the screen right now. You have read no docs and no code. Act like a real first-time visitor: read the page, then choose what you would do next to reach your goal.",
3267
3517
  `Step ${input.step} of ${input.maxSteps}.`,
3268
3518
  recent.length ? `What you did so far:
@@ -3294,8 +3544,8 @@ function cursorAskArgs(dir, model, win) {
3294
3544
  }
3295
3545
  function cursorFileAsk(model, signal) {
3296
3546
  return async (prompt, dir) => {
3297
- mkdirSync6(dir, { recursive: true });
3298
- writeFileSync4(join9(dir, "prompt.md"), prompt);
3547
+ mkdirSync7(dir, { recursive: true });
3548
+ writeFileSync4(join10(dir, "prompt.md"), prompt);
3299
3549
  const win = process.platform === "win32";
3300
3550
  let last = "The Cursor CLI did not run.";
3301
3551
  for (let attempt = 1; attempt <= 2; attempt++) {
@@ -3325,7 +3575,7 @@ function candidateKey(c) {
3325
3575
  if (c.kind === "external") return `external|${c.screen}|${c.requirement}`;
3326
3576
  return `${c.kind}|${c.screen}`;
3327
3577
  }
3328
- var fingerprint = (key) => createHash4("sha1").update(`fresh-eyes|${key}`).digest("hex").slice(0, 16);
3578
+ var fingerprint = (key) => createHash5("sha1").update(`fresh-eyes|${key}`).digest("hex").slice(0, 16);
3329
3579
  var SIGNAL_SEVERITY = { "page-error": "high", "blank-screen": "high", "server-error": "high", "console-error": "medium" };
3330
3580
  var SIGNAL_LABEL = {
3331
3581
  "console-error": "A console error",
@@ -3510,8 +3760,8 @@ async function runFreshEyes(opts) {
3510
3760
  });
3511
3761
  if (opts.runId !== void 0 && !/^[0-9]{8}-[0-9]{6}-[a-z0-9]{4}$/.test(opts.runId)) throw new Error(`Bad run id "${opts.runId.slice(0, 40)}".`);
3512
3762
  const runId = opts.runId ?? newRunId();
3513
- const dir = resolve(opts.outDir ?? join9(process.env.LOCALAPPDATA ?? join9(process.env.HOME ?? ".", ".cache"), "mushi", "fresh-eyes", runId));
3514
- mkdirSync6(join9(dir, "shots"), { recursive: true });
3763
+ const dir = resolve(opts.outDir ?? join10(process.env.LOCALAPPDATA ?? join10(process.env.HOME ?? ".", ".cache"), "mushi", "fresh-eyes", runId));
3764
+ mkdirSync7(join10(dir, "shots"), { recursive: true });
3515
3765
  const sessions = Math.max(1, Math.min(10, opts.sessions ?? 3));
3516
3766
  const maxSteps = Math.max(1, Math.min(80, opts.steps ?? 30));
3517
3767
  const model = opts.model ?? DEFAULT_CURSOR_REVIEW_MODEL;
@@ -3521,6 +3771,7 @@ async function runFreshEyes(opts) {
3521
3771
  const apiHosts = appOrigins.map((o) => new URL(o).host);
3522
3772
  const dryRun = !!opts.dryRun;
3523
3773
  const readOnly = dryRun || !opts.identity;
3774
+ const look = personaBrowser(opts.persona);
3524
3775
  const browser = await (opts.session?.() ?? // Writes only with a synthetic identity to write as: a run with no account stays read-only.
3525
3776
  openSession({ headless: true, allow: opts.allow, policy: !dryRun && opts.identity ? { writes: "same-origin", appOrigins } : { writes: "read-only" } }));
3526
3777
  const result = {
@@ -3558,12 +3809,12 @@ async function runFreshEyes(opts) {
3558
3809
  identities.set(index, identity);
3559
3810
  if (identity) result.hasAccount = true;
3560
3811
  progress(`session ${index} of ${sessions}${identity ? ` (${identity.userId ? `synthetic account ${identity.userId}` : "test account"})` : " (no account)"}`);
3561
- const s = await runSession({ readOnly, index, identity, browser, opts, ask, base, apiHosts, appOrigins, maxSteps, dir, addCandidate, progress, refused: result.refused });
3812
+ const s = await runSession({ readOnly, index, identity, browser, opts, ask, base, apiHosts, appOrigins, maxSteps, dir, addCandidate, progress, refused: result.refused, look });
3562
3813
  if (identity?.userId) s.accountId = identity.userId;
3563
3814
  result.sessions.push(redact(s, identity));
3564
3815
  }
3565
3816
  for (const c of candidates.values()) {
3566
- const confirmed = await replayCandidate(browser, base, c, identities.get(c.session) ?? null);
3817
+ const confirmed = await replayCandidate(browser, base, c, identities.get(c.session) ?? null, look);
3567
3818
  progress(redact(` ${confirmed ? "confirmed" : "not reproduced"}: ${candidateKey(c)}`, identities.get(c.session) ?? null));
3568
3819
  if (confirmed) result.findings.push(redact(measuredFinding(c, { start: opts.url, goal: opts.goal, hasAccount: result.hasAccount, sessions: [...c.sessions].sort((a, b) => a - b) }), identities.get(c.session) ?? null));
3569
3820
  }
@@ -3577,14 +3828,14 @@ async function runFreshEyes(opts) {
3577
3828
  const capped = result.sessions.reduce((n, x) => n + x.steps.filter((st) => st.capped && st.outcome === "ok").length, 0);
3578
3829
  if (capped) result.warnings.push(`${capped} step(s) waited the full 20 s for the app's page to stop showing a loading sign: those waits are the cap, not the app's real time, and a path through one has no time to first value.`);
3579
3830
  result.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
3580
- writeFileSync4(join9(dir, "result.json"), JSON.stringify(result, null, 2));
3831
+ writeFileSync4(join10(dir, "result.json"), JSON.stringify(result, null, 2));
3581
3832
  return result;
3582
3833
  }
3583
3834
  async function runSession(x) {
3584
3835
  const { index, identity, browser, opts, base } = x;
3585
3836
  const say = (line) => x.progress(redact(line, identity));
3586
3837
  const session = { index, outcome: "stalled", stall: null, ttfvSeconds: null, appSeconds: 0, readSeconds: 0, modelSeconds: 0, backtracks: 0, steps: [], opinions: [] };
3587
- const ctx = await browser.freshContext();
3838
+ const ctx = await browser.freshContext(x.look.context);
3588
3839
  await likeARealBrowser(ctx, base.origin);
3589
3840
  let docStatus = null;
3590
3841
  let captchaSeen = false;
@@ -3603,13 +3854,13 @@ async function runSession(x) {
3603
3854
  });
3604
3855
  };
3605
3856
  attach(page);
3606
- await page.setViewportSize(VIEWPORT);
3857
+ await page.setViewportSize(x.look.viewport);
3607
3858
  const switchTo = async (p) => {
3608
3859
  windows.push(page);
3609
3860
  page = p;
3610
3861
  attach(p);
3611
3862
  watcher = watch(p, base.origin, x.apiHosts);
3612
- await p.setViewportSize(VIEWPORT).catch(() => {
3863
+ await p.setViewportSize(x.look.viewport).catch(() => {
3613
3864
  });
3614
3865
  };
3615
3866
  const actions = [];
@@ -3621,7 +3872,7 @@ async function runSession(x) {
3621
3872
  const shoot = async (n) => {
3622
3873
  const name = `s${index}-step${String(n).padStart(2, "0")}.png`;
3623
3874
  try {
3624
- writeFileSync4(join9(x.dir, "shots", name), await page.screenshot({ animations: "disabled", caret: "hide", mask: [page.locator("input[type=password], input[type=email], input[autocomplete=email], input[autocomplete=username]")] }));
3875
+ writeFileSync4(join10(x.dir, "shots", name), await page.screenshot({ animations: "disabled", caret: "hide", mask: [page.locator("input[type=password], input[type=email], input[autocomplete=email], input[autocomplete=username]")] }));
3625
3876
  return name;
3626
3877
  } catch {
3627
3878
  return void 0;
@@ -3680,8 +3931,8 @@ async function runSession(x) {
3680
3931
  const snapshot = redact(await screenForModel(page), identity);
3681
3932
  const tAsk = performance.now();
3682
3933
  const answer = await x.ask(
3683
- freshEyesPrompt({ goal: opts.goal, snapshot, done: session.steps.slice(1).map((s) => s.action), step: n, maxSteps: x.maxSteps, hasAccount: !!identity }),
3684
- join9(x.dir, "ask", `s${index}-${String(n).padStart(2, "0")}`)
3934
+ freshEyesPrompt({ goal: opts.goal, snapshot, done: session.steps.slice(1).map((s) => s.action), step: n, maxSteps: x.maxSteps, hasAccount: !!identity, persona: opts.persona?.brief }),
3935
+ join10(x.dir, "ask", `s${index}-${String(n).padStart(2, "0")}`)
3685
3936
  );
3686
3937
  const modelMs = since(tAsk);
3687
3938
  const parsed = parseFreshAction(answer.text);
@@ -3835,7 +4086,7 @@ async function runSession(x) {
3835
4086
  const values = extractSetupValues(after.text) ?? opts.setupValues ?? null;
3836
4087
  if (values) {
3837
4088
  terminalUsed = true;
3838
- const res = await opts.terminal({ ...values, dir: join9(x.dir, "terminal", `s${index}`) });
4089
+ const res = await opts.terminal({ ...values, dir: join10(x.dir, "terminal", `s${index}`) });
3839
4090
  for (const ph of res.phases) {
3840
4091
  session.steps.push({ n: session.steps.length, action: `Terminal: ${ph.name}`, path, screen: afterScreen, modelMs: 0, appMs: ph.ms, readMs: 0, outcome: "terminal", note: ph.detail.slice(0, 200) });
3841
4092
  say(` terminal ${ph.name}: ${ph.ok ? "ok" : "failed"} in ${(ph.ms / 1e3).toFixed(1)} s`);
@@ -3872,11 +4123,11 @@ function finish(s) {
3872
4123
  }
3873
4124
  return s;
3874
4125
  }
3875
- async function replayCandidate(browser, base, c, identity) {
3876
- const ctx = await browser.freshContext();
4126
+ async function replayCandidate(browser, base, c, identity, look) {
4127
+ const ctx = await browser.freshContext(look.context);
3877
4128
  await likeARealBrowser(ctx, base.origin);
3878
4129
  const page = await ctx.newPage();
3879
- await page.setViewportSize(VIEWPORT);
4130
+ await page.setViewportSize(look.viewport);
3880
4131
  const watcher = watch(page, base.origin, []);
3881
4132
  let docStatus = null;
3882
4133
  let captchaSeen = false;
@@ -3919,9 +4170,9 @@ async function replayCandidate(browser, base, c, identity) {
3919
4170
  }
3920
4171
 
3921
4172
  // src/fresh-eyes-terminal.ts
3922
- import { existsSync as existsSync4, mkdirSync as mkdirSync7, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
4173
+ import { existsSync as existsSync4, mkdirSync as mkdirSync8, readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "fs";
3923
4174
  import { createServer as createServer3 } from "http";
3924
- import { join as join10 } from "path";
4175
+ import { join as join11 } from "path";
3925
4176
  var DEFAULT_SETUP_COMMAND = "npx --yes mushi-mushi@latest --yes --project-id {projectId} --api-key {apiKey}";
3926
4177
  var HOSTED_API_ORIGIN = "https://dxptnwrhwsqckaftyymj.supabase.co";
3927
4178
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -3959,16 +4210,16 @@ function setupEnv(home, base = process.env) {
3959
4210
  env[k] = v;
3960
4211
  }
3961
4212
  const realHome = base.HOME ?? base.USERPROFILE ?? "";
3962
- const npmCache = base.npm_config_cache ?? (realHome ? join10(realHome, process.platform === "win32" ? "AppData/Local/npm-cache" : ".npm") : void 0);
4213
+ const npmCache = base.npm_config_cache ?? (realHome ? join11(realHome, process.platform === "win32" ? "AppData/Local/npm-cache" : ".npm") : void 0);
3963
4214
  return {
3964
4215
  ...env,
3965
4216
  HOME: home,
3966
4217
  USERPROFILE: home,
3967
- APPDATA: join10(home, "AppData", "Roaming"),
3968
- LOCALAPPDATA: join10(home, "AppData", "Local"),
3969
- XDG_CONFIG_HOME: join10(home, ".config"),
3970
- XDG_DATA_HOME: join10(home, ".local", "share"),
3971
- XDG_STATE_HOME: join10(home, ".local", "state"),
4218
+ APPDATA: join11(home, "AppData", "Roaming"),
4219
+ LOCALAPPDATA: join11(home, "AppData", "Local"),
4220
+ XDG_CONFIG_HOME: join11(home, ".config"),
4221
+ XDG_DATA_HOME: join11(home, ".local", "share"),
4222
+ XDG_STATE_HOME: join11(home, ".local", "state"),
3972
4223
  ...npmCache ? { npm_config_cache: npmCache } : {},
3973
4224
  CI: "1",
3974
4225
  MUSHI_TELEMETRY: "0"
@@ -3982,11 +4233,11 @@ async function runTerminalSetup(o) {
3982
4233
  out.failedAt = name;
3983
4234
  return out;
3984
4235
  };
3985
- const sample = join10(o.dir, "sample");
4236
+ const sample = join11(o.dir, "sample");
3986
4237
  const sc = await timed(async () => {
3987
- mkdirSync7(sample, { recursive: true });
3988
- writeFileSync5(join10(sample, "package.json"), JSON.stringify({ name: "fresh-eyes-sample", version: "0.0.0", private: true, type: "module" }, null, 2));
3989
- writeFileSync5(join10(sample, "index.html"), "<!doctype html><title>Sample app</title><h1>Sample app</h1>");
4238
+ mkdirSync8(sample, { recursive: true });
4239
+ writeFileSync5(join11(sample, "package.json"), JSON.stringify({ name: "fresh-eyes-sample", version: "0.0.0", private: true, type: "module" }, null, 2));
4240
+ writeFileSync5(join11(sample, "index.html"), "<!doctype html><title>Sample app</title><h1>Sample app</h1>");
3990
4241
  });
3991
4242
  phases.push({ name: "scaffold", ms: sc.ms, ok: true, detail: "A plain HTML app with a package.json." });
3992
4243
  let argv;
@@ -3996,8 +4247,8 @@ async function runTerminalSetup(o) {
3996
4247
  return fail("setup", 0, err.message);
3997
4248
  }
3998
4249
  const exec = o.runCommand ?? ((cmd, args, cwd) => {
3999
- const home = join10(o.dir, "home");
4000
- mkdirSync7(join10(home, ".config"), { recursive: true });
4250
+ const home = join11(o.dir, "home");
4251
+ mkdirSync8(join11(home, ".config"), { recursive: true });
4001
4252
  return run(cmd, args, { cwd, env: setupEnv(home), shell: process.platform === "win32", timeoutMs: o.setupTimeoutMs ?? 3e5 });
4002
4253
  });
4003
4254
  const st = await timed(() => exec(argv.cmd, argv.args, sample));
@@ -4005,7 +4256,7 @@ async function runTerminalSetup(o) {
4005
4256
  if (st.value.exitCode !== 0) return fail("setup", st.ms, `The setup command exited ${st.value.exitCode}: ${st.value.tail.trim().slice(-300)}`);
4006
4257
  phases.push({ name: "setup", ms: st.ms, ok: true, detail: `${argv.cmd} ${argv.args.join(" ")}`.replace(o.apiKey, "{{apiKey}}").slice(0, 300) });
4007
4258
  const en = await timed(async () => {
4008
- const text = [".env.local", ".env"].map((f) => join10(sample, f)).filter((f) => existsSync4(f)).map((f) => readFileSync7(f, "utf8")).join("\n");
4259
+ const text = [".env.local", ".env"].map((f) => join11(sample, f)).filter((f) => existsSync4(f)).map((f) => readFileSync8(f, "utf8")).join("\n");
4009
4260
  return parseSetupEnv(text);
4010
4261
  });
4011
4262
  if (!en.value.projectId || !en.value.apiKey) return fail("env", en.ms, "The setup finished but wrote no project id and key to .env.local or .env.");
@@ -4068,8 +4319,9 @@ async function sendReportThroughWidget(sampleUrl, apiOrigin, timeoutMs) {
4068
4319
  // src/judge.ts
4069
4320
  import Anthropic3 from "@anthropic-ai/sdk";
4070
4321
  import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
4071
- import { readFileSync as readFileSync8 } from "fs";
4072
- import { join as join11 } from "path";
4322
+ import { createHash as createHash6 } from "crypto";
4323
+ import { existsSync as existsSync5, mkdirSync as mkdirSync9, readFileSync as readFileSync9, writeFileSync as writeFileSync6 } from "fs";
4324
+ import { join as join12 } from "path";
4073
4325
  import { z as z2 } from "zod";
4074
4326
  var DEFAULT_JUDGE_MODEL = "claude-opus-5-5";
4075
4327
  var MAX_DESIGN_CHARS = 16e3;
@@ -4119,7 +4371,7 @@ function designContext(repoRoot, files) {
4119
4371
  for (const f of files) {
4120
4372
  if (out.length >= MAX_DESIGN_CHARS) break;
4121
4373
  try {
4122
- const text = readFileSync8(join11(repoRoot, f), "utf8");
4374
+ const text = readFileSync9(join12(repoRoot, f), "utf8");
4123
4375
  out += `
4124
4376
  --- ${f} ---
4125
4377
  ${text.slice(0, MAX_DESIGN_CHARS - out.length)}
@@ -4167,11 +4419,16 @@ async function judgeSurface(s, viewport, opts) {
4167
4419
  const after = kept.after[viewport];
4168
4420
  const model = opts.model ?? DEFAULT_JUDGE_MODEL;
4169
4421
  const client = opts.client ?? new Anthropic3();
4170
- const beforePng = readFileSync8(join11(opts.dir, before.png));
4422
+ const beforePng = readFileSync9(join12(opts.dir, before.png));
4171
4423
  const width = pngSize(beforePng).width;
4172
4424
  const maxHeight = Math.round(width * (viewport === "mobile" ? 2.5 : 1.25));
4173
4425
  const bImg = cropTop(beforePng, maxHeight);
4174
- const aImg = cropTop(readFileSync8(join11(opts.dir, after.png)), maxHeight);
4426
+ const aImg = cropTop(readFileSync9(join12(opts.dir, after.png)), maxHeight);
4427
+ if (looksSame(bImg, aImg)) return unchangedVerdict(viewport, model);
4428
+ const design = designContext(opts.repoRoot, opts.designFiles);
4429
+ const cacheKey = judgeCacheKey(bImg, aImg, viewport, model, design);
4430
+ const cached = opts.cacheDir ? readCachedVerdict(opts.cacheDir, cacheKey) : null;
4431
+ if (cached) return { ...cached, viewport, reused: "cache", usage: void 0 };
4175
4432
  const aIsBefore = (opts.random ?? Math.random)() < 0.5;
4176
4433
  const [imgA, imgB] = aIsBefore ? [bImg, aImg] : [aImg, bImg];
4177
4434
  const [probeA, probeB] = aIsBefore ? [before.probes, after.probes] : [after.probes, before.probes];
@@ -4191,7 +4448,7 @@ async function judgeSurface(s, viewport, opts) {
4191
4448
  {
4192
4449
  type: "text",
4193
4450
  text: `Design system of this repository:
4194
- ${designContext(opts.repoRoot, opts.designFiles)}`,
4451
+ ${design}`,
4195
4452
  // Same rubric + tokens for every screen in the run: cache the prefix.
4196
4453
  cache_control: { type: "ephemeral" }
4197
4454
  }
@@ -4218,7 +4475,12 @@ Which is better, A or B?` }
4218
4475
  }
4219
4476
  const parsed = response.parsed_output;
4220
4477
  if (!parsed) return failed(viewport, model, `No structured answer (stop reason ${response.stop_reason}).`);
4221
- return unshuffle(parsed, aIsBefore, { A: pngSize(imgA), B: pngSize(imgB) }, viewport, response.model);
4478
+ const verdict = {
4479
+ ...unshuffle(parsed, aIsBefore, { A: pngSize(imgA), B: pngSize(imgB) }, viewport, response.model),
4480
+ usage: usageOf(response.usage)
4481
+ };
4482
+ if (opts.cacheDir) writeCachedVerdict(opts.cacheDir, cacheKey, verdict);
4483
+ return verdict;
4222
4484
  } catch (err) {
4223
4485
  if (err instanceof Anthropic3.AuthenticationError) {
4224
4486
  return failed(viewport, model, "No valid Anthropic credentials. Set ANTHROPIC_API_KEY or run `ant auth login`.");
@@ -4228,6 +4490,61 @@ Which is better, A or B?` }
4228
4490
  throw err;
4229
4491
  }
4230
4492
  }
4493
+ var JUDGE_CACHE_VERSION = "judge-2026-11-27";
4494
+ function judgeCacheKey(before, after, viewport, model, design) {
4495
+ return createHash6("sha256").update(JUDGE_CACHE_VERSION).update("\0").update(RUBRIC).update("\0").update(design).update("\0").update(`${viewport}\0${model}\0`).update(before).update("\0").update(after).digest("hex");
4496
+ }
4497
+ function looksSame(before, after) {
4498
+ if (before.equals(after)) return true;
4499
+ try {
4500
+ return pixelDiff(before, after).changedPixels === 0;
4501
+ } catch {
4502
+ return false;
4503
+ }
4504
+ }
4505
+ function unchangedVerdict(viewport, model) {
4506
+ return {
4507
+ viewport,
4508
+ model,
4509
+ preferred: "tie",
4510
+ confidence: "high",
4511
+ summary: "The kept version looks the same as the original here, so it was not reviewed.",
4512
+ better: [],
4513
+ worse: [],
4514
+ designBreaks: [],
4515
+ droppedClaims: 0,
4516
+ reused: "unchanged"
4517
+ };
4518
+ }
4519
+ function readCachedVerdict(dir, key) {
4520
+ const file = join12(dir, `${key}.json`);
4521
+ if (!existsSync5(file)) return null;
4522
+ try {
4523
+ const v = JSON.parse(readFileSync9(file, "utf8"));
4524
+ return v && typeof v.preferred === "string" && !v.error ? v : null;
4525
+ } catch {
4526
+ return null;
4527
+ }
4528
+ }
4529
+ function writeCachedVerdict(dir, key, v) {
4530
+ if (v.error) return;
4531
+ try {
4532
+ mkdirSync9(dir, { recursive: true });
4533
+ writeFileSync6(join12(dir, `${key}.json`), JSON.stringify({ ...v, usage: void 0 }));
4534
+ } catch {
4535
+ }
4536
+ }
4537
+ function usageOf(u) {
4538
+ if (!u || typeof u !== "object") return void 0;
4539
+ const o = u;
4540
+ const n = (k) => typeof o[k] === "number" && Number.isFinite(o[k]) ? Math.max(0, Math.round(o[k])) : 0;
4541
+ return {
4542
+ input_tokens: n("input_tokens"),
4543
+ output_tokens: n("output_tokens"),
4544
+ cache_read_input_tokens: n("cache_read_input_tokens"),
4545
+ cache_creation_input_tokens: n("cache_creation_input_tokens")
4546
+ };
4547
+ }
4231
4548
  function failed(viewport, model, error) {
4232
4549
  return {
4233
4550
  viewport,
@@ -4244,12 +4561,12 @@ function failed(viewport, model, error) {
4244
4561
  }
4245
4562
 
4246
4563
  // src/loop.ts
4247
- import { appendFileSync as appendFileSync2, existsSync as existsSync7, mkdirSync as mkdirSync9, readFileSync as readFileSync11, rmSync as rmSync3, writeFileSync as writeFileSync8 } from "fs";
4248
- import { dirname as dirname5, join as join15 } from "path";
4564
+ import { appendFileSync as appendFileSync2, existsSync as existsSync8, mkdirSync as mkdirSync11, readFileSync as readFileSync12, rmSync as rmSync4, writeFileSync as writeFileSync9 } from "fs";
4565
+ import { dirname as dirname5, join as join16 } from "path";
4249
4566
 
4250
4567
  // src/packet.ts
4251
- import { closeSync as closeSync2, existsSync as existsSync5, fstatSync as fstatSync2, openSync as openSync2, readdirSync as readdirSync5, readFileSync as readFileSync9 } from "fs";
4252
- import { join as join12, relative as relative3 } from "path";
4568
+ import { closeSync as closeSync2, existsSync as existsSync6, fstatSync as fstatSync2, openSync as openSync2, readdirSync as readdirSync5, readFileSync as readFileSync10 } from "fs";
4569
+ import { join as join13, relative as relative3 } from "path";
4253
4570
  var MAX_PACKET_CHARS = 24e3;
4254
4571
  var MAX_SKILL_CHARS = 12e3;
4255
4572
  var DEFAULT_GUIDANCE = `Improve this one screen's UI and UX. In order of priority:
@@ -4373,8 +4690,8 @@ var POINTER_PROMPT = "Read .mushi-ux/PROMPT.md in this repository and follow it
4373
4690
  var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".turbo", ".worktrees", ".mushi", ".mushi-ux", "coverage"]);
4374
4691
  function findDesignFiles(root, maxFiles = 12) {
4375
4692
  const found = [];
4376
- const recipe = join12(root, "mushi.recipe.json");
4377
- if (existsSync5(recipe)) found.push("mushi.recipe.json");
4693
+ const recipe = join13(root, "mushi.recipe.json");
4694
+ if (existsSync6(recipe)) found.push("mushi.recipe.json");
4378
4695
  const walk = (dir, depth) => {
4379
4696
  if (depth > 5 || found.length >= maxFiles) return;
4380
4697
  let names;
@@ -4386,7 +4703,7 @@ function findDesignFiles(root, maxFiles = 12) {
4386
4703
  for (const name of names) {
4387
4704
  if (found.length >= maxFiles) return;
4388
4705
  if (SKIP_DIRS2.has(name)) continue;
4389
- const abs = join12(dir, name);
4706
+ const abs = join13(dir, name);
4390
4707
  let fd;
4391
4708
  let isDir;
4392
4709
  let css = null;
@@ -4398,7 +4715,7 @@ function findDesignFiles(root, maxFiles = 12) {
4398
4715
  try {
4399
4716
  const st = fstatSync2(fd);
4400
4717
  isDir = st.isDirectory();
4401
- if (!isDir && name.endsWith(".css") && st.size < 3e5) css = readFileSync9(fd, "utf8");
4718
+ if (!isDir && name.endsWith(".css") && st.size < 3e5) css = readFileSync10(fd, "utf8");
4402
4719
  } catch {
4403
4720
  continue;
4404
4721
  } finally {
@@ -4422,9 +4739,9 @@ function findDesignFiles(root, maxFiles = 12) {
4422
4739
 
4423
4740
  // src/preflight.ts
4424
4741
  import { randomBytes as randomBytes2 } from "crypto";
4425
- import { mkdtempSync, rmSync, writeFileSync as writeFileSync6 } from "fs";
4742
+ import { mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "fs";
4426
4743
  import { tmpdir } from "os";
4427
- import { join as join13 } from "path";
4744
+ import { join as join14 } from "path";
4428
4745
 
4429
4746
  // src/verdict.ts
4430
4747
  var MIN_VISIBLE_RATIO = 5e-4;
@@ -4548,10 +4865,10 @@ function preflightAdvice(agent, output, platform = process.platform) {
4548
4865
  return "Run the agent once by hand in this repo to see what it needs, then start the run again.";
4549
4866
  }
4550
4867
  async function preflightAgent(agent, opts = {}) {
4551
- const dir = mkdtempSync(join13(tmpdir(), "mushi-ux-preflight-"));
4868
+ const dir = mkdtempSync(join14(tmpdir(), "mushi-ux-preflight-"));
4552
4869
  const word = randomBytes2(4).toString("hex");
4553
4870
  try {
4554
- writeFileSync6(join13(dir, "PREFLIGHT.txt"), `The code word is ${word}.
4871
+ writeFileSync7(join14(dir, "PREFLIGHT.txt"), `The code word is ${word}.
4555
4872
  `);
4556
4873
  const timeoutMs = opts.timeoutMs ?? PREFLIGHT_TIMEOUT_MS;
4557
4874
  const res = await agent.run({
@@ -4572,20 +4889,20 @@ ${res.tail}`;
4572
4889
  } catch (err) {
4573
4890
  return `Agent check failed: could not start ${agent.name}: ${err.message}. Is it installed and on PATH?`;
4574
4891
  } finally {
4575
- rmSync(dir, { recursive: true, force: true });
4892
+ rmSync2(dir, { recursive: true, force: true });
4576
4893
  }
4577
4894
  }
4578
4895
 
4579
4896
  // src/resume.ts
4580
- import { existsSync as existsSync6, mkdirSync as mkdirSync8, readdirSync as readdirSync6, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "fs";
4581
- import { dirname as dirname4, join as join14, relative as relative4 } from "path";
4897
+ import { existsSync as existsSync7, mkdirSync as mkdirSync10, readdirSync as readdirSync6, readFileSync as readFileSync11, rmSync as rmSync3, writeFileSync as writeFileSync8 } from "fs";
4898
+ import { dirname as dirname4, join as join15, relative as relative4 } from "path";
4582
4899
  function saveSkillFiles(dir, skill) {
4583
- const root = join14(dir, "skill");
4584
- rmSync2(root, { recursive: true, force: true });
4900
+ const root = join15(dir, "skill");
4901
+ rmSync3(root, { recursive: true, force: true });
4585
4902
  for (const [rel, buf] of Object.entries(skill.files)) {
4586
- const target2 = join14(root, ...rel.split("/"));
4587
- mkdirSync8(dirname4(target2), { recursive: true });
4588
- writeFileSync7(target2, buf);
4903
+ const target2 = join15(root, ...rel.split("/"));
4904
+ mkdirSync10(dirname4(target2), { recursive: true });
4905
+ writeFileSync8(target2, buf);
4589
4906
  }
4590
4907
  }
4591
4908
  function expectedHead(state) {
@@ -4614,7 +4931,7 @@ function timeoutNote(timeoutMs) {
4614
4931
  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.`;
4615
4932
  }
4616
4933
  function scrubFrameworkNoise(state) {
4617
- const clean = (ref) => {
4934
+ const clean2 = (ref) => {
4618
4935
  if (!ref) return;
4619
4936
  const kept = ref.probes.consoleErrors.filter((e) => !isFrameworkNoise(e));
4620
4937
  if (kept.length === ref.probes.consoleErrors.length) return;
@@ -4622,8 +4939,8 @@ function scrubFrameworkNoise(state) {
4622
4939
  ref.penalty = probePenalty(ref.probes);
4623
4940
  };
4624
4941
  for (const s of state.surfaces) {
4625
- Object.values(s.baseline).forEach(clean);
4626
- for (const it of s.iterations) Object.values(it.after).forEach(clean);
4942
+ Object.values(s.baseline).forEach(clean2);
4943
+ for (const it of s.iterations) Object.values(it.after).forEach(clean2);
4627
4944
  }
4628
4945
  }
4629
4946
  function noScreensMessage(skipped, devError) {
@@ -4697,8 +5014,8 @@ async function runLoop(opts, runId, dir) {
4697
5014
  const log = (message) => {
4698
5015
  emit(events, { type: "log", message });
4699
5016
  try {
4700
- mkdirSync9(dir, { recursive: true });
4701
- appendFileSync2(join15(dir, "run.log"), `${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)} ${message}
5017
+ mkdirSync11(dir, { recursive: true });
5018
+ appendFileSync2(join16(dir, "run.log"), `${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)} ${message}
4702
5019
  `);
4703
5020
  } catch {
4704
5021
  }
@@ -4806,7 +5123,7 @@ async function runLoop(opts, runId, dir) {
4806
5123
  state.branch = wt.branch;
4807
5124
  state.baseSha = wt.baseSha;
4808
5125
  persist();
4809
- } else if (!existsSync7(state.worktree)) {
5126
+ } else if (!existsSync8(state.worktree)) {
4810
5127
  throw new Error(`The run's worktree ${state.worktree} is gone, so this run cannot continue. Start a new run.`);
4811
5128
  }
4812
5129
  if (state.installed === void 0 && state.surfaces.length > 0) state.installed = true;
@@ -4931,19 +5248,19 @@ ${second.stdout}`
4931
5248
  };
4932
5249
  }
4933
5250
  function prepareScratch(current) {
4934
- const scratch = join15(wtPath, SCRATCH_DIR);
4935
- rmSync3(scratch, { recursive: true, force: true });
4936
- mkdirSync9(scratch, { recursive: true });
5251
+ const scratch = join16(wtPath, SCRATCH_DIR);
5252
+ rmSync4(scratch, { recursive: true, force: true });
5253
+ mkdirSync11(scratch, { recursive: true });
4937
5254
  if (opts.skill) {
4938
5255
  for (const [rel, buf] of Object.entries(opts.skill.files)) {
4939
- const target2 = join15(scratch, "skill", ...rel.split("/"));
4940
- mkdirSync9(dirname5(target2), { recursive: true });
4941
- writeFileSync8(target2, buf);
5256
+ const target2 = join16(scratch, "skill", ...rel.split("/"));
5257
+ mkdirSync11(dirname5(target2), { recursive: true });
5258
+ writeFileSync9(target2, buf);
4942
5259
  }
4943
5260
  }
4944
5261
  const shots = {};
4945
5262
  for (const [vp, ref] of Object.entries(current)) {
4946
- writeFileSync8(join15(scratch, `${vp}.png`), readFileSync11(join15(dir, ref.png)));
5263
+ writeFileSync9(join16(scratch, `${vp}.png`), readFileSync12(join16(dir, ref.png)));
4947
5264
  shots[vp] = `${SCRATCH_DIR}/${vp}.png`;
4948
5265
  }
4949
5266
  return { shots, probes: Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes])) };
@@ -4952,8 +5269,8 @@ ${second.stdout}`
4952
5269
  const planMs = Math.min(timeoutMs, PLAN_TIMEOUT_MS);
4953
5270
  const { shots, probes } = prepareScratch(current);
4954
5271
  const maxSteps = Math.min(MAX_PLAN_STEPS, iterations);
4955
- writeFileSync8(
4956
- join15(wtPath, SCRATCH_DIR, "PROMPT.md"),
5272
+ writeFileSync9(
5273
+ join16(wtPath, SCRATCH_DIR, "PROMPT.md"),
4957
5274
  buildPlanPacket({ surface: s.surface, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, timeBudgetMin: Math.round(planMs / 6e4), entryFiles }, maxSteps)
4958
5275
  );
4959
5276
  s.status = "iterating";
@@ -4961,13 +5278,13 @@ ${second.stdout}`
4961
5278
  state.current = { surface: s.surface.key, attempt: 1, startedAt, timeoutMs: planMs, steps: 0, lastStep: null, files: [], heartbeatAt: startedAt };
4962
5279
  phase("working", `${s.surface.label}, planning small steps`);
4963
5280
  log(` planning ${s.surface.label} in small steps\u2026`);
4964
- const planLog = join15(dir, "agent", `${attemptLogBase(s.surface.key, 0).slice(0, -2)}-plan.steps.log`);
5281
+ const planLog = join16(dir, "agent", `${attemptLogBase(s.surface.key, 0).slice(0, -2)}-plan.steps.log`);
4965
5282
  try {
4966
- mkdirSync9(dirname5(planLog), { recursive: true });
4967
- writeFileSync8(planLog, "");
5283
+ mkdirSync11(dirname5(planLog), { recursive: true });
5284
+ writeFileSync9(planLog, "");
4968
5285
  } catch {
4969
5286
  }
4970
- const planFile = join15(wtPath, SCRATCH_DIR, "PLAN.md");
5287
+ const planFile = join16(wtPath, SCRATCH_DIR, "PLAN.md");
4971
5288
  const res = await runWithNudge({
4972
5289
  cwd: wtPath,
4973
5290
  prompt: PLAN_POINTER_PROMPT,
@@ -4977,7 +5294,7 @@ ${second.stdout}`
4977
5294
  nudge: {
4978
5295
  prompt: PLAN_NUDGE,
4979
5296
  ms: PLAN_NUDGE_MS,
4980
- needed: async () => !existsSync7(planFile) || parsePlan(readFileSync11(planFile, "utf8")).length === 0
5297
+ needed: async () => !existsSync8(planFile) || parsePlan(readFileSync12(planFile, "utf8")).length === 0
4981
5298
  },
4982
5299
  onLine: (line) => {
4983
5300
  for (const step of describeAgentLine(line, wtPath)) {
@@ -4992,7 +5309,7 @@ ${second.stdout}`
4992
5309
  }
4993
5310
  });
4994
5311
  if (opts.signal?.aborted) throw new Error("Stopped.");
4995
- const fromFile = existsSync7(planFile) ? readFileSync11(planFile, "utf8") : "";
5312
+ const fromFile = existsSync8(planFile) ? readFileSync12(planFile, "utf8") : "";
4996
5313
  const text = parsePlan(fromFile).length ? fromFile : agentFinalMessage(res.stdout) ?? assistantText(res.stdout);
4997
5314
  await revertAll(wtPath);
4998
5315
  const items = parsePlan(text, maxSteps);
@@ -5055,8 +5372,8 @@ ${second.stdout}`
5055
5372
  const step = plan?.steps.find((p) => p.status === "pending") ?? null;
5056
5373
  const stepInfo = step && plan ? { 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) } : null;
5057
5374
  const { shots, probes } = prepareScratch(current);
5058
- writeFileSync8(
5059
- join15(wtPath, SCRATCH_DIR, "PROMPT.md"),
5375
+ writeFileSync9(
5376
+ join16(wtPath, SCRATCH_DIR, "PROMPT.md"),
5060
5377
  buildPacket({ surface: s.surface, iteration: n, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, previousRejection, timeBudgetMin: Math.round(timeoutMs / 6e4), entryFiles, step: stepInfo })
5061
5378
  );
5062
5379
  s.status = "iterating";
@@ -5065,11 +5382,11 @@ ${second.stdout}`
5065
5382
  state.current = live;
5066
5383
  phase("working", stepInfo ? `${s.surface.label}, step ${stepInfo.index} of ${stepInfo.total}` : `${s.surface.label}, attempt ${n} of ${iterations}`);
5067
5384
  const steps = [];
5068
- const logDir = join15(dir, "agent");
5069
- const logBase = join15(logDir, attemptLogBase(s.surface.key, n));
5385
+ const logDir = join16(dir, "agent");
5386
+ const logBase = join16(logDir, attemptLogBase(s.surface.key, n));
5070
5387
  try {
5071
- mkdirSync9(logDir, { recursive: true });
5072
- writeFileSync8(`${logBase}.steps.log`, "");
5388
+ mkdirSync11(logDir, { recursive: true });
5389
+ writeFileSync9(`${logBase}.steps.log`, "");
5073
5390
  } catch {
5074
5391
  }
5075
5392
  const heartbeat = setInterval(() => {
@@ -5116,8 +5433,8 @@ This continues your session for this screen: you have already read its files. Do
5116
5433
  clearInterval(heartbeat);
5117
5434
  }
5118
5435
  try {
5119
- mkdirSync9(logDir, { recursive: true });
5120
- writeFileSync8(`${logBase}.log`, res.stdout);
5436
+ mkdirSync11(logDir, { recursive: true });
5437
+ writeFileSync9(`${logBase}.log`, res.stdout);
5121
5438
  } catch {
5122
5439
  }
5123
5440
  if (opts.signal?.aborted) throw new Error("Stopped.");
@@ -5168,7 +5485,7 @@ This continues your session for this screen: you have already read its files. Do
5168
5485
  if (afterShots) {
5169
5486
  record.after = shotRefs(s, `iter${n}`, afterShots);
5170
5487
  for (const [vp, shot] of Object.entries(afterShots)) {
5171
- const before = readFileSync11(join15(dir, current[vp].png));
5488
+ const before = readFileSync12(join16(dir, current[vp].png));
5172
5489
  const d = pixelDiff(before, shot.png);
5173
5490
  ratios[vp] = Math.round(d.ratio * 1e4) / 1e4;
5174
5491
  record.diffPng[vp] = savePng(dir, `shots/${s.surface.key}/iter${n}-${vp}-diff.png`, d.diffPng);
@@ -5206,7 +5523,7 @@ This continues your session for this screen: you have already read its files. Do
5206
5523
  name: `${s.surface.key}-iter${n}`,
5207
5524
  screen: s.surface.label,
5208
5525
  step: step?.text ?? "Improve this screen for the person using it.",
5209
- visual: visible ? { before: readFileSync11(join15(dir, current[vp].png)), after: afterShots[vp].png, regions: record.changes?.[vp]?.boxes ?? [] } : null,
5526
+ visual: visible ? { before: readFileSync12(join16(dir, current[vp].png)), after: afterShots[vp].png, regions: record.changes?.[vp]?.boxes ?? [] } : null,
5210
5527
  diff: await diffText(wtPath).catch(() => ""),
5211
5528
  repoDir: wtPath,
5212
5529
  spec: opts.checker,
@@ -5252,7 +5569,7 @@ This continues your session for this screen: you have already read its files. Do
5252
5569
  s.status = rejected ? "reverted" : neverFinished ? "blocked" : "skipped";
5253
5570
  s.note = s.iterations[s.iterations.length - 1]?.reason ?? null;
5254
5571
  }
5255
- rmSync3(join15(wtPath, SCRATCH_DIR), { recursive: true, force: true });
5572
+ rmSync4(join16(wtPath, SCRATCH_DIR), { recursive: true, force: true });
5256
5573
  persist();
5257
5574
  }
5258
5575
  async function runJudge(model) {
@@ -5264,8 +5581,11 @@ This continues your session for this screen: you have already read its files. Do
5264
5581
  if (s.judge?.length) continue;
5265
5582
  const verdicts = [];
5266
5583
  for (const vp of VIEWPORTS) {
5267
- const v = await judgeSurface(s, vp.name, { dir, repoRoot: wtPath, designFiles, model });
5268
- if (v) verdicts.push(v);
5584
+ const v = await judgeSurface(s, vp.name, { dir, repoRoot: wtPath, designFiles, model, cacheDir: join16(dirname5(dir), "judge-cache") });
5585
+ if (v) {
5586
+ verdicts.push(v);
5587
+ addJudgeUsage(state, model, v);
5588
+ }
5269
5589
  }
5270
5590
  s.judge = verdicts;
5271
5591
  const errors = verdicts.filter((v) => v.error);
@@ -5283,7 +5603,7 @@ This continues your session for this screen: you have already read its files. Do
5283
5603
  for (const other of finished) {
5284
5604
  const ref = referenceShot(other, desktop.name);
5285
5605
  if (!ref) continue;
5286
- const refPng = readFileSync11(join15(dir, ref.png));
5606
+ const refPng = readFileSync12(join16(dir, ref.png));
5287
5607
  const moved = (png) => {
5288
5608
  const diff = pixelDiff(refPng, png);
5289
5609
  return diff.contentRatio > REGRESSION_CONTENT_RATIO && diff.changedPixels > REGRESSION_MIN_PIXELS ? diff : null;
@@ -5308,8 +5628,8 @@ This continues your session for this screen: you have already read its files. Do
5308
5628
 
5309
5629
  // src/scorecard.ts
5310
5630
  import Anthropic4 from "@anthropic-ai/sdk";
5311
- import { existsSync as existsSync8, mkdirSync as mkdirSync10, readdirSync as readdirSync7, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "fs";
5312
- import { join as join16 } from "path";
5631
+ import { existsSync as existsSync9, mkdirSync as mkdirSync12, readdirSync as readdirSync7, readFileSync as readFileSync13, writeFileSync as writeFileSync10 } from "fs";
5632
+ import { join as join17 } from "path";
5313
5633
 
5314
5634
  // src/scorecard-rubric.ts
5315
5635
  var UX_SCORECARD_PROMPT_VERSION = "ux-scorecard-2026-11-21.2";
@@ -5917,22 +6237,22 @@ function captureFolder(key) {
5917
6237
  return key.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).join("-").slice(0, 110) || "root";
5918
6238
  }
5919
6239
  function writeCapture(dir, c) {
5920
- const folder = join16(dir, "pages", captureFolder(c.facts.key));
5921
- mkdirSync10(folder, { recursive: true });
5922
- writeFileSync9(join16(folder, "facts.json"), JSON.stringify(c.facts, null, 2));
5923
- writeFileSync9(join16(folder, "early.png"), c.early);
5924
- writeFileSync9(join16(folder, "settled.png"), c.settled);
6240
+ const folder = join17(dir, "pages", captureFolder(c.facts.key));
6241
+ mkdirSync12(folder, { recursive: true });
6242
+ writeFileSync10(join17(folder, "facts.json"), JSON.stringify(c.facts, null, 2));
6243
+ writeFileSync10(join17(folder, "early.png"), c.early);
6244
+ writeFileSync10(join17(folder, "settled.png"), c.settled);
5925
6245
  return folder;
5926
6246
  }
5927
6247
  function readCaptures(dir) {
5928
- const root = join16(dir, "pages");
5929
- if (!existsSync8(root)) return [];
6248
+ const root = join17(dir, "pages");
6249
+ if (!existsSync9(root)) return [];
5930
6250
  const out = [];
5931
6251
  for (const name of readdirSync7(root).sort()) {
5932
- const folder = join16(root, name);
5933
- const file = join16(folder, "facts.json");
5934
- if (!existsSync8(file)) continue;
5935
- const facts = JSON.parse(readFileSync12(file, "utf8"));
6252
+ const folder = join17(root, name);
6253
+ const file = join17(folder, "facts.json");
6254
+ if (!existsSync9(file)) continue;
6255
+ const facts = JSON.parse(readFileSync13(file, "utf8"));
5936
6256
  out.push({ folder, facts: { ...facts, key: scorecardPageKey(facts.key || facts.path) } });
5937
6257
  }
5938
6258
  return out;
@@ -5941,13 +6261,13 @@ function localScorer(via, model, client) {
5941
6261
  const ask = async (prompt, folder, images) => {
5942
6262
  if (via === "claude-code") return askClaudeCode(prompt, folder, model, void 0, images.length + 3);
5943
6263
  if (via === "cursor") return askCursor(prompt, folder, model);
5944
- const bufs = images.map((n) => readFileSync12(join16(folder, n)));
6264
+ const bufs = images.map((n) => readFileSync13(join17(folder, n)));
5945
6265
  return askApi(prompt, bufs, model, client ?? new Anthropic4(), images);
5946
6266
  };
5947
6267
  return {
5948
6268
  name: `${via}:${model}`,
5949
6269
  async score(facts, folder, ctx) {
5950
- const images = ["early.png", "settled.png"].filter((n) => existsSync8(join16(folder, n)));
6270
+ const images = ["early.png", "settled.png"].filter((n) => existsSync9(join17(folder, n)));
5951
6271
  const prompt = `${pageSystemPrompt()}
5952
6272
 
5953
6273
  ${pageUserPrompt(facts, { ...ctx, images })}`;
@@ -5959,8 +6279,8 @@ ${pageUserPrompt(facts, { ...ctx, images })}`;
5959
6279
  async group(pages, base, priorKeys) {
5960
6280
  if (pages.length < 2) return { causes: [...base] };
5961
6281
  const p = groupingPrompt(pages, priorKeys);
5962
- const dir = join16(auditHome(), "scorecard-group");
5963
- mkdirSync10(dir, { recursive: true });
6282
+ const dir = join17(auditHome(), "scorecard-group");
6283
+ mkdirSync12(dir, { recursive: true });
5964
6284
  const a = await ask(`${p.system}
5965
6285
 
5966
6286
  ${p.user}`, dir, []);
@@ -5983,18 +6303,27 @@ function apiError(r) {
5983
6303
  }
5984
6304
  async function uploadShots(cfg, runId, folder, key) {
5985
6305
  const base = captureFolder(key);
5986
- const names = ["early", "settled"].filter((n) => existsSync8(join16(folder, `${n}.png`))).map((n) => `${base}/${n}.png`);
6306
+ const names = ["early", "settled"].filter((n) => existsSync9(join17(folder, `${n}.png`))).map((n) => `${base}/${n}.png`);
5987
6307
  if (!names.length) return [];
5988
6308
  const r = await api(cfg, `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}/uploads`, { method: "POST", body: JSON.stringify({ names }) });
5989
6309
  if (!r.ok) throw new Error(`Screenshots not uploaded: ${apiError(r)}`);
5990
6310
  const uploads = r.body?.data?.uploads ?? [];
5991
6311
  for (const u of uploads) {
5992
- const png = readFileSync12(join16(folder, u.name.split("/").pop()));
6312
+ const png = readFileSync13(join17(folder, u.name.split("/").pop()));
5993
6313
  const put = await fetch(u.signedUrl, { method: "PUT", headers: { "Content-Type": "image/png" }, body: new Uint8Array(png) });
5994
6314
  if (!put.ok) throw new Error(`Screenshot ${u.name} not uploaded: storage answered ${put.status}`);
5995
6315
  }
5996
6316
  return names;
5997
6317
  }
6318
+ function settledShotHash(folder) {
6319
+ const file = join17(folder, "settled.png");
6320
+ if (!existsSync9(file)) return null;
6321
+ try {
6322
+ return dHash(readFileSync13(file));
6323
+ } catch {
6324
+ return null;
6325
+ }
6326
+ }
5998
6327
  function serverScorer(cfg, runId) {
5999
6328
  const uploaded = /* @__PURE__ */ new Map();
6000
6329
  return {
@@ -6003,9 +6332,10 @@ function serverScorer(cfg, runId) {
6003
6332
  async score(facts, folder, ctx) {
6004
6333
  const shots = await uploadShots(cfg, runId, folder, facts.key);
6005
6334
  uploaded.set(facts.key, shots);
6335
+ const shotHash = settledShotHash(folder);
6006
6336
  const r = await api(cfg, `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}/score`, {
6007
6337
  method: "POST",
6008
- body: JSON.stringify({ facts, shots, app: ctx.app, about: ctx.about, other_pages: ctx.otherPages })
6338
+ body: JSON.stringify({ facts, shots, app: ctx.app, about: ctx.about, other_pages: ctx.otherPages, ...shotHash ? { shot_hash: shotHash } : {} })
6009
6339
  });
6010
6340
  if (!r.ok) return { error: apiError(r) };
6011
6341
  const score = r.body?.data?.score;
@@ -6063,7 +6393,7 @@ async function captureAll(opts, dir, progress) {
6063
6393
  } catch (err) {
6064
6394
  const key = scorecardPageKey(path);
6065
6395
  const msg = err.message.split("\n")[0].slice(0, 300);
6066
- out.push({ folder: join16(dir, "pages", captureFolder(key)), facts: blankFacts(key, path, viewport), error: `Not captured: ${msg}` });
6396
+ out.push({ folder: join17(dir, "pages", captureFolder(key)), facts: blankFacts(key, path, viewport), error: `Not captured: ${msg}` });
6067
6397
  progress(`could not capture ${path}: ${msg}`);
6068
6398
  } finally {
6069
6399
  await ctx.close();
@@ -6087,8 +6417,8 @@ async function pool(items, n, fn) {
6087
6417
  async function runScorecard(opts) {
6088
6418
  const progress = opts.onProgress ?? (() => {
6089
6419
  });
6090
- const dir = opts.outDir ?? opts.fromCaptures ?? join16(auditHome(), `scorecard-${opts.runId}`);
6091
- mkdirSync10(dir, { recursive: true });
6420
+ const dir = opts.outDir ?? opts.fromCaptures ?? join17(auditHome(), `scorecard-${opts.runId}`);
6421
+ mkdirSync12(dir, { recursive: true });
6092
6422
  const captured = opts.fromCaptures ? readCaptures(opts.fromCaptures) : await captureAll(opts, dir, progress);
6093
6423
  if (!captured.length) throw new Error(opts.fromCaptures ? `No captures in ${opts.fromCaptures}/pages.` : "No pages to score.");
6094
6424
  const labels = captured.map((c) => c.facts.label);
@@ -6119,8 +6449,8 @@ async function runScorecard(opts) {
6119
6449
  rows: scorecardRows(scored, opts.history ?? []),
6120
6450
  causes: grouped.causes
6121
6451
  });
6122
- writeFileSync9(join16(dir, "scorecard.md"), markdown);
6123
- writeFileSync9(join16(dir, "scorecard.json"), JSON.stringify({ runId: opts.runId, app: opts.app, url: opts.url, scoredBy: opts.scorer.name, pages: results, causes: grouped.causes, groupError: grouped.error ?? null }, null, 2));
6452
+ writeFileSync10(join17(dir, "scorecard.md"), markdown);
6453
+ writeFileSync10(join17(dir, "scorecard.json"), JSON.stringify({ runId: opts.runId, app: opts.app, url: opts.url, scoredBy: opts.scorer.name, pages: results, causes: grouped.causes, groupError: grouped.error ?? null }, null, 2));
6124
6454
  return { runId: opts.runId, dir, pages: results, causes: grouped.causes, ...grouped.error ? { groupError: grouped.error } : {}, markdown };
6125
6455
  }
6126
6456
  async function syncScorecard(cfg, input) {
@@ -6164,10 +6494,134 @@ async function scorecardContext(cfg) {
6164
6494
  };
6165
6495
  }
6166
6496
 
6497
+ // src/native-facts.ts
6498
+ var MAX_TEXT2 = 12e3;
6499
+ var MAX_CONTROLS = 120;
6500
+ var MAX_HEADINGS = 40;
6501
+ var XML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
6502
+ function decodeXml(s) {
6503
+ return s.replace(/&(amp|lt|gt|quot|apos|#\d{1,7}|#x[0-9a-f]{1,6});/gi, (_, e) => {
6504
+ if (e[0] === "#") {
6505
+ const code = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
6506
+ return Number.isFinite(code) && code > 0 && code < 1114112 ? String.fromCodePoint(code) : "";
6507
+ }
6508
+ return XML_ENTITIES[e.toLowerCase()] ?? "";
6509
+ });
6510
+ }
6511
+ var clean = (t) => t.replace(/\s+/g, " ").trim();
6512
+ function parseUiautomator(xml) {
6513
+ const out = [];
6514
+ for (const m of xml.matchAll(/<node\b([^>]*?)\/?>/g)) {
6515
+ const attrs = {};
6516
+ for (const a of m[1].matchAll(/\s([\w:-]+)="([^"]*)"/g)) attrs[a[1]] = decodeXml(a[2]);
6517
+ const bounds = /^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(attrs.bounds ?? "");
6518
+ const visible = attrs["visible-to-user"] !== "false" && (!bounds || Number(bounds[3]) > Number(bounds[1]) && Number(bounds[4]) > Number(bounds[2]));
6519
+ out.push({
6520
+ text: clean(attrs.text ?? ""),
6521
+ label: clean(attrs["content-desc"] ?? ""),
6522
+ className: attrs.class ?? "",
6523
+ clickable: attrs.clickable === "true",
6524
+ heading: attrs.heading === "true",
6525
+ visible
6526
+ });
6527
+ }
6528
+ return out;
6529
+ }
6530
+ function parseMaestroHierarchy(json) {
6531
+ let root;
6532
+ try {
6533
+ root = JSON.parse(json);
6534
+ } catch {
6535
+ return [];
6536
+ }
6537
+ const out = [];
6538
+ const stack = [root];
6539
+ while (stack.length && out.length < 5e3) {
6540
+ const n = stack.pop();
6541
+ const a = n.attributes ?? {};
6542
+ const str3 = (k) => typeof a[k] === "string" ? clean(a[k]) : "";
6543
+ const flag = (k) => a[k] === true || a[k] === "true";
6544
+ if (Object.keys(a).length) {
6545
+ out.push({
6546
+ text: str3("text"),
6547
+ label: str3("accessibilityText") || str3("content-desc") || str3("hintText"),
6548
+ className: str3("class") || str3("elementType"),
6549
+ clickable: flag("clickable") || /button/i.test(str3("class") || str3("elementType")),
6550
+ heading: flag("heading") || /header/i.test(str3("traits")),
6551
+ visible: a.visible !== false && a.visible !== "false"
6552
+ });
6553
+ }
6554
+ for (const c of [...n.children ?? []].reverse()) stack.push(c);
6555
+ }
6556
+ return out;
6557
+ }
6558
+ function nodesToContent(nodes) {
6559
+ const words = [];
6560
+ const controls = [];
6561
+ const headings = [];
6562
+ for (const n of nodes) {
6563
+ if (!n.visible) continue;
6564
+ const said = n.text || n.label;
6565
+ if (!said) continue;
6566
+ if (words[words.length - 1] !== said) words.push(said);
6567
+ if (n.clickable && said.length <= 80 && !controls.includes(said) && controls.length < MAX_CONTROLS) controls.push(said);
6568
+ if (n.heading && said.length <= 200 && !headings.includes(said) && headings.length < MAX_HEADINGS) headings.push(said);
6569
+ }
6570
+ return { text: words.join("\n").slice(0, MAX_TEXT2), controls, headings };
6571
+ }
6572
+ function pngSize2(bytes) {
6573
+ const sig = [137, 80, 78, 71, 13, 10, 26, 10];
6574
+ if (bytes.length < 24 || sig.some((b, i) => bytes[i] !== b)) return null;
6575
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
6576
+ if (String.fromCharCode(bytes[12], bytes[13], bytes[14], bytes[15]) !== "IHDR") return null;
6577
+ const width = view.getUint32(16);
6578
+ const height = view.getUint32(20);
6579
+ return width > 0 && height > 0 ? { width, height } : null;
6580
+ }
6581
+ function screenPath(name) {
6582
+ const slug = name.toLowerCase().split(/[^a-z0-9/]+/).filter(Boolean).join("-").replace(/\/+/g, "/").replace(/^\/|\/$/g, "");
6583
+ return `/${slug || "screen"}`.slice(0, 500);
6584
+ }
6585
+ var clampDim = (n) => Math.max(200, Math.min(4e3, Math.round(n)));
6586
+ function nativeFacts(input) {
6587
+ const g = input.given ?? {};
6588
+ const content = input.nodes?.length ? nodesToContent(input.nodes) : { text: "", controls: [], headings: [] };
6589
+ const path = typeof g.path === "string" && g.path.startsWith("/") ? g.path.slice(0, 500) : screenPath(typeof g.key === "string" && g.key ? g.key : input.folder);
6590
+ const key = typeof g.key === "string" && g.key ? g.key.slice(0, 500) : path;
6591
+ const scale = input.scale && input.scale > 0 ? input.scale : 1;
6592
+ const vp = g.viewport && Number.isFinite(g.viewport.width) && Number.isFinite(g.viewport.height) ? { width: clampDim(g.viewport.width), height: clampDim(g.viewport.height) } : input.png ? { width: clampDim(input.png.width / scale), height: clampDim(input.png.height / scale) } : { width: 390, height: 844 };
6593
+ const label = typeof g.label === "string" && g.label ? g.label.slice(0, 300) : content.headings[0] ?? input.folder.replace(/[-_]+/g, " ").slice(0, 300);
6594
+ return {
6595
+ key,
6596
+ path,
6597
+ label,
6598
+ title: typeof g.title === "string" ? g.title.slice(0, 300) : label,
6599
+ ...typeof g.breadcrumb === "string" ? { breadcrumb: g.breadcrumb.slice(0, 300) } : {},
6600
+ headings: Array.isArray(g.headings) ? g.headings.slice(0, MAX_HEADINGS).map((h) => String(h).slice(0, 200)) : content.headings,
6601
+ text: typeof g.text === "string" ? g.text.slice(0, MAX_TEXT2) : content.text,
6602
+ controls: Array.isArray(g.controls) ? g.controls.slice(0, MAX_CONTROLS).map((c) => String(c).slice(0, 120)) : content.controls,
6603
+ ...typeof g.earlyText === "string" ? { earlyText: g.earlyText.slice(0, 4e3) } : {},
6604
+ settleMs: typeof g.settleMs === "number" && g.settleMs >= 0 ? Math.min(6e5, Math.round(g.settleMs)) : null,
6605
+ axe: g.axe ?? null,
6606
+ overflowX: g.overflowX === true,
6607
+ consoleErrors: typeof g.consoleErrors === "number" && g.consoleErrors >= 0 ? Math.min(1e4, Math.round(g.consoleErrors)) : 0,
6608
+ cls: typeof g.cls === "number" && g.cls >= 0 ? Math.min(100, g.cls) : 0,
6609
+ viewport: vp
6610
+ };
6611
+ }
6612
+
6613
+ // src/upload.ts
6614
+ import { closeSync as closeSync3, existsSync as existsSync11, fstatSync as fstatSync3, openSync as openSync3, readdirSync as readdirSync8, readFileSync as readFileSync15, readSync, statSync as statSync4 } from "fs";
6615
+ import { join as join19 } from "path";
6616
+
6167
6617
  // src/sync.ts
6168
- import { existsSync as existsSync9, readFileSync as readFileSync13 } from "fs";
6169
- import { join as join17 } from "path";
6618
+ import { existsSync as existsSync10, readFileSync as readFileSync14 } from "fs";
6619
+ import { join as join18 } from "path";
6170
6620
  var CLOUD_API_ENDPOINT = "https://dxptnwrhwsqckaftyymj.supabase.co/functions/v1/api";
6621
+ var HOSTED_CONSOLE_URL = "https://kensaur.us/mushi-mushi/admin";
6622
+ function consoleBaseUrl(env = process.env) {
6623
+ return trimTrailingSlashes(env.MUSHI_CONSOLE_URL?.trim() || HOSTED_CONSOLE_URL);
6624
+ }
6171
6625
  var VIEWPORT_NAMES = ["desktop", "mobile"];
6172
6626
  var UPLOAD_BATCH = 40;
6173
6627
  function syncConfigFromEnv(env = process.env) {
@@ -6238,6 +6692,7 @@ function toSnapshot(state, finished, uploaded, mode = "local") {
6238
6692
  agent: state.agent,
6239
6693
  model: state.model,
6240
6694
  judge_model: state.judgeModel ?? null,
6695
+ ...state.judgeUsage ? { judge_usage: state.judgeUsage } : {},
6241
6696
  skill: state.skill?.name?.slice(0, 120) ?? null,
6242
6697
  base_ref: state.baseRef?.slice(0, 200) ?? null,
6243
6698
  phase: state.phase ?? null,
@@ -6332,7 +6787,7 @@ function startSync(dir, cfg, events, log) {
6332
6787
  "X-Mushi-Project": cfg.projectId,
6333
6788
  "Content-Type": "application/json"
6334
6789
  };
6335
- async function api2(method, path, body) {
6790
+ async function api3(method, path, body) {
6336
6791
  const res = await fetch(`${cfg.endpoint}/v1/admin/projects/${cfg.projectId}/ux-runs/${path}`, {
6337
6792
  method,
6338
6793
  headers,
@@ -6350,11 +6805,11 @@ function startSync(dir, cfg, events, log) {
6350
6805
  const todo = wantedShots(state).filter((w) => uploaded.get(w.name) !== w.rel);
6351
6806
  for (let i = 0; i < todo.length; i += UPLOAD_BATCH) {
6352
6807
  const batch = todo.slice(i, i + UPLOAD_BATCH);
6353
- const data = await api2("POST", `${state.runId}/uploads`, { names: batch.map((w) => w.name) });
6808
+ const data = await api3("POST", `${state.runId}/uploads`, { names: batch.map((w) => w.name) });
6354
6809
  for (const u of data.uploads) {
6355
6810
  const want = batch.find((w) => w.name === u.name);
6356
6811
  if (!want) continue;
6357
- const png = cropTop(readFileSync13(join17(dir, want.rel)), 2400);
6812
+ const png = cropTop(readFileSync14(join18(dir, want.rel)), 2400);
6358
6813
  const put = await fetch(u.signedUrl, {
6359
6814
  method: "PUT",
6360
6815
  headers: { "Content-Type": "image/png", "x-upsert": "true" },
@@ -6370,9 +6825,9 @@ function startSync(dir, cfg, events, log) {
6370
6825
  const state = loadState(dir);
6371
6826
  if (!state) return;
6372
6827
  try {
6373
- await api2("PUT", state.runId, toSnapshot(state, false, uploaded, cfg.mode));
6828
+ await api3("PUT", state.runId, toSnapshot(state, false, uploaded, cfg.mode));
6374
6829
  await uploadShots2(state);
6375
- await api2("PUT", state.runId, toSnapshot(state, finished, uploaded, cfg.mode));
6830
+ await api3("PUT", state.runId, toSnapshot(state, finished, uploaded, cfg.mode));
6376
6831
  lastError = null;
6377
6832
  } catch (err) {
6378
6833
  lastError = err.message;
@@ -6402,14 +6857,189 @@ function startSync(dir, cfg, events, log) {
6402
6857
  }
6403
6858
  };
6404
6859
  }
6860
+
6861
+ // src/upload.ts
6862
+ function sizeAndHead(file) {
6863
+ const fd = openSync3(file, "r");
6864
+ try {
6865
+ const head = Buffer.alloc(32);
6866
+ const n = readSync(fd, head, 0, 32, 0);
6867
+ return { size: fstatSync3(fd).size, head: head.subarray(0, n) };
6868
+ } finally {
6869
+ closeSync3(fd);
6870
+ }
6871
+ }
6872
+ var UPLOAD_PLATFORMS = ["ios", "android", "flutter", "react_native", "capacitor", "web", "other"];
6873
+ var UPLOAD_SOURCES = ["maestro", "adb", "simctl", "sdk", "playwright", "other"];
6874
+ var UPLOAD_MAX_PAGES = 60;
6875
+ var UPLOAD_MAX_PNG_BYTES = 8 * 1024 * 1024;
6876
+ function readScreens(dir, opts = {}) {
6877
+ const root = join19(dir, "pages");
6878
+ if (!existsSync11(root)) throw new Error(`No ${root} folder. Put each screen in <dir>/pages/<screen>/settled.png (see docs/templates/ux-native/).`);
6879
+ const out = [];
6880
+ for (const name of readdirSync8(root).sort()) {
6881
+ const folder = join19(root, name);
6882
+ if (!statSync4(folder).isDirectory()) continue;
6883
+ const shots = ["early", "settled"].filter((s) => existsSync11(join19(folder, `${s}.png`)));
6884
+ if (!shots.length) continue;
6885
+ let settledSize = null;
6886
+ for (const s of shots) {
6887
+ const file = join19(folder, `${s}.png`);
6888
+ const { size, head } = sizeAndHead(file);
6889
+ if (size > UPLOAD_MAX_PNG_BYTES) throw new Error(`${file} is ${(size / 1024 / 1024).toFixed(1)} MB; a screenshot may be at most 8 MB.`);
6890
+ const dims = pngSize2(head);
6891
+ if (!dims) throw new Error(`${file} is not a PNG. (In Windows PowerShell 5.1, \`adb exec-out screencap -p > x.png\` corrupts it: run the template in bash or Git Bash.)`);
6892
+ if (s === "settled" || !settledSize) settledSize = dims;
6893
+ }
6894
+ let given = null;
6895
+ const factsFile = join19(folder, "facts.json");
6896
+ if (existsSync11(factsFile)) {
6897
+ try {
6898
+ given = JSON.parse(readFileSync15(factsFile, "utf8"));
6899
+ } catch {
6900
+ throw new Error(`${factsFile} is not valid JSON.`);
6901
+ }
6902
+ }
6903
+ let nodes = null;
6904
+ if (existsSync11(join19(folder, "window.xml"))) nodes = parseUiautomator(readFileSync15(join19(folder, "window.xml"), "utf8"));
6905
+ else if (existsSync11(join19(folder, "hierarchy.json"))) nodes = parseMaestroHierarchy(readFileSync15(join19(folder, "hierarchy.json"), "utf8"));
6906
+ const facts = nativeFacts({ folder: name, given, nodes, png: settledSize, scale: opts.scale });
6907
+ out.push({ folder, facts: { ...facts, key: scorecardPageKey(facts.key) }, shots: [...shots] });
6908
+ }
6909
+ if (!out.length) throw new Error(`No screenshots in ${root}: each screen needs a settled.png (or early.png).`);
6910
+ if (out.length > UPLOAD_MAX_PAGES) throw new Error(`${out.length} screens; one upload takes at most ${UPLOAD_MAX_PAGES}. Split the folder.`);
6911
+ const keys = /* @__PURE__ */ new Set();
6912
+ for (const s of out) {
6913
+ if (keys.has(s.facts.key)) throw new Error(`Two screens have the key "${s.facts.key}". Give each its own name or facts.json key.`);
6914
+ keys.add(s.facts.key);
6915
+ }
6916
+ return out;
6917
+ }
6918
+ async function api2(cfg, path, init, fetchImpl) {
6919
+ const res = await fetchImpl(`${cfg.endpoint}${path}`, {
6920
+ ...init,
6921
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${cfg.apiKey}`, "X-Mushi-Api-Key": cfg.apiKey, "X-Mushi-Project-Id": cfg.projectId, ...init.headers ?? {} }
6922
+ });
6923
+ return { ok: res.ok, status: res.status, body: await res.json().catch(() => null) };
6924
+ }
6925
+ function apiError2(r) {
6926
+ const e = r.body?.error?.message;
6927
+ return `the API answered ${r.status}${e ? `: ${e.slice(0, 300)}` : ""}`;
6928
+ }
6929
+ async function pool2(items, n, fn) {
6930
+ let i = 0;
6931
+ const worker = async () => {
6932
+ while (i < items.length) await fn(items[i++]);
6933
+ };
6934
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(n, items.length)) }, worker));
6935
+ }
6936
+ async function uploadCaptures(cfg, opts) {
6937
+ const progress = opts.onProgress ?? (() => {
6938
+ });
6939
+ const doFetch = opts.fetchImpl ?? fetch;
6940
+ const screens = readScreens(opts.dir, { scale: opts.scale });
6941
+ progress(`${screens.length} screen(s) to upload (${opts.platform}${opts.device ? `, ${opts.device}` : ""})`);
6942
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
6943
+ const created = await api2(
6944
+ cfg,
6945
+ "/v1/ux/captures",
6946
+ {
6947
+ method: "POST",
6948
+ body: JSON.stringify({
6949
+ platform: opts.platform,
6950
+ ...opts.device ? { device: opts.device } : {},
6951
+ ...opts.source ? { source: opts.source } : {},
6952
+ ...opts.app ? { app: opts.app } : {},
6953
+ ...opts.viewport ? { viewport: opts.viewport } : {},
6954
+ ...opts.maxCostUsd !== void 0 ? { maxCostUsd: opts.maxCostUsd } : {},
6955
+ pages: screens.map((s) => ({ facts: s.facts, shots: s.shots }))
6956
+ })
6957
+ },
6958
+ doFetch
6959
+ );
6960
+ if (!created.ok) throw new Error(`The captures were not accepted: ${apiError2(created)}`);
6961
+ const d = created.body?.data;
6962
+ if (!d?.runId) throw new Error("The API returned no run id.");
6963
+ const runId = d.runId;
6964
+ const byKey = new Map(screens.map((s) => [s.facts.key, s]));
6965
+ const shotNames = /* @__PURE__ */ new Map();
6966
+ let uploaded = 0;
6967
+ for (const u of d.uploads ?? []) {
6968
+ const screen = byKey.get(u.page);
6969
+ if (!screen) continue;
6970
+ const shot = u.name.endsWith("/early.png") ? "early" : "settled";
6971
+ const png = readFileSync15(join19(screen.folder, `${shot}.png`));
6972
+ const put = await doFetch(u.signedUrl, { method: "PUT", headers: { "Content-Type": "image/png" }, body: new Uint8Array(png) });
6973
+ if (!put.ok) throw new Error(`Screenshot ${u.name} not uploaded: storage answered ${put.status}. Retry; the run is ${runId}.`);
6974
+ shotNames.set(u.page, [...shotNames.get(u.page) ?? [], u.name]);
6975
+ uploaded++;
6976
+ }
6977
+ progress(`uploaded ${uploaded} screenshot(s) to run ${runId}`);
6978
+ const consoleUrl = `${consoleBaseUrl()}/ux-runs?view=scorecard&run=${runId}`;
6979
+ const result = { runId, pages: screens.length, uploaded, reservedUsd: d.reservedUsd ?? null, scored: 0, mean: null, causes: [], errors: [], consoleUrl };
6980
+ if (!opts.score) return result;
6981
+ const scores = /* @__PURE__ */ new Map();
6982
+ const labels = screens.map((s) => s.facts.label);
6983
+ await pool2(screens, opts.concurrency ?? 3, async (s) => {
6984
+ const ask = () => api2(
6985
+ cfg,
6986
+ `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}/score`,
6987
+ { method: "POST", body: JSON.stringify({ facts: s.facts, shots: shotNames.get(s.facts.key) ?? [], app: opts.app ?? "this app", about: opts.about, other_pages: labels.filter((l) => l !== s.facts.label) }) },
6988
+ doFetch
6989
+ );
6990
+ let r = await ask();
6991
+ if (!r.ok && r.status !== 402) r = await ask();
6992
+ const score = r.body?.data?.score;
6993
+ if (r.ok && score) {
6994
+ scores.set(s.facts.key, score);
6995
+ progress(`scored ${s.facts.key}: ${score.overall}/10`);
6996
+ } else {
6997
+ result.errors.push(`${s.facts.key}: ${apiError2(r)}`);
6998
+ progress(`could not score ${s.facts.key}: ${apiError2(r)}`);
6999
+ }
7000
+ });
7001
+ result.scored = scores.size;
7002
+ result.mean = scores.size ? Math.round([...scores.values()].reduce((n, x) => n + x.overall, 0) / scores.size * 10) / 10 : null;
7003
+ const grouped = await api2(cfg, `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}/group`, { method: "POST", body: "{}" }, doFetch);
7004
+ if (grouped.ok) result.causes = grouped.body?.data?.causes ?? [];
7005
+ else result.errors.push(`grouping: ${apiError2(grouped)}`);
7006
+ const vp = opts.viewport ?? `${screens[0].facts.viewport.width}x${screens[0].facts.viewport.height}`;
7007
+ const closed = await api2(
7008
+ cfg,
7009
+ `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}`,
7010
+ {
7011
+ method: "PUT",
7012
+ body: JSON.stringify({
7013
+ status: "done",
7014
+ viewport: vp,
7015
+ scored_by: "server",
7016
+ started_at: startedAt,
7017
+ finished_at: (/* @__PURE__ */ new Date()).toISOString(),
7018
+ error: null,
7019
+ pages: screens.map((s) => ({ facts: s.facts, score: scores.get(s.facts.key) ?? null, shots: shotNames.get(s.facts.key) ?? [], ...scores.has(s.facts.key) ? {} : { error: "Not scored." } })),
7020
+ causes: result.causes
7021
+ })
7022
+ },
7023
+ doFetch
7024
+ );
7025
+ if (!closed.ok) result.errors.push(`closing the run: ${apiError2(closed)}`);
7026
+ if (opts.file) result.filed = await fileScorecard(cfg, runId, { causes: result.causes, dryRun: opts.dryRun });
7027
+ return result;
7028
+ }
6405
7029
  export {
6406
7030
  AGENTS,
7031
+ CLIP_LIMITS,
7032
+ DEFAULT_CLIP_VIEWPORT,
6407
7033
  DEFAULT_JUDGE_MODEL,
6408
7034
  DEFAULT_SCORECARD_MODEL,
6409
7035
  DEFAULT_SCORECARD_VIEWPORT,
6410
7036
  DEFAULT_SETUP_COMMAND,
6411
7037
  FACTS_SCRIPT,
6412
7038
  POINTER_PROMPT,
7039
+ UPLOAD_MAX_PAGES,
7040
+ UPLOAD_MAX_PNG_BYTES,
7041
+ UPLOAD_PLATFORMS,
7042
+ UPLOAD_SOURCES,
6413
7043
  UX_DIMENSIONS,
6414
7044
  UX_RUBRIC,
6415
7045
  UX_SCORECARD_LIMITS,
@@ -6418,6 +7048,7 @@ export {
6418
7048
  VIEWPORTS,
6419
7049
  accessibilityCap,
6420
7050
  buildPacket,
7051
+ capFlows,
6421
7052
  captureFolder,
6422
7053
  capturePage,
6423
7054
  captureSurface,
@@ -6426,13 +7057,18 @@ export {
6426
7057
  causeReportBody,
6427
7058
  causeSlug,
6428
7059
  causeTokens,
7060
+ clampCaps,
7061
+ clipSlug,
7062
+ clipUploadBody,
6429
7063
  cropTop,
6430
7064
  cursorCloudAdapter,
6431
7065
  cursorModel,
6432
7066
  dHash,
6433
7067
  decide,
6434
7068
  discover,
7069
+ effectiveClipCaps,
6435
7070
  evidenceSeenIn,
7071
+ fetchClipCaps,
6436
7072
  fileScorecard,
6437
7073
  findDesignFiles,
6438
7074
  firstJsonObject,
@@ -6440,6 +7076,7 @@ export {
6440
7076
  groupCauses,
6441
7077
  groupingPrompt,
6442
7078
  hammingHex,
7079
+ hasTimeForScreen,
6443
7080
  httpsRepoUrl,
6444
7081
  installGuard,
6445
7082
  isDestructiveLabel,
@@ -6448,23 +7085,31 @@ export {
6448
7085
  loadState,
6449
7086
  localScorer,
6450
7087
  mergeGrouping,
7088
+ nativeFacts,
6451
7089
  newRunId,
6452
7090
  nextRoutePath,
7091
+ nodesToContent,
6453
7092
  normText,
6454
7093
  normalizeLink,
6455
7094
  openSession,
6456
7095
  overallScore,
6457
7096
  pageSystemPrompt,
6458
7097
  pageUserPrompt,
7098
+ parseFlow,
7099
+ parseMaestroHierarchy,
6459
7100
  parsePageAnswer,
7101
+ parseUiautomator,
6460
7102
  patternKeyFor,
6461
7103
  performanceCap,
6462
7104
  pixelDiff,
6463
7105
  planFiling,
7106
+ pngSize2 as pngSize,
6464
7107
  probePenalty,
6465
7108
  quoteArg,
6466
7109
  reactRouterPaths,
6467
7110
  readCaptures,
7111
+ readScreens,
7112
+ recordClips,
6468
7113
  routesFromSource,
6469
7114
  runDir,
6470
7115
  runFreshEyes,
@@ -6480,6 +7125,7 @@ export {
6480
7125
  scorecardPageKey,
6481
7126
  scorecardRows,
6482
7127
  scorecardRunId,
7128
+ screenPath,
6483
7129
  serverScorer,
6484
7130
  settle,
6485
7131
  sitemapPaths,
@@ -6492,5 +7138,7 @@ export {
6492
7138
  toSnapshot,
6493
7139
  topCauses,
6494
7140
  unshuffle,
6495
- uploadAllShots
7141
+ uploadAllShots,
7142
+ uploadCaptures,
7143
+ uploadClips
6496
7144
  };