@mushi-mushi/ux 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1004 @@
1
+ import { BrowserContext, Page } from 'playwright';
2
+ import { EventEmitter } from 'node:events';
3
+ import Anthropic from '@anthropic-ai/sdk';
4
+ import { z } from 'zod';
5
+
6
+ /**
7
+ * Child processes for agents, installs and dev servers. Prompts go on stdin
8
+ * (cmd.exe caps a command line near 8 KB), timeouts kill the whole process
9
+ * tree (`taskkill /T /F` on Windows), and agents get a scrubbed environment.
10
+ */
11
+ interface RunResult {
12
+ exitCode: number | null;
13
+ timedOut: boolean;
14
+ durationMs: number;
15
+ /** Last ~4 KB of combined output. */
16
+ tail: string;
17
+ /** Full stdout, capped at 1 MB. */
18
+ stdout: string;
19
+ }
20
+
21
+ /**
22
+ * Coding agents the loop can drive, each as a headless subprocess in the
23
+ * worktree. The full instructions live in `.mushi-ux/PROMPT.md`; the agent
24
+ * gets a one-line pointer to it, edits files, and the loop decides what to
25
+ * keep.
26
+ *
27
+ * Credential boundary (ADR 0006 / 0020): the agent never gets the browser
28
+ * profile or the Mushi CLI config. Its environment is scrubbed of every
29
+ * credential except its own model key, and Claude Code runs `--restricted`,
30
+ * which removes shell tools and confines file access to the worktree.
31
+ *
32
+ * `claude-code` is verified on Windows. `cursor` and `codex` follow their
33
+ * documented headless flags and are unverified until the Plan 021 Phase 0
34
+ * probes run (docs/execplans/ux-loop.md §5).
35
+ */
36
+
37
+ type AgentName = 'claude-code' | 'cursor' | 'codex' | 'cursor-cloud';
38
+ interface AgentRunOptions {
39
+ cwd: string;
40
+ prompt: string;
41
+ model?: string | null;
42
+ timeoutMs: number;
43
+ onLine?: (line: string) => void;
44
+ /** Aborted by the studio's Stop button: the agent's process tree is killed. */
45
+ signal?: AbortSignal;
46
+ /** Continue this earlier session (adapters with canResume) instead of starting a new one. */
47
+ resumeSession?: string;
48
+ }
49
+ interface AgentAdapter {
50
+ name: AgentName | (string & {});
51
+ verified: boolean;
52
+ /** Can continue a session by id (its stream reports session_id): used for "time is up, finish now". */
53
+ canResume?: boolean;
54
+ run(opts: AgentRunOptions): Promise<RunResult>;
55
+ }
56
+ /**
57
+ * Quote one argument for the shell `spawn({ shell: true })` uses, so model
58
+ * specs like `grok-4.7?reasoning_effort=xhigh&context=500k` survive.
59
+ * cmd.exe has no escape inside double quotes, so quotes are dropped there.
60
+ */
61
+ declare function quoteArg(s: string, platform?: NodeJS.Platform): string;
62
+ declare const AGENTS: Record<AgentName, AgentAdapter>;
63
+ declare function getAgent(name: string): AgentAdapter;
64
+
65
+ /**
66
+ * `--agent cursor-cloud`: the edit runs in a Cursor Cloud agent (your Cursor
67
+ * plan pays), the measuring stays local. One attempt:
68
+ *
69
+ * push the run branch → POST /v1/agents on it (workOnCurrentBranch, no PR)
70
+ * → poll the run → fetch the branch → apply the agent's commit to the
71
+ * worktree, uncommitted
72
+ *
73
+ * so the loop's own capture, verdict and commit/revert work unchanged. The
74
+ * agent cannot see the local `.mushi-ux/` files, so the prompt text and the
75
+ * screenshots are sent inline.
76
+ *
77
+ * Wire shape: cursor.com/docs/cloud-agent/api/endpoints (read 2026-10-06).
78
+ * `workOnCurrentBranch: true` makes the agent push to the run branch itself
79
+ * instead of a new `cursor/...` branch, so every push of a run is under
80
+ * `mushi-ux/**` and one `branches-ignore` keeps the host's CI quiet. The next
81
+ * attempt's force-with-lease push replaces whatever the loop did not keep.
82
+ * Images are `{ data, mimeType }`, at most 5; if Cursor still refuses them the
83
+ * run goes on text only.
84
+ */
85
+
86
+ interface CursorCloudDeps {
87
+ fetch?: typeof fetch;
88
+ apiKey?: string;
89
+ /** Override the repo URL read from `git remote get-url origin` (tests). */
90
+ repoUrl?: string;
91
+ sleep?: (ms: number) => Promise<void>;
92
+ }
93
+ /** `git@github.com:o/r.git` / `https://github.com/o/r(.git)` → `https://github.com/o/r`. */
94
+ declare function httpsRepoUrl(remote: string): string | null;
95
+ /** Model spec like `grok-4.7?reasoning_effort=xhigh` → Cursor's `{ id, params }`. */
96
+ declare function cursorModel(spec: string | null | undefined): Record<string, unknown> | undefined;
97
+ declare function cursorCloudAdapter(deps?: CursorCloudDeps): AgentAdapter;
98
+
99
+ /**
100
+ * Hard rule of the loop: exploring and screenshotting an app never writes
101
+ * to it. A localhost dev server often talks to a real backend, so one stray
102
+ * "Delete" click or form submit during discovery would mutate real data.
103
+ *
104
+ * - Every request that is not GET / HEAD / OPTIONS is aborted unless it
105
+ * matches the per-target allowlist (reads some apps make with POST, such as
106
+ * PostgREST `rpc/` calls or GraphQL queries).
107
+ * - Form submission is cancelled in the page itself.
108
+ * - Discovery never clicks an element whose label reads as destructive.
109
+ * - Service Workers are blocked where the context is created (capture.ts):
110
+ * requests a worker handles never reach `context.route`.
111
+ *
112
+ * WebSockets are not routed: a Supabase Realtime socket only subscribes, and
113
+ * table writes go through REST, which the route sees.
114
+ */
115
+
116
+ /** `"POST /rest/v1/rpc/*"`, or a bare path glob meaning any method. */
117
+ type AllowRule = string;
118
+ interface GuardLog {
119
+ blocked: Array<{
120
+ method: string;
121
+ url: string;
122
+ }>;
123
+ }
124
+ /** Pure decision, exported for tests: may this request leave the browser? */
125
+ declare function isRequestAllowed(method: string, url: string, allow: readonly AllowRule[]): boolean;
126
+ /** Pure: should discovery refuse to click an element with this label? */
127
+ declare function isDestructiveLabel(label: string): boolean;
128
+ declare function installGuard(context: BrowserContext, allow: readonly AllowRule[], log?: GuardLog): Promise<GuardLog>;
129
+
130
+ /**
131
+ * Shared shapes for the UX loop: a surface is one screen state worth
132
+ * reviewing (a page, a tab on it, a dialog it opens), reached by loading a
133
+ * URL path and replaying a few clicks.
134
+ */
135
+ type SurfaceKind = 'page' | 'tab' | 'dialog' | 'menu';
136
+ /** One replayable click. `selector` is a Playwright selector string. */
137
+ interface ReplayStep {
138
+ action: 'click';
139
+ selector: string;
140
+ label: string;
141
+ }
142
+ interface Surface {
143
+ /** Stable id: path + replay labels, slugged. */
144
+ key: string;
145
+ kind: SurfaceKind;
146
+ /** Same-origin path with query. Never a full URL, never a token. */
147
+ path: string;
148
+ steps: ReplayStep[];
149
+ label: string;
150
+ /** Structural hash of the rendered DOM, for dedupe across param routes. */
151
+ domHash: string;
152
+ }
153
+ interface Viewport {
154
+ name: 'desktop' | 'mobile';
155
+ width: number;
156
+ height: number;
157
+ }
158
+ declare const VIEWPORTS: readonly Viewport[];
159
+ interface AxeViolation {
160
+ id: string;
161
+ impact: string | null;
162
+ help: string;
163
+ /** How many nodes fail the rule. */
164
+ count: number;
165
+ /** CSS selectors of the offending nodes (first few). */
166
+ targets: string[];
167
+ }
168
+ /** Objective, repeatable measurements of one surface at one viewport. */
169
+ interface ProbeResult {
170
+ axe: AxeViolation[];
171
+ /** Page scrolls sideways at this width. */
172
+ overflowX: boolean;
173
+ /** Interactive elements smaller than 24×24 CSS px (WCAG 2.2 target size). */
174
+ smallTargets: number;
175
+ consoleErrors: string[];
176
+ /** Cumulative layout shift observed while the surface settled. */
177
+ cls: number;
178
+ }
179
+
180
+ /**
181
+ * Browser sessions and screenshots. Every session goes through the write
182
+ * guard (guard.ts) before any page opens.
183
+ *
184
+ * A session can reuse the persistent profile `mushi-ux login` created, so
185
+ * captures see the signed-in app. The profile lives outside the repo and is
186
+ * never named to the coding agent (ADR 0006).
187
+ */
188
+
189
+ interface BrowserSession {
190
+ /** Discovery browses here; app state it leaves behind stays here. */
191
+ context: BrowserContext;
192
+ /**
193
+ * A clean context for one capture: the cookies and storage the session
194
+ * started with (a saved login included), the same guard and init scripts.
195
+ * Captures share no client state, so a screen looks the same however many
196
+ * other screens were visited before it (glot.it /words lost its empty
197
+ * state after other screens wrote to localStorage, 2026-10-07).
198
+ */
199
+ freshContext(): Promise<BrowserContext>;
200
+ /**
201
+ * Visit each path once in the shared context, then seed every later capture
202
+ * from the storage that leaves behind. A first-ever visit can sit on a boot
203
+ * screen past the content wait (glot.it /chat: a skeleton on desktop, blank
204
+ * on the phone, 2026-10-07), so captures start from a visited app, the same
205
+ * one for every screen.
206
+ */
207
+ warmUp(baseUrl: string, paths: readonly string[]): Promise<void>;
208
+ guard: GuardLog;
209
+ /** Selectors hidden in screenshots and left out of every probe (ignore.ts). */
210
+ ignore: readonly string[];
211
+ close(): Promise<void>;
212
+ }
213
+ interface SessionOptions {
214
+ /** Persistent profile directory from `mushi-ux login`; omit for a clean browser. */
215
+ profileDir?: string;
216
+ headless?: boolean;
217
+ allow?: readonly AllowRule[];
218
+ /** Extra selectors to ignore on top of DEFAULT_IGNORE. */
219
+ ignore?: readonly string[];
220
+ }
221
+ declare function openSession(opts?: SessionOptions): Promise<BrowserSession>;
222
+ /**
223
+ * Wait for the network to go quiet and the DOM to stop changing, both
224
+ * bounded. Apps that hold a socket or poll never reach "network idle", so
225
+ * that wait is capped short and the DOM-quiet wait does the real work.
226
+ */
227
+ declare function settle(page: Page, quietMs?: number, maxMs?: number): Promise<void>;
228
+ interface Capture {
229
+ png: Buffer;
230
+ probes: ProbeResult;
231
+ }
232
+ /** Load one surface at one viewport, screenshot it, and measure it. */
233
+ declare function captureSurface(session: BrowserSession, baseUrl: string, surface: Pick<Surface, 'path' | 'steps'>, viewport: Viewport): Promise<Capture>;
234
+
235
+ interface ResolvedSkill {
236
+ name: string;
237
+ /** Skills this one hands over to, from its "## Related" list and "→ skill" mentions. */
238
+ related?: string[];
239
+ /** SKILL.md text. */
240
+ text: string;
241
+ /** Every file of the skill folder, by path relative to it (includes SKILL.md). */
242
+ files: Record<string, Buffer>;
243
+ /** Where it came from: a path, or owner/repo@ref. */
244
+ source: string;
245
+ }
246
+
247
+ /**
248
+ * The local studio: start a run (agent, model, skill, pages) and watch it:
249
+ * phase and progress, the burndown, every attempt's screenshot against the
250
+ * baseline with a slider and a diff overlay, problem scores, and the agent's
251
+ * output as it streams. Served on 127.0.0.1 only, behind a random token,
252
+ * reading nothing but `.mushi/ux/` in the repo.
253
+ *
254
+ * `mushi-ux ui` opens it with the launcher; `mushi-ux run` and `open` open it
255
+ * on one run, read-only.
256
+ */
257
+
258
+ interface Dashboard {
259
+ url: string;
260
+ close(): Promise<void>;
261
+ }
262
+ /** Pure: resolve a requested shot path inside the run dir, or null if it escapes. */
263
+ declare function safeShotPath(runDirPath: string, requested: string): string | null;
264
+ /** One run, read-only (used by `mushi-ux run` and `open`). `dir` is `<repo>/.mushi/ux/<runId>`. */
265
+ declare function startDashboard(dir: string, events?: EventEmitter, port?: number): Promise<Dashboard>;
266
+
267
+ /**
268
+ * Turns a running app into a list of surfaces: every same-origin page
269
+ * reachable from the start paths, plus the tabs, dialogs and menus each page
270
+ * opens. Runs inside a guarded session, so nothing it clicks can write.
271
+ *
272
+ * Pages whose DOM structure matches one already seen (`/reports/1` and
273
+ * `/reports/2`) are kept once.
274
+ */
275
+
276
+ interface DiscoverOptions {
277
+ baseUrl: string;
278
+ startPaths?: string[];
279
+ /** Repo (or app) directory to read routes from; see routes.ts. */
280
+ sourceDir?: string;
281
+ maxPages?: number;
282
+ maxStatesPerPage?: number;
283
+ /** Paths never visited (globs on pathname), on top of sign-out routes. */
284
+ excludePaths?: string[];
285
+ /**
286
+ * Visit only startPaths (and the tabs, dialogs and menus they open): no
287
+ * routes from the source or sitemap, no following links. Set when the
288
+ * person named the pages.
289
+ */
290
+ onlyStartPaths?: boolean;
291
+ onProgress?: (msg: string) => void;
292
+ /** Stops discovery between pages (the studio's Stop button). */
293
+ signal?: AbortSignal;
294
+ }
295
+ /** Pure: same-origin, normalized path (no hash), or null to skip. */
296
+ declare function normalizeLink(href: string, baseUrl: string): string | null;
297
+ declare function surfaceKey(path: string, steps: readonly ReplayStep[]): string;
298
+ declare function discover(session: BrowserSession, opts: DiscoverOptions): Promise<Surface[]>;
299
+
300
+ /**
301
+ * PNG helpers: decode, pad two captures to one size, pixel diff, and a
302
+ * difference hash (dHash) for "is this the same screen" checks. No native
303
+ * image library, so the package installs anywhere Node does.
304
+ */
305
+ interface PixelDiff {
306
+ /** Share of pixels that differ, 0..1, over the larger of the two sizes. */
307
+ ratio: number;
308
+ changedPixels: number;
309
+ /**
310
+ * Changed pixels over the "before" image's content pixels (those unlike
311
+ * its background). A shifted paragraph on a mostly blank page is a small
312
+ * share of the canvas but a large share of what is on it.
313
+ */
314
+ contentRatio: number;
315
+ width: number;
316
+ height: number;
317
+ /** Red-on-grey overlay of the changed pixels. */
318
+ diffPng: Buffer;
319
+ /** Where the change is, largest first, so a viewer can zoom to it. */
320
+ regions: ChangeRegion[];
321
+ }
322
+ interface ChangeRegion {
323
+ x: number;
324
+ y: number;
325
+ w: number;
326
+ h: number;
327
+ }
328
+ declare function pixelDiff(before: Buffer, after: Buffer, threshold?: number): PixelDiff;
329
+ /**
330
+ * Keep the top `maxHeight` px of a capture. Full-page shots of long pages
331
+ * would be downscaled by a vision model until text is unreadable; the top
332
+ * of the page is what the judge can actually see.
333
+ */
334
+ declare function cropTop(buf: Buffer, maxHeight: number): Buffer;
335
+ /**
336
+ * 64-bit difference hash: shrink to 9×8 greyscale by box averaging, then one
337
+ * bit per "left pixel brighter than right". Near-identical screens land
338
+ * within a few bits of each other. Returned as 16 hex chars.
339
+ */
340
+ declare function dHash(buf: Buffer): string;
341
+ declare function hammingHex(a: string, b: string): number;
342
+
343
+ /**
344
+ * The checker: a second model that reviews each kept step and may roll it
345
+ * back (ADR 0021). It never keeps anything the measurements rejected.
346
+ *
347
+ * - A visible change is judged from crops of the changed area, before and
348
+ * after, shown twice with the order swapped. Vision judges are near random
349
+ * on small UI differences (arxiv 2510.08783) and flip with order (arxiv
350
+ * 2305.17926), so a step is rolled back only when both orders prefer the
351
+ * original with at least medium confidence. Anything else keeps it.
352
+ * - A change with nothing visible (motion, haptics, another screen) is
353
+ * reviewed from its diff and the step it was meant to make.
354
+ *
355
+ * Transports: Claude Code (`claude -p`, the person's own sign-in, read-only
356
+ * tools) or the Anthropic API (ANTHROPIC_API_KEY).
357
+ */
358
+
359
+ type CheckerVia = 'claude-code' | 'anthropic-api';
360
+ interface CheckerSpec {
361
+ via: CheckerVia;
362
+ model: string;
363
+ }
364
+ /** One review's answer. @internal Exported for tests only. */
365
+ interface CheckerVote {
366
+ /** Which capture the model preferred, after mapping its A/B answer back. */
367
+ preferred: 'before' | 'after' | 'tie';
368
+ confidence: 'low' | 'medium' | 'high';
369
+ difference: string;
370
+ reason: string;
371
+ }
372
+ interface CheckerVerdict {
373
+ model: string;
374
+ mode: 'visual' | 'code';
375
+ /** revert = roll the step back; keep = no objection; unsure = keep, the votes disagreed or were weak. */
376
+ verdict: 'keep' | 'revert' | 'unsure';
377
+ summary: string;
378
+ votes: CheckerVote[];
379
+ costUsd: number | null;
380
+ /** The review could not run; the step is kept on its measurements. */
381
+ error?: string;
382
+ }
383
+
384
+ /**
385
+ * A finished run's pull request. The studio's "Open draft PR" pushes the run
386
+ * branch and opens a draft PR into the default branch, or, when the run
387
+ * started from a branch that already has an open PR, adds the run's commits to
388
+ * that PR with a fast-forward push. Nothing merges here: merging is a person's
389
+ * click in the Mushi console (ADR 0017).
390
+ *
391
+ * Uses the person's own `git` and `gh` sign-in. The PR's URL and number are
392
+ * saved in state.json and synced to the console.
393
+ */
394
+
395
+ interface RunPullRequest {
396
+ url: string;
397
+ number: number;
398
+ /** true: the run's commits went onto an existing PR instead of a new one. */
399
+ added: boolean;
400
+ }
401
+
402
+ /**
403
+ * Run state on disk: `.mushi/ux/<runId>/state.json` plus the PNGs beside it.
404
+ * Written atomically (temp file + rename) after every step, so a crashed or
405
+ * interrupted run resumes where it stopped.
406
+ */
407
+
408
+ type SurfaceStatus = 'pending' | 'baseline' | 'iterating' | 'accepted' | 'reverted' | 'skipped' | 'regressed' | 'blocked';
409
+ interface ShotRef {
410
+ /** PNG path relative to the run directory. */
411
+ png: string;
412
+ probes: ProbeResult;
413
+ penalty: number;
414
+ }
415
+ interface IterationRecord {
416
+ n: number;
417
+ agent: string;
418
+ model: string | null;
419
+ startedAt: string;
420
+ durationMs: number;
421
+ outcome: 'accepted' | 'rejected' | 'agent_failed' | 'capture_failed' | 'no_change';
422
+ reason: string;
423
+ commitSha: string | null;
424
+ /** Changed-pixel share per viewport, before vs after. */
425
+ pixelDiff: Record<string, number>;
426
+ after: Record<string, ShotRef>;
427
+ diffPng: Record<string, string>;
428
+ /**
429
+ * Where this attempt changed the screen, per viewport, against the screen
430
+ * before it (the last kept state): image size and up to four boxes.
431
+ */
432
+ changes?: Record<string, {
433
+ width: number;
434
+ height: number;
435
+ boxes: Array<{
436
+ x: number;
437
+ y: number;
438
+ w: number;
439
+ h: number;
440
+ }>;
441
+ }>;
442
+ logTail: string;
443
+ /** agent_failed because the time box ran out (another attempt may still succeed). */
444
+ timedOut?: boolean;
445
+ /** Steps mode: the plan step this attempt worked on. */
446
+ step?: string;
447
+ /** Kept without a visible change: a person should read the diff (ADR 0021). */
448
+ needsReview?: boolean;
449
+ /** The second model's review of a kept step (ADR 0021). */
450
+ checker?: CheckerVerdict;
451
+ }
452
+ /** One small, separate improvement from a screen's plan; each gets its own attempt. */
453
+ interface PlanStep {
454
+ text: string;
455
+ status: 'pending' | 'done' | 'skipped' | 'failed';
456
+ /** The attempt that worked on it. */
457
+ attempt?: number;
458
+ reason?: string;
459
+ }
460
+ interface SurfaceState {
461
+ /** Steps mode: the screen's plan, made before any edit; null when planning produced none. */
462
+ /** `session`: the agent session that planned, resumed by each step so it keeps what it read. */
463
+ plan?: {
464
+ steps: PlanStep[];
465
+ session?: string | null;
466
+ } | null;
467
+ surface: Surface;
468
+ status: SurfaceStatus;
469
+ /** Why it is blocked / skipped / regressed, in a sentence. */
470
+ note: string | null;
471
+ baseline: Record<string, ShotRef>;
472
+ iterations: IterationRecord[];
473
+ /** Final pairwise review per viewport; advisory only. */
474
+ judge?: JudgeVerdict[];
475
+ }
476
+ /** Where the run is, for the live views. */
477
+ type RunPhase = 'starting' | 'worktree' | 'install' | 'dev-server' | 'mapping' | 'working' | 'reviewing' | 'done' | 'failed';
478
+ /** Live progress of the attempt in flight, refreshed at least every HEARTBEAT_MS. */
479
+ interface CurrentAttempt {
480
+ surface: string;
481
+ attempt: number;
482
+ startedAt: string;
483
+ /** The agent is stopped after this long. */
484
+ timeoutMs?: number;
485
+ /** Steps the agent took so far (reads, edits, commands, messages). */
486
+ steps?: number;
487
+ /** The latest step, one line ("[edit] app/page.tsx"). */
488
+ lastStep?: string | null;
489
+ /** Files changed in the worktree so far (git status). */
490
+ files?: string[];
491
+ /** When the run last checked in; an old value means the run has stopped. */
492
+ heartbeatAt?: string;
493
+ }
494
+ /**
495
+ * The settings a run started with, so a resume needs only the run id (from
496
+ * the studio's Resume button or `mushi-ux run --resume <id>`). The signed-in
497
+ * profile is saved as its login URL, never as a path (ADR 0006); the skill's
498
+ * files are kept beside the state in `skill/`.
499
+ */
500
+ interface SavedRunOptions {
501
+ agent: string;
502
+ model: string | null;
503
+ devCommand: string;
504
+ /** null = no install; undefined = detect from the lockfile. */
505
+ installCommand?: string | null;
506
+ startPaths?: string[];
507
+ crawl?: boolean;
508
+ iterations: number;
509
+ maxSurfaces: number;
510
+ agentTimeoutMs: number;
511
+ ignore?: string[];
512
+ allow?: string[];
513
+ judgeModel?: string | null;
514
+ loginUrl?: string | null;
515
+ /** Mirror to the console again when resumed (needs the login then too). */
516
+ sync?: boolean;
517
+ /** Steps mode: plan each screen, then one small change per attempt. */
518
+ steps?: boolean;
519
+ /** The reviewing model that may veto a kept step (ADR 0021). */
520
+ checker?: {
521
+ via: 'claude-code' | 'anthropic-api';
522
+ model: string;
523
+ } | null;
524
+ /** Keep edits with nothing visible, flagged for review. */
525
+ keepInvisible?: boolean;
526
+ }
527
+ interface RunState {
528
+ version: 1;
529
+ runId: string;
530
+ baseUrl: string;
531
+ createdAt: string;
532
+ updatedAt: string;
533
+ agent: string;
534
+ model: string | null;
535
+ /** Skill the agent applies, if any (name and where it came from). */
536
+ skill?: {
537
+ name: string;
538
+ source: string;
539
+ } | null;
540
+ /** Git ref the worktree branched from (HEAD unless --base). */
541
+ baseRef?: string;
542
+ phase?: RunPhase;
543
+ /** One line on what the phase is doing ("npm ci", "Home, attempt 2 of 2"). */
544
+ phaseDetail?: string | null;
545
+ /** The screen and attempt the agent is on, while it works. */
546
+ current?: CurrentAttempt | null;
547
+ finishedAt?: string | null;
548
+ /** Why the run stopped, when it failed. */
549
+ error?: string | null;
550
+ /** Stopped from the studio rather than failed. */
551
+ stopped?: boolean;
552
+ /** Model of the final review; null when the review is off. */
553
+ judgeModel?: string | null;
554
+ /** Settings to resume with; absent on runs from before 2026-10-06. */
555
+ options?: SavedRunOptions;
556
+ /** The worktree's install finished; a run killed mid-install installs again. */
557
+ installed?: boolean;
558
+ /** Worktree and branch the agent edits; null before the worktree exists. */
559
+ worktree: string | null;
560
+ branch: string | null;
561
+ baseSha: string | null;
562
+ /** The PR the studio opened from the branch, or the existing PR the run was added to. */
563
+ pr?: RunPullRequest | null;
564
+ surfaces: SurfaceState[];
565
+ }
566
+ declare function runDir(repoRoot: string, runId: string): string;
567
+ declare function newRunId(now?: Date): string;
568
+ declare function saveState(dir: string, state: RunState): void;
569
+ declare function loadState(dir: string): RunState | null;
570
+
571
+ /**
572
+ * Final review by a different model: for each screen the loop changed, one
573
+ * pairwise comparison of the original against the kept version, per
574
+ * viewport, grounded in the repo's design tokens and the measured probe
575
+ * deltas.
576
+ *
577
+ * Why pairwise and evidence-bound: open-ended screenshot critique is mostly
578
+ * wrong (Baymard measured an 80% error rate for GPT-4 UX audits; UICrit found
579
+ * 13% of zero-shot critiques valid). Asking "which is better, and point at
580
+ * where" is a narrower question, every claim must carry a bounding box, and
581
+ * the two images are shown in random order so the model cannot learn that
582
+ * "the second one is the new one".
583
+ *
584
+ * The judge advises; it never reverts or keeps anything. Runs on the
585
+ * person's own Anthropic credentials.
586
+ */
587
+
588
+ declare const DEFAULT_JUDGE_MODEL = "claude-opus-5-5";
589
+ declare const JudgeOutput: z.ZodObject<{
590
+ preferred: z.ZodEnum<{
591
+ A: "A";
592
+ tie: "tie";
593
+ B: "B";
594
+ }>;
595
+ confidence: z.ZodEnum<{
596
+ low: "low";
597
+ medium: "medium";
598
+ high: "high";
599
+ }>;
600
+ summary: z.ZodString;
601
+ better: z.ZodArray<z.ZodObject<{
602
+ image: z.ZodEnum<{
603
+ A: "A";
604
+ B: "B";
605
+ }>;
606
+ box: z.ZodObject<{
607
+ x: z.ZodNumber;
608
+ y: z.ZodNumber;
609
+ width: z.ZodNumber;
610
+ height: z.ZodNumber;
611
+ }, z.core.$strip>;
612
+ what: z.ZodString;
613
+ why: z.ZodString;
614
+ }, z.core.$strip>>;
615
+ worse: z.ZodArray<z.ZodObject<{
616
+ image: z.ZodEnum<{
617
+ A: "A";
618
+ B: "B";
619
+ }>;
620
+ box: z.ZodObject<{
621
+ x: z.ZodNumber;
622
+ y: z.ZodNumber;
623
+ width: z.ZodNumber;
624
+ height: z.ZodNumber;
625
+ }, z.core.$strip>;
626
+ what: z.ZodString;
627
+ why: z.ZodString;
628
+ }, z.core.$strip>>;
629
+ design_system_breaks: z.ZodArray<z.ZodObject<{
630
+ image: z.ZodEnum<{
631
+ A: "A";
632
+ B: "B";
633
+ }>;
634
+ box: z.ZodObject<{
635
+ x: z.ZodNumber;
636
+ y: z.ZodNumber;
637
+ width: z.ZodNumber;
638
+ height: z.ZodNumber;
639
+ }, z.core.$strip>;
640
+ what: z.ZodString;
641
+ why: z.ZodString;
642
+ token_or_rule: z.ZodString;
643
+ }, z.core.$strip>>;
644
+ }, z.core.$strip>;
645
+ type JudgeOutputT = z.infer<typeof JudgeOutput>;
646
+ interface JudgeClaim {
647
+ /** Which capture the claim points at, after un-shuffling. */
648
+ image: 'before' | 'after';
649
+ box: {
650
+ x: number;
651
+ y: number;
652
+ width: number;
653
+ height: number;
654
+ };
655
+ what: string;
656
+ why: string;
657
+ tokenOrRule?: string;
658
+ }
659
+ interface JudgeVerdict {
660
+ viewport: string;
661
+ model: string;
662
+ preferred: 'before' | 'after' | 'tie';
663
+ confidence: 'low' | 'medium' | 'high';
664
+ summary: string;
665
+ better: JudgeClaim[];
666
+ worse: JudgeClaim[];
667
+ designBreaks: JudgeClaim[];
668
+ /** Claims dropped because their box fell outside the image. */
669
+ droppedClaims: number;
670
+ /** Set when the model declined or the call failed; no verdict then. */
671
+ error?: string;
672
+ }
673
+ interface JudgeOptions {
674
+ dir: string;
675
+ repoRoot: string;
676
+ designFiles: string[];
677
+ model?: string;
678
+ client?: Anthropic;
679
+ /** Deterministic order for tests; defaults to Math.random. */
680
+ random?: () => number;
681
+ }
682
+ /** Pure: map the shuffled A/B answer back to before/after and drop out-of-image claims. */
683
+ declare function unshuffle(out: JudgeOutputT, aIsBefore: boolean, sizes: {
684
+ A: {
685
+ width: number;
686
+ height: number;
687
+ };
688
+ B: {
689
+ width: number;
690
+ height: number;
691
+ };
692
+ }, viewport: string, model: string): JudgeVerdict;
693
+ /** Judge one screen at one viewport: its baseline against its last kept capture. */
694
+ declare function judgeSurface(s: SurfaceState, viewport: string, opts: JudgeOptions): Promise<JudgeVerdict | null>;
695
+
696
+ /**
697
+ * The loop. One run:
698
+ *
699
+ * worktree + dev server → discover surfaces → for each surface:
700
+ * baseline (desktop + mobile) → prompt packet → agent edits →
701
+ * recapture → pixel diff + probes → keep (commit) or roll back →
702
+ * re-check a sample of finished screens for collateral changes
703
+ *
704
+ * State is saved after every step, so `--resume <runId>` continues an
705
+ * interrupted run. Events go to the dashboard (dashboard.ts) as they happen.
706
+ */
707
+
708
+ type LoopEvent = {
709
+ type: 'log';
710
+ message: string;
711
+ } | {
712
+ type: 'agent';
713
+ surface: string;
714
+ line: string;
715
+ kind?: string;
716
+ } | {
717
+ type: 'state';
718
+ } | {
719
+ type: 'phase';
720
+ phase: RunPhase;
721
+ detail: string | null;
722
+ };
723
+ interface LoopOptions {
724
+ repoRoot: string;
725
+ devCommand: string;
726
+ /** null skips the install; undefined detects it from the lockfile. */
727
+ installCommand?: string | null;
728
+ startPaths?: string[];
729
+ agent: AgentName;
730
+ /** Overrides `agent` with a custom adapter (tests, other harnesses). */
731
+ agentAdapter?: AgentAdapter;
732
+ model?: string | null;
733
+ iterations?: number;
734
+ maxSurfaces?: number;
735
+ agentTimeoutMs?: number;
736
+ skillText?: string | null;
737
+ /** A skill folder (SKILL.md + references); wins over skillText. */
738
+ skill?: ResolvedSkill | null;
739
+ /** Git ref the worktree branches from. Default HEAD. */
740
+ baseRef?: string;
741
+ allow?: AllowRule[];
742
+ /** Selectors that are not the app's UI, on top of DEFAULT_IGNORE (ignore.ts). */
743
+ ignore?: string[];
744
+ profileDir?: string;
745
+ regressionSample?: number;
746
+ /** Model for the final pairwise review; null turns it off. */
747
+ judgeModel?: string | null;
748
+ resumeRunId?: string;
749
+ /** Follow links from startPaths too. Off: only the named pages and the states they open. */
750
+ crawl?: boolean;
751
+ /** Aborting stops the run between steps and kills a running agent. */
752
+ signal?: AbortSignal;
753
+ /** Check the agent can read a file before anything slow starts. Default on (off for a custom adapter and the cloud agent). */
754
+ preflight?: boolean;
755
+ /** Plan each screen into small steps first, then make one step per attempt (iterations caps the steps). */
756
+ steps?: boolean;
757
+ /**
758
+ * A second model that reviews each kept step and may roll it back, never
759
+ * keep a rejected one (ADR 0021). null: measurements alone decide.
760
+ */
761
+ checker?: CheckerSpec | null;
762
+ /** Keep an edit with nothing visible, flagged for review (ADR 0021). Default on. */
763
+ keepInvisible?: boolean;
764
+ /** Saved with the run for a later resume only: the login URL behind profileDir, and whether it synced. */
765
+ loginUrl?: string | null;
766
+ sync?: boolean;
767
+ events?: EventEmitter;
768
+ }
769
+ interface LoopHandle {
770
+ runId: string;
771
+ dir: string;
772
+ done: Promise<RunState>;
773
+ }
774
+ declare function startLoop(opts: LoopOptions): LoopHandle;
775
+
776
+ /**
777
+ * The instructions one agent run gets, written to `.mushi-ux/PROMPT.md` in
778
+ * the worktree: which screen, its screenshots, the measured problems, where
779
+ * the design system lives, the skill to apply, and what not to touch.
780
+ *
781
+ * File paths only for the design system: the agent reads what it needs, and
782
+ * the packet stays small enough for weaker, short-context models.
783
+ */
784
+
785
+ interface PacketInput {
786
+ surface: Surface;
787
+ iteration: number;
788
+ /** Screenshot paths relative to the worktree, per viewport name. */
789
+ shots: Record<string, string>;
790
+ probes: Record<string, ProbeResult>;
791
+ designFiles: string[];
792
+ skillText: string | null;
793
+ /** Worktree-relative folder holding the skill's files (SKILL.md, references/). */
794
+ skillDir?: string | null;
795
+ /** Why the previous attempt on this screen was rejected, if it was. */
796
+ previousRejection: string | null;
797
+ /** Minutes the agent has before it is stopped; shapes the work plan. */
798
+ timeBudgetMin?: number | null;
799
+ /** Repo-relative files that render this screen (routes.ts screenFiles); empty when unknown. */
800
+ entryFiles?: string[];
801
+ /** Steps mode: the one plan step this attempt makes. */
802
+ step?: {
803
+ text: string;
804
+ index: number;
805
+ total: number;
806
+ done: string[];
807
+ } | null;
808
+ }
809
+ declare function buildPacket(input: PacketInput): string;
810
+ /** One-line instruction handed to the agent on stdin / argv. */
811
+ declare const POINTER_PROMPT = "Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It names the screenshots to look at and the screen to improve.";
812
+ /**
813
+ * Likely design-system sources, as repo-relative paths: the recipe manifest,
814
+ * Tailwind configs, DTCG token files, and CSS files that declare theme
815
+ * tokens (`@theme` or many custom properties on :root).
816
+ */
817
+ declare function findDesignFiles(root: string, maxFiles?: number): string[];
818
+
819
+ /**
820
+ * Objective checks run on every capture. A vision model's opinion of a
821
+ * screenshot is unreliable (Baymard: 80% of GPT-4 audit suggestions were
822
+ * wrong or wasted effort; UICrit: 13% of zero-shot critiques valid), so the
823
+ * loop's accept/reject leans on these numbers, not on taste.
824
+ *
825
+ * Contrast comes from axe-core's `color-contrast` rule, which parses modern
826
+ * colour syntax (oklch, color-mix) itself.
827
+ */
828
+
829
+ declare function runProbes(page: Page, consoleErrors: readonly string[], ignore?: readonly string[]): Promise<ProbeResult>;
830
+ /**
831
+ * One number per capture, lower is better. Used only to compare the same
832
+ * surface before and after an agent run, never across surfaces.
833
+ */
834
+ declare function probePenalty(p: ProbeResult): number;
835
+
836
+ /**
837
+ * Start paths read from the source, so discovery reaches pages nothing links
838
+ * to (a settings tab only the sidebar opens, a page behind a button).
839
+ *
840
+ * - React Router: absolute `path="/x"` props and `path: '/x'` route objects.
841
+ * Relative child paths are left to the crawler, which follows the links
842
+ * their layouts render.
843
+ * - Next.js: `app/**\/page.*` and `pages/**\/*.*` files.
844
+ * - Anything with a parameter (`:id`, `[id]`, `*`) is skipped: there is no
845
+ * safe value to invent for it.
846
+ */
847
+ /** Pure, for tests: absolute static paths declared in one React Router source file. */
848
+ declare function reactRouterPaths(source: string): string[];
849
+ /** Pure, for tests: the URL path a Next.js route file serves, or null. */
850
+ declare function nextRoutePath(relFile: string): string | null;
851
+ declare function routesFromSource(root: string): string[];
852
+ /** Paths listed in /sitemap.xml on the same origin; empty when there is none. */
853
+ declare function sitemapPaths(baseUrl: string): Promise<string[]>;
854
+
855
+ interface SyncConfig {
856
+ apiKey: string;
857
+ projectId: string;
858
+ endpoint: string;
859
+ /** 'cloud' when the run executes on the host's CI rather than a laptop. */
860
+ mode: 'local' | 'cloud';
861
+ }
862
+ declare function syncConfigFromEnv(env?: NodeJS.ProcessEnv): SyncConfig | null;
863
+ /** Pure, for tests: the PUT body for one run state. `uploaded` maps upload name → the file it came from. */
864
+ declare function toSnapshot(state: RunState, finished: boolean, uploaded: ReadonlyMap<string, string>, mode?: SyncConfig['mode']): {
865
+ started_at: string;
866
+ finished_at: string | null;
867
+ surfaces: {
868
+ surface_key: string;
869
+ kind: SurfaceKind;
870
+ path: string;
871
+ label: string;
872
+ status: SurfaceStatus;
873
+ note: string | null;
874
+ plan: {
875
+ text: string;
876
+ status: "done" | "pending" | "skipped" | "failed";
877
+ attempt: number | null;
878
+ }[] | null;
879
+ penalty_before: number | null;
880
+ penalty_after: number | null;
881
+ probe_before: {
882
+ axe: {
883
+ id: string;
884
+ impact: string | null;
885
+ help: string;
886
+ count: number;
887
+ }[];
888
+ overflowX: boolean;
889
+ smallTargets: number;
890
+ consoleErrors: number;
891
+ cls: number;
892
+ } | null;
893
+ probe_after: {
894
+ axe: {
895
+ id: string;
896
+ impact: string | null;
897
+ help: string;
898
+ count: number;
899
+ }[];
900
+ overflowX: boolean;
901
+ smallTargets: number;
902
+ consoleErrors: number;
903
+ cls: number;
904
+ } | null;
905
+ judge: {
906
+ error?: string | undefined;
907
+ viewport: string;
908
+ model: string;
909
+ preferred: "before" | "after" | "tie";
910
+ confidence: "low" | "medium" | "high";
911
+ summary: string;
912
+ better: {
913
+ what: string;
914
+ why: string;
915
+ }[];
916
+ worse: {
917
+ what: string;
918
+ why: string;
919
+ }[];
920
+ }[] | null;
921
+ thumbs: {
922
+ before: string;
923
+ after: string;
924
+ diff: string;
925
+ };
926
+ shots: Record<string, string>;
927
+ iterations: {
928
+ n: number;
929
+ agent: string;
930
+ model: string | null;
931
+ duration_ms: number;
932
+ outcome: "accepted" | "rejected" | "agent_failed" | "capture_failed" | "no_change";
933
+ reason: string;
934
+ commit_sha: string | null;
935
+ pixel_diff: Record<string, number>;
936
+ penalty_after: number | null;
937
+ steps: string | null;
938
+ step: string | null;
939
+ shots: Record<string, string>;
940
+ }[];
941
+ }[];
942
+ pr?: {
943
+ url: string;
944
+ number: number;
945
+ } | undefined;
946
+ mode: "local" | "cloud";
947
+ status: string;
948
+ agent: string;
949
+ model: string | null;
950
+ judge_model: string | null;
951
+ skill: string | null;
952
+ base_ref: string | null;
953
+ phase: RunPhase | null;
954
+ phase_detail: string | null;
955
+ current_surface: string | null;
956
+ current_attempt: number | null;
957
+ current_progress: {
958
+ steps: number;
959
+ last_step: string | null;
960
+ files: string[];
961
+ started_at: string;
962
+ timeout_ms: number | null;
963
+ } | null;
964
+ error: string | null;
965
+ branch: string | null;
966
+ base_sha: string | null;
967
+ cli_version: null;
968
+ };
969
+ interface SyncHandle {
970
+ /** Final sync; resolves with an error message when it did not land. */
971
+ finish(): Promise<string | null>;
972
+ }
973
+ declare function startSync(dir: string, cfg: SyncConfig, events: EventEmitter, log: (m: string) => void): SyncHandle;
974
+
975
+ /**
976
+ * The cheap, objective keep-or-revert decision after one agent run. It only
977
+ * uses measurements (probes, pixel diff, files changed), never a model's
978
+ * taste: an edit that makes any measured problem worse is rolled back, and an
979
+ * edit with no visible effect is not worth a commit. Taste is the judge's job
980
+ * (judge.ts), and the judge never auto-accepts.
981
+ */
982
+
983
+ interface VerdictInput {
984
+ filesChanged: number;
985
+ before: Record<string, ProbeResult>;
986
+ /** Null when the after-capture failed (page broke, axe failed, timeout). */
987
+ after: Record<string, ProbeResult> | null;
988
+ pixelRatios: Record<string, number>;
989
+ /**
990
+ * Keep an edit whose effect is not visible in a still screenshot (motion,
991
+ * haptics, another screen) when nothing measured got worse, flagged for a
992
+ * person to read (ADR 0021). Off: such an edit is rolled back.
993
+ */
994
+ keepInvisible?: boolean;
995
+ }
996
+ interface Verdict {
997
+ outcome: 'accepted' | 'rejected' | 'no_change' | 'capture_failed';
998
+ reason: string;
999
+ /** Kept without a visible change: a person should read the diff. */
1000
+ needsReview?: boolean;
1001
+ }
1002
+ declare function decide(input: VerdictInput): Verdict;
1003
+
1004
+ export { AGENTS, type AgentAdapter, type AgentName, type AgentRunOptions, type AllowRule, type AxeViolation, type BrowserSession, type Capture, type CursorCloudDeps, DEFAULT_JUDGE_MODEL, type Dashboard, type DiscoverOptions, type IterationRecord, type JudgeClaim, type JudgeOptions, type JudgeVerdict, type LoopEvent, type LoopHandle, type LoopOptions, POINTER_PROMPT, type PacketInput, type ProbeResult, type ReplayStep, type RunState, type Surface, type SurfaceKind, type SurfaceState, type SurfaceStatus, type SyncConfig, type SyncHandle, VIEWPORTS, type Verdict, type VerdictInput, type Viewport, buildPacket, captureSurface, cropTop, cursorCloudAdapter, cursorModel, dHash, decide, discover, findDesignFiles, getAgent, hammingHex, httpsRepoUrl, installGuard, isDestructiveLabel, isRequestAllowed, judgeSurface, loadState, newRunId, nextRoutePath, normalizeLink, openSession, pixelDiff, probePenalty, quoteArg, reactRouterPaths, routesFromSource, runDir, runProbes, safeShotPath, saveState, settle, sitemapPaths, startDashboard, startLoop, startSync, surfaceKey, syncConfigFromEnv, toSnapshot, unshuffle };