@mushi-mushi/ux 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3,12 +3,12 @@
3
3
  // src/cli.ts
4
4
  import { spawn as spawn2 } from "child_process";
5
5
  import { EventEmitter } from "events";
6
- import { createHash as createHash5 } from "crypto";
7
- import { existsSync as existsSync12, readFileSync as readFileSync17, writeFileSync as writeFileSync11 } from "fs";
8
- import { homedir as homedir3 } from "os";
9
- import { join as join21 } from "path";
6
+ import { createHash as createHash7 } from "crypto";
7
+ import { existsSync as existsSync15, readFileSync as readFileSync20, writeFileSync as writeFileSync12 } from "fs";
8
+ import { homedir as homedir4 } from "os";
9
+ import { join as join24 } from "path";
10
10
  import { Command, InvalidArgumentError, Option } from "commander";
11
- import { chromium as chromium2 } from "playwright";
11
+ import { chromium as chromium3 } from "playwright";
12
12
 
13
13
  // src/cursor-cloud.ts
14
14
  import { readdirSync as readdirSync2, readFileSync as readFileSync2 } from "fs";
@@ -819,8 +819,8 @@ async function openSession(opts = {}) {
819
819
  }
820
820
  seed = await context.storageState({ indexedDB: true });
821
821
  };
822
- const freshContext = async () => {
823
- const fresh = await browser.newContext({ serviceWorkers: "block", storageState: seed });
822
+ const freshContext = async (extra = {}) => {
823
+ const fresh = await browser.newContext({ ...extra, serviceWorkers: "block", storageState: seed });
824
824
  await installGuard(fresh, opts.allow ?? [], guard, opts.policy);
825
825
  await fresh.addInitScript({ content: CLS_SCRIPT });
826
826
  return fresh;
@@ -1696,6 +1696,39 @@ function contentPixels(png) {
1696
1696
  }
1697
1697
  return n;
1698
1698
  }
1699
+ function dHash(buf) {
1700
+ const png = decodePng(buf);
1701
+ const cols = 9;
1702
+ const rows = 8;
1703
+ const grey = [];
1704
+ for (let r = 0; r < rows; r++) {
1705
+ const y0 = Math.floor(r * png.height / rows);
1706
+ const y1 = Math.max(y0 + 1, Math.floor((r + 1) * png.height / rows));
1707
+ for (let c = 0; c < cols; c++) {
1708
+ const x0 = Math.floor(c * png.width / cols);
1709
+ const x1 = Math.max(x0 + 1, Math.floor((c + 1) * png.width / cols));
1710
+ let sum = 0;
1711
+ let n = 0;
1712
+ for (let y = y0; y < y1; y++) {
1713
+ for (let x = x0; x < x1; x++) {
1714
+ const i = (y * png.width + x) * 4;
1715
+ sum += 0.299 * png.data[i] + 0.587 * png.data[i + 1] + 0.114 * png.data[i + 2];
1716
+ n++;
1717
+ }
1718
+ }
1719
+ grey.push(sum / n);
1720
+ }
1721
+ }
1722
+ let hex = "";
1723
+ for (let r = 0; r < rows; r++) {
1724
+ let byte = 0;
1725
+ for (let c = 0; c < cols - 1; c++) {
1726
+ byte = byte << 1 | (grey[r * cols + c] > grey[r * cols + c + 1] ? 1 : 0);
1727
+ }
1728
+ hex += byte.toString(16).padStart(2, "0");
1729
+ }
1730
+ return hex;
1731
+ }
1699
1732
 
1700
1733
  // src/types.ts
1701
1734
  var VIEWPORTS = [
@@ -2159,11 +2192,232 @@ function writePending(dir, pending) {
2159
2192
  return path;
2160
2193
  }
2161
2194
 
2195
+ // src/clips.ts
2196
+ import { createHash as createHash3 } from "crypto";
2197
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, renameSync, rmSync, statSync as statSync3 } from "fs";
2198
+ import { join as join6 } from "path";
2199
+ import { chromium as chromium2 } from "playwright";
2200
+ var CLIP_LIMITS = {
2201
+ maxFlows: 5,
2202
+ maxPathsPerFlow: 6,
2203
+ defaultSeconds: 30,
2204
+ maxSeconds: 60,
2205
+ minSeconds: 5,
2206
+ defaultBytes: 25 * 1024 * 1024,
2207
+ maxBytes: 100 * 1024 * 1024,
2208
+ /** How long each screen stays on camera after it settles. */
2209
+ dwellMs: 1500
2210
+ };
2211
+ var DEFAULT_CLIP_VIEWPORT = { width: 390, height: 844 };
2212
+ var SLUG_RE = /[^a-z0-9]+/g;
2213
+ function clipSlug(name) {
2214
+ const s = name.toLowerCase().replace(SLUG_RE, "-");
2215
+ let a = 0;
2216
+ let b = s.length;
2217
+ while (a < b && s[a] === "-") a++;
2218
+ while (b > a && s[b - 1] === "-") b--;
2219
+ return s.slice(a, b).slice(0, 60) || "flow";
2220
+ }
2221
+ function parseFlow(value) {
2222
+ const raw = value.trim();
2223
+ const colon = raw.indexOf(":");
2224
+ const hasName = colon > 0 && !raw.slice(0, colon).includes("/");
2225
+ const name = hasName ? raw.slice(0, colon).trim() : "";
2226
+ const paths = (hasName ? raw.slice(colon + 1) : raw).split(",").map((p) => p.trim()).filter(Boolean);
2227
+ if (!paths.length) throw new Error(`--flow "${value}" names no paths; use name:/a,/b`);
2228
+ for (const p of paths) if (!p.startsWith("/") || p.startsWith("//")) throw new Error(`--flow path "${p}" must start with a single /`);
2229
+ return { name: (name || paths[0]).slice(0, 80), paths };
2230
+ }
2231
+ function capFlows(flows) {
2232
+ const notes = [];
2233
+ if (flows.length > CLIP_LIMITS.maxFlows) notes.push(`Only the first ${CLIP_LIMITS.maxFlows} of ${flows.length} flows are recorded.`);
2234
+ const seen = /* @__PURE__ */ new Set();
2235
+ const out = [];
2236
+ for (const f of flows.slice(0, CLIP_LIMITS.maxFlows)) {
2237
+ let slug = clipSlug(f.name);
2238
+ for (let i = 2; seen.has(slug); i++) slug = `${clipSlug(f.name)}-${i}`;
2239
+ seen.add(slug);
2240
+ if (f.paths.length > CLIP_LIMITS.maxPathsPerFlow) notes.push(`"${f.name}": only the first ${CLIP_LIMITS.maxPathsPerFlow} of ${f.paths.length} screens.`);
2241
+ out.push({ name: f.name, paths: f.paths.slice(0, CLIP_LIMITS.maxPathsPerFlow) });
2242
+ }
2243
+ return { flows: out, notes };
2244
+ }
2245
+ function clampCaps(input) {
2246
+ const secs2 = Number.isFinite(input.maxSeconds) ? Number(input.maxSeconds) : CLIP_LIMITS.defaultSeconds;
2247
+ const bytes = Number.isFinite(input.maxBytes) ? Number(input.maxBytes) : CLIP_LIMITS.defaultBytes;
2248
+ return {
2249
+ maxSeconds: Math.min(CLIP_LIMITS.maxSeconds, Math.max(CLIP_LIMITS.minSeconds, Math.floor(secs2))),
2250
+ maxBytes: Math.min(CLIP_LIMITS.maxBytes, Math.max(1024 * 1024, Math.floor(bytes)))
2251
+ };
2252
+ }
2253
+ function hasTimeForScreen(elapsedMs, slowestScreenMs, maxSeconds) {
2254
+ const next = Math.max(3e3, slowestScreenMs) + CLIP_LIMITS.dwellMs;
2255
+ return elapsedMs + next <= maxSeconds * 1e3;
2256
+ }
2257
+ async function recordClips(opts) {
2258
+ const log = opts.log ?? (() => {
2259
+ });
2260
+ const { flows, notes } = capFlows(opts.flows);
2261
+ const { maxSeconds, maxBytes } = clampCaps({ maxSeconds: opts.maxSeconds, maxBytes: opts.maxBytes });
2262
+ const viewport = opts.viewport ?? DEFAULT_CLIP_VIEWPORT;
2263
+ const headless = opts.headless ?? true;
2264
+ const channel = opts.channel === "chrome" ? { channel: "chrome" } : {};
2265
+ mkdirSync4(opts.outDir, { recursive: true });
2266
+ const guard = { blocked: [] };
2267
+ const clips = [];
2268
+ const skipped = [];
2269
+ let storageState;
2270
+ if (opts.profileDir) {
2271
+ const persistent = await chromium2.launchPersistentContext(opts.profileDir, { headless, serviceWorkers: "block", ...channel });
2272
+ try {
2273
+ storageState = await persistent.storageState();
2274
+ } finally {
2275
+ await persistent.close();
2276
+ }
2277
+ }
2278
+ const browser = await chromium2.launch({ headless, ...channel });
2279
+ try {
2280
+ for (const flow of flows) {
2281
+ const slug = clipSlug(flow.name);
2282
+ const rawDir = join6(opts.outDir, `.raw-${slug}`);
2283
+ const context = await browser.newContext({
2284
+ serviceWorkers: "block",
2285
+ viewport,
2286
+ recordVideo: { dir: rawDir, size: viewport },
2287
+ ...storageState ? { storageState } : {}
2288
+ });
2289
+ await installGuard(context, opts.allow ?? [], guard);
2290
+ const page = await context.newPage();
2291
+ const started = Date.now();
2292
+ const shown = [];
2293
+ let slowest = 0;
2294
+ let failure = null;
2295
+ try {
2296
+ for (const p of flow.paths) {
2297
+ if (!hasTimeForScreen(Date.now() - started, slowest, maxSeconds)) {
2298
+ notes.push(`"${flow.name}": stopped after ${shown.length} screen(s) to stay under ${maxSeconds} s.`);
2299
+ break;
2300
+ }
2301
+ const t0 = Date.now();
2302
+ await gotoPatiently(page, surfaceUrl(opts.baseUrl, p));
2303
+ await settle(page);
2304
+ slowest = Math.max(slowest, Date.now() - t0);
2305
+ await page.waitForTimeout(CLIP_LIMITS.dwellMs);
2306
+ shown.push(p);
2307
+ }
2308
+ } catch (err) {
2309
+ failure = err.message.split("\n")[0].slice(0, 200);
2310
+ }
2311
+ const durationMs = Date.now() - started;
2312
+ const video = page.video();
2313
+ await context.close();
2314
+ const rawPath = await video?.path().catch(() => null);
2315
+ const file = join6(opts.outDir, `${slug}.webm`);
2316
+ if (!rawPath || shown.length === 0) {
2317
+ skipped.push({ name: flow.name, reason: failure ?? "No screen loaded." });
2318
+ rmSync(rawDir, { recursive: true, force: true });
2319
+ continue;
2320
+ }
2321
+ renameSync(rawPath, file);
2322
+ rmSync(rawDir, { recursive: true, force: true });
2323
+ const bytes = statSync3(file).size;
2324
+ if (bytes > maxBytes) {
2325
+ rmSync(file, { force: true });
2326
+ skipped.push({ name: flow.name, reason: `${(bytes / 1048576).toFixed(1)} MB is over the ${(maxBytes / 1048576).toFixed(0)} MB cap.` });
2327
+ continue;
2328
+ }
2329
+ if (failure) notes.push(`"${flow.name}": stopped at an error after ${shown.length} screen(s): ${failure}`);
2330
+ clips.push({ name: flow.name, file, bytes, durationMs, width: viewport.width, height: viewport.height, paths: shown });
2331
+ log(`Recorded "${flow.name}" (${shown.length} screen(s), ${(durationMs / 1e3).toFixed(1)} s, ${(bytes / 1048576).toFixed(1)} MB)`);
2332
+ }
2333
+ } finally {
2334
+ await browser.close();
2335
+ }
2336
+ return { clips, skipped, notes, guard };
2337
+ }
2338
+ function clipUploadBody(clips) {
2339
+ return {
2340
+ files: clips.map((c) => ({
2341
+ name: `${clipSlug(c.name)}.webm`,
2342
+ kind: "clip",
2343
+ mime: "video/webm",
2344
+ bytes: c.bytes,
2345
+ source: "playwright",
2346
+ platform: "web",
2347
+ durationMs: Math.max(1, Math.round(c.durationMs)),
2348
+ width: c.width,
2349
+ height: c.height,
2350
+ surfacePath: c.paths[0] ?? null,
2351
+ label: c.name.slice(0, 200)
2352
+ }))
2353
+ };
2354
+ }
2355
+ async function call(fetchImpl, cfg, path, init = {}) {
2356
+ const res = await fetchImpl(`${cfg.endpoint}${path}`, {
2357
+ ...init,
2358
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${cfg.apiKey}`, "X-Mushi-Api-Key": cfg.apiKey, "X-Mushi-Project": cfg.projectId, ...init.headers ?? {} }
2359
+ });
2360
+ const body = await res.json().catch(() => null);
2361
+ return { ok: res.ok, status: res.status, body };
2362
+ }
2363
+ function apiMessage(r) {
2364
+ const e = r.body?.error;
2365
+ return e?.message ? e.message.slice(0, 300) : `the API answered ${r.status}`;
2366
+ }
2367
+ async function fetchClipCaps(cfg, releaseId, fetchImpl = fetch) {
2368
+ try {
2369
+ const r = await call(fetchImpl, cfg, `/v1/admin/projects/${encodeURIComponent(cfg.projectId)}/releases/${encodeURIComponent(releaseId)}/kit`);
2370
+ if (!r.ok) return null;
2371
+ const s = r.body?.data?.settings;
2372
+ if (!s || typeof s.clipsEnabled !== "boolean" || typeof s.clipMaxSeconds !== "number" || typeof s.clipMaxMb !== "number") return null;
2373
+ return { clipsEnabled: s.clipsEnabled, maxSeconds: s.clipMaxSeconds, maxBytes: s.clipMaxMb * 1024 * 1024 };
2374
+ } catch {
2375
+ return null;
2376
+ }
2377
+ }
2378
+ function effectiveClipCaps(requested, server) {
2379
+ const asked = clampCaps(requested);
2380
+ if (!server) {
2381
+ return { ...asked, blocked: null, notes: ["Could not read this app's clip settings; using the local caps (the server still checks them on upload)."] };
2382
+ }
2383
+ if (!server.clipsEnabled) {
2384
+ 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.` };
2385
+ }
2386
+ const capped = clampCaps({ maxSeconds: Math.min(asked.maxSeconds, server.maxSeconds), maxBytes: Math.min(asked.maxBytes, server.maxBytes) });
2387
+ const notes = [];
2388
+ if (capped.maxSeconds < asked.maxSeconds) notes.push(`This app caps clips at ${capped.maxSeconds} s; recording up to that.`);
2389
+ if (capped.maxBytes < asked.maxBytes) notes.push(`This app caps clips at ${Math.round(capped.maxBytes / 1048576)} MB; larger ones are dropped before upload.`);
2390
+ return { ...capped, notes, blocked: null };
2391
+ }
2392
+ async function uploadClips(cfg, releaseId, clips, fetchImpl = fetch) {
2393
+ const base = `/v1/admin/projects/${encodeURIComponent(cfg.projectId)}/releases/${encodeURIComponent(releaseId)}/kit`;
2394
+ const out = { uploaded: [], failed: [] };
2395
+ if (!clips.length) return out;
2396
+ const r = await call(fetchImpl, cfg, `${base}/uploads`, { method: "POST", body: JSON.stringify(clipUploadBody(clips)) });
2397
+ if (!r.ok) throw new Error(`Clips not uploaded: ${apiMessage(r)}`);
2398
+ const uploads = r.body?.data?.uploads ?? [];
2399
+ for (let i = 0; i < uploads.length; i++) {
2400
+ const u = uploads[i];
2401
+ const clip3 = clips[i];
2402
+ const bytes = readFileSync5(clip3.file);
2403
+ const put = await fetchImpl(u.signedUrl, { method: "PUT", headers: { "Content-Type": "video/webm" }, body: new Uint8Array(bytes) });
2404
+ if (!put.ok) {
2405
+ out.failed.push({ name: clip3.name, reason: `storage answered ${put.status}` });
2406
+ continue;
2407
+ }
2408
+ const sha256 = createHash3("sha256").update(bytes).digest("hex");
2409
+ const fin = await call(fetchImpl, cfg, `${base}/assets/${encodeURIComponent(u.assetId)}/finalize`, { method: "POST", body: JSON.stringify({ sha256 }) });
2410
+ if (!fin.ok) out.failed.push({ name: clip3.name, reason: apiMessage(fin) });
2411
+ else out.uploaded.push({ name: clip3.name, assetId: u.assetId });
2412
+ }
2413
+ return out;
2414
+ }
2415
+
2162
2416
  // src/dashboard.ts
2163
2417
  import { randomBytes } from "crypto";
2164
- import { existsSync as existsSync3, readdirSync as readdirSync4, readFileSync as readFileSync6 } from "fs";
2418
+ import { existsSync as existsSync3, readdirSync as readdirSync4, readFileSync as readFileSync7 } from "fs";
2165
2419
  import { createServer as createServer2 } from "http";
2166
- import { basename, dirname as dirname3, join as join7, normalize, sep } from "path";
2420
+ import { basename, dirname as dirname3, join as join8, normalize, sep } from "path";
2167
2421
  import { z } from "zod";
2168
2422
  import { PNG as PNG3 } from "pngjs";
2169
2423
 
@@ -2306,33 +2560,47 @@ function formatStep(step) {
2306
2560
  }
2307
2561
 
2308
2562
  // src/state.ts
2309
- import { existsSync as existsSync2, mkdirSync as mkdirSync4, readFileSync as readFileSync5, renameSync, writeFileSync as writeFileSync3 } from "fs";
2310
- import { dirname as dirname2, join as join6 } from "path";
2563
+ import { existsSync as existsSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync6, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
2564
+ import { dirname as dirname2, join as join7 } from "path";
2565
+ function addJudgeUsage(state, model, v) {
2566
+ 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 };
2567
+ t.model = model;
2568
+ if (v.reused) {
2569
+ t.reused++;
2570
+ return;
2571
+ }
2572
+ t.judged++;
2573
+ if (!v.usage) return;
2574
+ t.input_tokens += v.usage.input_tokens;
2575
+ t.output_tokens += v.usage.output_tokens;
2576
+ t.cache_read_input_tokens += v.usage.cache_read_input_tokens;
2577
+ t.cache_creation_input_tokens += v.usage.cache_creation_input_tokens;
2578
+ }
2311
2579
  function runDir(repoRoot, runId) {
2312
- return join6(repoRoot, ".mushi", "ux", runId);
2580
+ return join7(repoRoot, ".mushi", "ux", runId);
2313
2581
  }
2314
2582
  function newRunId(now = /* @__PURE__ */ new Date()) {
2315
2583
  const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-");
2316
2584
  return `${stamp}-${Math.random().toString(36).slice(2, 6)}`;
2317
2585
  }
2318
2586
  function saveState(dir, state) {
2319
- mkdirSync4(dir, { recursive: true });
2587
+ mkdirSync5(dir, { recursive: true });
2320
2588
  state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2321
- const file = join6(dir, "state.json");
2589
+ const file = join7(dir, "state.json");
2322
2590
  const tmp = `${file}.${process.pid}.tmp`;
2323
2591
  writeFileSync3(tmp, JSON.stringify(state, null, 2));
2324
- renameSync(tmp, file);
2592
+ renameSync2(tmp, file);
2325
2593
  }
2326
2594
  function loadState(dir) {
2327
- const file = join6(dir, "state.json");
2595
+ const file = join7(dir, "state.json");
2328
2596
  if (!existsSync2(file)) return null;
2329
- const parsed = JSON.parse(readFileSync5(file, "utf8"));
2597
+ const parsed = JSON.parse(readFileSync6(file, "utf8"));
2330
2598
  if (parsed.version !== 1) throw new Error(`Unsupported run state version ${String(parsed.version)} in ${file}`);
2331
2599
  return parsed;
2332
2600
  }
2333
2601
  function savePng(dir, rel, png) {
2334
- const abs = join6(dir, rel);
2335
- mkdirSync4(dirname2(abs), { recursive: true });
2602
+ const abs = join7(dir, rel);
2603
+ mkdirSync5(dirname2(abs), { recursive: true });
2336
2604
  writeFileSync3(abs, png);
2337
2605
  return rel.replace(/\\/g, "/");
2338
2606
  }
@@ -2750,7 +3018,7 @@ async function openLauncher() {
2750
3018
  '<div class="grid">' +
2751
3019
  '<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>' +
2752
3020
  '</div>' +
2753
- '<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>' +
3021
+ '<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>' +
2754
3022
  '<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>' +
2755
3023
  '<div class="row"><span class="sub mono" id="f-spec"></span><button type="button" class="btn" id="f-refresh">Refresh list</button></div></div>' +
2756
3024
  '<div class="card"><h2><span class="n">3</span>How much</h2><div class="grid">' +
@@ -2996,7 +3264,7 @@ es.onmessage = (m) => {
2996
3264
  var RUN_ID_RE = /^[0-9]{8}-[0-9]{6}-[a-z0-9]{4}$/;
2997
3265
  function safeShotPath(runDirPath, requested) {
2998
3266
  if (!/^shots\/[\w./-]+\.png$/.test(requested) || requested.includes("..")) return null;
2999
- const abs = normalize(join7(runDirPath, requested));
3267
+ const abs = normalize(join8(runDirPath, requested));
3000
3268
  return abs.startsWith(normalize(runDirPath) + sep) ? abs : null;
3001
3269
  }
3002
3270
  var LaunchInput = z.object({
@@ -3048,7 +3316,7 @@ async function readBody(req, limit = 64e3) {
3048
3316
  }
3049
3317
  async function startStudio(opts) {
3050
3318
  const token = randomBytes(16).toString("hex");
3051
- const uxDir = join7(opts.repoRoot, ".mushi", "ux");
3319
+ const uxDir = join8(opts.repoRoot, ".mushi", "ux");
3052
3320
  const clients = /* @__PURE__ */ new Set();
3053
3321
  let active = null;
3054
3322
  const send = (payload) => {
@@ -3071,7 +3339,7 @@ async function startStudio(opts) {
3071
3339
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
3072
3340
  res.end(JSON.stringify(body));
3073
3341
  };
3074
- const runDirOf = (runId) => runId && RUN_ID_RE.test(runId) ? join7(uxDir, runId) : null;
3342
+ const runDirOf = (runId) => runId && RUN_ID_RE.test(runId) ? join8(uxDir, runId) : null;
3075
3343
  const server = createServer2((req, res) => {
3076
3344
  const url = new URL(req.url ?? "/", "http://127.0.0.1");
3077
3345
  if (url.searchParams.get("t") !== token) {
@@ -3088,7 +3356,7 @@ async function startStudio(opts) {
3088
3356
  }
3089
3357
  if (req.method === "GET" && url.pathname === "/api/runs") {
3090
3358
  const ids = existsSync3(uxDir) ? readdirSync4(uxDir).filter((d) => RUN_ID_RE.test(d)) : [];
3091
- const runs = ids.map((id) => loadState(join7(uxDir, id))).filter((s) => s !== null).map(summarize).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
3359
+ const runs = ids.map((id) => loadState(join8(uxDir, id))).filter((s) => s !== null).map(summarize).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
3092
3360
  return json(res, 200, { runs });
3093
3361
  }
3094
3362
  if (req.method === "GET" && url.pathname === "/api/state") {
@@ -3097,8 +3365,8 @@ async function startStudio(opts) {
3097
3365
  }
3098
3366
  if (req.method === "GET" && url.pathname === "/api/log") {
3099
3367
  const dir = runDirOf(url.searchParams.get("run"));
3100
- const file = dir ? join7(dir, "run.log") : null;
3101
- const lines = file && existsSync3(file) ? readFileSync6(file, "utf8").split("\n").filter(Boolean).slice(-400) : [];
3368
+ const file = dir ? join8(dir, "run.log") : null;
3369
+ const lines = file && existsSync3(file) ? readFileSync7(file, "utf8").split("\n").filter(Boolean).slice(-400) : [];
3102
3370
  return json(res, 200, { lines });
3103
3371
  }
3104
3372
  if (req.method === "GET" && url.pathname === "/api/steps") {
@@ -3106,12 +3374,12 @@ async function startStudio(opts) {
3106
3374
  const key = url.searchParams.get("surface") ?? "";
3107
3375
  const n = url.searchParams.get("attempt");
3108
3376
  if (!dir || !/^[\w.:-]{1,160}$/.test(key) || n !== null && !/^[0-9]{1,2}$/.test(n)) return json(res, 400, { error: "bad request" });
3109
- const agentDir = join7(dir, "agent");
3377
+ const agentDir = join8(dir, "agent");
3110
3378
  const prefix = attemptLogBase(key, 0).slice(0, -1);
3111
3379
  const attempts = existsSync3(agentDir) ? readdirSync4(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) : [];
3112
3380
  const attempt = n !== null ? Number(n) : attempts.length ? Math.max(...attempts) : null;
3113
- const file = attempt !== null && attempts.includes(attempt) ? join7(agentDir, `${prefix}${attempt}.steps.log`) : null;
3114
- const lines = file ? readFileSync6(file, "utf8").split("\n").filter(Boolean).slice(-200) : [];
3381
+ const file = attempt !== null && attempts.includes(attempt) ? join8(agentDir, `${prefix}${attempt}.steps.log`) : null;
3382
+ const lines = file ? readFileSync7(file, "utf8").split("\n").filter(Boolean).slice(-200) : [];
3115
3383
  return json(res, 200, { attempt, lines });
3116
3384
  }
3117
3385
  if (req.method === "GET" && url.pathname === "/api/events") {
@@ -3129,13 +3397,13 @@ async function startStudio(opts) {
3129
3397
  return res.end();
3130
3398
  }
3131
3399
  res.writeHead(200, { "content-type": "image/png", "cache-control": "max-age=3600" });
3132
- return res.end(readFileSync6(abs));
3400
+ return res.end(readFileSync7(abs));
3133
3401
  }
3134
3402
  if (req.method === "GET" && url.pathname === "/api/changes") {
3135
3403
  const dir = runDirOf(url.searchParams.get("run"));
3136
3404
  const abs = dir ? safeShotPath(dir, url.searchParams.get("p") ?? "") : null;
3137
3405
  if (!abs || !existsSync3(abs)) return json(res, 404, { error: "No such diff image" });
3138
- const png = PNG3.sync.read(readFileSync6(abs));
3406
+ const png = PNG3.sync.read(readFileSync7(abs));
3139
3407
  return json(res, 200, { width: png.width, height: png.height, boxes: changeRegions(png) });
3140
3408
  }
3141
3409
  if (req.method === "GET" && url.pathname === "/api/options") {
@@ -3188,7 +3456,7 @@ async function startStudio(opts) {
3188
3456
  const origin = req.headers.origin;
3189
3457
  if (origin && origin !== `http://127.0.0.1:${server.address().port}`) return json(res, 403, { error: "Wrong origin" });
3190
3458
  if (active && active.runId !== resumeMatch[1]) {
3191
- const state = loadState(join7(uxDir, active.runId));
3459
+ const state = loadState(join8(uxDir, active.runId));
3192
3460
  if (state && !["done", "failed"].includes(state.phase ?? "")) return json(res, 409, { error: `Run ${active.runId} is still going. Stop it first.` });
3193
3461
  }
3194
3462
  const started = await opts.resume(resumeMatch[1]).catch((err) => err);
@@ -3204,7 +3472,7 @@ async function startStudio(opts) {
3204
3472
  const origin = req.headers.origin;
3205
3473
  if (origin && origin !== `http://127.0.0.1:${server.address().port}`) return json(res, 403, { error: "Wrong origin" });
3206
3474
  if (active) {
3207
- const state = loadState(join7(uxDir, active.runId));
3475
+ const state = loadState(join8(uxDir, active.runId));
3208
3476
  if (state && !["done", "failed"].includes(state.phase ?? "")) return json(res, 409, { error: `Run ${active.runId} is still going.` });
3209
3477
  }
3210
3478
  const parsed = LaunchInput.safeParse(await readBody(req));
@@ -3241,9 +3509,9 @@ async function startDashboard(dir, events, port = 0) {
3241
3509
  }
3242
3510
 
3243
3511
  // src/explore.ts
3244
- import { mkdirSync as mkdirSync5 } from "fs";
3245
- import { createHash as createHash3 } from "crypto";
3246
- import { join as join8 } from "path";
3512
+ import { mkdirSync as mkdirSync6 } from "fs";
3513
+ import { createHash as createHash4 } from "crypto";
3514
+ import { join as join9 } from "path";
3247
3515
  var CHARTERS = {
3248
3516
  forms: "Use the forms and inputs on this page like a careless user: type odd values (very long text, emoji, spaces only, negative or huge numbers, a date far in the past), clear required fields, toggle every checkbox and switch, open and close dialogs. Never press a button whose label reads as destructive.",
3249
3517
  navigation: "Move around like an impatient user: open links and tabs, use back and forward, reload in the middle of a task, open the same thing twice, then go back to where you started.",
@@ -3524,7 +3792,7 @@ var KIND_SEVERITY = {
3524
3792
  };
3525
3793
  function exploreFinding(s, steps, start2, charter) {
3526
3794
  const path = new URL(s.url).pathname + new URL(s.url).search;
3527
- const fingerprint2 = createHash3("sha1").update(`explore|${signalKey(s)}`).digest("hex").slice(0, 16);
3795
+ const fingerprint2 = createHash4("sha1").update(`explore|${signalKey(s)}`).digest("hex").slice(0, 16);
3528
3796
  const label = { "console-error": "A console error", "page-error": "An uncaught error", "server-error": "A server error", "blank-screen": "The page goes blank" }[s.kind];
3529
3797
  return {
3530
3798
  fingerprint: fingerprint2,
@@ -3545,8 +3813,8 @@ async function runExplore(opts) {
3545
3813
  const progress = opts.onProgress ?? (() => {
3546
3814
  });
3547
3815
  const runId = `explore-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
3548
- const dir = opts.outDir ?? join8(auditHome(), runId);
3549
- mkdirSync5(dir, { recursive: true });
3816
+ const dir = opts.outDir ?? join9(auditHome(), runId);
3817
+ mkdirSync6(dir, { recursive: true });
3550
3818
  const maxSteps = Math.max(1, Math.min(60, opts.steps ?? 35));
3551
3819
  const model = opts.model ?? DEFAULT_CURSOR_REVIEW_MODEL;
3552
3820
  const ask = opts.ask ?? ((prompt, cwd) => askCursor(prompt, cwd, model));
@@ -3649,9 +3917,9 @@ async function runExplore(opts) {
3649
3917
  }
3650
3918
 
3651
3919
  // src/fresh-eyes.ts
3652
- import { createHash as createHash4 } from "crypto";
3653
- import { mkdirSync as mkdirSync6, writeFileSync as writeFileSync4 } from "fs";
3654
- import { join as join9, resolve } from "path";
3920
+ import { createHash as createHash5 } from "crypto";
3921
+ import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync4 } from "fs";
3922
+ import { join as join10, resolve } from "path";
3655
3923
  var OPINION_CATEGORIES = ["confusing", "unclear_copy", "too_many_choices"];
3656
3924
  function parseFreshAction(text) {
3657
3925
  const j = firstJson(text ?? "");
@@ -3774,11 +4042,13 @@ async function successReached(page, c) {
3774
4042
  }
3775
4043
  return true;
3776
4044
  }
3777
- function presetFor(url) {
4045
+ function presetFor(url, presets) {
3778
4046
  try {
3779
4047
  const u = new URL(url);
3780
- if (u.hostname === "kensaur.us" && u.pathname.startsWith("/mushi-mushi")) {
3781
- return { appHosts: ["dxptnwrhwsqckaftyymj.supabase.co"], success: { url: "/mushi-mushi/admin/reports/*", text: "Why it broke" } };
4048
+ for (const p of presets) {
4049
+ const m = new URL(p.match);
4050
+ const prefix = m.pathname.replace(/\/+$/, "");
4051
+ if (u.origin === m.origin && (prefix === "" || u.pathname === prefix || u.pathname.startsWith(`${prefix}/`))) return p;
3782
4052
  }
3783
4053
  } catch {
3784
4054
  }
@@ -3812,14 +4082,14 @@ function dropSnapshotNodes(snapshot, drop) {
3812
4082
  var SNAPSHOT_NAME_RE = /^\s*- [a-z]+ "((?:[^"\\]|\\.)*)"/;
3813
4083
  function composeSnapshot(parts, budget = MAX_SNAPSHOT_CHARS2) {
3814
4084
  const hidden = new Set(parts.hidden);
3815
- const clean = (snap) => hidden.size ? dropSnapshotNodes(snap, (line) => {
4085
+ const clean2 = (snap) => hidden.size ? dropSnapshotNodes(snap, (line) => {
3816
4086
  const m = SNAPSHOT_NAME_RE.exec(line);
3817
4087
  return !!m && hidden.has(m[1].replace(/\\(.)/g, "$1"));
3818
4088
  }) : snap;
3819
- const body = clean(parts.body);
4089
+ const body = clean2(parts.body);
3820
4090
  if (!parts.main?.trim()) return body.slice(0, budget);
3821
4091
  const head = `Main content:
3822
- ${clean(parts.main)}`;
4092
+ ${clean2(parts.main)}`;
3823
4093
  const rest = dropSnapshotNodes(body, (line) => /^\s*- main\b/.test(line));
3824
4094
  const tail = rest.trim() ? `
3825
4095
 
@@ -3848,10 +4118,25 @@ async function screenForModel(page) {
3848
4118
  }).catch(() => []);
3849
4119
  return composeSnapshot({ main, body, hidden });
3850
4120
  }
4121
+ function personaBrowser(p) {
4122
+ if (!p) return { viewport: VIEWPORT, context: {} };
4123
+ 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 };
4124
+ const zoom = p.needs.includes("low_vision") ? 1.5 : 1;
4125
+ return {
4126
+ viewport: { width: Math.round(base.width / zoom), height: Math.round(base.height / zoom) },
4127
+ context: {
4128
+ deviceScaleFactor: base.scale * zoom,
4129
+ ...p.device === "desktop" ? {} : { isMobile: true, hasTouch: true },
4130
+ locale: p.locale,
4131
+ ...p.needs.includes("reduced_motion") ? { reducedMotion: "reduce" } : {}
4132
+ }
4133
+ };
4134
+ }
3851
4135
  function freshEyesPrompt(input) {
3852
4136
  const recent = input.done.slice(-8).map((a, i) => `${i + 1}. ${a}`);
3853
4137
  return [
3854
4138
  `You have never seen this product before. You came with one goal: ${input.goal}.`,
4139
+ ...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)}`] : [],
3855
4140
  "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.",
3856
4141
  `Step ${input.step} of ${input.maxSteps}.`,
3857
4142
  recent.length ? `What you did so far:
@@ -3883,8 +4168,8 @@ function cursorAskArgs(dir, model, win) {
3883
4168
  }
3884
4169
  function cursorFileAsk(model, signal) {
3885
4170
  return async (prompt, dir) => {
3886
- mkdirSync6(dir, { recursive: true });
3887
- writeFileSync4(join9(dir, "prompt.md"), prompt);
4171
+ mkdirSync7(dir, { recursive: true });
4172
+ writeFileSync4(join10(dir, "prompt.md"), prompt);
3888
4173
  const win = process.platform === "win32";
3889
4174
  let last = "The Cursor CLI did not run.";
3890
4175
  for (let attempt = 1; attempt <= 2; attempt++) {
@@ -3914,7 +4199,7 @@ function candidateKey(c) {
3914
4199
  if (c.kind === "external") return `external|${c.screen}|${c.requirement}`;
3915
4200
  return `${c.kind}|${c.screen}`;
3916
4201
  }
3917
- var fingerprint = (key) => createHash4("sha1").update(`fresh-eyes|${key}`).digest("hex").slice(0, 16);
4202
+ var fingerprint = (key) => createHash5("sha1").update(`fresh-eyes|${key}`).digest("hex").slice(0, 16);
3918
4203
  var SIGNAL_SEVERITY = { "page-error": "high", "blank-screen": "high", "server-error": "high", "console-error": "medium" };
3919
4204
  var SIGNAL_LABEL = {
3920
4205
  "console-error": "A console error",
@@ -4099,8 +4384,8 @@ async function runFreshEyes(opts) {
4099
4384
  });
4100
4385
  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)}".`);
4101
4386
  const runId = opts.runId ?? newRunId();
4102
- const dir = resolve(opts.outDir ?? join9(process.env.LOCALAPPDATA ?? join9(process.env.HOME ?? ".", ".cache"), "mushi", "fresh-eyes", runId));
4103
- mkdirSync6(join9(dir, "shots"), { recursive: true });
4387
+ const dir = resolve(opts.outDir ?? join10(process.env.LOCALAPPDATA ?? join10(process.env.HOME ?? ".", ".cache"), "mushi", "fresh-eyes", runId));
4388
+ mkdirSync7(join10(dir, "shots"), { recursive: true });
4104
4389
  const sessions = Math.max(1, Math.min(10, opts.sessions ?? 3));
4105
4390
  const maxSteps = Math.max(1, Math.min(80, opts.steps ?? 30));
4106
4391
  const model = opts.model ?? DEFAULT_CURSOR_REVIEW_MODEL;
@@ -4110,6 +4395,7 @@ async function runFreshEyes(opts) {
4110
4395
  const apiHosts = appOrigins.map((o) => new URL(o).host);
4111
4396
  const dryRun = !!opts.dryRun;
4112
4397
  const readOnly = dryRun || !opts.identity;
4398
+ const look = personaBrowser(opts.persona);
4113
4399
  const browser = await (opts.session?.() ?? // Writes only with a synthetic identity to write as: a run with no account stays read-only.
4114
4400
  openSession({ headless: true, allow: opts.allow, policy: !dryRun && opts.identity ? { writes: "same-origin", appOrigins } : { writes: "read-only" } }));
4115
4401
  const result = {
@@ -4147,12 +4433,12 @@ async function runFreshEyes(opts) {
4147
4433
  identities.set(index, identity);
4148
4434
  if (identity) result.hasAccount = true;
4149
4435
  progress(`session ${index} of ${sessions}${identity ? ` (${identity.userId ? `synthetic account ${identity.userId}` : "test account"})` : " (no account)"}`);
4150
- const s = await runSession({ readOnly, index, identity, browser, opts, ask, base, apiHosts, appOrigins, maxSteps, dir, addCandidate, progress, refused: result.refused });
4436
+ const s = await runSession({ readOnly, index, identity, browser, opts, ask, base, apiHosts, appOrigins, maxSteps, dir, addCandidate, progress, refused: result.refused, look });
4151
4437
  if (identity?.userId) s.accountId = identity.userId;
4152
4438
  result.sessions.push(redact(s, identity));
4153
4439
  }
4154
4440
  for (const c of candidates.values()) {
4155
- const confirmed = await replayCandidate(browser, base, c, identities.get(c.session) ?? null);
4441
+ const confirmed = await replayCandidate(browser, base, c, identities.get(c.session) ?? null, look);
4156
4442
  progress(redact(` ${confirmed ? "confirmed" : "not reproduced"}: ${candidateKey(c)}`, identities.get(c.session) ?? null));
4157
4443
  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));
4158
4444
  }
@@ -4166,14 +4452,14 @@ async function runFreshEyes(opts) {
4166
4452
  const capped = result.sessions.reduce((n, x) => n + x.steps.filter((st) => st.capped && st.outcome === "ok").length, 0);
4167
4453
  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.`);
4168
4454
  result.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
4169
- writeFileSync4(join9(dir, "result.json"), JSON.stringify(result, null, 2));
4455
+ writeFileSync4(join10(dir, "result.json"), JSON.stringify(result, null, 2));
4170
4456
  return result;
4171
4457
  }
4172
4458
  async function runSession(x) {
4173
4459
  const { index, identity, browser, opts, base } = x;
4174
4460
  const say = (line) => x.progress(redact(line, identity));
4175
4461
  const session = { index, outcome: "stalled", stall: null, ttfvSeconds: null, appSeconds: 0, readSeconds: 0, modelSeconds: 0, backtracks: 0, steps: [], opinions: [] };
4176
- const ctx = await browser.freshContext();
4462
+ const ctx = await browser.freshContext(x.look.context);
4177
4463
  await likeARealBrowser(ctx, base.origin);
4178
4464
  let docStatus = null;
4179
4465
  let captchaSeen = false;
@@ -4192,13 +4478,13 @@ async function runSession(x) {
4192
4478
  });
4193
4479
  };
4194
4480
  attach(page);
4195
- await page.setViewportSize(VIEWPORT);
4481
+ await page.setViewportSize(x.look.viewport);
4196
4482
  const switchTo = async (p) => {
4197
4483
  windows.push(page);
4198
4484
  page = p;
4199
4485
  attach(p);
4200
4486
  watcher = watch(p, base.origin, x.apiHosts);
4201
- await p.setViewportSize(VIEWPORT).catch(() => {
4487
+ await p.setViewportSize(x.look.viewport).catch(() => {
4202
4488
  });
4203
4489
  };
4204
4490
  const actions = [];
@@ -4210,7 +4496,7 @@ async function runSession(x) {
4210
4496
  const shoot = async (n) => {
4211
4497
  const name = `s${index}-step${String(n).padStart(2, "0")}.png`;
4212
4498
  try {
4213
- 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]")] }));
4499
+ 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]")] }));
4214
4500
  return name;
4215
4501
  } catch {
4216
4502
  return void 0;
@@ -4269,8 +4555,8 @@ async function runSession(x) {
4269
4555
  const snapshot = redact(await screenForModel(page), identity);
4270
4556
  const tAsk = performance.now();
4271
4557
  const answer = await x.ask(
4272
- freshEyesPrompt({ goal: opts.goal, snapshot, done: session.steps.slice(1).map((s) => s.action), step: n, maxSteps: x.maxSteps, hasAccount: !!identity }),
4273
- join9(x.dir, "ask", `s${index}-${String(n).padStart(2, "0")}`)
4558
+ 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 }),
4559
+ join10(x.dir, "ask", `s${index}-${String(n).padStart(2, "0")}`)
4274
4560
  );
4275
4561
  const modelMs = since(tAsk);
4276
4562
  const parsed = parseFreshAction(answer.text);
@@ -4424,7 +4710,7 @@ async function runSession(x) {
4424
4710
  const values = extractSetupValues(after.text) ?? opts.setupValues ?? null;
4425
4711
  if (values) {
4426
4712
  terminalUsed = true;
4427
- const res = await opts.terminal({ ...values, dir: join9(x.dir, "terminal", `s${index}`) });
4713
+ const res = await opts.terminal({ ...values, dir: join10(x.dir, "terminal", `s${index}`) });
4428
4714
  for (const ph of res.phases) {
4429
4715
  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) });
4430
4716
  say(` terminal ${ph.name}: ${ph.ok ? "ok" : "failed"} in ${(ph.ms / 1e3).toFixed(1)} s`);
@@ -4461,11 +4747,11 @@ function finish(s) {
4461
4747
  }
4462
4748
  return s;
4463
4749
  }
4464
- async function replayCandidate(browser, base, c, identity) {
4465
- const ctx = await browser.freshContext();
4750
+ async function replayCandidate(browser, base, c, identity, look) {
4751
+ const ctx = await browser.freshContext(look.context);
4466
4752
  await likeARealBrowser(ctx, base.origin);
4467
4753
  const page = await ctx.newPage();
4468
- await page.setViewportSize(VIEWPORT);
4754
+ await page.setViewportSize(look.viewport);
4469
4755
  const watcher = watch(page, base.origin, []);
4470
4756
  let docStatus = null;
4471
4757
  let captchaSeen = false;
@@ -4508,8 +4794,8 @@ async function replayCandidate(browser, base, c, identity) {
4508
4794
  }
4509
4795
 
4510
4796
  // src/fresh-eyes-report.ts
4511
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
4512
- import { join as join10 } from "path";
4797
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "fs";
4798
+ import { join as join11 } from "path";
4513
4799
  var STALL_TEXT = {
4514
4800
  signup_wall: "stopped at a sign-in wall it could not pass",
4515
4801
  captcha: "stopped at a captcha (never solved)",
@@ -4574,14 +4860,14 @@ function timelineMarkdown(r) {
4574
4860
  return lines.join("\n");
4575
4861
  }
4576
4862
  function writeTimeline(r) {
4577
- const path = join10(r.dir, "timeline.md");
4863
+ const path = join11(r.dir, "timeline.md");
4578
4864
  writeFileSync5(path, timelineMarkdown(r));
4579
4865
  return path;
4580
4866
  }
4581
4867
  function headers(cfg) {
4582
4868
  return { Authorization: `Bearer ${cfg.apiKey}`, "X-Mushi-Api-Key": cfg.apiKey, "X-Mushi-Project": cfg.projectId, "Content-Type": "application/json" };
4583
4869
  }
4584
- async function call(cfg, method, path, body) {
4870
+ async function call2(cfg, method, path, body) {
4585
4871
  const res = await fetch(`${cfg.endpoint}${path}`, { method, headers: headers(cfg), body: body === void 0 ? void 0 : JSON.stringify(body), signal: AbortSignal.timeout(3e4) });
4586
4872
  const json = await res.json().catch(() => null);
4587
4873
  if (!res.ok || !json?.ok) throw new Error(json?.error?.message ?? `HTTP ${res.status}`);
@@ -4637,22 +4923,22 @@ function runSnapshot(r, status, cliVersion) {
4637
4923
  async function syncFreshEyes(cfg, r, cliVersion) {
4638
4924
  const base = `/v1/admin/projects/${cfg.projectId}/fresh-eyes/${r.runId}`;
4639
4925
  try {
4640
- await call(cfg, "PUT", base, runSnapshot(r, "running", cliVersion));
4926
+ await call2(cfg, "PUT", base, runSnapshot(r, "running", cliVersion));
4641
4927
  const shots = r.sessions.flatMap((s) => s.steps.map((st) => st.shot).filter((x) => !!x));
4642
4928
  for (let i = 0; i < shots.length; i += 40) {
4643
4929
  const batch = shots.slice(i, i + 40);
4644
- const data = await call(cfg, "POST", `${base}/uploads`, { names: batch });
4930
+ const data = await call2(cfg, "POST", `${base}/uploads`, { names: batch });
4645
4931
  for (const u of data.uploads) {
4646
4932
  const put = await fetch(u.signedUrl, {
4647
4933
  method: "PUT",
4648
4934
  headers: { "Content-Type": "image/png", "x-upsert": "true" },
4649
- body: new Uint8Array(readFileSync7(join10(r.dir, "shots", u.name))),
4935
+ body: new Uint8Array(readFileSync8(join11(r.dir, "shots", u.name))),
4650
4936
  signal: AbortSignal.timeout(6e4)
4651
4937
  });
4652
4938
  if (!put.ok) throw new Error(`screenshot upload failed (HTTP ${put.status})`);
4653
4939
  }
4654
4940
  }
4655
- await call(cfg, "PUT", base, runSnapshot(r, "done", cliVersion));
4941
+ await call2(cfg, "PUT", base, runSnapshot(r, "done", cliVersion));
4656
4942
  return null;
4657
4943
  } catch (err) {
4658
4944
  return err.message;
@@ -4689,7 +4975,7 @@ async function fileFreshEyesFindings(cfg, r, dryRun) {
4689
4975
  continue;
4690
4976
  }
4691
4977
  try {
4692
- const data = await call(cfg, "POST", `/v1/admin/projects/${cfg.projectId}/fresh-eyes/${r.runId}/findings`, body);
4978
+ const data = await call2(cfg, "POST", `/v1/admin/projects/${cfg.projectId}/fresh-eyes/${r.runId}/findings`, body);
4693
4979
  if (data.reportId) out.filed.push({ fingerprint: f.fingerprint, reportId: data.reportId, title: String(body.title) });
4694
4980
  else out.skipped.push({ fingerprint: f.fingerprint, reason: `an open report has it (${data.duplicateOf ?? "unknown"})` });
4695
4981
  } catch (err) {
@@ -4699,12 +4985,28 @@ async function fileFreshEyesFindings(cfg, r, dryRun) {
4699
4985
  return out;
4700
4986
  }
4701
4987
  async function mintTestAccount(cfg) {
4702
- const data = await call(cfg, "POST", "/v1/admin/fresh-eyes/test-account", { purpose: "fresh_eyes" });
4988
+ const data = await call2(cfg, "POST", "/v1/admin/fresh-eyes/test-account", { purpose: "fresh_eyes", projectId: cfg.projectId });
4703
4989
  if (!data?.email || !data?.password) throw new Error("The console did not return an account.");
4704
4990
  return { email: data.email, password: data.password, name: data.name, ...typeof data.user_id === "string" ? { userId: data.user_id } : {} };
4705
4991
  }
4706
4992
 
4707
4993
  // src/fresh-eyes-request.ts
4994
+ var LOCALE_RE = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8}){0,3}$/;
4995
+ var DEVICES = ["desktop", "mobile", "tablet"];
4996
+ var NEEDS = ["screen_reader", "low_vision", "keyboard_only", "reduced_motion", "color_blind", "motor", "plain_language"];
4997
+ function parsePersona(raw) {
4998
+ if (raw == null) return null;
4999
+ const p = raw;
5000
+ const name = plain(p.name, 60);
5001
+ const brief = plain(p.brief, 600);
5002
+ if (!name || !brief) throw new Error("The persona in the request is malformed.");
5003
+ if (typeof p.locale !== "string" || p.locale.length > 35 || !LOCALE_RE.test(p.locale)) throw new Error("The persona language must be a code like en-US.");
5004
+ if (!DEVICES.includes(p.device)) throw new Error("The persona device must be desktop, mobile or tablet.");
5005
+ const needs = Array.isArray(p.needs) ? p.needs : [];
5006
+ if (needs.length > NEEDS.length || needs.some((n) => typeof n !== "string" || !NEEDS.includes(n))) throw new Error("The persona needs are malformed.");
5007
+ if (typeof p.steps !== "number" || !Number.isInteger(p.steps) || p.steps < 5 || p.steps > 80) throw new Error("The persona step cap must be 5 to 80.");
5008
+ return { name, brief, locale: p.locale, device: p.device, needs: [...new Set(needs)], steps: p.steps };
5009
+ }
4708
5010
  var RUN_ID_RE2 = /^[0-9]{8}-[0-9]{6}-[a-z0-9]{4}$/;
4709
5011
  var CONTROL_RE = /[\u0000-\u001f\u007f]/;
4710
5012
  var MAX_BYTES = 64 * 1024;
@@ -4743,13 +5045,14 @@ function parseStdinRequest(text) {
4743
5045
  accounts.push({ email, password: a.password, name: plain(a.name, 80) ?? void 0, ...userId ? { userId } : {} });
4744
5046
  }
4745
5047
  if (r.dryRun && accounts.length) throw new Error("A look-around run uses no account.");
4746
- return { runId: r.runId, url: url.toString(), goal, sessions: r.sessions, successText, dryRun: r.dryRun, accounts };
5048
+ return { runId: r.runId, url: url.toString(), goal, sessions: r.sessions, successText, dryRun: r.dryRun, accounts, persona: parsePersona(r.persona) };
4747
5049
  }
4748
5050
  function syncsToConsole(flags, hasLogin) {
4749
5051
  return !!(flags.sync || flags.file) && hasLogin;
4750
5052
  }
4751
- function stepsFor(given, hasAccount) {
5053
+ function stepsFor(given, hasAccount, personaSteps) {
4752
5054
  if (given !== void 0 && given.trim() !== "") return Number(given);
5055
+ if (personaSteps != null) return personaSteps;
4753
5056
  return hasAccount ? 60 : 30;
4754
5057
  }
4755
5058
  function literalPattern(text) {
@@ -4768,9 +5071,9 @@ async function readStdin(stream = process.stdin) {
4768
5071
  }
4769
5072
 
4770
5073
  // src/fresh-eyes-terminal.ts
4771
- import { existsSync as existsSync4, mkdirSync as mkdirSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync6 } from "fs";
5074
+ import { existsSync as existsSync4, mkdirSync as mkdirSync8, readFileSync as readFileSync9, writeFileSync as writeFileSync6 } from "fs";
4772
5075
  import { createServer as createServer3 } from "http";
4773
- import { join as join11 } from "path";
5076
+ import { join as join12 } from "path";
4774
5077
  var DEFAULT_SETUP_COMMAND = "npx --yes mushi-mushi@latest --yes --project-id {projectId} --api-key {apiKey}";
4775
5078
  var HOSTED_API_ORIGIN = "https://dxptnwrhwsqckaftyymj.supabase.co";
4776
5079
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -4808,16 +5111,16 @@ function setupEnv(home, base = process.env) {
4808
5111
  env[k] = v;
4809
5112
  }
4810
5113
  const realHome = base.HOME ?? base.USERPROFILE ?? "";
4811
- const npmCache2 = base.npm_config_cache ?? (realHome ? join11(realHome, process.platform === "win32" ? "AppData/Local/npm-cache" : ".npm") : void 0);
5114
+ const npmCache2 = base.npm_config_cache ?? (realHome ? join12(realHome, process.platform === "win32" ? "AppData/Local/npm-cache" : ".npm") : void 0);
4812
5115
  return {
4813
5116
  ...env,
4814
5117
  HOME: home,
4815
5118
  USERPROFILE: home,
4816
- APPDATA: join11(home, "AppData", "Roaming"),
4817
- LOCALAPPDATA: join11(home, "AppData", "Local"),
4818
- XDG_CONFIG_HOME: join11(home, ".config"),
4819
- XDG_DATA_HOME: join11(home, ".local", "share"),
4820
- XDG_STATE_HOME: join11(home, ".local", "state"),
5119
+ APPDATA: join12(home, "AppData", "Roaming"),
5120
+ LOCALAPPDATA: join12(home, "AppData", "Local"),
5121
+ XDG_CONFIG_HOME: join12(home, ".config"),
5122
+ XDG_DATA_HOME: join12(home, ".local", "share"),
5123
+ XDG_STATE_HOME: join12(home, ".local", "state"),
4821
5124
  ...npmCache2 ? { npm_config_cache: npmCache2 } : {},
4822
5125
  CI: "1",
4823
5126
  MUSHI_TELEMETRY: "0"
@@ -4831,11 +5134,11 @@ async function runTerminalSetup(o) {
4831
5134
  out.failedAt = name;
4832
5135
  return out;
4833
5136
  };
4834
- const sample = join11(o.dir, "sample");
5137
+ const sample = join12(o.dir, "sample");
4835
5138
  const sc = await timed(async () => {
4836
- mkdirSync7(sample, { recursive: true });
4837
- writeFileSync6(join11(sample, "package.json"), JSON.stringify({ name: "fresh-eyes-sample", version: "0.0.0", private: true, type: "module" }, null, 2));
4838
- writeFileSync6(join11(sample, "index.html"), "<!doctype html><title>Sample app</title><h1>Sample app</h1>");
5139
+ mkdirSync8(sample, { recursive: true });
5140
+ writeFileSync6(join12(sample, "package.json"), JSON.stringify({ name: "fresh-eyes-sample", version: "0.0.0", private: true, type: "module" }, null, 2));
5141
+ writeFileSync6(join12(sample, "index.html"), "<!doctype html><title>Sample app</title><h1>Sample app</h1>");
4839
5142
  });
4840
5143
  phases.push({ name: "scaffold", ms: sc.ms, ok: true, detail: "A plain HTML app with a package.json." });
4841
5144
  let argv;
@@ -4845,8 +5148,8 @@ async function runTerminalSetup(o) {
4845
5148
  return fail("setup", 0, err.message);
4846
5149
  }
4847
5150
  const exec = o.runCommand ?? ((cmd, args, cwd) => {
4848
- const home = join11(o.dir, "home");
4849
- mkdirSync7(join11(home, ".config"), { recursive: true });
5151
+ const home = join12(o.dir, "home");
5152
+ mkdirSync8(join12(home, ".config"), { recursive: true });
4850
5153
  return run(cmd, args, { cwd, env: setupEnv(home), shell: process.platform === "win32", timeoutMs: o.setupTimeoutMs ?? 3e5 });
4851
5154
  });
4852
5155
  const st = await timed(() => exec(argv.cmd, argv.args, sample));
@@ -4854,7 +5157,7 @@ async function runTerminalSetup(o) {
4854
5157
  if (st.value.exitCode !== 0) return fail("setup", st.ms, `The setup command exited ${st.value.exitCode}: ${st.value.tail.trim().slice(-300)}`);
4855
5158
  phases.push({ name: "setup", ms: st.ms, ok: true, detail: `${argv.cmd} ${argv.args.join(" ")}`.replace(o.apiKey, "{{apiKey}}").slice(0, 300) });
4856
5159
  const en = await timed(async () => {
4857
- const text = [".env.local", ".env"].map((f) => join11(sample, f)).filter((f) => existsSync4(f)).map((f) => readFileSync8(f, "utf8")).join("\n");
5160
+ const text = [".env.local", ".env"].map((f) => join12(sample, f)).filter((f) => existsSync4(f)).map((f) => readFileSync9(f, "utf8")).join("\n");
4858
5161
  return parseSetupEnv(text);
4859
5162
  });
4860
5163
  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.");
@@ -4914,11 +5217,60 @@ async function sendReportThroughWidget(sampleUrl, apiOrigin, timeoutMs) {
4914
5217
  }
4915
5218
  }
4916
5219
 
5220
+ // src/fresh-eyes-presets.ts
5221
+ import { existsSync as existsSync5, readFileSync as readFileSync10 } from "fs";
5222
+ import { homedir as homedir2 } from "os";
5223
+ import { join as join13 } from "path";
5224
+ var HOST_RE = /^[a-z0-9.-]{1,253}$/i;
5225
+ function presetsFile(env = process.env) {
5226
+ const given = env.MUSHI_FRESH_EYES_PRESETS_FILE?.trim();
5227
+ if (given) return given;
5228
+ const base = env.LOCALAPPDATA ?? env.XDG_CONFIG_HOME ?? join13(homedir2(), ".config");
5229
+ return join13(base, "mushi", "fresh-eyes-presets.json");
5230
+ }
5231
+ function parsePresets(text) {
5232
+ let raw;
5233
+ try {
5234
+ raw = JSON.parse(text);
5235
+ } catch {
5236
+ throw new Error("The fresh-eyes presets file is not JSON.");
5237
+ }
5238
+ if (!Array.isArray(raw)) throw new Error("The fresh-eyes presets file must be a JSON array.");
5239
+ return raw.map((e, i) => {
5240
+ const p = e ?? {};
5241
+ const bad = (why) => new Error(`Fresh-eyes preset ${i + 1}: ${why}`);
5242
+ let match;
5243
+ try {
5244
+ match = new URL(String(p.match));
5245
+ } catch {
5246
+ throw bad('"match" must be an http(s) address.');
5247
+ }
5248
+ if (match.protocol !== "https:" && match.protocol !== "http:") throw bad('"match" must be an http(s) address.');
5249
+ const appHosts = p.appHosts === void 0 ? [] : p.appHosts;
5250
+ if (!Array.isArray(appHosts) || appHosts.some((h) => typeof h !== "string" || !HOST_RE.test(h))) throw bad('"appHosts" must be a list of host names.');
5251
+ for (const k of ["successUrl", "successText"]) {
5252
+ if (p[k] !== void 0 && (typeof p[k] !== "string" || !p[k].trim() || p[k].length > 300)) throw bad(`"${k}" must be text up to 300 characters.`);
5253
+ }
5254
+ if (p.terminal !== void 0 && typeof p.terminal !== "boolean") throw bad('"terminal" must be true or false.');
5255
+ return {
5256
+ match: `${match.origin}${match.pathname}`,
5257
+ appHosts,
5258
+ success: { ...p.successUrl ? { url: p.successUrl } : {}, ...p.successText ? { text: p.successText } : {} },
5259
+ terminal: p.terminal === true
5260
+ };
5261
+ });
5262
+ }
5263
+ function loadPresets(env = process.env) {
5264
+ const file = presetsFile(env);
5265
+ return existsSync5(file) ? parsePresets(readFileSync10(file, "utf8")) : [];
5266
+ }
5267
+
4917
5268
  // src/judge.ts
4918
5269
  import Anthropic3 from "@anthropic-ai/sdk";
4919
5270
  import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
4920
- import { readFileSync as readFileSync9 } from "fs";
4921
- import { join as join12 } from "path";
5271
+ import { createHash as createHash6 } from "crypto";
5272
+ import { existsSync as existsSync6, mkdirSync as mkdirSync9, readFileSync as readFileSync11, writeFileSync as writeFileSync7 } from "fs";
5273
+ import { join as join14 } from "path";
4922
5274
  import { z as z2 } from "zod";
4923
5275
  var DEFAULT_JUDGE_MODEL = "claude-opus-5-5";
4924
5276
  var MAX_DESIGN_CHARS = 16e3;
@@ -4968,7 +5320,7 @@ function designContext(repoRoot, files) {
4968
5320
  for (const f of files) {
4969
5321
  if (out.length >= MAX_DESIGN_CHARS) break;
4970
5322
  try {
4971
- const text = readFileSync9(join12(repoRoot, f), "utf8");
5323
+ const text = readFileSync11(join14(repoRoot, f), "utf8");
4972
5324
  out += `
4973
5325
  --- ${f} ---
4974
5326
  ${text.slice(0, MAX_DESIGN_CHARS - out.length)}
@@ -5016,11 +5368,16 @@ async function judgeSurface(s, viewport, opts) {
5016
5368
  const after = kept.after[viewport];
5017
5369
  const model = opts.model ?? DEFAULT_JUDGE_MODEL;
5018
5370
  const client = opts.client ?? new Anthropic3();
5019
- const beforePng = readFileSync9(join12(opts.dir, before.png));
5371
+ const beforePng = readFileSync11(join14(opts.dir, before.png));
5020
5372
  const width = pngSize(beforePng).width;
5021
5373
  const maxHeight = Math.round(width * (viewport === "mobile" ? 2.5 : 1.25));
5022
5374
  const bImg = cropTop(beforePng, maxHeight);
5023
- const aImg = cropTop(readFileSync9(join12(opts.dir, after.png)), maxHeight);
5375
+ const aImg = cropTop(readFileSync11(join14(opts.dir, after.png)), maxHeight);
5376
+ if (looksSame(bImg, aImg)) return unchangedVerdict(viewport, model);
5377
+ const design = designContext(opts.repoRoot, opts.designFiles);
5378
+ const cacheKey = judgeCacheKey(bImg, aImg, viewport, model, design);
5379
+ const cached = opts.cacheDir ? readCachedVerdict(opts.cacheDir, cacheKey) : null;
5380
+ if (cached) return { ...cached, viewport, reused: "cache", usage: void 0 };
5024
5381
  const aIsBefore = (opts.random ?? Math.random)() < 0.5;
5025
5382
  const [imgA, imgB] = aIsBefore ? [bImg, aImg] : [aImg, bImg];
5026
5383
  const [probeA, probeB] = aIsBefore ? [before.probes, after.probes] : [after.probes, before.probes];
@@ -5040,7 +5397,7 @@ async function judgeSurface(s, viewport, opts) {
5040
5397
  {
5041
5398
  type: "text",
5042
5399
  text: `Design system of this repository:
5043
- ${designContext(opts.repoRoot, opts.designFiles)}`,
5400
+ ${design}`,
5044
5401
  // Same rubric + tokens for every screen in the run: cache the prefix.
5045
5402
  cache_control: { type: "ephemeral" }
5046
5403
  }
@@ -5067,7 +5424,12 @@ Which is better, A or B?` }
5067
5424
  }
5068
5425
  const parsed = response.parsed_output;
5069
5426
  if (!parsed) return failed(viewport, model, `No structured answer (stop reason ${response.stop_reason}).`);
5070
- return unshuffle(parsed, aIsBefore, { A: pngSize(imgA), B: pngSize(imgB) }, viewport, response.model);
5427
+ const verdict = {
5428
+ ...unshuffle(parsed, aIsBefore, { A: pngSize(imgA), B: pngSize(imgB) }, viewport, response.model),
5429
+ usage: usageOf(response.usage)
5430
+ };
5431
+ if (opts.cacheDir) writeCachedVerdict(opts.cacheDir, cacheKey, verdict);
5432
+ return verdict;
5071
5433
  } catch (err) {
5072
5434
  if (err instanceof Anthropic3.AuthenticationError) {
5073
5435
  return failed(viewport, model, "No valid Anthropic credentials. Set ANTHROPIC_API_KEY or run `ant auth login`.");
@@ -5077,6 +5439,61 @@ Which is better, A or B?` }
5077
5439
  throw err;
5078
5440
  }
5079
5441
  }
5442
+ var JUDGE_CACHE_VERSION = "judge-2026-11-27";
5443
+ function judgeCacheKey(before, after, viewport, model, design) {
5444
+ 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");
5445
+ }
5446
+ function looksSame(before, after) {
5447
+ if (before.equals(after)) return true;
5448
+ try {
5449
+ return pixelDiff(before, after).changedPixels === 0;
5450
+ } catch {
5451
+ return false;
5452
+ }
5453
+ }
5454
+ function unchangedVerdict(viewport, model) {
5455
+ return {
5456
+ viewport,
5457
+ model,
5458
+ preferred: "tie",
5459
+ confidence: "high",
5460
+ summary: "The kept version looks the same as the original here, so it was not reviewed.",
5461
+ better: [],
5462
+ worse: [],
5463
+ designBreaks: [],
5464
+ droppedClaims: 0,
5465
+ reused: "unchanged"
5466
+ };
5467
+ }
5468
+ function readCachedVerdict(dir, key) {
5469
+ const file = join14(dir, `${key}.json`);
5470
+ if (!existsSync6(file)) return null;
5471
+ try {
5472
+ const v = JSON.parse(readFileSync11(file, "utf8"));
5473
+ return v && typeof v.preferred === "string" && !v.error ? v : null;
5474
+ } catch {
5475
+ return null;
5476
+ }
5477
+ }
5478
+ function writeCachedVerdict(dir, key, v) {
5479
+ if (v.error) return;
5480
+ try {
5481
+ mkdirSync9(dir, { recursive: true });
5482
+ writeFileSync7(join14(dir, `${key}.json`), JSON.stringify({ ...v, usage: void 0 }));
5483
+ } catch {
5484
+ }
5485
+ }
5486
+ function usageOf(u) {
5487
+ if (!u || typeof u !== "object") return void 0;
5488
+ const o = u;
5489
+ const n = (k) => typeof o[k] === "number" && Number.isFinite(o[k]) ? Math.max(0, Math.round(o[k])) : 0;
5490
+ return {
5491
+ input_tokens: n("input_tokens"),
5492
+ output_tokens: n("output_tokens"),
5493
+ cache_read_input_tokens: n("cache_read_input_tokens"),
5494
+ cache_creation_input_tokens: n("cache_creation_input_tokens")
5495
+ };
5496
+ }
5080
5497
  function failed(viewport, model, error) {
5081
5498
  return {
5082
5499
  viewport,
@@ -5094,8 +5511,8 @@ function failed(viewport, model, error) {
5094
5511
 
5095
5512
  // src/scorecard.ts
5096
5513
  import Anthropic4 from "@anthropic-ai/sdk";
5097
- import { existsSync as existsSync5, mkdirSync as mkdirSync8, readdirSync as readdirSync5, readFileSync as readFileSync10, writeFileSync as writeFileSync7 } from "fs";
5098
- import { join as join13 } from "path";
5514
+ import { existsSync as existsSync7, mkdirSync as mkdirSync10, readdirSync as readdirSync5, readFileSync as readFileSync12, writeFileSync as writeFileSync8 } from "fs";
5515
+ import { join as join15 } from "path";
5099
5516
 
5100
5517
  // src/scorecard-rubric.ts
5101
5518
  var UX_SCORECARD_PROMPT_VERSION = "ux-scorecard-2026-11-21.2";
@@ -5662,22 +6079,22 @@ function captureFolder(key) {
5662
6079
  return key.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).join("-").slice(0, 110) || "root";
5663
6080
  }
5664
6081
  function writeCapture(dir, c) {
5665
- const folder = join13(dir, "pages", captureFolder(c.facts.key));
5666
- mkdirSync8(folder, { recursive: true });
5667
- writeFileSync7(join13(folder, "facts.json"), JSON.stringify(c.facts, null, 2));
5668
- writeFileSync7(join13(folder, "early.png"), c.early);
5669
- writeFileSync7(join13(folder, "settled.png"), c.settled);
6082
+ const folder = join15(dir, "pages", captureFolder(c.facts.key));
6083
+ mkdirSync10(folder, { recursive: true });
6084
+ writeFileSync8(join15(folder, "facts.json"), JSON.stringify(c.facts, null, 2));
6085
+ writeFileSync8(join15(folder, "early.png"), c.early);
6086
+ writeFileSync8(join15(folder, "settled.png"), c.settled);
5670
6087
  return folder;
5671
6088
  }
5672
6089
  function readCaptures(dir) {
5673
- const root = join13(dir, "pages");
5674
- if (!existsSync5(root)) return [];
6090
+ const root = join15(dir, "pages");
6091
+ if (!existsSync7(root)) return [];
5675
6092
  const out = [];
5676
6093
  for (const name of readdirSync5(root).sort()) {
5677
- const folder = join13(root, name);
5678
- const file = join13(folder, "facts.json");
5679
- if (!existsSync5(file)) continue;
5680
- const facts = JSON.parse(readFileSync10(file, "utf8"));
6094
+ const folder = join15(root, name);
6095
+ const file = join15(folder, "facts.json");
6096
+ if (!existsSync7(file)) continue;
6097
+ const facts = JSON.parse(readFileSync12(file, "utf8"));
5681
6098
  out.push({ folder, facts: { ...facts, key: scorecardPageKey(facts.key || facts.path) } });
5682
6099
  }
5683
6100
  return out;
@@ -5686,13 +6103,13 @@ function localScorer(via, model, client) {
5686
6103
  const ask = async (prompt, folder, images) => {
5687
6104
  if (via === "claude-code") return askClaudeCode(prompt, folder, model, void 0, images.length + 3);
5688
6105
  if (via === "cursor") return askCursor(prompt, folder, model);
5689
- const bufs = images.map((n) => readFileSync10(join13(folder, n)));
6106
+ const bufs = images.map((n) => readFileSync12(join15(folder, n)));
5690
6107
  return askApi(prompt, bufs, model, client ?? new Anthropic4(), images);
5691
6108
  };
5692
6109
  return {
5693
6110
  name: `${via}:${model}`,
5694
6111
  async score(facts, folder, ctx) {
5695
- const images = ["early.png", "settled.png"].filter((n) => existsSync5(join13(folder, n)));
6112
+ const images = ["early.png", "settled.png"].filter((n) => existsSync7(join15(folder, n)));
5696
6113
  const prompt = `${pageSystemPrompt()}
5697
6114
 
5698
6115
  ${pageUserPrompt(facts, { ...ctx, images })}`;
@@ -5704,8 +6121,8 @@ ${pageUserPrompt(facts, { ...ctx, images })}`;
5704
6121
  async group(pages, base, priorKeys) {
5705
6122
  if (pages.length < 2) return { causes: [...base] };
5706
6123
  const p = groupingPrompt(pages, priorKeys);
5707
- const dir = join13(auditHome(), "scorecard-group");
5708
- mkdirSync8(dir, { recursive: true });
6124
+ const dir = join15(auditHome(), "scorecard-group");
6125
+ mkdirSync10(dir, { recursive: true });
5709
6126
  const a = await ask(`${p.system}
5710
6127
 
5711
6128
  ${p.user}`, dir, []);
@@ -5728,18 +6145,27 @@ function apiError(r) {
5728
6145
  }
5729
6146
  async function uploadShots(cfg, runId, folder, key) {
5730
6147
  const base = captureFolder(key);
5731
- const names = ["early", "settled"].filter((n) => existsSync5(join13(folder, `${n}.png`))).map((n) => `${base}/${n}.png`);
6148
+ const names = ["early", "settled"].filter((n) => existsSync7(join15(folder, `${n}.png`))).map((n) => `${base}/${n}.png`);
5732
6149
  if (!names.length) return [];
5733
6150
  const r = await api2(cfg, `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}/uploads`, { method: "POST", body: JSON.stringify({ names }) });
5734
6151
  if (!r.ok) throw new Error(`Screenshots not uploaded: ${apiError(r)}`);
5735
6152
  const uploads = r.body?.data?.uploads ?? [];
5736
6153
  for (const u of uploads) {
5737
- const png = readFileSync10(join13(folder, u.name.split("/").pop()));
6154
+ const png = readFileSync12(join15(folder, u.name.split("/").pop()));
5738
6155
  const put = await fetch(u.signedUrl, { method: "PUT", headers: { "Content-Type": "image/png" }, body: new Uint8Array(png) });
5739
6156
  if (!put.ok) throw new Error(`Screenshot ${u.name} not uploaded: storage answered ${put.status}`);
5740
6157
  }
5741
6158
  return names;
5742
6159
  }
6160
+ function settledShotHash(folder) {
6161
+ const file = join15(folder, "settled.png");
6162
+ if (!existsSync7(file)) return null;
6163
+ try {
6164
+ return dHash(readFileSync12(file));
6165
+ } catch {
6166
+ return null;
6167
+ }
6168
+ }
5743
6169
  function serverScorer(cfg, runId) {
5744
6170
  const uploaded = /* @__PURE__ */ new Map();
5745
6171
  return {
@@ -5748,9 +6174,10 @@ function serverScorer(cfg, runId) {
5748
6174
  async score(facts, folder, ctx) {
5749
6175
  const shots = await uploadShots(cfg, runId, folder, facts.key);
5750
6176
  uploaded.set(facts.key, shots);
6177
+ const shotHash = settledShotHash(folder);
5751
6178
  const r = await api2(cfg, `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}/score`, {
5752
6179
  method: "POST",
5753
- body: JSON.stringify({ facts, shots, app: ctx.app, about: ctx.about, other_pages: ctx.otherPages })
6180
+ body: JSON.stringify({ facts, shots, app: ctx.app, about: ctx.about, other_pages: ctx.otherPages, ...shotHash ? { shot_hash: shotHash } : {} })
5754
6181
  });
5755
6182
  if (!r.ok) return { error: apiError(r) };
5756
6183
  const score = r.body?.data?.score;
@@ -5808,7 +6235,7 @@ async function captureAll(opts, dir, progress) {
5808
6235
  } catch (err) {
5809
6236
  const key = scorecardPageKey(path);
5810
6237
  const msg = err.message.split("\n")[0].slice(0, 300);
5811
- out.push({ folder: join13(dir, "pages", captureFolder(key)), facts: blankFacts(key, path, viewport), error: `Not captured: ${msg}` });
6238
+ out.push({ folder: join15(dir, "pages", captureFolder(key)), facts: blankFacts(key, path, viewport), error: `Not captured: ${msg}` });
5812
6239
  progress(`could not capture ${path}: ${msg}`);
5813
6240
  } finally {
5814
6241
  await ctx.close();
@@ -5832,8 +6259,8 @@ async function pool(items, n, fn) {
5832
6259
  async function runScorecard(opts) {
5833
6260
  const progress = opts.onProgress ?? (() => {
5834
6261
  });
5835
- const dir = opts.outDir ?? opts.fromCaptures ?? join13(auditHome(), `scorecard-${opts.runId}`);
5836
- mkdirSync8(dir, { recursive: true });
6262
+ const dir = opts.outDir ?? opts.fromCaptures ?? join15(auditHome(), `scorecard-${opts.runId}`);
6263
+ mkdirSync10(dir, { recursive: true });
5837
6264
  const captured = opts.fromCaptures ? readCaptures(opts.fromCaptures) : await captureAll(opts, dir, progress);
5838
6265
  if (!captured.length) throw new Error(opts.fromCaptures ? `No captures in ${opts.fromCaptures}/pages.` : "No pages to score.");
5839
6266
  const labels = captured.map((c) => c.facts.label);
@@ -5864,8 +6291,8 @@ async function runScorecard(opts) {
5864
6291
  rows: scorecardRows(scored, opts.history ?? []),
5865
6292
  causes: grouped.causes
5866
6293
  });
5867
- writeFileSync7(join13(dir, "scorecard.md"), markdown);
5868
- writeFileSync7(join13(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));
6294
+ writeFileSync8(join15(dir, "scorecard.md"), markdown);
6295
+ writeFileSync8(join15(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));
5869
6296
  return { runId: opts.runId, dir, pages: results, causes: grouped.causes, ...grouped.error ? { groupError: grouped.error } : {}, markdown };
5870
6297
  }
5871
6298
  async function syncScorecard(cfg, input) {
@@ -5909,125 +6336,673 @@ async function scorecardContext(cfg) {
5909
6336
  };
5910
6337
  }
5911
6338
 
5912
- // src/profile.ts
5913
- import { homedir as homedir2 } from "os";
5914
- import { resolve as resolve2 } from "path";
5915
- function cachedProfile(o, home = homedir2()) {
5916
- if (!o.profileDir?.trim()) return null;
5917
- const raw = o.profileDir.trim();
5918
- const dir = raw === "~" ? home : raw.startsWith("~/") ? resolve2(home, raw.slice(2)) : resolve2(raw);
5919
- return { profileDir: dir, channel: o.channel === "chromium" ? "chromium" : "chrome" };
5920
- }
5921
- function parseChannel(v) {
5922
- if (v !== "chrome" && v !== "chromium") throw new Error("--channel is chrome or chromium");
5923
- return v;
5924
- }
5925
-
5926
- // src/launcher.ts
5927
- import { existsSync as existsSync8, readdirSync as readdirSync8, readFileSync as readFileSync13 } from "fs";
5928
- import { join as join16 } from "path";
5929
-
5930
- // src/skills.ts
5931
- import { closeSync as closeSync3, existsSync as existsSync7, fstatSync as fstatSync3, openSync as openSync3, readdirSync as readdirSync7, readFileSync as readFileSync12 } from "fs";
5932
- import { basename as basename2, dirname as dirname4, join as join15, relative as relative4, sep as sep2 } from "path";
5933
-
5934
- // src/packet.ts
5935
- import { closeSync as closeSync2, existsSync as existsSync6, fstatSync as fstatSync2, openSync as openSync2, readdirSync as readdirSync6, readFileSync as readFileSync11 } from "fs";
5936
- import { join as join14, relative as relative3 } from "path";
5937
- var MAX_PACKET_CHARS = 24e3;
5938
- var MAX_SKILL_CHARS = 12e3;
5939
- var DEFAULT_GUIDANCE = `Improve this one screen's UI and UX. In order of priority:
5940
- 1. Fix every measured problem listed below (accessibility violations, sideways scrolling, tap targets under 24\xD724 px, console errors).
5941
- 2. Make the primary action obvious: one clear call to action, visual hierarchy that matches importance.
5942
- 3. Cut noise: shorter copy, group related controls, remove duplicated information, use icons and colour to carry meaning where text is long.
5943
- 4. Spacing and alignment on the design system's scale; readable line length; consistent type sizes.
5944
- 5. The mobile screenshot must work as well as the desktop one.`;
5945
- var GUARDRAILS = `Rules:
5946
- - Change only what this screen needs. Shared components and design tokens affect every other screen; edit them only when the fix truly belongs there, and say so in your final message.
5947
- - Use the existing design tokens, components and icon set. Do not add dependencies.
5948
- - Do not change data fetching, API calls, auth, routing, state management or tests.
5949
- - Do not run the dev server, install packages, or commit. The tool reviews and commits your edits.
5950
- - Do not modify anything under .mushi-ux/. Read only the screenshots and skill files you are pointed to.
5951
- - Do not read or change node_modules or the framework's own code. A problem that comes from there is not yours to fix: say so and move on.
5952
- - If the screen is already good, make no edits and say why.`;
5953
- var MAX_STEP_FILES = 6;
5954
- var MAX_PLAN_STEPS = 5;
5955
- var PLAN_READ_BUDGET = 6;
5956
- function buildPlanPacket(input, maxSteps) {
5957
- const { surface } = input;
5958
- const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p));
5959
- const sections = [
5960
- `# UX plan \u2014 ${surface.label}`,
5961
- `Screen: \`${surface.path}\` (${surface.kind}). Plan only: do not edit any file except \`.mushi-ux/PLAN.md\`.`,
5962
- input.timeBudgetMin ? `## Time
5963
- You have ${input.timeBudgetMin} minutes. Look, decide, write the list.` : "",
5964
- input.entryFiles?.length ? `## Start here
5965
- These files render this screen:
5966
- ${input.entryFiles.map((f) => `- ${f}`).join("\n")}` : "",
5967
- `## Screenshots (read these images first)
5968
- ${Object.entries(input.shots).map(([vp, p]) => `- ${vp}: ${p}`).join("\n")}
5969
- Your read tool opens them as images where they are: do not copy them anywhere.`,
5970
- `## Measured problems
5971
- ${findings.length ? findings.join("\n") : "- None measured."}`,
5972
- input.skillText ? `## Guidance
5973
- Use this skill to choose what to improve on this one screen (its supporting files are in \`${input.skillDir ?? ".mushi-ux/skill"}/\`):
6339
+ // src/upload.ts
6340
+ import { closeSync as closeSync2, existsSync as existsSync9, fstatSync as fstatSync2, openSync as openSync2, readdirSync as readdirSync6, readFileSync as readFileSync14, readSync, statSync as statSync4 } from "fs";
6341
+ import { join as join17 } from "path";
5974
6342
 
5975
- ${input.skillText.slice(0, MAX_SKILL_CHARS)}` : `## Guidance
5976
- ${DEFAULT_GUIDANCE}`,
5977
- `## What to do
5978
- List 2 to ${maxSteps} small, separate improvements for this screen, most valuable first. Each must be one focused change a developer could make in a few minutes, touching at most 3 files, that does not depend on the others. Start each item with a short summary a user of the app would understand, without file or code names, then a colon, then the change, naming the component or file it changes (for example "- Make the caption readable: in \`x.tsx\`, ..."). Open at most ${PLAN_READ_BUDGET} source files besides the "Start here" ones; each step's own attempt reads the rest. Write them to \`.mushi-ux/PLAN.md\`, one per line starting with "- ", within your first 2 minutes, from the screenshots and the "Start here" files alone; then refine the file if you have time, and reply with the same list. You are stopped when the time is up, and a missing PLAN.md wastes the whole pass. Do not edit any other file: each item gets its own attempt later.`,
5979
- `## Rules
5980
- - Do not install anything, and do not run scripts on the screenshots: look at them.
5981
- - Do not read or change node_modules or the framework's own code.
5982
- - Do not plan changes to data fetching, API calls, auth, routing, state management or tests.
5983
- - If the screen is already good, write fewer items.`
5984
- ];
5985
- return sections.filter(Boolean).join("\n\n").slice(0, MAX_PACKET_CHARS);
6343
+ // src/native-facts.ts
6344
+ var MAX_TEXT2 = 12e3;
6345
+ var MAX_CONTROLS = 120;
6346
+ var MAX_HEADINGS = 40;
6347
+ var XML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
6348
+ function decodeXml(s) {
6349
+ return s.replace(/&(amp|lt|gt|quot|apos|#\d{1,7}|#x[0-9a-f]{1,6});/gi, (_, e) => {
6350
+ if (e[0] === "#") {
6351
+ const code = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
6352
+ return Number.isFinite(code) && code > 0 && code < 1114112 ? String.fromCodePoint(code) : "";
6353
+ }
6354
+ return XML_ENTITIES[e.toLowerCase()] ?? "";
6355
+ });
5986
6356
  }
5987
- function parsePlan(text, max = MAX_PLAN_STEPS) {
6357
+ var clean = (t) => t.replace(/\s+/g, " ").trim();
6358
+ function parseUiautomator(xml) {
5988
6359
  const out = [];
5989
- for (const line of text.split(/\r?\n/)) {
5990
- const m = line.match(/^\s*(?:[-*•]|\d+[.)])\s+(?:\[[ xX]\]\s*)?(.+?)\s*$/);
5991
- const item = m?.[1]?.replace(/\*\*/g, "").replace(/&(amp|lt|gt|quot|#39);/g, (_, e) => ({ amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'" })[e] ?? _).trim();
5992
- if (!item || item.length < 8 || out.includes(item)) continue;
5993
- out.push(cutAtWord(item, 280));
5994
- if (out.length >= max) break;
6360
+ for (const m of xml.matchAll(/<node\b([^>]*?)\/?>/g)) {
6361
+ const attrs = {};
6362
+ for (const a of m[1].matchAll(/\s([\w:-]+)="([^"]*)"/g)) attrs[a[1]] = decodeXml(a[2]);
6363
+ const bounds = /^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(attrs.bounds ?? "");
6364
+ const visible = attrs["visible-to-user"] !== "false" && (!bounds || Number(bounds[3]) > Number(bounds[1]) && Number(bounds[4]) > Number(bounds[2]));
6365
+ out.push({
6366
+ text: clean(attrs.text ?? ""),
6367
+ label: clean(attrs["content-desc"] ?? ""),
6368
+ className: attrs.class ?? "",
6369
+ clickable: attrs.clickable === "true",
6370
+ heading: attrs.heading === "true",
6371
+ visible
6372
+ });
5995
6373
  }
5996
6374
  return out;
5997
6375
  }
5998
- function cutAtWord(text, max) {
5999
- if (text.length <= max) return text;
6000
- const head = text.slice(0, max - 1);
6001
- const space = head.lastIndexOf(" ");
6002
- let cut = (space > max / 2 ? head.slice(0, space) : head).replace(/[\s,;:.(-]+$/, "");
6003
- if ((cut.match(/`/g)?.length ?? 0) % 2 === 1) cut = cut.slice(0, cut.lastIndexOf("`")).trimEnd();
6004
- return `${cut}\u2026`;
6005
- }
6006
- var PLAN_POINTER_PROMPT = "Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It asks for a plan only: write .mushi-ux/PLAN.md and edit nothing else.";
6007
- function describeProbes(viewport, p) {
6008
- const lines = [];
6009
- for (const v of p.axe) {
6010
- lines.push(`- [${viewport}] ${v.id} (${v.impact ?? "n/a"}, ${v.count} node${v.count === 1 ? "" : "s"}): ${v.help} \u2014 e.g. ${v.targets.slice(0, 3).join(", ")}`);
6376
+ function parseMaestroHierarchy(json) {
6377
+ let root;
6378
+ try {
6379
+ root = JSON.parse(json);
6380
+ } catch {
6381
+ return [];
6011
6382
  }
6012
- if (p.overflowX) lines.push(`- [${viewport}] The page scrolls sideways at this width.`);
6013
- if (p.smallTargets > 0) lines.push(`- [${viewport}] ${p.smallTargets} tap target(s) smaller than 24\xD724 px.`);
6014
- for (const i of p.layout ?? []) lines.push(`- [${viewport}] ${i.kind === "overlap" ? "Overlap" : "Too big"}: ${i.selector} ${i.detail}.`);
6015
- for (const e of p.consoleErrors.slice(0, 5)) lines.push(`- [${viewport}] Console error: ${e}`);
6016
- if (p.cls > CLS_GOOD) lines.push(`- [${viewport}] Layout shift ${p.cls} while loading (aim below ${CLS_GOOD}).`);
6017
- return lines;
6383
+ const out = [];
6384
+ const stack = [root];
6385
+ while (stack.length && out.length < 5e3) {
6386
+ const n = stack.pop();
6387
+ const a = n.attributes ?? {};
6388
+ const str3 = (k) => typeof a[k] === "string" ? clean(a[k]) : "";
6389
+ const flag = (k) => a[k] === true || a[k] === "true";
6390
+ if (Object.keys(a).length) {
6391
+ out.push({
6392
+ text: str3("text"),
6393
+ label: str3("accessibilityText") || str3("content-desc") || str3("hintText"),
6394
+ className: str3("class") || str3("elementType"),
6395
+ clickable: flag("clickable") || /button/i.test(str3("class") || str3("elementType")),
6396
+ heading: flag("heading") || /header/i.test(str3("traits")),
6397
+ visible: a.visible !== false && a.visible !== "false"
6398
+ });
6399
+ }
6400
+ for (const c of [...n.children ?? []].reverse()) stack.push(c);
6401
+ }
6402
+ return out;
6018
6403
  }
6019
- function buildPacket(input) {
6020
- const { surface } = input;
6021
- const steps = surface.steps.length ? ` then click ${surface.steps.map((s) => `"${s.label}"`).join(" \u2192 ")}` : "";
6022
- const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p));
6023
- const skill = input.skillText ? [
6024
- `Apply this skill to this one screen only. Skip its whole-app steps (stack detection, scoring every screen, app-wide inventories): another pass handles each other screen. Its supporting files (references, scorecards) are in \`${input.skillDir ?? ".mushi-ux/skill"}/\`; read only the ones this screen needs.`,
6025
- input.skillText.slice(0, MAX_SKILL_CHARS)
6026
- ].join("\n\n") : DEFAULT_GUIDANCE;
6027
- const sections = [
6028
- `# UX pass \u2014 ${surface.label}`,
6029
- `Screen: \`${surface.path}\`${steps} (${surface.kind}). Attempt ${input.iteration}.`,
6030
- input.timeBudgetMin ? `## Time
6404
+ function nodesToContent(nodes) {
6405
+ const words = [];
6406
+ const controls = [];
6407
+ const headings = [];
6408
+ for (const n of nodes) {
6409
+ if (!n.visible) continue;
6410
+ const said = n.text || n.label;
6411
+ if (!said) continue;
6412
+ if (words[words.length - 1] !== said) words.push(said);
6413
+ if (n.clickable && said.length <= 80 && !controls.includes(said) && controls.length < MAX_CONTROLS) controls.push(said);
6414
+ if (n.heading && said.length <= 200 && !headings.includes(said) && headings.length < MAX_HEADINGS) headings.push(said);
6415
+ }
6416
+ return { text: words.join("\n").slice(0, MAX_TEXT2), controls, headings };
6417
+ }
6418
+ function pngSize2(bytes) {
6419
+ const sig = [137, 80, 78, 71, 13, 10, 26, 10];
6420
+ if (bytes.length < 24 || sig.some((b, i) => bytes[i] !== b)) return null;
6421
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
6422
+ if (String.fromCharCode(bytes[12], bytes[13], bytes[14], bytes[15]) !== "IHDR") return null;
6423
+ const width = view.getUint32(16);
6424
+ const height = view.getUint32(20);
6425
+ return width > 0 && height > 0 ? { width, height } : null;
6426
+ }
6427
+ function screenPath(name) {
6428
+ const slug = name.toLowerCase().split(/[^a-z0-9/]+/).filter(Boolean).join("-").replace(/\/+/g, "/").replace(/^\/|\/$/g, "");
6429
+ return `/${slug || "screen"}`.slice(0, 500);
6430
+ }
6431
+ var clampDim = (n) => Math.max(200, Math.min(4e3, Math.round(n)));
6432
+ function nativeFacts(input) {
6433
+ const g = input.given ?? {};
6434
+ const content = input.nodes?.length ? nodesToContent(input.nodes) : { text: "", controls: [], headings: [] };
6435
+ 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);
6436
+ const key = typeof g.key === "string" && g.key ? g.key.slice(0, 500) : path;
6437
+ const scale = input.scale && input.scale > 0 ? input.scale : 1;
6438
+ 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 };
6439
+ const label = typeof g.label === "string" && g.label ? g.label.slice(0, 300) : content.headings[0] ?? input.folder.replace(/[-_]+/g, " ").slice(0, 300);
6440
+ return {
6441
+ key,
6442
+ path,
6443
+ label,
6444
+ title: typeof g.title === "string" ? g.title.slice(0, 300) : label,
6445
+ ...typeof g.breadcrumb === "string" ? { breadcrumb: g.breadcrumb.slice(0, 300) } : {},
6446
+ headings: Array.isArray(g.headings) ? g.headings.slice(0, MAX_HEADINGS).map((h) => String(h).slice(0, 200)) : content.headings,
6447
+ text: typeof g.text === "string" ? g.text.slice(0, MAX_TEXT2) : content.text,
6448
+ controls: Array.isArray(g.controls) ? g.controls.slice(0, MAX_CONTROLS).map((c) => String(c).slice(0, 120)) : content.controls,
6449
+ ...typeof g.earlyText === "string" ? { earlyText: g.earlyText.slice(0, 4e3) } : {},
6450
+ settleMs: typeof g.settleMs === "number" && g.settleMs >= 0 ? Math.min(6e5, Math.round(g.settleMs)) : null,
6451
+ axe: g.axe ?? null,
6452
+ overflowX: g.overflowX === true,
6453
+ consoleErrors: typeof g.consoleErrors === "number" && g.consoleErrors >= 0 ? Math.min(1e4, Math.round(g.consoleErrors)) : 0,
6454
+ cls: typeof g.cls === "number" && g.cls >= 0 ? Math.min(100, g.cls) : 0,
6455
+ viewport: vp
6456
+ };
6457
+ }
6458
+
6459
+ // src/sync.ts
6460
+ import { existsSync as existsSync8, readFileSync as readFileSync13 } from "fs";
6461
+ import { join as join16 } from "path";
6462
+ var CLOUD_API_ENDPOINT = "https://dxptnwrhwsqckaftyymj.supabase.co/functions/v1/api";
6463
+ var HOSTED_CONSOLE_URL = "https://kensaur.us/mushi-mushi/admin";
6464
+ function consoleBaseUrl(env = process.env) {
6465
+ return trimTrailingSlashes(env.MUSHI_CONSOLE_URL?.trim() || HOSTED_CONSOLE_URL);
6466
+ }
6467
+ var VIEWPORT_NAMES = ["desktop", "mobile"];
6468
+ var UPLOAD_BATCH = 40;
6469
+ function syncConfigFromEnv(env = process.env) {
6470
+ const apiKey = env.MUSHI_API_KEY?.trim();
6471
+ const projectId = env.MUSHI_PROJECT_ID?.trim();
6472
+ if (!apiKey || !projectId) return null;
6473
+ return {
6474
+ apiKey,
6475
+ projectId,
6476
+ endpoint: trimTrailingSlashes(env.MUSHI_API_ENDPOINT?.trim() || CLOUD_API_ENDPOINT),
6477
+ mode: env.GITHUB_ACTIONS === "true" ? "cloud" : "local"
6478
+ };
6479
+ }
6480
+ var PROJECT_LINE_RE = /^\s*(?:NEXT_PUBLIC_|VITE_|EXPO_PUBLIC_|PUBLIC_)?MUSHI_PROJECT_ID\s*=\s*["']?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})["']?\s*$/im;
6481
+ function repoProjectId(repoRoot) {
6482
+ for (const name of [".env.local", ".env.development.local", ".env.development", ".env"]) {
6483
+ const file = join16(repoRoot, name);
6484
+ if (!existsSync8(file)) continue;
6485
+ const m = readFileSync13(file, "utf8").match(PROJECT_LINE_RE);
6486
+ if (m) return m[1];
6487
+ }
6488
+ return null;
6489
+ }
6490
+ function syncProjectMismatch(cfg, repoRoot) {
6491
+ const repoProject = repoProjectId(repoRoot);
6492
+ if (!repoProject || repoProject === cfg.projectId) return null;
6493
+ return `This repo's app reports to Mushi project ${repoProject}, but your login is for ${cfg.projectId}. Run \`mushi login\` and pick this app's project (or set MUSHI_PROJECT_ID), so the run lands on the right project.`;
6494
+ }
6495
+ function probeSummary(p) {
6496
+ if (!p) return null;
6497
+ return {
6498
+ axe: p.axe.map((v) => ({ id: v.id, impact: v.impact, help: v.help.slice(0, 300), count: v.count })).slice(0, 60),
6499
+ overflowX: p.overflowX,
6500
+ smallTargets: p.smallTargets,
6501
+ consoleErrors: p.consoleErrors.length,
6502
+ cls: p.cls
6503
+ };
6504
+ }
6505
+ function syncableStep(line) {
6506
+ if (/^\[(read|edit)\] \S/.test(line)) return line.slice(0, 300);
6507
+ if (line.startsWith("[run] ")) return "[run] a command";
6508
+ if (line.startsWith("[find] ")) return "[find] a search";
6509
+ if (line === "[done] Finished") return line;
6510
+ return null;
6511
+ }
6512
+ function syncableSteps(log) {
6513
+ const kept = (log ?? "").split("\n").map(syncableStep).filter((l) => l !== null);
6514
+ return kept.length ? kept.join("\n").slice(-2e3) : null;
6515
+ }
6516
+ function worstPenalty(shots) {
6517
+ const scores = Object.values(shots).flatMap((r) => r && typeof r.penalty === "number" ? [r.penalty] : []);
6518
+ return scores.length ? Math.max(...scores) : null;
6519
+ }
6520
+ function lastKept(s) {
6521
+ return [...s.iterations].reverse().find((i) => i.outcome === "accepted") ?? null;
6522
+ }
6523
+ function wantedShots(state) {
6524
+ const out = [];
6525
+ for (const s of state.surfaces) {
6526
+ const key = s.surface.key;
6527
+ const kept = lastKept(s);
6528
+ for (const vp of VIEWPORT_NAMES) {
6529
+ const before = s.baseline[vp]?.png;
6530
+ if (before) out.push({ name: `${key}/before-${vp}.png`, rel: before });
6531
+ const after = kept?.after[vp]?.png;
6532
+ if (after) out.push({ name: `${key}/after-${vp}.png`, rel: after });
6533
+ const diff = kept?.diffPng[vp];
6534
+ if (diff) out.push({ name: `${key}/diff-${vp}.png`, rel: diff });
6535
+ for (const it of s.iterations) {
6536
+ if (it.after[vp]?.png) out.push({ name: `${key}/iter${it.n}-after-${vp}.png`, rel: it.after[vp].png });
6537
+ if (it.diffPng[vp]) out.push({ name: `${key}/iter${it.n}-diff-${vp}.png`, rel: it.diffPng[vp] });
6538
+ }
6539
+ }
6540
+ }
6541
+ return out;
6542
+ }
6543
+ function toSnapshot(state, finished, uploaded, mode = "local") {
6544
+ const have = (name) => uploaded.has(name) ? name : null;
6545
+ const status = state.stopped ? "stopped" : state.phase === "failed" ? "failed" : finished ? "done" : "running";
6546
+ return {
6547
+ mode,
6548
+ status,
6549
+ agent: state.agent,
6550
+ model: state.model,
6551
+ judge_model: state.judgeModel ?? null,
6552
+ ...state.judgeUsage ? { judge_usage: state.judgeUsage } : {},
6553
+ skill: state.skill?.name?.slice(0, 120) ?? null,
6554
+ base_ref: state.baseRef?.slice(0, 200) ?? null,
6555
+ phase: state.phase ?? null,
6556
+ phase_detail: state.phaseDetail?.slice(0, 300) ?? null,
6557
+ current_surface: state.current?.surface ?? null,
6558
+ current_attempt: state.current?.attempt ?? null,
6559
+ current_progress: state.current ? {
6560
+ steps: state.current.steps ?? 0,
6561
+ last_step: state.current.lastStep ? syncableStep(state.current.lastStep) : null,
6562
+ files: (state.current.files ?? []).slice(0, 20).map((f) => f.slice(0, 300)),
6563
+ started_at: state.current.startedAt,
6564
+ timeout_ms: state.current.timeoutMs ?? null
6565
+ } : null,
6566
+ error: state.error?.slice(0, 1e3) ?? null,
6567
+ branch: state.branch,
6568
+ base_sha: state.baseSha,
6569
+ cli_version: null,
6570
+ ...state.pr ? { pr: { url: state.pr.url, number: state.pr.number } } : {},
6571
+ started_at: state.createdAt,
6572
+ finished_at: finished || status === "failed" ? state.finishedAt ?? (/* @__PURE__ */ new Date()).toISOString() : null,
6573
+ surfaces: state.surfaces.map((s) => {
6574
+ const kept = lastKept(s);
6575
+ const key = s.surface.key;
6576
+ const shots = {};
6577
+ for (const vp of VIEWPORT_NAMES) {
6578
+ for (const kind of ["before", "after", "diff"]) {
6579
+ const name = have(`${key}/${kind}-${vp}.png`);
6580
+ if (name) shots[`${kind}-${vp}`] = name;
6581
+ }
6582
+ }
6583
+ return {
6584
+ surface_key: key,
6585
+ kind: s.surface.kind,
6586
+ path: s.surface.path,
6587
+ label: s.surface.label.slice(0, 300),
6588
+ status: s.status,
6589
+ note: s.note?.slice(0, 1e3) ?? null,
6590
+ // Small-steps mode: the plan as a checklist (the step texts are the agent's own plan, file names included).
6591
+ plan: s.plan?.steps.length ? s.plan.steps.slice(0, 8).map((p) => ({ text: p.text.slice(0, 300), status: p.status, attempt: p.attempt ?? null })) : null,
6592
+ penalty_before: worstPenalty(s.baseline),
6593
+ penalty_after: kept ? worstPenalty(kept.after) : null,
6594
+ probe_before: probeSummary(s.baseline.desktop?.probes),
6595
+ probe_after: probeSummary(kept?.after.desktop?.probes),
6596
+ judge: s.judge?.length ? s.judge.map((j) => ({
6597
+ viewport: j.viewport,
6598
+ model: j.model,
6599
+ preferred: j.preferred,
6600
+ confidence: j.confidence,
6601
+ summary: j.summary.slice(0, 2e3),
6602
+ better: j.better.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),
6603
+ worse: j.worse.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),
6604
+ ...j.error ? { error: j.error.slice(0, 500) } : {}
6605
+ })) : null,
6606
+ thumbs: { before: shots["before-desktop"] ?? null, after: shots["after-desktop"] ?? null, diff: shots["diff-desktop"] ?? null },
6607
+ shots,
6608
+ iterations: s.iterations.map((it) => {
6609
+ const itShots = {};
6610
+ for (const vp of VIEWPORT_NAMES) {
6611
+ for (const kind of ["after", "diff"]) {
6612
+ const name = have(`${key}/iter${it.n}-${kind}-${vp}.png`);
6613
+ if (name) itShots[`${kind}-${vp}`] = name;
6614
+ }
6615
+ }
6616
+ return {
6617
+ n: it.n,
6618
+ agent: it.agent,
6619
+ model: it.model,
6620
+ duration_ms: it.durationMs,
6621
+ outcome: it.outcome,
6622
+ reason: it.reason.slice(0, 1e3),
6623
+ commit_sha: it.commitSha,
6624
+ pixel_diff: it.pixelDiff,
6625
+ penalty_after: worstPenalty(it.after),
6626
+ steps: syncableSteps(it.logTail),
6627
+ step: it.step?.slice(0, 300) ?? null,
6628
+ shots: itShots
6629
+ };
6630
+ })
6631
+ };
6632
+ })
6633
+ };
6634
+ }
6635
+ function startSync(dir, cfg, events, log) {
6636
+ const uploaded = /* @__PURE__ */ new Map();
6637
+ let timer = null;
6638
+ let running = Promise.resolve();
6639
+ let lastError = null;
6640
+ let warned = false;
6641
+ const headers2 = {
6642
+ Authorization: `Bearer ${cfg.apiKey}`,
6643
+ "X-Mushi-Api-Key": cfg.apiKey,
6644
+ "X-Mushi-Project": cfg.projectId,
6645
+ "Content-Type": "application/json"
6646
+ };
6647
+ async function api4(method, path, body) {
6648
+ const res = await fetch(`${cfg.endpoint}/v1/admin/projects/${cfg.projectId}/ux-runs/${path}`, {
6649
+ method,
6650
+ headers: headers2,
6651
+ body: JSON.stringify(body),
6652
+ signal: AbortSignal.timeout(3e4)
6653
+ });
6654
+ const json = await res.json().catch(() => null);
6655
+ if (json?.error?.code === "INSUFFICIENT_SCOPE") {
6656
+ throw new Error("this Mushi key cannot write to the console. Run `mushi login` (browser sign-in) for a key that can, then retry");
6657
+ }
6658
+ if (!res.ok || !json?.ok) throw new Error(json?.error?.message ?? `HTTP ${res.status}`);
6659
+ return json.data;
6660
+ }
6661
+ async function uploadShots2(state) {
6662
+ const todo = wantedShots(state).filter((w) => uploaded.get(w.name) !== w.rel);
6663
+ for (let i = 0; i < todo.length; i += UPLOAD_BATCH) {
6664
+ const batch = todo.slice(i, i + UPLOAD_BATCH);
6665
+ const data = await api4("POST", `${state.runId}/uploads`, { names: batch.map((w) => w.name) });
6666
+ for (const u of data.uploads) {
6667
+ const want = batch.find((w) => w.name === u.name);
6668
+ if (!want) continue;
6669
+ const png = cropTop(readFileSync13(join16(dir, want.rel)), 2400);
6670
+ const put = await fetch(u.signedUrl, {
6671
+ method: "PUT",
6672
+ headers: { "Content-Type": "image/png", "x-upsert": "true" },
6673
+ body: new Uint8Array(png),
6674
+ signal: AbortSignal.timeout(6e4)
6675
+ });
6676
+ if (!put.ok) throw new Error(`screenshot upload failed (HTTP ${put.status})`);
6677
+ uploaded.set(want.name, want.rel);
6678
+ }
6679
+ }
6680
+ }
6681
+ async function syncOnce(finished) {
6682
+ const state = loadState(dir);
6683
+ if (!state) return;
6684
+ try {
6685
+ await api4("PUT", state.runId, toSnapshot(state, false, uploaded, cfg.mode));
6686
+ await uploadShots2(state);
6687
+ await api4("PUT", state.runId, toSnapshot(state, finished, uploaded, cfg.mode));
6688
+ lastError = null;
6689
+ } catch (err) {
6690
+ lastError = err.message;
6691
+ if (!warned) {
6692
+ log(`Console sync failed (will retry): ${lastError}`);
6693
+ warned = true;
6694
+ }
6695
+ }
6696
+ }
6697
+ const schedule = () => {
6698
+ if (timer) return;
6699
+ timer = setTimeout(() => {
6700
+ timer = null;
6701
+ running = running.then(() => syncOnce(false));
6702
+ }, 1500);
6703
+ };
6704
+ events.on("event", (e) => {
6705
+ if (e.type === "state" || e.type === "phase") schedule();
6706
+ });
6707
+ return {
6708
+ async finish() {
6709
+ if (timer) clearTimeout(timer);
6710
+ timer = null;
6711
+ await running;
6712
+ await syncOnce(true);
6713
+ return lastError;
6714
+ }
6715
+ };
6716
+ }
6717
+
6718
+ // src/upload.ts
6719
+ function sizeAndHead(file) {
6720
+ const fd = openSync2(file, "r");
6721
+ try {
6722
+ const head = Buffer.alloc(32);
6723
+ const n = readSync(fd, head, 0, 32, 0);
6724
+ return { size: fstatSync2(fd).size, head: head.subarray(0, n) };
6725
+ } finally {
6726
+ closeSync2(fd);
6727
+ }
6728
+ }
6729
+ var UPLOAD_PLATFORMS = ["ios", "android", "flutter", "react_native", "capacitor", "web", "other"];
6730
+ var UPLOAD_SOURCES = ["maestro", "adb", "simctl", "sdk", "playwright", "other"];
6731
+ var UPLOAD_MAX_PAGES = 60;
6732
+ var UPLOAD_MAX_PNG_BYTES = 8 * 1024 * 1024;
6733
+ function readScreens(dir, opts = {}) {
6734
+ const root = join17(dir, "pages");
6735
+ if (!existsSync9(root)) throw new Error(`No ${root} folder. Put each screen in <dir>/pages/<screen>/settled.png (see docs/templates/ux-native/).`);
6736
+ const out = [];
6737
+ for (const name of readdirSync6(root).sort()) {
6738
+ const folder = join17(root, name);
6739
+ if (!statSync4(folder).isDirectory()) continue;
6740
+ const shots = ["early", "settled"].filter((s) => existsSync9(join17(folder, `${s}.png`)));
6741
+ if (!shots.length) continue;
6742
+ let settledSize = null;
6743
+ for (const s of shots) {
6744
+ const file = join17(folder, `${s}.png`);
6745
+ const { size, head } = sizeAndHead(file);
6746
+ 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.`);
6747
+ const dims = pngSize2(head);
6748
+ 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.)`);
6749
+ if (s === "settled" || !settledSize) settledSize = dims;
6750
+ }
6751
+ let given = null;
6752
+ const factsFile = join17(folder, "facts.json");
6753
+ if (existsSync9(factsFile)) {
6754
+ try {
6755
+ given = JSON.parse(readFileSync14(factsFile, "utf8"));
6756
+ } catch {
6757
+ throw new Error(`${factsFile} is not valid JSON.`);
6758
+ }
6759
+ }
6760
+ let nodes = null;
6761
+ if (existsSync9(join17(folder, "window.xml"))) nodes = parseUiautomator(readFileSync14(join17(folder, "window.xml"), "utf8"));
6762
+ else if (existsSync9(join17(folder, "hierarchy.json"))) nodes = parseMaestroHierarchy(readFileSync14(join17(folder, "hierarchy.json"), "utf8"));
6763
+ const facts = nativeFacts({ folder: name, given, nodes, png: settledSize, scale: opts.scale });
6764
+ out.push({ folder, facts: { ...facts, key: scorecardPageKey(facts.key) }, shots: [...shots] });
6765
+ }
6766
+ if (!out.length) throw new Error(`No screenshots in ${root}: each screen needs a settled.png (or early.png).`);
6767
+ if (out.length > UPLOAD_MAX_PAGES) throw new Error(`${out.length} screens; one upload takes at most ${UPLOAD_MAX_PAGES}. Split the folder.`);
6768
+ const keys = /* @__PURE__ */ new Set();
6769
+ for (const s of out) {
6770
+ 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.`);
6771
+ keys.add(s.facts.key);
6772
+ }
6773
+ return out;
6774
+ }
6775
+ async function api3(cfg, path, init, fetchImpl) {
6776
+ const res = await fetchImpl(`${cfg.endpoint}${path}`, {
6777
+ ...init,
6778
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${cfg.apiKey}`, "X-Mushi-Api-Key": cfg.apiKey, "X-Mushi-Project-Id": cfg.projectId, ...init.headers ?? {} }
6779
+ });
6780
+ return { ok: res.ok, status: res.status, body: await res.json().catch(() => null) };
6781
+ }
6782
+ function apiError2(r) {
6783
+ const e = r.body?.error?.message;
6784
+ return `the API answered ${r.status}${e ? `: ${e.slice(0, 300)}` : ""}`;
6785
+ }
6786
+ async function pool2(items, n, fn) {
6787
+ let i = 0;
6788
+ const worker = async () => {
6789
+ while (i < items.length) await fn(items[i++]);
6790
+ };
6791
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(n, items.length)) }, worker));
6792
+ }
6793
+ async function uploadCaptures(cfg, opts) {
6794
+ const progress = opts.onProgress ?? (() => {
6795
+ });
6796
+ const doFetch = opts.fetchImpl ?? fetch;
6797
+ const screens = readScreens(opts.dir, { scale: opts.scale });
6798
+ progress(`${screens.length} screen(s) to upload (${opts.platform}${opts.device ? `, ${opts.device}` : ""})`);
6799
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
6800
+ const created = await api3(
6801
+ cfg,
6802
+ "/v1/ux/captures",
6803
+ {
6804
+ method: "POST",
6805
+ body: JSON.stringify({
6806
+ platform: opts.platform,
6807
+ ...opts.device ? { device: opts.device } : {},
6808
+ ...opts.source ? { source: opts.source } : {},
6809
+ ...opts.app ? { app: opts.app } : {},
6810
+ ...opts.viewport ? { viewport: opts.viewport } : {},
6811
+ ...opts.maxCostUsd !== void 0 ? { maxCostUsd: opts.maxCostUsd } : {},
6812
+ pages: screens.map((s) => ({ facts: s.facts, shots: s.shots }))
6813
+ })
6814
+ },
6815
+ doFetch
6816
+ );
6817
+ if (!created.ok) throw new Error(`The captures were not accepted: ${apiError2(created)}`);
6818
+ const d = created.body?.data;
6819
+ if (!d?.runId) throw new Error("The API returned no run id.");
6820
+ const runId = d.runId;
6821
+ const byKey = new Map(screens.map((s) => [s.facts.key, s]));
6822
+ const shotNames = /* @__PURE__ */ new Map();
6823
+ let uploaded = 0;
6824
+ for (const u of d.uploads ?? []) {
6825
+ const screen = byKey.get(u.page);
6826
+ if (!screen) continue;
6827
+ const shot = u.name.endsWith("/early.png") ? "early" : "settled";
6828
+ const png = readFileSync14(join17(screen.folder, `${shot}.png`));
6829
+ const put = await doFetch(u.signedUrl, { method: "PUT", headers: { "Content-Type": "image/png" }, body: new Uint8Array(png) });
6830
+ if (!put.ok) throw new Error(`Screenshot ${u.name} not uploaded: storage answered ${put.status}. Retry; the run is ${runId}.`);
6831
+ shotNames.set(u.page, [...shotNames.get(u.page) ?? [], u.name]);
6832
+ uploaded++;
6833
+ }
6834
+ progress(`uploaded ${uploaded} screenshot(s) to run ${runId}`);
6835
+ const consoleUrl = `${consoleBaseUrl()}/ux-runs?view=scorecard&run=${runId}`;
6836
+ const result = { runId, pages: screens.length, uploaded, reservedUsd: d.reservedUsd ?? null, scored: 0, mean: null, causes: [], errors: [], consoleUrl };
6837
+ if (!opts.score) return result;
6838
+ const scores = /* @__PURE__ */ new Map();
6839
+ const labels = screens.map((s) => s.facts.label);
6840
+ await pool2(screens, opts.concurrency ?? 3, async (s) => {
6841
+ const ask = () => api3(
6842
+ cfg,
6843
+ `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}/score`,
6844
+ { 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) }) },
6845
+ doFetch
6846
+ );
6847
+ let r = await ask();
6848
+ if (!r.ok && r.status !== 402) r = await ask();
6849
+ const score = r.body?.data?.score;
6850
+ if (r.ok && score) {
6851
+ scores.set(s.facts.key, score);
6852
+ progress(`scored ${s.facts.key}: ${score.overall}/10`);
6853
+ } else {
6854
+ result.errors.push(`${s.facts.key}: ${apiError2(r)}`);
6855
+ progress(`could not score ${s.facts.key}: ${apiError2(r)}`);
6856
+ }
6857
+ });
6858
+ result.scored = scores.size;
6859
+ result.mean = scores.size ? Math.round([...scores.values()].reduce((n, x) => n + x.overall, 0) / scores.size * 10) / 10 : null;
6860
+ const grouped = await api3(cfg, `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}/group`, { method: "POST", body: "{}" }, doFetch);
6861
+ if (grouped.ok) result.causes = grouped.body?.data?.causes ?? [];
6862
+ else result.errors.push(`grouping: ${apiError2(grouped)}`);
6863
+ const vp = opts.viewport ?? `${screens[0].facts.viewport.width}x${screens[0].facts.viewport.height}`;
6864
+ const closed = await api3(
6865
+ cfg,
6866
+ `/v1/admin/projects/${cfg.projectId}/ux-scorecard/${runId}`,
6867
+ {
6868
+ method: "PUT",
6869
+ body: JSON.stringify({
6870
+ status: "done",
6871
+ viewport: vp,
6872
+ scored_by: "server",
6873
+ started_at: startedAt,
6874
+ finished_at: (/* @__PURE__ */ new Date()).toISOString(),
6875
+ error: null,
6876
+ 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." } })),
6877
+ causes: result.causes
6878
+ })
6879
+ },
6880
+ doFetch
6881
+ );
6882
+ if (!closed.ok) result.errors.push(`closing the run: ${apiError2(closed)}`);
6883
+ if (opts.file) result.filed = await fileScorecard(cfg, runId, { causes: result.causes, dryRun: opts.dryRun });
6884
+ return result;
6885
+ }
6886
+
6887
+ // src/profile.ts
6888
+ import { homedir as homedir3 } from "os";
6889
+ import { resolve as resolve2 } from "path";
6890
+ function cachedProfile(o, home = homedir3()) {
6891
+ if (!o.profileDir?.trim()) return null;
6892
+ const raw = o.profileDir.trim();
6893
+ const dir = raw === "~" ? home : raw.startsWith("~/") ? resolve2(home, raw.slice(2)) : resolve2(raw);
6894
+ return { profileDir: dir, channel: o.channel === "chromium" ? "chromium" : "chrome" };
6895
+ }
6896
+ function parseChannel(v) {
6897
+ if (v !== "chrome" && v !== "chromium") throw new Error("--channel is chrome or chromium");
6898
+ return v;
6899
+ }
6900
+
6901
+ // src/launcher.ts
6902
+ import { existsSync as existsSync12, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "fs";
6903
+ import { join as join20 } from "path";
6904
+
6905
+ // src/skills.ts
6906
+ import { closeSync as closeSync4, existsSync as existsSync11, fstatSync as fstatSync4, openSync as openSync4, readdirSync as readdirSync8, readFileSync as readFileSync16 } from "fs";
6907
+ import { basename as basename2, dirname as dirname4, join as join19, relative as relative4, sep as sep2 } from "path";
6908
+
6909
+ // src/packet.ts
6910
+ import { closeSync as closeSync3, existsSync as existsSync10, fstatSync as fstatSync3, openSync as openSync3, readdirSync as readdirSync7, readFileSync as readFileSync15 } from "fs";
6911
+ import { join as join18, relative as relative3 } from "path";
6912
+ var MAX_PACKET_CHARS = 24e3;
6913
+ var MAX_SKILL_CHARS = 12e3;
6914
+ var DEFAULT_GUIDANCE = `Improve this one screen's UI and UX. In order of priority:
6915
+ 1. Fix every measured problem listed below (accessibility violations, sideways scrolling, tap targets under 24\xD724 px, console errors).
6916
+ 2. Make the primary action obvious: one clear call to action, visual hierarchy that matches importance.
6917
+ 3. Cut noise: shorter copy, group related controls, remove duplicated information, use icons and colour to carry meaning where text is long.
6918
+ 4. Spacing and alignment on the design system's scale; readable line length; consistent type sizes.
6919
+ 5. The mobile screenshot must work as well as the desktop one.`;
6920
+ var GUARDRAILS = `Rules:
6921
+ - Change only what this screen needs. Shared components and design tokens affect every other screen; edit them only when the fix truly belongs there, and say so in your final message.
6922
+ - Use the existing design tokens, components and icon set. Do not add dependencies.
6923
+ - Do not change data fetching, API calls, auth, routing, state management or tests.
6924
+ - Do not run the dev server, install packages, or commit. The tool reviews and commits your edits.
6925
+ - Do not modify anything under .mushi-ux/. Read only the screenshots and skill files you are pointed to.
6926
+ - Do not read or change node_modules or the framework's own code. A problem that comes from there is not yours to fix: say so and move on.
6927
+ - If the screen is already good, make no edits and say why.`;
6928
+ var MAX_STEP_FILES = 6;
6929
+ var MAX_PLAN_STEPS = 5;
6930
+ var PLAN_READ_BUDGET = 6;
6931
+ function buildPlanPacket(input, maxSteps) {
6932
+ const { surface } = input;
6933
+ const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p));
6934
+ const sections = [
6935
+ `# UX plan \u2014 ${surface.label}`,
6936
+ `Screen: \`${surface.path}\` (${surface.kind}). Plan only: do not edit any file except \`.mushi-ux/PLAN.md\`.`,
6937
+ input.timeBudgetMin ? `## Time
6938
+ You have ${input.timeBudgetMin} minutes. Look, decide, write the list.` : "",
6939
+ input.entryFiles?.length ? `## Start here
6940
+ These files render this screen:
6941
+ ${input.entryFiles.map((f) => `- ${f}`).join("\n")}` : "",
6942
+ `## Screenshots (read these images first)
6943
+ ${Object.entries(input.shots).map(([vp, p]) => `- ${vp}: ${p}`).join("\n")}
6944
+ Your read tool opens them as images where they are: do not copy them anywhere.`,
6945
+ `## Measured problems
6946
+ ${findings.length ? findings.join("\n") : "- None measured."}`,
6947
+ input.skillText ? `## Guidance
6948
+ Use this skill to choose what to improve on this one screen (its supporting files are in \`${input.skillDir ?? ".mushi-ux/skill"}/\`):
6949
+
6950
+ ${input.skillText.slice(0, MAX_SKILL_CHARS)}` : `## Guidance
6951
+ ${DEFAULT_GUIDANCE}`,
6952
+ `## What to do
6953
+ List 2 to ${maxSteps} small, separate improvements for this screen, most valuable first. Each must be one focused change a developer could make in a few minutes, touching at most 3 files, that does not depend on the others. Start each item with a short summary a user of the app would understand, without file or code names, then a colon, then the change, naming the component or file it changes (for example "- Make the caption readable: in \`x.tsx\`, ..."). Open at most ${PLAN_READ_BUDGET} source files besides the "Start here" ones; each step's own attempt reads the rest. Write them to \`.mushi-ux/PLAN.md\`, one per line starting with "- ", within your first 2 minutes, from the screenshots and the "Start here" files alone; then refine the file if you have time, and reply with the same list. You are stopped when the time is up, and a missing PLAN.md wastes the whole pass. Do not edit any other file: each item gets its own attempt later.`,
6954
+ `## Rules
6955
+ - Do not install anything, and do not run scripts on the screenshots: look at them.
6956
+ - Do not read or change node_modules or the framework's own code.
6957
+ - Do not plan changes to data fetching, API calls, auth, routing, state management or tests.
6958
+ - If the screen is already good, write fewer items.`
6959
+ ];
6960
+ return sections.filter(Boolean).join("\n\n").slice(0, MAX_PACKET_CHARS);
6961
+ }
6962
+ function parsePlan(text, max = MAX_PLAN_STEPS) {
6963
+ const out = [];
6964
+ for (const line of text.split(/\r?\n/)) {
6965
+ const m = line.match(/^\s*(?:[-*•]|\d+[.)])\s+(?:\[[ xX]\]\s*)?(.+?)\s*$/);
6966
+ const item = m?.[1]?.replace(/\*\*/g, "").replace(/&(amp|lt|gt|quot|#39);/g, (_, e) => ({ amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'" })[e] ?? _).trim();
6967
+ if (!item || item.length < 8 || out.includes(item)) continue;
6968
+ out.push(cutAtWord(item, 280));
6969
+ if (out.length >= max) break;
6970
+ }
6971
+ return out;
6972
+ }
6973
+ function cutAtWord(text, max) {
6974
+ if (text.length <= max) return text;
6975
+ const head = text.slice(0, max - 1);
6976
+ const space = head.lastIndexOf(" ");
6977
+ let cut = (space > max / 2 ? head.slice(0, space) : head).replace(/[\s,;:.(-]+$/, "");
6978
+ if ((cut.match(/`/g)?.length ?? 0) % 2 === 1) cut = cut.slice(0, cut.lastIndexOf("`")).trimEnd();
6979
+ return `${cut}\u2026`;
6980
+ }
6981
+ var PLAN_POINTER_PROMPT = "Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It asks for a plan only: write .mushi-ux/PLAN.md and edit nothing else.";
6982
+ function describeProbes(viewport, p) {
6983
+ const lines = [];
6984
+ for (const v of p.axe) {
6985
+ lines.push(`- [${viewport}] ${v.id} (${v.impact ?? "n/a"}, ${v.count} node${v.count === 1 ? "" : "s"}): ${v.help} \u2014 e.g. ${v.targets.slice(0, 3).join(", ")}`);
6986
+ }
6987
+ if (p.overflowX) lines.push(`- [${viewport}] The page scrolls sideways at this width.`);
6988
+ if (p.smallTargets > 0) lines.push(`- [${viewport}] ${p.smallTargets} tap target(s) smaller than 24\xD724 px.`);
6989
+ for (const i of p.layout ?? []) lines.push(`- [${viewport}] ${i.kind === "overlap" ? "Overlap" : "Too big"}: ${i.selector} ${i.detail}.`);
6990
+ for (const e of p.consoleErrors.slice(0, 5)) lines.push(`- [${viewport}] Console error: ${e}`);
6991
+ if (p.cls > CLS_GOOD) lines.push(`- [${viewport}] Layout shift ${p.cls} while loading (aim below ${CLS_GOOD}).`);
6992
+ return lines;
6993
+ }
6994
+ function buildPacket(input) {
6995
+ const { surface } = input;
6996
+ const steps = surface.steps.length ? ` then click ${surface.steps.map((s) => `"${s.label}"`).join(" \u2192 ")}` : "";
6997
+ const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p));
6998
+ const skill = input.skillText ? [
6999
+ `Apply this skill to this one screen only. Skip its whole-app steps (stack detection, scoring every screen, app-wide inventories): another pass handles each other screen. Its supporting files (references, scorecards) are in \`${input.skillDir ?? ".mushi-ux/skill"}/\`; read only the ones this screen needs.`,
7000
+ input.skillText.slice(0, MAX_SKILL_CHARS)
7001
+ ].join("\n\n") : DEFAULT_GUIDANCE;
7002
+ const sections = [
7003
+ `# UX pass \u2014 ${surface.label}`,
7004
+ `Screen: \`${surface.path}\`${steps} (${surface.kind}). Attempt ${input.iteration}.`,
7005
+ input.timeBudgetMin ? `## Time
6031
7006
  You have ${input.timeBudgetMin} minutes, then you are stopped and unsaved work is lost. Make your first edit within ${Math.max(1, Math.round(input.timeBudgetMin / 3))} minutes: an attempt that ends without an edit counts as a failure. Do not survey the whole design system; read only what the edit needs. A small, finished improvement beats a large unfinished one: make it, then stop.` : "",
6032
7007
  input.entryFiles?.length ? `## Start here
6033
7008
  These files render this screen. Read them first instead of searching the repo:
@@ -6057,36 +7032,36 @@ var POINTER_PROMPT = "Read .mushi-ux/PROMPT.md in this repository and follow it
6057
7032
  var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".turbo", ".worktrees", ".mushi", ".mushi-ux", "coverage"]);
6058
7033
  function findDesignFiles(root, maxFiles = 12) {
6059
7034
  const found = [];
6060
- const recipe = join14(root, "mushi.recipe.json");
6061
- if (existsSync6(recipe)) found.push("mushi.recipe.json");
7035
+ const recipe = join18(root, "mushi.recipe.json");
7036
+ if (existsSync10(recipe)) found.push("mushi.recipe.json");
6062
7037
  const walk = (dir, depth) => {
6063
7038
  if (depth > 5 || found.length >= maxFiles) return;
6064
7039
  let names;
6065
7040
  try {
6066
- names = readdirSync6(dir);
7041
+ names = readdirSync7(dir);
6067
7042
  } catch {
6068
7043
  return;
6069
7044
  }
6070
7045
  for (const name of names) {
6071
7046
  if (found.length >= maxFiles) return;
6072
7047
  if (SKIP_DIRS2.has(name)) continue;
6073
- const abs = join14(dir, name);
7048
+ const abs = join18(dir, name);
6074
7049
  let fd;
6075
7050
  let isDir;
6076
7051
  let css = null;
6077
7052
  try {
6078
- fd = openSync2(abs, "r");
7053
+ fd = openSync3(abs, "r");
6079
7054
  } catch {
6080
7055
  continue;
6081
7056
  }
6082
7057
  try {
6083
- const st = fstatSync2(fd);
7058
+ const st = fstatSync3(fd);
6084
7059
  isDir = st.isDirectory();
6085
- if (!isDir && name.endsWith(".css") && st.size < 3e5) css = readFileSync11(fd, "utf8");
7060
+ if (!isDir && name.endsWith(".css") && st.size < 3e5) css = readFileSync15(fd, "utf8");
6086
7061
  } catch {
6087
7062
  continue;
6088
7063
  } finally {
6089
- closeSync2(fd);
7064
+ closeSync3(fd);
6090
7065
  }
6091
7066
  if (isDir) {
6092
7067
  walk(abs, depth + 1);
@@ -6105,9 +7080,10 @@ function findDesignFiles(root, maxFiles = 12) {
6105
7080
  }
6106
7081
 
6107
7082
  // src/skills.ts
6108
- var DEFAULT_SKILLS_REPO = "npm:@kensaurus/skills";
7083
+ var BUILTIN_SKILLS_REPO = "npm:@kensaurus/skills";
7084
+ var DEFAULT_SKILLS_REPO = process.env.MUSHI_UX_SKILLS_REPO?.trim() || BUILTIN_SKILLS_REPO;
6109
7085
  var NPM_RE = /^npm:((?:@[\w.-]+\/)?[\w.-]+)(?:@([\w.+-]+))?$/;
6110
- var SLUG_RE = /^[a-z0-9][a-z0-9-]{0,80}$/;
7086
+ var SLUG_RE2 = /^[a-z0-9][a-z0-9-]{0,80}$/;
6111
7087
  var REPO_RE = /^([\w.-]+)\/([\w.-]+)(?:@([\w./-]+))?$/;
6112
7088
  var MAX_FILES2 = 40;
6113
7089
  var MAX_BYTES2 = 1e6;
@@ -6162,7 +7138,7 @@ function relatedSkills(text) {
6162
7138
  for (const m of section.matchAll(/`([a-z0-9][a-z0-9-]{1,80})`/g)) out.push(m[1]);
6163
7139
  for (const m of text.matchAll(/(?:→|->)\s*`?([a-z][a-z0-9]*(?:-[a-z0-9]+)+)`?/g)) out.push(m[1]);
6164
7140
  const self = skillName(text, "");
6165
- return [...new Set(out)].filter((n) => n !== self && SLUG_RE.test(n)).slice(0, 12);
7141
+ return [...new Set(out)].filter((n) => n !== self && SLUG_RE2.test(n)).slice(0, 12);
6166
7142
  }
6167
7143
  function chainSkills(skills) {
6168
7144
  if (skills.length === 1) return skills[0];
@@ -6203,19 +7179,19 @@ function readFolder(dir, source) {
6203
7179
  const files = {};
6204
7180
  let bytes = 0;
6205
7181
  const walk = (d) => {
6206
- for (const entry of readdirSync7(d, { withFileTypes: true })) {
7182
+ for (const entry of readdirSync8(d, { withFileTypes: true })) {
6207
7183
  if (Object.keys(files).length >= MAX_FILES2 || entry.name.startsWith(".")) continue;
6208
- const abs = join15(d, entry.name);
7184
+ const abs = join19(d, entry.name);
6209
7185
  if (entry.isDirectory()) walk(abs);
6210
7186
  else if (entry.isFile()) {
6211
- const fd = openSync3(abs, "r");
7187
+ const fd = openSync4(abs, "r");
6212
7188
  try {
6213
- const size = fstatSync3(fd).size;
7189
+ const size = fstatSync4(fd).size;
6214
7190
  if (bytes + size > MAX_BYTES2) continue;
6215
7191
  bytes += size;
6216
- files[relative4(dir, abs).split(sep2).join("/")] = readFileSync12(fd);
7192
+ files[relative4(dir, abs).split(sep2).join("/")] = readFileSync16(fd);
6217
7193
  } finally {
6218
- closeSync3(fd);
7194
+ closeSync4(fd);
6219
7195
  }
6220
7196
  }
6221
7197
  }
@@ -6261,7 +7237,7 @@ async function fetchFolder(slug, opts) {
6261
7237
  async function resolveSkill(spec, opts = {}) {
6262
7238
  let text = null;
6263
7239
  try {
6264
- text = readFileSync12(spec, "utf8");
7240
+ text = readFileSync16(spec, "utf8");
6265
7241
  } catch (err) {
6266
7242
  const code = err.code;
6267
7243
  if (code === "EISDIR") return readFolder(spec, spec);
@@ -6271,11 +7247,11 @@ async function resolveSkill(spec, opts = {}) {
6271
7247
  if (basename2(spec) === "SKILL.md") return readFolder(dirname4(spec), spec);
6272
7248
  return { name: skillName(text, basename2(spec).replace(/\.md$/i, "")), text, files: { "SKILL.md": Buffer.from(text) }, source: spec };
6273
7249
  }
6274
- if (!SLUG_RE.test(spec)) throw new Error(`"${spec}" is neither a file nor a skill name.`);
7250
+ if (!SLUG_RE2.test(spec)) throw new Error(`"${spec}" is neither a file nor a skill name.`);
6275
7251
  const local = opts.localDir === void 0 ? process.env.MUSHI_UX_SKILLS_DIR : opts.localDir;
6276
7252
  if (local) {
6277
- const dir = join15(local, "skills", spec);
6278
- if (existsSync7(join15(dir, "SKILL.md"))) return readFolder(dir, dir);
7253
+ const dir = join19(local, "skills", spec);
7254
+ if (existsSync11(join19(dir, "SKILL.md"))) return readFolder(dir, dir);
6279
7255
  }
6280
7256
  const doFetch = opts.fetch ?? fetch;
6281
7257
  const npm = npmSource(opts.repo ?? DEFAULT_SKILLS_REPO, doFetch);
@@ -6294,16 +7270,16 @@ async function listSkills(opts = {}) {
6294
7270
  const groupings = index?.groupings;
6295
7271
  if (!Array.isArray(groupings)) return null;
6296
7272
  return groupings.flatMap(
6297
- (g) => (g.skills ?? []).filter((s) => typeof s === "string" && SLUG_RE.test(s)).map((name) => ({ name, group: g.title ?? null }))
7273
+ (g) => (g.skills ?? []).filter((s) => typeof s === "string" && SLUG_RE2.test(s)).map((name) => ({ name, group: g.title ?? null }))
6298
7274
  );
6299
7275
  };
6300
- if (local && existsSync7(join15(local, "skills"))) {
7276
+ if (local && existsSync11(join19(local, "skills"))) {
6301
7277
  let index = null;
6302
7278
  try {
6303
- index = JSON.parse(readFileSync12(join15(local, "skills.sh.json"), "utf8"));
7279
+ index = JSON.parse(readFileSync16(join19(local, "skills.sh.json"), "utf8"));
6304
7280
  } catch {
6305
7281
  }
6306
- const dirs2 = readdirSync7(join15(local, "skills"), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
7282
+ const dirs2 = readdirSync8(join19(local, "skills"), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
6307
7283
  return mergeSkillList(dirs2, fromIndex(index));
6308
7284
  }
6309
7285
  const doFetch = opts.fetch ?? fetch;
@@ -6329,7 +7305,7 @@ async function listSkills(opts = {}) {
6329
7305
  );
6330
7306
  }
6331
7307
  function mergeSkillList(dirs, index) {
6332
- const exists = new Set(dirs.filter((d) => SLUG_RE.test(d)));
7308
+ const exists = new Set(dirs.filter((d) => SLUG_RE2.test(d)));
6333
7309
  const grouped = (index ?? []).filter((s) => exists.has(s.name));
6334
7310
  const seen = new Set(grouped.map((s) => s.name));
6335
7311
  const rest = [...exists].filter((d) => !seen.has(d)).sort();
@@ -6358,12 +7334,12 @@ async function agentAvailability(env = process.env) {
6358
7334
  );
6359
7335
  }
6360
7336
  function devCommandGuesses(repoRoot) {
6361
- const file = join16(repoRoot, "package.json");
6362
- if (!existsSync8(file)) return { commands: [], warning: null };
6363
- const pkg = JSON.parse(readFileSync13(file, "utf8"));
7337
+ const file = join20(repoRoot, "package.json");
7338
+ if (!existsSync12(file)) return { commands: [], warning: null };
7339
+ const pkg = JSON.parse(readFileSync17(file, "utf8"));
6364
7340
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
6365
7341
  const scripts = pkg.scripts ?? {};
6366
- const pm = existsSync8(join16(repoRoot, "pnpm-lock.yaml")) ? "pnpm" : existsSync8(join16(repoRoot, "yarn.lock")) ? "yarn" : existsSync8(join16(repoRoot, "bun.lock")) || existsSync8(join16(repoRoot, "bun.lockb")) ? "bun" : "npm";
7342
+ const pm = existsSync12(join20(repoRoot, "pnpm-lock.yaml")) ? "pnpm" : existsSync12(join20(repoRoot, "yarn.lock")) ? "yarn" : existsSync12(join20(repoRoot, "bun.lock")) || existsSync12(join20(repoRoot, "bun.lockb")) ? "bun" : "npm";
6367
7343
  const out = [];
6368
7344
  const devScript = scripts.dev ?? "";
6369
7345
  const envPrefix = devScript.match(/^cross-env\s+((?:[A-Z_][A-Z0-9_]*=\S+\s+)+)/)?.[1]?.replace(/\b[A-Z_]*PORT=\S+\s*/g, "").trim();
@@ -6383,15 +7359,15 @@ function devCommandGuesses(repoRoot) {
6383
7359
  return { commands: [...new Set(out)], warning };
6384
7360
  }
6385
7361
  function lastWorkingRun(repoRoot) {
6386
- const dir = join16(repoRoot, ".mushi", "ux");
7362
+ const dir = join20(repoRoot, ".mushi", "ux");
6387
7363
  let ids;
6388
7364
  try {
6389
- ids = readdirSync8(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && /^\d{8}-\d{6}-[a-z0-9]+$/.test(e.name)).map((e) => e.name).sort().reverse();
7365
+ ids = readdirSync9(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && /^\d{8}-\d{6}-[a-z0-9]+$/.test(e.name)).map((e) => e.name).sort().reverse();
6390
7366
  } catch {
6391
7367
  return null;
6392
7368
  }
6393
7369
  for (const runId of ids.slice(0, 30)) {
6394
- const state = loadState(join16(dir, runId));
7370
+ const state = loadState(join20(dir, runId));
6395
7371
  if (state?.options?.devCommand && state.surfaces.length > 0) {
6396
7372
  return { runId, devCommand: state.options.devCommand, startPaths: state.options.startPaths ?? [] };
6397
7373
  }
@@ -6555,14 +7531,14 @@ async function listModels(agent, deps = {}) {
6555
7531
  }
6556
7532
 
6557
7533
  // src/loop.ts
6558
- import { appendFileSync as appendFileSync2, existsSync as existsSync10, mkdirSync as mkdirSync10, readFileSync as readFileSync15, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "fs";
6559
- import { dirname as dirname6, join as join19 } from "path";
7534
+ import { appendFileSync as appendFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync12, readFileSync as readFileSync19, rmSync as rmSync4, writeFileSync as writeFileSync11 } from "fs";
7535
+ import { dirname as dirname6, join as join23 } from "path";
6560
7536
 
6561
7537
  // src/preflight.ts
6562
7538
  import { randomBytes as randomBytes2 } from "crypto";
6563
- import { mkdtempSync, rmSync, writeFileSync as writeFileSync8 } from "fs";
7539
+ import { mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "fs";
6564
7540
  import { tmpdir } from "os";
6565
- import { join as join17 } from "path";
7541
+ import { join as join21 } from "path";
6566
7542
 
6567
7543
  // src/verdict.ts
6568
7544
  var MIN_VISIBLE_RATIO = 5e-4;
@@ -6686,10 +7662,10 @@ function preflightAdvice(agent, output, platform = process.platform) {
6686
7662
  return "Run the agent once by hand in this repo to see what it needs, then start the run again.";
6687
7663
  }
6688
7664
  async function preflightAgent(agent, opts = {}) {
6689
- const dir = mkdtempSync(join17(tmpdir(), "mushi-ux-preflight-"));
7665
+ const dir = mkdtempSync(join21(tmpdir(), "mushi-ux-preflight-"));
6690
7666
  const word = randomBytes2(4).toString("hex");
6691
7667
  try {
6692
- writeFileSync8(join17(dir, "PREFLIGHT.txt"), `The code word is ${word}.
7668
+ writeFileSync9(join21(dir, "PREFLIGHT.txt"), `The code word is ${word}.
6693
7669
  `);
6694
7670
  const timeoutMs = opts.timeoutMs ?? PREFLIGHT_TIMEOUT_MS;
6695
7671
  const res = await agent.run({
@@ -6710,32 +7686,32 @@ ${res.tail}`;
6710
7686
  } catch (err) {
6711
7687
  return `Agent check failed: could not start ${agent.name}: ${err.message}. Is it installed and on PATH?`;
6712
7688
  } finally {
6713
- rmSync(dir, { recursive: true, force: true });
7689
+ rmSync2(dir, { recursive: true, force: true });
6714
7690
  }
6715
7691
  }
6716
7692
 
6717
7693
  // src/resume.ts
6718
- import { existsSync as existsSync9, mkdirSync as mkdirSync9, readdirSync as readdirSync9, readFileSync as readFileSync14, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "fs";
6719
- import { dirname as dirname5, join as join18, relative as relative5 } from "path";
7694
+ import { existsSync as existsSync13, mkdirSync as mkdirSync11, readdirSync as readdirSync10, readFileSync as readFileSync18, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "fs";
7695
+ import { dirname as dirname5, join as join22, relative as relative5 } from "path";
6720
7696
  var ALIVE_WITHIN_MS = 9e4;
6721
7697
  function saveSkillFiles(dir, skill) {
6722
- const root = join18(dir, "skill");
6723
- rmSync2(root, { recursive: true, force: true });
7698
+ const root = join22(dir, "skill");
7699
+ rmSync3(root, { recursive: true, force: true });
6724
7700
  for (const [rel, buf] of Object.entries(skill.files)) {
6725
- const target2 = join18(root, ...rel.split("/"));
6726
- mkdirSync9(dirname5(target2), { recursive: true });
6727
- writeFileSync9(target2, buf);
7701
+ const target2 = join22(root, ...rel.split("/"));
7702
+ mkdirSync11(dirname5(target2), { recursive: true });
7703
+ writeFileSync10(target2, buf);
6728
7704
  }
6729
7705
  }
6730
7706
  function loadSkillFiles(dir, meta) {
6731
- const root = join18(dir, "skill");
6732
- if (!existsSync9(join18(root, "SKILL.md"))) return null;
7707
+ const root = join22(dir, "skill");
7708
+ if (!existsSync13(join22(root, "SKILL.md"))) return null;
6733
7709
  const files = {};
6734
7710
  const walk = (d) => {
6735
- for (const entry of readdirSync9(d, { withFileTypes: true })) {
6736
- const abs = join18(d, entry.name);
7711
+ for (const entry of readdirSync10(d, { withFileTypes: true })) {
7712
+ const abs = join22(d, entry.name);
6737
7713
  if (entry.isDirectory()) walk(abs);
6738
- else files[relative5(root, abs).replace(/\\/g, "/")] = readFileSync14(abs);
7714
+ else files[relative5(root, abs).replace(/\\/g, "/")] = readFileSync18(abs);
6739
7715
  }
6740
7716
  };
6741
7717
  walk(root);
@@ -6752,7 +7728,7 @@ function expectedHead(state) {
6752
7728
  }
6753
7729
  function resumeSettings(repoRoot, runId, now = Date.now()) {
6754
7730
  const state = loadState(runDir(repoRoot, runId));
6755
- if (!state) throw new Error(`No run ${runId} in ${join18(repoRoot, ".mushi", "ux")}.`);
7731
+ if (!state) throw new Error(`No run ${runId} in ${join22(repoRoot, ".mushi", "ux")}.`);
6756
7732
  if (state.phase === "done") throw new Error(`Run ${runId} already finished. Start a new run instead.`);
6757
7733
  if (isRunAlive(state, now)) {
6758
7734
  throw new Error(`Run ${runId} saved its state less than a minute ago, so it is still running somewhere. Stop it there first.`);
@@ -6790,7 +7766,7 @@ function timeoutNote(timeoutMs) {
6790
7766
  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.`;
6791
7767
  }
6792
7768
  function scrubFrameworkNoise(state) {
6793
- const clean = (ref) => {
7769
+ const clean2 = (ref) => {
6794
7770
  if (!ref) return;
6795
7771
  const kept = ref.probes.consoleErrors.filter((e) => !isFrameworkNoise(e));
6796
7772
  if (kept.length === ref.probes.consoleErrors.length) return;
@@ -6798,8 +7774,8 @@ function scrubFrameworkNoise(state) {
6798
7774
  ref.penalty = probePenalty(ref.probes);
6799
7775
  };
6800
7776
  for (const s of state.surfaces) {
6801
- Object.values(s.baseline).forEach(clean);
6802
- for (const it of s.iterations) Object.values(it.after).forEach(clean);
7777
+ Object.values(s.baseline).forEach(clean2);
7778
+ for (const it of s.iterations) Object.values(it.after).forEach(clean2);
6803
7779
  }
6804
7780
  }
6805
7781
  function noScreensMessage(skipped, devError) {
@@ -6873,8 +7849,8 @@ async function runLoop(opts, runId, dir) {
6873
7849
  const log = (message) => {
6874
7850
  emit(events, { type: "log", message });
6875
7851
  try {
6876
- mkdirSync10(dir, { recursive: true });
6877
- appendFileSync2(join19(dir, "run.log"), `${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)} ${message}
7852
+ mkdirSync12(dir, { recursive: true });
7853
+ appendFileSync2(join23(dir, "run.log"), `${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)} ${message}
6878
7854
  `);
6879
7855
  } catch {
6880
7856
  }
@@ -6982,7 +7958,7 @@ async function runLoop(opts, runId, dir) {
6982
7958
  state.branch = wt.branch;
6983
7959
  state.baseSha = wt.baseSha;
6984
7960
  persist();
6985
- } else if (!existsSync10(state.worktree)) {
7961
+ } else if (!existsSync14(state.worktree)) {
6986
7962
  throw new Error(`The run's worktree ${state.worktree} is gone, so this run cannot continue. Start a new run.`);
6987
7963
  }
6988
7964
  if (state.installed === void 0 && state.surfaces.length > 0) state.installed = true;
@@ -7107,19 +8083,19 @@ ${second.stdout}`
7107
8083
  };
7108
8084
  }
7109
8085
  function prepareScratch(current) {
7110
- const scratch = join19(wtPath, SCRATCH_DIR);
7111
- rmSync3(scratch, { recursive: true, force: true });
7112
- mkdirSync10(scratch, { recursive: true });
8086
+ const scratch = join23(wtPath, SCRATCH_DIR);
8087
+ rmSync4(scratch, { recursive: true, force: true });
8088
+ mkdirSync12(scratch, { recursive: true });
7113
8089
  if (opts.skill) {
7114
8090
  for (const [rel, buf] of Object.entries(opts.skill.files)) {
7115
- const target2 = join19(scratch, "skill", ...rel.split("/"));
7116
- mkdirSync10(dirname6(target2), { recursive: true });
7117
- writeFileSync10(target2, buf);
8091
+ const target2 = join23(scratch, "skill", ...rel.split("/"));
8092
+ mkdirSync12(dirname6(target2), { recursive: true });
8093
+ writeFileSync11(target2, buf);
7118
8094
  }
7119
8095
  }
7120
8096
  const shots = {};
7121
8097
  for (const [vp, ref] of Object.entries(current)) {
7122
- writeFileSync10(join19(scratch, `${vp}.png`), readFileSync15(join19(dir, ref.png)));
8098
+ writeFileSync11(join23(scratch, `${vp}.png`), readFileSync19(join23(dir, ref.png)));
7123
8099
  shots[vp] = `${SCRATCH_DIR}/${vp}.png`;
7124
8100
  }
7125
8101
  return { shots, probes: Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes])) };
@@ -7128,8 +8104,8 @@ ${second.stdout}`
7128
8104
  const planMs = Math.min(timeoutMs, PLAN_TIMEOUT_MS);
7129
8105
  const { shots, probes } = prepareScratch(current);
7130
8106
  const maxSteps = Math.min(MAX_PLAN_STEPS, iterations);
7131
- writeFileSync10(
7132
- join19(wtPath, SCRATCH_DIR, "PROMPT.md"),
8107
+ writeFileSync11(
8108
+ join23(wtPath, SCRATCH_DIR, "PROMPT.md"),
7133
8109
  buildPlanPacket({ surface: s.surface, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, timeBudgetMin: Math.round(planMs / 6e4), entryFiles }, maxSteps)
7134
8110
  );
7135
8111
  s.status = "iterating";
@@ -7137,13 +8113,13 @@ ${second.stdout}`
7137
8113
  state.current = { surface: s.surface.key, attempt: 1, startedAt, timeoutMs: planMs, steps: 0, lastStep: null, files: [], heartbeatAt: startedAt };
7138
8114
  phase("working", `${s.surface.label}, planning small steps`);
7139
8115
  log(` planning ${s.surface.label} in small steps\u2026`);
7140
- const planLog = join19(dir, "agent", `${attemptLogBase(s.surface.key, 0).slice(0, -2)}-plan.steps.log`);
8116
+ const planLog = join23(dir, "agent", `${attemptLogBase(s.surface.key, 0).slice(0, -2)}-plan.steps.log`);
7141
8117
  try {
7142
- mkdirSync10(dirname6(planLog), { recursive: true });
7143
- writeFileSync10(planLog, "");
8118
+ mkdirSync12(dirname6(planLog), { recursive: true });
8119
+ writeFileSync11(planLog, "");
7144
8120
  } catch {
7145
8121
  }
7146
- const planFile = join19(wtPath, SCRATCH_DIR, "PLAN.md");
8122
+ const planFile = join23(wtPath, SCRATCH_DIR, "PLAN.md");
7147
8123
  const res = await runWithNudge({
7148
8124
  cwd: wtPath,
7149
8125
  prompt: PLAN_POINTER_PROMPT,
@@ -7153,7 +8129,7 @@ ${second.stdout}`
7153
8129
  nudge: {
7154
8130
  prompt: PLAN_NUDGE,
7155
8131
  ms: PLAN_NUDGE_MS,
7156
- needed: async () => !existsSync10(planFile) || parsePlan(readFileSync15(planFile, "utf8")).length === 0
8132
+ needed: async () => !existsSync14(planFile) || parsePlan(readFileSync19(planFile, "utf8")).length === 0
7157
8133
  },
7158
8134
  onLine: (line) => {
7159
8135
  for (const step of describeAgentLine(line, wtPath)) {
@@ -7168,7 +8144,7 @@ ${second.stdout}`
7168
8144
  }
7169
8145
  });
7170
8146
  if (opts.signal?.aborted) throw new Error("Stopped.");
7171
- const fromFile = existsSync10(planFile) ? readFileSync15(planFile, "utf8") : "";
8147
+ const fromFile = existsSync14(planFile) ? readFileSync19(planFile, "utf8") : "";
7172
8148
  const text = parsePlan(fromFile).length ? fromFile : agentFinalMessage(res.stdout) ?? assistantText(res.stdout);
7173
8149
  await revertAll(wtPath);
7174
8150
  const items = parsePlan(text, maxSteps);
@@ -7231,8 +8207,8 @@ ${second.stdout}`
7231
8207
  const step = plan?.steps.find((p) => p.status === "pending") ?? null;
7232
8208
  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;
7233
8209
  const { shots, probes } = prepareScratch(current);
7234
- writeFileSync10(
7235
- join19(wtPath, SCRATCH_DIR, "PROMPT.md"),
8210
+ writeFileSync11(
8211
+ join23(wtPath, SCRATCH_DIR, "PROMPT.md"),
7236
8212
  buildPacket({ surface: s.surface, iteration: n, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, previousRejection, timeBudgetMin: Math.round(timeoutMs / 6e4), entryFiles, step: stepInfo })
7237
8213
  );
7238
8214
  s.status = "iterating";
@@ -7241,11 +8217,11 @@ ${second.stdout}`
7241
8217
  state.current = live;
7242
8218
  phase("working", stepInfo ? `${s.surface.label}, step ${stepInfo.index} of ${stepInfo.total}` : `${s.surface.label}, attempt ${n} of ${iterations}`);
7243
8219
  const steps = [];
7244
- const logDir = join19(dir, "agent");
7245
- const logBase = join19(logDir, attemptLogBase(s.surface.key, n));
8220
+ const logDir = join23(dir, "agent");
8221
+ const logBase = join23(logDir, attemptLogBase(s.surface.key, n));
7246
8222
  try {
7247
- mkdirSync10(logDir, { recursive: true });
7248
- writeFileSync10(`${logBase}.steps.log`, "");
8223
+ mkdirSync12(logDir, { recursive: true });
8224
+ writeFileSync11(`${logBase}.steps.log`, "");
7249
8225
  } catch {
7250
8226
  }
7251
8227
  const heartbeat = setInterval(() => {
@@ -7292,8 +8268,8 @@ This continues your session for this screen: you have already read its files. Do
7292
8268
  clearInterval(heartbeat);
7293
8269
  }
7294
8270
  try {
7295
- mkdirSync10(logDir, { recursive: true });
7296
- writeFileSync10(`${logBase}.log`, res.stdout);
8271
+ mkdirSync12(logDir, { recursive: true });
8272
+ writeFileSync11(`${logBase}.log`, res.stdout);
7297
8273
  } catch {
7298
8274
  }
7299
8275
  if (opts.signal?.aborted) throw new Error("Stopped.");
@@ -7344,7 +8320,7 @@ This continues your session for this screen: you have already read its files. Do
7344
8320
  if (afterShots) {
7345
8321
  record.after = shotRefs(s, `iter${n}`, afterShots);
7346
8322
  for (const [vp, shot] of Object.entries(afterShots)) {
7347
- const before = readFileSync15(join19(dir, current[vp].png));
8323
+ const before = readFileSync19(join23(dir, current[vp].png));
7348
8324
  const d = pixelDiff(before, shot.png);
7349
8325
  ratios[vp] = Math.round(d.ratio * 1e4) / 1e4;
7350
8326
  record.diffPng[vp] = savePng(dir, `shots/${s.surface.key}/iter${n}-${vp}-diff.png`, d.diffPng);
@@ -7382,7 +8358,7 @@ This continues your session for this screen: you have already read its files. Do
7382
8358
  name: `${s.surface.key}-iter${n}`,
7383
8359
  screen: s.surface.label,
7384
8360
  step: step?.text ?? "Improve this screen for the person using it.",
7385
- visual: visible ? { before: readFileSync15(join19(dir, current[vp].png)), after: afterShots[vp].png, regions: record.changes?.[vp]?.boxes ?? [] } : null,
8361
+ visual: visible ? { before: readFileSync19(join23(dir, current[vp].png)), after: afterShots[vp].png, regions: record.changes?.[vp]?.boxes ?? [] } : null,
7386
8362
  diff: await diffText(wtPath).catch(() => ""),
7387
8363
  repoDir: wtPath,
7388
8364
  spec: opts.checker,
@@ -7422,382 +8398,127 @@ This continues your session for this screen: you have already read its files. Do
7422
8398
  if (kept.length > 0) {
7423
8399
  s.status = "accepted";
7424
8400
  s.note = kept[kept.length - 1].reason;
7425
- } else {
7426
- const rejected = s.iterations.some((i) => i.outcome === "rejected" || i.outcome === "capture_failed");
7427
- const neverFinished = s.iterations.length > 0 && s.iterations.every((i) => i.outcome === "agent_failed");
7428
- s.status = rejected ? "reverted" : neverFinished ? "blocked" : "skipped";
7429
- s.note = s.iterations[s.iterations.length - 1]?.reason ?? null;
7430
- }
7431
- rmSync3(join19(wtPath, SCRATCH_DIR), { recursive: true, force: true });
7432
- persist();
7433
- }
7434
- async function runJudge(model) {
7435
- state.judgeModel = model;
7436
- const changed = state.surfaces.filter((x) => x.iterations.some((i) => i.outcome === "accepted"));
7437
- if (changed.length === 0) return;
7438
- log(`Reviewing ${changed.length} changed screen(s) with ${model}\u2026`);
7439
- for (const s of changed) {
7440
- if (s.judge?.length) continue;
7441
- const verdicts = [];
7442
- for (const vp of VIEWPORTS) {
7443
- const v = await judgeSurface(s, vp.name, { dir, repoRoot: wtPath, designFiles, model });
7444
- if (v) verdicts.push(v);
7445
- }
7446
- s.judge = verdicts;
7447
- const errors = verdicts.filter((v) => v.error);
7448
- if (errors.length) log(` review of ${s.surface.label} failed: ${errors[0].error}`);
7449
- const prefersBefore = verdicts.filter((v) => !v.error && v.preferred === "before" && v.confidence !== "low");
7450
- if (prefersBefore.length) {
7451
- log(` \u26A0 reviewer prefers the original ${s.surface.label} (${prefersBefore.map((v) => v.viewport).join(", ")}) \u2014 check it before merging`);
7452
- }
7453
- persist();
7454
- }
7455
- }
7456
- async function checkRegressions(changed) {
7457
- const finished = state.surfaces.filter((x) => x !== changed && ["accepted", "reverted", "skipped"].includes(x.status)).slice(-(opts.regressionSample ?? 5));
7458
- const desktop = VIEWPORTS[0];
7459
- for (const other of finished) {
7460
- const ref = referenceShot(other, desktop.name);
7461
- if (!ref) continue;
7462
- const refPng = readFileSync15(join19(dir, ref.png));
7463
- const moved = (png) => {
7464
- const diff = pixelDiff(refPng, png);
7465
- return diff.contentRatio > REGRESSION_CONTENT_RATIO && diff.changedPixels > REGRESSION_MIN_PIXELS ? diff : null;
7466
- };
7467
- let now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null);
7468
- if (!now || !moved(now.png)) continue;
7469
- await new Promise((r) => setTimeout(r, 3e3));
7470
- now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null);
7471
- const d = now ? moved(now.png) : null;
7472
- if (now && d) {
7473
- const pct = (d.contentRatio * 100).toFixed(0);
7474
- other.status = "regressed";
7475
- other.note = `${pct}% of this screen changed after "${changed.surface.label}" was kept. Check whether a shared component or token moved.`;
7476
- savePng(dir, `shots/${other.surface.key}/regressed-${desktop.name}.png`, now.png);
7477
- log(` \u26A0 ${other.surface.label}: ${pct}% of the screen moved \u2014 marked regressed`);
7478
- }
7479
- }
7480
- persist();
7481
- }
7482
- }
7483
- }
7484
-
7485
- // src/pr.ts
7486
- var PR_URL_RE = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)/;
7487
- function continuedBranch(baseRef, defaultBranch) {
7488
- const m = baseRef?.match(/^origin\/(.+)$/);
7489
- if (!m || m[1] === defaultBranch || m[1] === "HEAD") return null;
7490
- return m[1];
7491
- }
7492
- var keptOf = (iterations) => iterations.filter((it) => it.outcome === "accepted" && it.commitSha);
7493
- function prTitle(state) {
7494
- const names = state.surfaces.filter((s) => keptOf(s.iterations).length > 0).map((s) => s.surface.label.split(/\s+[—|–·]\s+/)[0].trim());
7495
- const joined = names.length <= 1 ? names[0] ?? "app" : names.length <= 3 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : `${names.slice(0, 2).join(", ")} and ${names.length - 2} more`;
7496
- const title = `fix(ux): polish the ${joined} screen${names.length === 1 ? "" : "s"}`;
7497
- return title.length <= 72 ? title : `fix(ux): polish ${names.length} screens`;
7498
- }
7499
- function prBody(state) {
7500
- const lines = [
7501
- `Made by Mushi's UX loop (\`mushi ux\`): ${state.agent}${state.model ? ` \xB7 ${state.model}` : ""}${state.skill?.name ? ` \xB7 skills: ${state.skill.name}` : ""}.`,
7502
- "Each commit is one step that did not make accessibility, layout or console measurements worse; a second model could roll a kept step back. Each commit can be kept or dropped on its own.",
7503
- ""
7504
- ];
7505
- const review = [];
7506
- for (const s of state.surfaces) {
7507
- const kept = keptOf(s.iterations);
7508
- const tried = s.iterations.length;
7509
- if (tried === 0) continue;
7510
- lines.push(`### ${s.surface.label} \`${s.surface.path}\``, `${kept.length} of ${tried} attempts kept.`, "");
7511
- for (const it of kept) {
7512
- const what = (it.step ?? it.reason).replace(/\s+/g, " ").slice(0, 220);
7513
- const checker = it.checker ? ` ${it.checker.model}: ${it.checker.error ? "could not review" : it.checker.verdict === "keep" ? "agrees" : "unsure"}.` : "";
7514
- lines.push(`- \`${it.commitSha.slice(0, 9)}\` ${what}${it.needsReview ? " **Needs your review.**" : ""}${checker}`);
7515
- if (it.needsReview) review.push(`\`${it.commitSha.slice(0, 9)}\` (${s.surface.label})`);
7516
- }
7517
- const vetoed = s.iterations.filter((it) => it.checker?.verdict === "revert");
7518
- for (const it of vetoed) lines.push(`- Rolled back by ${it.checker.model}: ${it.checker.summary.replace(/\s+/g, " ").slice(0, 200)}`);
7519
- lines.push("");
7520
- }
7521
- if (review.length) lines.push("## Read these diffs", `Nothing visible changed in a screenshot, so the measurements could not judge them: ${review.join(", ")}.`, "");
7522
- lines.push(`Run \`${state.runId}\`, branch \`${state.branch}\`. Screenshots of every attempt are on the Mushi console's UX runs page.`);
7523
- return lines.join("\n");
7524
- }
7525
- async function openRunPullRequest(state, exec) {
7526
- if (!state.branch) throw new Error("This run has no branch yet.");
7527
- if (!state.surfaces.some((s) => keptOf(s.iterations).length > 0)) throw new Error("This run kept no change, so there is nothing to open a pull request for.");
7528
- if (state.pr) return state.pr;
7529
- const defaultBranch = (await exec("gh", ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"])).trim() || "main";
7530
- const onto = continuedBranch(state.baseRef, defaultBranch);
7531
- if (onto) {
7532
- const open = JSON.parse(await exec("gh", ["pr", "list", "--head", onto, "--state", "open", "--json", "number,url", "--limit", "1"]) || "[]");
7533
- if (open[0]) {
7534
- await exec("git", ["push", "origin", `${state.branch}:${onto}`]);
7535
- return { url: open[0].url, number: open[0].number, added: true };
7536
- }
7537
- }
7538
- await exec("git", ["push", "-u", "origin", state.branch]);
7539
- const out = await exec("gh", ["pr", "create", "--draft", "--base", defaultBranch, "--head", state.branch, "--title", prTitle(state), "--body", prBody(state)]);
7540
- const m = out.match(PR_URL_RE);
7541
- if (!m) throw new Error(`gh did not print the new pull request's URL: ${out.trim().slice(0, 200)}`);
7542
- return { url: m[0], number: Number(m[1]), added: false };
7543
- }
7544
-
7545
- // src/sync.ts
7546
- import { existsSync as existsSync11, readFileSync as readFileSync16 } from "fs";
7547
- import { join as join20 } from "path";
7548
- var CLOUD_API_ENDPOINT = "https://dxptnwrhwsqckaftyymj.supabase.co/functions/v1/api";
7549
- var HOSTED_CONSOLE_URL = "https://kensaur.us/mushi-mushi/admin";
7550
- function consoleBaseUrl(env = process.env) {
7551
- return trimTrailingSlashes(env.MUSHI_CONSOLE_URL?.trim() || HOSTED_CONSOLE_URL);
7552
- }
7553
- var VIEWPORT_NAMES = ["desktop", "mobile"];
7554
- var UPLOAD_BATCH = 40;
7555
- function syncConfigFromEnv(env = process.env) {
7556
- const apiKey = env.MUSHI_API_KEY?.trim();
7557
- const projectId = env.MUSHI_PROJECT_ID?.trim();
7558
- if (!apiKey || !projectId) return null;
7559
- return {
7560
- apiKey,
7561
- projectId,
7562
- endpoint: trimTrailingSlashes(env.MUSHI_API_ENDPOINT?.trim() || CLOUD_API_ENDPOINT),
7563
- mode: env.GITHUB_ACTIONS === "true" ? "cloud" : "local"
7564
- };
7565
- }
7566
- var PROJECT_LINE_RE = /^\s*(?:NEXT_PUBLIC_|VITE_|EXPO_PUBLIC_|PUBLIC_)?MUSHI_PROJECT_ID\s*=\s*["']?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})["']?\s*$/im;
7567
- function repoProjectId(repoRoot) {
7568
- for (const name of [".env.local", ".env.development.local", ".env.development", ".env"]) {
7569
- const file = join20(repoRoot, name);
7570
- if (!existsSync11(file)) continue;
7571
- const m = readFileSync16(file, "utf8").match(PROJECT_LINE_RE);
7572
- if (m) return m[1];
7573
- }
7574
- return null;
7575
- }
7576
- function syncProjectMismatch(cfg, repoRoot) {
7577
- const repoProject = repoProjectId(repoRoot);
7578
- if (!repoProject || repoProject === cfg.projectId) return null;
7579
- return `This repo's app reports to Mushi project ${repoProject}, but your login is for ${cfg.projectId}. Run \`mushi login\` and pick this app's project (or set MUSHI_PROJECT_ID), so the run lands on the right project.`;
7580
- }
7581
- function probeSummary(p) {
7582
- if (!p) return null;
7583
- return {
7584
- axe: p.axe.map((v) => ({ id: v.id, impact: v.impact, help: v.help.slice(0, 300), count: v.count })).slice(0, 60),
7585
- overflowX: p.overflowX,
7586
- smallTargets: p.smallTargets,
7587
- consoleErrors: p.consoleErrors.length,
7588
- cls: p.cls
7589
- };
7590
- }
7591
- function syncableStep(line) {
7592
- if (/^\[(read|edit)\] \S/.test(line)) return line.slice(0, 300);
7593
- if (line.startsWith("[run] ")) return "[run] a command";
7594
- if (line.startsWith("[find] ")) return "[find] a search";
7595
- if (line === "[done] Finished") return line;
7596
- return null;
7597
- }
7598
- function syncableSteps(log) {
7599
- const kept = (log ?? "").split("\n").map(syncableStep).filter((l) => l !== null);
7600
- return kept.length ? kept.join("\n").slice(-2e3) : null;
7601
- }
7602
- function worstPenalty(shots) {
7603
- const scores = Object.values(shots).flatMap((r) => r && typeof r.penalty === "number" ? [r.penalty] : []);
7604
- return scores.length ? Math.max(...scores) : null;
7605
- }
7606
- function lastKept(s) {
7607
- return [...s.iterations].reverse().find((i) => i.outcome === "accepted") ?? null;
7608
- }
7609
- function wantedShots(state) {
7610
- const out = [];
7611
- for (const s of state.surfaces) {
7612
- const key = s.surface.key;
7613
- const kept = lastKept(s);
7614
- for (const vp of VIEWPORT_NAMES) {
7615
- const before = s.baseline[vp]?.png;
7616
- if (before) out.push({ name: `${key}/before-${vp}.png`, rel: before });
7617
- const after = kept?.after[vp]?.png;
7618
- if (after) out.push({ name: `${key}/after-${vp}.png`, rel: after });
7619
- const diff = kept?.diffPng[vp];
7620
- if (diff) out.push({ name: `${key}/diff-${vp}.png`, rel: diff });
7621
- for (const it of s.iterations) {
7622
- if (it.after[vp]?.png) out.push({ name: `${key}/iter${it.n}-after-${vp}.png`, rel: it.after[vp].png });
7623
- if (it.diffPng[vp]) out.push({ name: `${key}/iter${it.n}-diff-${vp}.png`, rel: it.diffPng[vp] });
7624
- }
7625
- }
7626
- }
7627
- return out;
7628
- }
7629
- function toSnapshot(state, finished, uploaded, mode = "local") {
7630
- const have = (name) => uploaded.has(name) ? name : null;
7631
- const status = state.stopped ? "stopped" : state.phase === "failed" ? "failed" : finished ? "done" : "running";
7632
- return {
7633
- mode,
7634
- status,
7635
- agent: state.agent,
7636
- model: state.model,
7637
- judge_model: state.judgeModel ?? null,
7638
- skill: state.skill?.name?.slice(0, 120) ?? null,
7639
- base_ref: state.baseRef?.slice(0, 200) ?? null,
7640
- phase: state.phase ?? null,
7641
- phase_detail: state.phaseDetail?.slice(0, 300) ?? null,
7642
- current_surface: state.current?.surface ?? null,
7643
- current_attempt: state.current?.attempt ?? null,
7644
- current_progress: state.current ? {
7645
- steps: state.current.steps ?? 0,
7646
- last_step: state.current.lastStep ? syncableStep(state.current.lastStep) : null,
7647
- files: (state.current.files ?? []).slice(0, 20).map((f) => f.slice(0, 300)),
7648
- started_at: state.current.startedAt,
7649
- timeout_ms: state.current.timeoutMs ?? null
7650
- } : null,
7651
- error: state.error?.slice(0, 1e3) ?? null,
7652
- branch: state.branch,
7653
- base_sha: state.baseSha,
7654
- cli_version: null,
7655
- ...state.pr ? { pr: { url: state.pr.url, number: state.pr.number } } : {},
7656
- started_at: state.createdAt,
7657
- finished_at: finished || status === "failed" ? state.finishedAt ?? (/* @__PURE__ */ new Date()).toISOString() : null,
7658
- surfaces: state.surfaces.map((s) => {
7659
- const kept = lastKept(s);
7660
- const key = s.surface.key;
7661
- const shots = {};
7662
- for (const vp of VIEWPORT_NAMES) {
7663
- for (const kind of ["before", "after", "diff"]) {
7664
- const name = have(`${key}/${kind}-${vp}.png`);
7665
- if (name) shots[`${kind}-${vp}`] = name;
7666
- }
8401
+ } else {
8402
+ const rejected = s.iterations.some((i) => i.outcome === "rejected" || i.outcome === "capture_failed");
8403
+ const neverFinished = s.iterations.length > 0 && s.iterations.every((i) => i.outcome === "agent_failed");
8404
+ s.status = rejected ? "reverted" : neverFinished ? "blocked" : "skipped";
8405
+ s.note = s.iterations[s.iterations.length - 1]?.reason ?? null;
7667
8406
  }
7668
- return {
7669
- surface_key: key,
7670
- kind: s.surface.kind,
7671
- path: s.surface.path,
7672
- label: s.surface.label.slice(0, 300),
7673
- status: s.status,
7674
- note: s.note?.slice(0, 1e3) ?? null,
7675
- // Small-steps mode: the plan as a checklist (the step texts are the agent's own plan, file names included).
7676
- plan: s.plan?.steps.length ? s.plan.steps.slice(0, 8).map((p) => ({ text: p.text.slice(0, 300), status: p.status, attempt: p.attempt ?? null })) : null,
7677
- penalty_before: worstPenalty(s.baseline),
7678
- penalty_after: kept ? worstPenalty(kept.after) : null,
7679
- probe_before: probeSummary(s.baseline.desktop?.probes),
7680
- probe_after: probeSummary(kept?.after.desktop?.probes),
7681
- judge: s.judge?.length ? s.judge.map((j) => ({
7682
- viewport: j.viewport,
7683
- model: j.model,
7684
- preferred: j.preferred,
7685
- confidence: j.confidence,
7686
- summary: j.summary.slice(0, 2e3),
7687
- better: j.better.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),
7688
- worse: j.worse.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),
7689
- ...j.error ? { error: j.error.slice(0, 500) } : {}
7690
- })) : null,
7691
- thumbs: { before: shots["before-desktop"] ?? null, after: shots["after-desktop"] ?? null, diff: shots["diff-desktop"] ?? null },
7692
- shots,
7693
- iterations: s.iterations.map((it) => {
7694
- const itShots = {};
7695
- for (const vp of VIEWPORT_NAMES) {
7696
- for (const kind of ["after", "diff"]) {
7697
- const name = have(`${key}/iter${it.n}-${kind}-${vp}.png`);
7698
- if (name) itShots[`${kind}-${vp}`] = name;
7699
- }
8407
+ rmSync4(join23(wtPath, SCRATCH_DIR), { recursive: true, force: true });
8408
+ persist();
8409
+ }
8410
+ async function runJudge(model) {
8411
+ state.judgeModel = model;
8412
+ const changed = state.surfaces.filter((x) => x.iterations.some((i) => i.outcome === "accepted"));
8413
+ if (changed.length === 0) return;
8414
+ log(`Reviewing ${changed.length} changed screen(s) with ${model}\u2026`);
8415
+ for (const s of changed) {
8416
+ if (s.judge?.length) continue;
8417
+ const verdicts = [];
8418
+ for (const vp of VIEWPORTS) {
8419
+ const v = await judgeSurface(s, vp.name, { dir, repoRoot: wtPath, designFiles, model, cacheDir: join23(dirname6(dir), "judge-cache") });
8420
+ if (v) {
8421
+ verdicts.push(v);
8422
+ addJudgeUsage(state, model, v);
7700
8423
  }
7701
- return {
7702
- n: it.n,
7703
- agent: it.agent,
7704
- model: it.model,
7705
- duration_ms: it.durationMs,
7706
- outcome: it.outcome,
7707
- reason: it.reason.slice(0, 1e3),
7708
- commit_sha: it.commitSha,
7709
- pixel_diff: it.pixelDiff,
7710
- penalty_after: worstPenalty(it.after),
7711
- steps: syncableSteps(it.logTail),
7712
- step: it.step?.slice(0, 300) ?? null,
7713
- shots: itShots
7714
- };
7715
- })
7716
- };
7717
- })
7718
- };
7719
- }
7720
- function startSync(dir, cfg, events, log) {
7721
- const uploaded = /* @__PURE__ */ new Map();
7722
- let timer = null;
7723
- let running = Promise.resolve();
7724
- let lastError = null;
7725
- let warned = false;
7726
- const headers2 = {
7727
- Authorization: `Bearer ${cfg.apiKey}`,
7728
- "X-Mushi-Api-Key": cfg.apiKey,
7729
- "X-Mushi-Project": cfg.projectId,
7730
- "Content-Type": "application/json"
7731
- };
7732
- async function api3(method, path, body) {
7733
- const res = await fetch(`${cfg.endpoint}/v1/admin/projects/${cfg.projectId}/ux-runs/${path}`, {
7734
- method,
7735
- headers: headers2,
7736
- body: JSON.stringify(body),
7737
- signal: AbortSignal.timeout(3e4)
7738
- });
7739
- const json = await res.json().catch(() => null);
7740
- if (json?.error?.code === "INSUFFICIENT_SCOPE") {
7741
- throw new Error("this Mushi key cannot write to the console. Run `mushi login` (browser sign-in) for a key that can, then retry");
8424
+ }
8425
+ s.judge = verdicts;
8426
+ const errors = verdicts.filter((v) => v.error);
8427
+ if (errors.length) log(` review of ${s.surface.label} failed: ${errors[0].error}`);
8428
+ const prefersBefore = verdicts.filter((v) => !v.error && v.preferred === "before" && v.confidence !== "low");
8429
+ if (prefersBefore.length) {
8430
+ log(` \u26A0 reviewer prefers the original ${s.surface.label} (${prefersBefore.map((v) => v.viewport).join(", ")}) \u2014 check it before merging`);
8431
+ }
8432
+ persist();
8433
+ }
7742
8434
  }
7743
- if (!res.ok || !json?.ok) throw new Error(json?.error?.message ?? `HTTP ${res.status}`);
7744
- return json.data;
7745
- }
7746
- async function uploadShots2(state) {
7747
- const todo = wantedShots(state).filter((w) => uploaded.get(w.name) !== w.rel);
7748
- for (let i = 0; i < todo.length; i += UPLOAD_BATCH) {
7749
- const batch = todo.slice(i, i + UPLOAD_BATCH);
7750
- const data = await api3("POST", `${state.runId}/uploads`, { names: batch.map((w) => w.name) });
7751
- for (const u of data.uploads) {
7752
- const want = batch.find((w) => w.name === u.name);
7753
- if (!want) continue;
7754
- const png = cropTop(readFileSync16(join20(dir, want.rel)), 2400);
7755
- const put = await fetch(u.signedUrl, {
7756
- method: "PUT",
7757
- headers: { "Content-Type": "image/png", "x-upsert": "true" },
7758
- body: new Uint8Array(png),
7759
- signal: AbortSignal.timeout(6e4)
7760
- });
7761
- if (!put.ok) throw new Error(`screenshot upload failed (HTTP ${put.status})`);
7762
- uploaded.set(want.name, want.rel);
8435
+ async function checkRegressions(changed) {
8436
+ const finished = state.surfaces.filter((x) => x !== changed && ["accepted", "reverted", "skipped"].includes(x.status)).slice(-(opts.regressionSample ?? 5));
8437
+ const desktop = VIEWPORTS[0];
8438
+ for (const other of finished) {
8439
+ const ref = referenceShot(other, desktop.name);
8440
+ if (!ref) continue;
8441
+ const refPng = readFileSync19(join23(dir, ref.png));
8442
+ const moved = (png) => {
8443
+ const diff = pixelDiff(refPng, png);
8444
+ return diff.contentRatio > REGRESSION_CONTENT_RATIO && diff.changedPixels > REGRESSION_MIN_PIXELS ? diff : null;
8445
+ };
8446
+ let now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null);
8447
+ if (!now || !moved(now.png)) continue;
8448
+ await new Promise((r) => setTimeout(r, 3e3));
8449
+ now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null);
8450
+ const d = now ? moved(now.png) : null;
8451
+ if (now && d) {
8452
+ const pct = (d.contentRatio * 100).toFixed(0);
8453
+ other.status = "regressed";
8454
+ other.note = `${pct}% of this screen changed after "${changed.surface.label}" was kept. Check whether a shared component or token moved.`;
8455
+ savePng(dir, `shots/${other.surface.key}/regressed-${desktop.name}.png`, now.png);
8456
+ log(` \u26A0 ${other.surface.label}: ${pct}% of the screen moved \u2014 marked regressed`);
8457
+ }
7763
8458
  }
8459
+ persist();
7764
8460
  }
7765
8461
  }
7766
- async function syncOnce(finished) {
7767
- const state = loadState(dir);
7768
- if (!state) return;
7769
- try {
7770
- await api3("PUT", state.runId, toSnapshot(state, false, uploaded, cfg.mode));
7771
- await uploadShots2(state);
7772
- await api3("PUT", state.runId, toSnapshot(state, finished, uploaded, cfg.mode));
7773
- lastError = null;
7774
- } catch (err) {
7775
- lastError = err.message;
7776
- if (!warned) {
7777
- log(`Console sync failed (will retry): ${lastError}`);
7778
- warned = true;
7779
- }
8462
+ }
8463
+
8464
+ // src/pr.ts
8465
+ var PR_URL_RE = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)/;
8466
+ function continuedBranch(baseRef, defaultBranch) {
8467
+ const m = baseRef?.match(/^origin\/(.+)$/);
8468
+ if (!m || m[1] === defaultBranch || m[1] === "HEAD") return null;
8469
+ return m[1];
8470
+ }
8471
+ var keptOf = (iterations) => iterations.filter((it) => it.outcome === "accepted" && it.commitSha);
8472
+ function prTitle(state) {
8473
+ const names = state.surfaces.filter((s) => keptOf(s.iterations).length > 0).map((s) => s.surface.label.split(/\s+[—|–·]\s+/)[0].trim());
8474
+ const joined = names.length <= 1 ? names[0] ?? "app" : names.length <= 3 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : `${names.slice(0, 2).join(", ")} and ${names.length - 2} more`;
8475
+ const title = `fix(ux): polish the ${joined} screen${names.length === 1 ? "" : "s"}`;
8476
+ return title.length <= 72 ? title : `fix(ux): polish ${names.length} screens`;
8477
+ }
8478
+ function prBody(state) {
8479
+ const lines = [
8480
+ `Made by Mushi's UX loop (\`mushi ux\`): ${state.agent}${state.model ? ` \xB7 ${state.model}` : ""}${state.skill?.name ? ` \xB7 skills: ${state.skill.name}` : ""}.`,
8481
+ "Each commit is one step that did not make accessibility, layout or console measurements worse; a second model could roll a kept step back. Each commit can be kept or dropped on its own.",
8482
+ ""
8483
+ ];
8484
+ const review = [];
8485
+ for (const s of state.surfaces) {
8486
+ const kept = keptOf(s.iterations);
8487
+ const tried = s.iterations.length;
8488
+ if (tried === 0) continue;
8489
+ lines.push(`### ${s.surface.label} \`${s.surface.path}\``, `${kept.length} of ${tried} attempts kept.`, "");
8490
+ for (const it of kept) {
8491
+ const what = (it.step ?? it.reason).replace(/\s+/g, " ").slice(0, 220);
8492
+ const checker = it.checker ? ` ${it.checker.model}: ${it.checker.error ? "could not review" : it.checker.verdict === "keep" ? "agrees" : "unsure"}.` : "";
8493
+ lines.push(`- \`${it.commitSha.slice(0, 9)}\` ${what}${it.needsReview ? " **Needs your review.**" : ""}${checker}`);
8494
+ if (it.needsReview) review.push(`\`${it.commitSha.slice(0, 9)}\` (${s.surface.label})`);
7780
8495
  }
8496
+ const vetoed = s.iterations.filter((it) => it.checker?.verdict === "revert");
8497
+ for (const it of vetoed) lines.push(`- Rolled back by ${it.checker.model}: ${it.checker.summary.replace(/\s+/g, " ").slice(0, 200)}`);
8498
+ lines.push("");
7781
8499
  }
7782
- const schedule = () => {
7783
- if (timer) return;
7784
- timer = setTimeout(() => {
7785
- timer = null;
7786
- running = running.then(() => syncOnce(false));
7787
- }, 1500);
7788
- };
7789
- events.on("event", (e) => {
7790
- if (e.type === "state" || e.type === "phase") schedule();
7791
- });
7792
- return {
7793
- async finish() {
7794
- if (timer) clearTimeout(timer);
7795
- timer = null;
7796
- await running;
7797
- await syncOnce(true);
7798
- return lastError;
8500
+ if (review.length) lines.push("## Read these diffs", `Nothing visible changed in a screenshot, so the measurements could not judge them: ${review.join(", ")}.`, "");
8501
+ lines.push(`Run \`${state.runId}\`, branch \`${state.branch}\`. Screenshots of every attempt are on the Mushi console's UX runs page.`);
8502
+ return lines.join("\n");
8503
+ }
8504
+ async function openRunPullRequest(state, exec) {
8505
+ if (!state.branch) throw new Error("This run has no branch yet.");
8506
+ if (!state.surfaces.some((s) => keptOf(s.iterations).length > 0)) throw new Error("This run kept no change, so there is nothing to open a pull request for.");
8507
+ if (state.pr) return state.pr;
8508
+ const defaultBranch = (await exec("gh", ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"])).trim() || "main";
8509
+ const onto = continuedBranch(state.baseRef, defaultBranch);
8510
+ if (onto) {
8511
+ const open = JSON.parse(await exec("gh", ["pr", "list", "--head", onto, "--state", "open", "--json", "number,url", "--limit", "1"]) || "[]");
8512
+ if (open[0]) {
8513
+ await exec("git", ["push", "origin", `${state.branch}:${onto}`]);
8514
+ return { url: open[0].url, number: open[0].number, added: true };
7799
8515
  }
7800
- };
8516
+ }
8517
+ await exec("git", ["push", "-u", "origin", state.branch]);
8518
+ const out = await exec("gh", ["pr", "create", "--draft", "--base", defaultBranch, "--head", state.branch, "--title", prTitle(state), "--body", prBody(state)]);
8519
+ const m = out.match(PR_URL_RE);
8520
+ if (!m) throw new Error(`gh did not print the new pull request's URL: ${out.trim().slice(0, 200)}`);
8521
+ return { url: m[0], number: Number(m[1]), added: false };
7801
8522
  }
7802
8523
 
7803
8524
  // src/cli.ts
@@ -7807,8 +8528,8 @@ function openInBrowser(url) {
7807
8528
  }
7808
8529
  function profileDirFor(url) {
7809
8530
  const origin = new URL(url).origin;
7810
- const base = process.env.LOCALAPPDATA ?? join21(homedir3(), ".cache");
7811
- return join21(base, "mushi", "ux-profiles", createHash5("sha1").update(origin).digest("hex").slice(0, 12));
8531
+ const base = process.env.LOCALAPPDATA ?? join24(homedir4(), ".cache");
8532
+ return join24(base, "mushi", "ux-profiles", createHash7("sha1").update(origin).digest("hex").slice(0, 12));
7812
8533
  }
7813
8534
  var collect = (v, prev) => [...prev, v];
7814
8535
  function settingsFromSaved(saved, runId) {
@@ -7844,7 +8565,7 @@ var collectSelector = (v, prev) => {
7844
8565
  var program = new Command().name("mushi-ux").description("Run a coding agent over every screen of your app, one at a time, and keep only measured improvements.");
7845
8566
  program.command("login").description("Open a browser window to sign in to your app once; later runs reuse the session.").requiredOption("--url <url>", "Your app, e.g. http://localhost:5173").action(async (o) => {
7846
8567
  const dir = profileDirFor(o.url);
7847
- const ctx = await chromium2.launchPersistentContext(dir, { headless: false });
8568
+ const ctx = await chromium3.launchPersistentContext(dir, { headless: false });
7848
8569
  const page = ctx.pages()[0] ?? await ctx.newPage();
7849
8570
  await page.goto(o.url);
7850
8571
  console.log("Sign in, then close the browser window. The session stays on this machine only.");
@@ -8001,7 +8722,7 @@ program.command("audit").description("Find UI/UX bugs on the signed-in screens o
8001
8722
  ${result.screens} screen(s), ${result.findings.length} finding(s), ${result.blockedWrites} write request(s) blocked. Summary: ${result.dir}/summary.md`);
8002
8723
  for (const e of result.reviewErrors.slice(0, 5)) console.warn(`Review: ${e}`);
8003
8724
  if (!o.file) return;
8004
- const outcome = await fileFindings({ findings: result.findings, baseUrl: o.url, cfg, ledgerPath: join21(auditHome(), "filed.json"), dryRun: o.dryRun });
8725
+ const outcome = await fileFindings({ findings: result.findings, baseUrl: o.url, cfg, ledgerPath: join24(auditHome(), "filed.json"), dryRun: o.dryRun });
8005
8726
  for (const f of outcome.filed) console.log(`Filed ${f.reportId}: ${f.title}`);
8006
8727
  for (const s of outcome.skipped) console.log(`Skipped ${s.fingerprint}: ${s.reason}`);
8007
8728
  const pending = writePending(result.dir, outcome.pending);
@@ -8027,7 +8748,7 @@ program.command("scorecard").description("Score every page of a live app against
8027
8748
  const m = /^([0-9]{3,4})x([0-9]{3,4})$/.exec(vp);
8028
8749
  if (!m) throw new InvalidArgumentError(`--viewport must look like 1440x900, not ${vp}`);
8029
8750
  const viewport = { width: Number(m[1]), height: Number(m[2]) };
8030
- const fromFile = o.pathsFile ? readFileSync17(o.pathsFile, "utf8").split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#")) : [];
8751
+ const fromFile = o.pathsFile ? readFileSync20(o.pathsFile, "utf8").split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#")) : [];
8031
8752
  const runId = scorecardRunId(/* @__PURE__ */ new Date());
8032
8753
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
8033
8754
  const scorer = o.scoreVia === "server" ? serverScorer(cfg, runId) : localScorer(o.scoreVia, o.model ?? (o.scoreVia === "cursor" ? DEFAULT_CURSOR_REVIEW_MODEL : DEFAULT_SCORECARD_MODEL));
@@ -8060,7 +8781,7 @@ program.command("scorecard").description("Score every page of a live app against
8060
8781
  const mean = scored.length ? scored.reduce((n, p) => n + (p.score?.overall ?? 0), 0) / scored.length : 0;
8061
8782
  const cross = result.causes.filter((c) => c.kind !== "page").length;
8062
8783
  console.log(`
8063
- ${scored.length} of ${result.pages.length} page(s) scored, average ${mean.toFixed(1)}/10; ${cross} cross-page cause(s). Scorecard: ${join21(result.dir, "scorecard.md")}`);
8784
+ ${scored.length} of ${result.pages.length} page(s) scored, average ${mean.toFixed(1)}/10; ${cross} cross-page cause(s). Scorecard: ${join24(result.dir, "scorecard.md")}`);
8064
8785
  if (result.groupError) console.warn(`Cross-page pass: ${result.groupError} (the code's grouping stands).`);
8065
8786
  if (!cfg) return;
8066
8787
  const uploaded = scorer.uploaded ?? await uploadAllShots(cfg, runId, result.pages);
@@ -8075,6 +8796,99 @@ ${scored.length} of ${result.pages.length} page(s) scored, average ${mean.toFixe
8075
8796
  for (const s of outcome.skipped) console.log(`Not filed ${s.patternKey}: ${s.reason}`);
8076
8797
  }
8077
8798
  );
8799
+ var collectFlow = (v, prev) => {
8800
+ try {
8801
+ return [...prev, parseFlow(v)];
8802
+ } catch (err) {
8803
+ throw new InvalidArgumentError(err.message);
8804
+ }
8805
+ };
8806
+ program.command("clips").description(`Record short clips of your top flows (Playwright video, read-only) and upload them into a release kit for a product video. Opt-in per app, at most ${CLIP_LIMITS.maxFlows} flows, capped in length and size.`).requiredOption("--url <url>", "The app to record, e.g. https://staging.example.com").option("--release <id>", "The release whose kit gets the clips (needs MUSHI_API_KEY / MUSHI_PROJECT_ID)").option("--flow <name:/a,/b>", "A flow: a name and the screens it visits in order (repeatable)", collectFlow, []).option("--viewport <WxH>", `Recording size (default ${DEFAULT_CLIP_VIEWPORT.width}x${DEFAULT_CLIP_VIEWPORT.height}, a phone)`).option("--max-seconds <n>", `Longest clip per flow (${CLIP_LIMITS.minSeconds}-${CLIP_LIMITS.maxSeconds})`, String(CLIP_LIMITS.defaultSeconds)).option("--max-mb <n>", "Largest clip kept, in MB (at most 100; the app's kit may cap it lower)", "25").option("--profile-dir <dir>", "A cached, signed-in browser profile to record signed in").option("--channel <name>", "Browser build for --profile-dir: chrome (default) or chromium", parseChannel).option("--allow <rule>", "Allow a non-GET request that only reads (repeatable)", collect, []).option("--out <dir>", "Where the clips are written", join24(process.cwd(), ".mushi-ux", "clips")).option("--no-upload", "Record only; do not upload").action(
8807
+ async (o) => {
8808
+ if (!o.flow.length) throw new InvalidArgumentError('Name at least one flow, e.g. --flow "signup:/,/signup"');
8809
+ let viewport = DEFAULT_CLIP_VIEWPORT;
8810
+ if (o.viewport) {
8811
+ const m = /^([0-9]{3,4})x([0-9]{3,4})$/.exec(o.viewport);
8812
+ if (!m) throw new InvalidArgumentError(`--viewport must look like 390x844, not ${o.viewport}`);
8813
+ viewport = { width: Number(m[1]), height: Number(m[2]) };
8814
+ }
8815
+ const cfg = o.upload ? syncConfigFromEnv() : null;
8816
+ for (const k of ["MUSHI_API_KEY", "MUSHI_PROJECT_ID", "MUSHI_API_ENDPOINT"]) delete process.env[k];
8817
+ if (o.upload && (!cfg || !o.release)) {
8818
+ console.warn(!cfg ? "No MUSHI_API_KEY / MUSHI_PROJECT_ID: recording only. Set them (mushi login) and pass --release <id> to upload." : "No --release: recording only. Pass --release <id> to upload into that release's kit.");
8819
+ }
8820
+ let caps = { maxSeconds: Number(o.maxSeconds), maxBytes: Number(o.maxMb) * 1024 * 1024 };
8821
+ if (cfg && o.release) {
8822
+ const eff = effectiveClipCaps(caps, await fetchClipCaps(cfg, o.release));
8823
+ for (const n of eff.notes) console.log(n);
8824
+ if (eff.blocked) {
8825
+ console.warn(eff.blocked);
8826
+ process.exitCode = 1;
8827
+ return;
8828
+ }
8829
+ caps = { maxSeconds: eff.maxSeconds, maxBytes: eff.maxBytes };
8830
+ }
8831
+ const cached = cachedProfile(o);
8832
+ const result = await recordClips({
8833
+ baseUrl: o.url,
8834
+ flows: o.flow,
8835
+ outDir: o.out,
8836
+ viewport,
8837
+ maxSeconds: caps.maxSeconds,
8838
+ maxBytes: caps.maxBytes,
8839
+ allow: o.allow,
8840
+ ...cached ? { profileDir: cached.profileDir, channel: cached.channel } : {},
8841
+ log: (m) => console.log(m)
8842
+ });
8843
+ for (const n of result.notes) console.log(n);
8844
+ for (const s of result.skipped) console.warn(`Dropped "${s.name}": ${s.reason}`);
8845
+ if (result.guard.blocked.length) console.log(`${result.guard.blocked.length} write request(s) were blocked while recording (read-only).`);
8846
+ console.log(`
8847
+ ${result.clips.length} clip(s) in ${o.out}`);
8848
+ if (!cfg || !o.release || !result.clips.length) return;
8849
+ const up = await uploadClips(cfg, o.release, result.clips);
8850
+ for (const f of up.failed) console.warn(`Not uploaded "${f.name}": ${f.reason}`);
8851
+ console.log(`${up.uploaded.length} clip(s) in the release kit: ${consoleBaseUrl()}/releases`);
8852
+ }
8853
+ );
8854
+ program.command("upload <dir>").description("Score screenshots any driver made (Maestro, adb, the iOS simulator, an SDK debug build) on the UX scorecard: <dir>/pages/<screen>/settled.png, plus facts.json, window.xml or hierarchy.json (ADR 0073).").addOption(new Option("--platform <name>", "What the screens are from").choices([...UPLOAD_PLATFORMS]).makeOptionMandatory()).option("--device <name>", 'The device or simulator, e.g. "Pixel 8 (API 35)"').addOption(new Option("--source <driver>", "The driver that captured them").choices([...UPLOAD_SOURCES])).option("--app <name>", "What to call the app in the prompts and the run").option("--about <text>", "One line on what the app is and who uses it").option("--scale <n>", "Pixels per point of the device (e.g. 3 for most phones), so the viewport is in points; default 1 (pixels)").option("--viewport <WxH>", "The run viewport (default: the first screen)").option("--max-cost <usd>", "The most this run may spend on server scoring").option("--no-score", "Only upload; score later").option("--file", "File the top root causes as reports (one per cause, at most 5 a run)").option("--dry-run", "With --file: show what would be filed, file nothing").action(
8855
+ async (dir, o) => {
8856
+ const cfg = syncConfigFromEnv();
8857
+ for (const k of ["MUSHI_API_KEY", "MUSHI_PROJECT_ID", "MUSHI_API_ENDPOINT"]) delete process.env[k];
8858
+ if (!cfg) throw new Error("upload needs MUSHI_API_KEY and MUSHI_PROJECT_ID (run mushi login, or `mushi ux upload`, which passes your login).");
8859
+ const num = (raw, name) => {
8860
+ if (raw === void 0) return void 0;
8861
+ const n = Number(raw);
8862
+ if (!Number.isFinite(n) || n <= 0) throw new InvalidArgumentError(`${name} must be a positive number, not ${raw}`);
8863
+ return n;
8864
+ };
8865
+ const r = await uploadCaptures(cfg, {
8866
+ dir,
8867
+ platform: o.platform,
8868
+ device: o.device,
8869
+ source: o.source,
8870
+ app: o.app,
8871
+ about: o.about,
8872
+ scale: num(o.scale, "--scale"),
8873
+ viewport: o.viewport,
8874
+ maxCostUsd: num(o.maxCost, "--max-cost"),
8875
+ score: o.score,
8876
+ file: o.file,
8877
+ dryRun: o.dryRun,
8878
+ onProgress: (m) => process.stderr.write(` ${m}
8879
+ `)
8880
+ });
8881
+ console.log(
8882
+ `
8883
+ Run ${r.runId}: ${r.uploaded} screenshot(s) of ${r.pages} screen(s)` + (r.reservedUsd != null ? `, up to $${r.reservedUsd.toFixed(2)} of AI budget held for scoring` : "") + (o.score ? `; ${r.scored} scored${r.mean != null ? `, average ${r.mean}/10` : ""}, ${r.causes.length} root cause(s).` : ". Not scored (--no-score).")
8884
+ );
8885
+ for (const e of r.errors) console.warn(` ${e}`);
8886
+ for (const f of r.filed?.filed ?? []) console.log(`Filed ${f.reportId}: ${f.title}`);
8887
+ for (const w of r.filed?.wouldFile ?? []) console.log(`Would file: ${w.title} (${w.pages} page(s), ${w.patternKey})`);
8888
+ console.log(`On the console: ${r.consoleUrl}`);
8889
+ if (r.errors.length && r.scored === 0 && o.score) process.exitCode = 1;
8890
+ }
8891
+ );
8078
8892
  program.command("explore").description("Let a model use the signed-in app like a careless user, read-only; file only the errors that happen again when its steps are replayed.").requiredOption("--url <url>", "The live app where your cached session is signed in; sessions start here").option("--profile-dir <dir>", "The cached, signed-in browser profile to reuse (e.g. ~/.playwright-cli-profiles/<app>); never a fresh browser").option("--channel <name>", "Browser build for --profile-dir: chrome (default) or chromium", parseChannel).option("--path <path>", "Start sessions from this path too (repeatable; default: the url)", collect, []).option("--charter <name>", `What a session tries: ${Object.keys(CHARTERS).join(", ")} (repeatable; default: all)`, collect, []).option("--steps <n>", "Actions per session (at most 60)", "35").option("--model <id>", "Cursor CLI model that picks the actions", DEFAULT_CURSOR_REVIEW_MODEL).option("--api-host <host>", "A host whose 5xx count as the app's, e.g. the API (repeatable)", collect, []).option("--allow <rule>", "Allow a non-GET request that only reads (repeatable)", collect, []).option("--ignore <selector>", "CSS selector that is not part of the app (repeatable)", collectSelector, []).option("--file", `File confirmed findings as Mushi reports (MUSHI_API_KEY / MUSHI_PROJECT_ID; at most ${AUDIT_FILE_CAP} a run, deduped)`).option("--dry-run", "With --file: show what would be filed, file nothing").action(
8079
8893
  async (o) => {
8080
8894
  const cached = cachedProfile(o);
@@ -8105,7 +8919,7 @@ ${result.sessions} session(s), ${result.steps} action(s), ${result.candidates} c
8105
8919
  for (const f of result.findings) console.log(`- ${f.severity} ${f.screen}: ${f.summary}`);
8106
8920
  return;
8107
8921
  }
8108
- const outcome = await fileFindings({ findings: result.findings, baseUrl: o.url, cfg, ledgerPath: join21(auditHome(), "filed.json"), dryRun: o.dryRun });
8922
+ const outcome = await fileFindings({ findings: result.findings, baseUrl: o.url, cfg, ledgerPath: join24(auditHome(), "filed.json"), dryRun: o.dryRun });
8109
8923
  for (const f of outcome.filed) console.log(`Filed ${f.reportId}: ${f.title}`);
8110
8924
  for (const s of outcome.skipped) console.log(`Skipped ${s.fingerprint}: ${s.reason}`);
8111
8925
  const pending = writePending(result.dir, outcome.pending);
@@ -8114,14 +8928,14 @@ ${result.sessions} session(s), ${result.steps} action(s), ${result.candidates} c
8114
8928
  }
8115
8929
  }
8116
8930
  );
8117
- program.command("fresh-eyes").description("Try one goal like a first-time visitor (signed out, never seen the product) and time the path; file what stops them (ADR 0053).").option("--url <url>", "Where a stranger starts: the landing page (required unless --request-stdin)").option("--goal <text>", 'What they came to do, in plain words, e.g. "get my first bug explained" (required unless --request-stdin)').option("--sessions <n>", "Independent sessions; opinions are filed only when 2 agree", "3").option("--steps <n>", "Actions per session (at most 80; default 30, or 60 with a test account)").option("--model <id>", "Cursor CLI model that plays the visitor", DEFAULT_CURSOR_REVIEW_MODEL).option("--app-host <host>", "A host that is the app's own (its API, its Supabase project): writes may reach it (repeatable)", collect, []).option("--success-url <glob>", 'The goal is reached at this path, e.g. "/admin/reports/*"').option("--success-text <regex>", "The goal is reached when this text is visible").option("--success-selector <css>", "The goal is reached when this element is visible").option("--success-api <url>", "The goal is reached when a GET here (with the session cookies) answers with data").option("--mint-account", "Mushi only: mint a synthetic account per session through the console (operator key; deleted after 24 h)").option("--terminal", "Run the CLI setup step itself when a screen asks for a terminal (scaffold a sample, run the setup, send a report)").option("--setup-command <cmd>", "With --terminal: the setup command; {projectId} and {apiKey} are filled in").option("--allow <rule>", "Allow a non-GET request that only reads (repeatable)", collect, []).option("--out <dir>", "Where the timeline, screenshots and result go").option("--sync", "Mirror the run to the console (First-time user test page)").option("--file", "File confirmed findings as Mushi reports (at most 15 a run, deduped); mirrors the run to the console too").option("--dry-run", "Read-only, no account, nothing filed: tests up to the sign-up wall (with --sync it still shows in the console)").option("--request-stdin", "Read the run as JSON on stdin (run id, start page, goal, visitors, test accounts): how a local worker runs a test the console queued").action(
8931
+ program.command("fresh-eyes").description("Try one goal like a first-time visitor (signed out, never seen the product) and time the path; file what stops them (ADR 0053).").option("--url <url>", "Where a stranger starts: the landing page (required unless --request-stdin)").option("--goal <text>", 'What they came to do, in plain words, e.g. "get my first bug explained" (required unless --request-stdin)').option("--sessions <n>", "Independent sessions; opinions are filed only when 2 agree", "3").option("--steps <n>", "Actions per session (at most 80; default 30, or 60 with a test account)").option("--model <id>", "Cursor CLI model that plays the visitor", DEFAULT_CURSOR_REVIEW_MODEL).option("--app-host <host>", "A host that is the app's own (its API, its Supabase project): writes may reach it (repeatable)", collect, []).option("--success-url <glob>", 'The goal is reached at this path, e.g. "/admin/reports/*"').option("--success-text <regex>", "The goal is reached when this text is visible").option("--success-selector <css>", "The goal is reached when this element is visible").option("--success-api <url>", "The goal is reached when a GET here (with the session cookies) answers with data").option("--mint-account", "Testing this Mushi instance itself: mint a synthetic console account per session (operator key only, checked by the server; deleted after 24 h)").option("--terminal", "Run the CLI setup step itself when a screen asks for a terminal (scaffold a sample, run the setup, send a report)").option("--setup-command <cmd>", "With --terminal: the setup command; {projectId} and {apiKey} are filled in").option("--allow <rule>", "Allow a non-GET request that only reads (repeatable)", collect, []).option("--out <dir>", "Where the timeline, screenshots and result go").option("--sync", "Mirror the run to the console (First-time user test page)").option("--file", "File confirmed findings as Mushi reports (at most 15 a run, deduped); mirrors the run to the console too").option("--dry-run", "Read-only, no account, nothing filed: tests up to the sign-up wall (with --sync it still shows in the console)").option("--request-stdin", "Read the run as JSON on stdin (run id, start page, goal, visitors, test accounts): how a local worker runs a test the console queued").action(
8118
8932
  async (o) => {
8119
8933
  const req = o.requestStdin ? parseStdinRequest(await readStdin()) : null;
8120
8934
  const url = req?.url ?? o.url;
8121
8935
  const goal = req?.goal ?? o.goal;
8122
8936
  if (!url || !goal) throw new Error("--url and --goal are required (or --request-stdin).");
8123
8937
  const dryRun = req ? req.dryRun : !!o.dryRun;
8124
- const preset = presetFor(url);
8938
+ const preset = presetFor(url, loadPresets());
8125
8939
  const given = req ? { text: req.successText ? literalPattern(req.successText) : void 0 } : { url: o.successUrl, text: o.successText, selector: o.successSelector, api: o.successApi };
8126
8940
  const success = hasSuccessCheck(given) ? given : preset?.success ?? {};
8127
8941
  const cfg = o.sync || o.file || o.mintAccount ? syncConfigFromEnv() : null;
@@ -8140,16 +8954,18 @@ program.command("fresh-eyes").description("Try one goal like a first-time visito
8140
8954
  goal,
8141
8955
  success,
8142
8956
  sessions,
8143
- steps: stepsFor(o.steps, !dryRun && (givenAccounts.length > 0 || !!o.mintAccount || !!appAccount)),
8957
+ steps: stepsFor(o.steps, !dryRun && (givenAccounts.length > 0 || !!o.mintAccount || !!appAccount), req?.persona?.steps),
8144
8958
  model: o.model,
8145
8959
  appHosts: [...preset?.appHosts ?? [], ...o.appHost],
8146
8960
  allow: o.allow,
8147
8961
  dryRun,
8148
8962
  outDir: o.out,
8149
8963
  runId: req?.runId,
8964
+ // The console's persona (ADR 0073): its brief, device, language and needs.
8965
+ persona: req?.persona ?? void 0,
8150
8966
  identity: givenAccounts.length ? async (session) => givenAccounts[session - 1] ?? null : o.mintAccount && cfg ? () => mintTestAccount(cfg) : appAccount ? async () => appAccount : void 0,
8151
- // Mushi's own path has a CLI step; a queued run with test accounts takes it too.
8152
- terminal: o.terminal || req && preset && givenAccounts.length ? (v) => runTerminalSetup({ ...v, setupCommand: o.setupCommand }) : void 0,
8967
+ // An app whose preset says its setup has a CLI step: a queued run with test accounts takes it too.
8968
+ terminal: o.terminal || req && preset?.terminal && givenAccounts.length ? (v) => runTerminalSetup({ ...v, setupCommand: o.setupCommand }) : void 0,
8153
8969
  onProgress: (m) => process.stderr.write(` ${m}
8154
8970
  `)
8155
8971
  });
@@ -8167,8 +8983,8 @@ ${result.reached} of ${result.sessions.length} session(s) reached the goal; time
8167
8983
  if (syncError) process.exitCode = 1;
8168
8984
  }
8169
8985
  if (o.file && syncError) {
8170
- const path = join21(result.dir, "to-file.json");
8171
- writeFileSync11(path, JSON.stringify(result.findings, null, 2));
8986
+ const path = join24(result.dir, "to-file.json");
8987
+ writeFileSync12(path, JSON.stringify(result.findings, null, 2));
8172
8988
  console.log(`Nothing filed because the run did not sync. ${result.findings.length} finding(s) kept in ${path}`);
8173
8989
  process.exitCode = 1;
8174
8990
  return;
@@ -8181,8 +8997,8 @@ ${result.reached} of ${result.sessions.length} session(s) reached the goal; time
8181
8997
  for (const f of outcome.filed) console.log(`Filed ${f.reportId}: ${f.title}`);
8182
8998
  for (const s of outcome.skipped) console.log(`Skipped ${s.fingerprint}: ${s.reason}`);
8183
8999
  if (outcome.pending.length) {
8184
- const path = join21(result.dir, "to-file.json");
8185
- writeFileSync11(path, JSON.stringify(outcome.pending, null, 2));
9000
+ const path = join24(result.dir, "to-file.json");
9001
+ writeFileSync12(path, JSON.stringify(outcome.pending, null, 2));
8186
9002
  console.log(dryRun ? `Dry run: ${outcome.pending.length} report(s) would be filed: ${path}` : `No MUSHI_API_KEY / MUSHI_PROJECT_ID: ${outcome.pending.length} report(s) left to file in ${path}`);
8187
9003
  }
8188
9004
  }
@@ -8253,7 +9069,7 @@ program.command("ui").description("Open the studio: pick an agent, a model from
8253
9069
  const dir = runDir(repoRoot, runId);
8254
9070
  const state = loadState(dir);
8255
9071
  if (!state) throw new Error("No such run.");
8256
- const cwd = state.worktree && existsSync12(state.worktree) ? state.worktree : repoRoot;
9072
+ const cwd = state.worktree && existsSync15(state.worktree) ? state.worktree : repoRoot;
8257
9073
  const exec = async (cmd, args) => {
8258
9074
  const r = await run(cmd, args, { cwd, timeoutMs: 6e5 });
8259
9075
  if (r.exitCode !== 0) throw new Error(`${cmd} ${args.slice(0, 2).join(" ")} failed: ${r.tail.trim().slice(-300)}`);