Cotton code
503 lines · 31.5 KB · TypeScriptRaw
#!/usr/bin/env tsx/** * Walk two fresh REAL phones against a throwaway household and retain accessibility evidence for every assertion. * Between them the board scenario is set up through a joined setter, and the later phone walks it (board-walk.ts, * the driver walk:board runs): same screens, same evidence names, prefixed `later-`. * Two more phones then update across a schema bump while holding unsent changes (update-walk.ts), each on a * household of its own — the Mac serving, then away; `--only update` walks that case alone. */import { execFileSync } from 'node:child_process';import { createHash, createPrivateKey, createPublicKey, randomBytes, sign } from 'node:crypto';import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';import { availableParallelism, homedir, loadavg } from 'node:os';import { basename, dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import { boardSetup, feedbackChecks, joinSetter, largestTypeBeforeLaunch, walkBoardScreens } from './board-walk';import { parseScreen, type Element } from './lib/describe-screen';import { buildIn, walkUpdate } from './update-walk';export type Json = Record<string, unknown>;export interface Database { id: string; name: string | null; kind: string }interface Fixtures {  personal: string; expectedTools: string[]; shapes: Record<string, boolean>; projects: {slug: string; name: string}[];  tables: {id: string; plural: string; title?: string}[]; tools: {id: string; tables: string[]}[];  messages: {thread_id: string; body: string}[];  chatCases: {shape: string; id: string}[];}export const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));export const flat = (s: unknown) => String(s).replace(/[\r\n]+/g, ' ').trim();/** Which app a Phone drives: its deep-link scheme and bundle id. Shared with `walk-board.ts`. */export interface AppIdentity { scheme: string; bundleId: string }/** The production app this walk gates. */export const REAL_APP: AppIdentity = { scheme: 'tinmen-cotton', bundleId: 'com.cottondb.cotton' };/** Cotton Dev (`project.yml`'s `_dev` settings), the app every other walk drives. */export const DEV_APP: AppIdentity = { scheme: 'cottondev', bundleId: 'com.cottondb.cotton.dev' };export function titleFailure(title: string): string | null {  const t = title.trim();  if (!t || /^(?:[^,]+,\s*)?[—–]$/.test(t)) return 'empty title';  if (/\[unsupported/i.test(t)) return 'unsupported title';  // A weekday alone or with a time says nothing; with its date it is a journal day's title.  if (/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)(?:\s*[,·—-]\s*\d{1,2}[:.]\d{2}(?:\s*[ap]m)?)?$/i.test(t)) return 'weekday used as title';  return null;}/** A record page's title, under whichever table the page names. */export const recordHeading = (id: string) => /^page-[a-z_]+-(?:heading|title|name|caption)$/.test(id);export function screenFailures(screen: Element[]): string[] {  return screen.filter(e => /refusal|error/.test(e.id) && e.label.trim() || /\[unsupported|isn.t here any more|couldn.t (?:be )?(?:load|read|opened)|failed to (?:load|read|sync)|could not (?:be )?(?:load|read|sync|opened)/i.test(e.label))    .map(e => flat(e.label || e.value));}/** The sheet's line while a database's copy is still coming down to this device. */export function downloading(screen: Element[]): boolean {  return screen.some(e => /is downloading to this device/i.test(e.label));}export function missingDatabases(databases: Database[], screen: Element[]): string[] {  // Names also occur in slips BEHIND the sheet; only the cap's identity proves a database exists.  return databases.filter(d => !screen.some(e => e.role === 'AXButton' && e.id === `database-${d.id}`))    .map(d => d.name || d.id);}/** * How much slower this Mac is than idle, as the launch smoke scales its budget * (ios-launch-smoke.sh LOAD_X): the 1-minute load average per CPU, rounded up, * 1x to 4x. A walk beside a prod cut's compile read an empty accessibility tree * over a drawn screen for the whole of an unscaled wait (10 Oct 2026). */export function loadFactor(load = loadavg()[0] ?? 0, cpus = availableParallelism()): number {  return Math.max(1, Math.min(4, Math.ceil(load / Math.max(1, cpus))));}export function command(program: string, args: string[], timeout = 60_000): string {  return execFileSync(program, args, { encoding: 'utf8', timeout, maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });}function disposeSimulator(udid: string) {  if (!/^[A-F0-9-]{36}$/i.test(udid)) throw new Error('invalid owned simulator id');  // The id comes only from this run's simctl create, never from a caller override.  try { command('xcrun', ['simctl', 'shutdown', udid]); } catch { /* Already shut down is harmless. */ }  command('bash', ['-c', '. "$1"; refuse_wide_root "release walk simulator" "$2"; xcrun simctl delete "$3"',    '_', join(dirname(fileURLToPath(import.meta.url)), 'lib/owned-root.sh'),    join(homedir(), 'Library/Developer/CoreSimulator/Devices', udid), udid]);}export class Report {  failures = 0; passed = 0;  constructor(readonly run: string) {}  line(text: string) { console.log(text); appendFileSync(join(this.run, 'assertions.log'), text + '\n'); }  check(ok: boolean, name: string, reason: unknown = '') {    if (ok) this.passed++; else this.failures++;    this.line(`${ok ? 'PASS' : 'FAIL'} ${flat(name)}${reason ? ': ' + flat(reason) : ''}`);  }}/** A signed `/v1` request as the household's own device (its `identity/device.seed`), the production routes' signature. */export function deviceRequester(data: string, origin: string) {  const privateKey = createPrivateKey({key: Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), readFileSync(join(data, 'identity/device.seed'))]), format: 'der', type: 'pkcs8'});  const device = createPublicKey(privateKey).export({format: 'jwk'}).x!;  return async function request(method: string, path: string, body?: Json): Promise<Json> {    const bytes = body ? JSON.stringify(body) : '';    const ts = Math.floor(Date.now() / 1000);    const nonce = method === 'GET' ? '' : randomBytes(16).toString('base64url');    const hash = createHash('sha256').update(bytes).digest('hex');    const signature = sign(null, Buffer.from(['cotton-device-v1', origin, method, path, ts, nonce, hash].join('\n')), privateKey).toString('base64url');    const response = await fetch(origin + path, {method, headers: {'x-cotton-device': device, 'x-cotton-device-sig': `${ts}.${nonce}.${signature}`, 'content-type': 'application/json'}, ...(body ? {body: bytes} : {}), signal: AbortSignal.timeout(30_000)});    if (!response.ok) throw new Error(`${method} ${path}: HTTP ${response.status}`);    return await response.json() as Json;  };}export class Phone {  seq = 0;  constructor(readonly udid: string, readonly phase: string, readonly report: Report, readonly app: AppIdentity = REAL_APP) {}  call(tool: string, args: Json = {}): Json {    // A first boot after an erase, an install and a first launch take minutes    // (the launch smoke measures ~2): only the quick tools are held to a minute.    const long = ['boot-device', 'reinstall-app', 'launch-app'].includes(tool);    if (long) this.report.line(`STEP ${this.phase} ${tool}`);    const result = JSON.parse(command('argent', ['run', tool, '--args', JSON.stringify({udid: this.udid, ...args}), '--json'], long ? 300_000 : 60_000)) as Json;    if (result.error) throw new Error(`${tool}: ${flat(result.error)}`);    return result;  }  see(): Element[] {    // A screen between two screens — or read on a loaded Mac — describes as an    // empty root for a while: it is read again, for 20s × the load, before it    // is called blank (a release walk died on one mid-transition, and on a drawn    // Home read empty for 15s under load, 10 Oct 2026).    const until = Date.now() + 20_000 * loadFactor();    for (;;) {      const description = String(this.call('describe').description ?? '');      writeFileSync(join(this.report.run, `${this.phase}-${++this.seq}.ax.txt`), description);      const screen = parseScreen(description);      if (screen.length) return screen;      if (Date.now() >= until) throw new Error('describe returned no accessibility elements');      Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 500);    }  }  shot(name: string) {    command('argent', ['run', 'screenshot', '--udid', this.udid, '--scale', '1', '--out', join(this.report.run, `${this.phase}-${name}.png`)]);  }  async wait(match: (e: Element) => boolean, ms = 30_000): Promise<Element> {    const until = Date.now() + ms * loadFactor();    do {      // A screen still launching describes as an empty root: not drawn yet, so look again until the deadline.      let screen: Element[];      try { screen = this.see(); } catch { await pause(500); continue; }      const prompt = screen.find(e => e.role === 'AXButton' && (["Don’t Allow", 'Don\'t Allow', 'Not Now'].includes(e.label) || e.label === 'Open' && screen.some(s => s.label.startsWith('Open in'))));      if (prompt) this.tap(prompt);      const found = screen.find(match);      if (found) return found;      await pause(500);    } while (Date.now() < until);    throw new Error('required accessibility element did not appear');  }  tap(e: Element) { this.call('gesture-tap', {x: e.frame.x + e.frame.width / 2, y: e.frame.y + e.frame.height / 2}); }  async id(id: string) { this.tap(await this.wait(e => e.id === id)); await pause(500); }  async label(label: string) { this.tap(await this.wait(e => e.role === 'AXButton' && e.label === label)); await pause(500); }  swipe(up = true) { this.call('gesture-swipe', {fromX: 0.5, fromY: up ? 0.78 : 0.25, toX: 0.5, toY: up ? 0.25 : 0.78, durationMs: 500, momentum: false}); }  /** A page's heading, flung up to when the page opens at its newest end (a long conversation). */  async heading(match: (e: Element) => boolean): Promise<Element> {    for (let n = 0; n < 8; n++) {      const found = this.see().find(match);      if (found) return found;      this.fling(); await pause(600);    }    return this.wait(match, 10_000);  }  /** A quick flick down the screen, carrying on, to reach the top of a long conversation. */  fling() { this.call('gesture-swipe', {fromX: 0.5, fromY: 0.25, toX: 0.5, toY: 0.85, durationMs: 120, momentum: true}); }  async findScrolling(match: (e: Element) => boolean): Promise<Element> {    // Returning from a page preserves scroll position. Search both directions.    for (let n = 0; n < 24; n++) {      const screen = this.see();      const found = screen.find(e => match(e) && e.frame.y > 0.06 && e.frame.y + e.frame.height < 0.91);      if (found) return found;      if (screen.some(e => e.id === 'board-name' && e.frame.y > 0)) break;      this.swipe(false); await pause(250);    }    for (let n = 0; n < 24; n++) {      const found = this.see().find(e => match(e) && e.frame.y > 0.06 && e.frame.y + e.frame.height < 0.91);      if (found) return found;      this.swipe(); await pause(250);    }    throw new Error('required element absent after scrolling');  }  async join(headless: string, data: string, app: string, origin: string, opts: {owner?: string; beforeLaunch?: () => void} = {}) {    this.call('boot-device', {headless: true});    // Booted is not finished booting: under a Mac's load a launch before the home screen is up is lost    // (the later phone on 2c766063b and ac1404fac drew nothing, twice). Wait for the boot to finish.    command('xcrun', ['simctl', 'bootstatus', this.udid, '-b'], 600_000);    this.call('reinstall-app', {bundleId: this.app.bundleId, appPath: app});    opts.beforeLaunch?.();    this.call('launch-app', {bundleId: this.app.bundleId});    // A first launch that never draws (an empty tree, then the home screen: release walk on 2c766063b's later phone)    // is launched once more and said as a NOTE, so a second blank launch still fails.    try { await this.label('Join my database'); }    catch {      this.report.line(`NOTE ${this.phase} phone: the first launch never drew a screen; launched again`);      this.shot('first-launch-blank');      this.call('launch-app', {bundleId: this.app.bundleId});      await this.label('Join my database');    }    this.tap(await this.wait(e => e.id === 'join-screen' && ['AXGroup', 'AXTextField'].includes(e.role) && (!e.value || /name your other device/.test(e.value))));    this.call('keyboard', {text: origin});    this.call('keyboard', {key: 'enter'}); await pause(500);    this.call('keyboard', {key: 'enter'});    // The keyboard can swallow the second enter (its first-run tip at the largest type did, 041e91caf): press Join itself.    let digits = '';    for (let n = 0; n < 4 && !digits; n++) {      try { digits = (await this.wait(e => /^\d{6}$/.test(e.label), 15_000)).label; }      catch { const join = this.see().find(e => e.role === 'AXButton' && e.label === 'Join'); if (join) this.tap(join); }    }    if (!digits) throw new Error('the phone never showed its pairing digits');    this.shot('pair');    const pending = command(headless, ['pending', '--data-dir', data]);    const entry = pending.split('\n').find(l => l.includes(`digits ${digits}`));    if (!entry) throw new Error('phone fingerprint does not match headless pending');    command(headless, ['approve', entry.trim().split(/\s+/)[0]!, '--data-dir', data]);    // A new household asks its owner's name after approval.    const until = Date.now() + 180_000;    while (Date.now() < until) {      const screen = this.see();      if (screen.some(e => e.id === 'bar-database')) return;      const name = screen.find(e => e.id === 'name-entry' && e.role === 'AXGroup');      if (name) { this.tap(name); this.call('keyboard', {text: opts.owner ?? 'Release Walker'}); await this.label('Continue'); }      await pause(1000);    }    throw new Error('fresh phone never reached its database page after approval');  }  async closeDatabases() {    const screen = this.see();    if (!screen.some(e => e.role === 'AXStaticText' && e.label === 'Databases')) return;    await this.label('Close');    const deadline = Date.now() + 10_000;    while (this.see().some(e => e.role === 'AXStaticText' && e.label === 'Databases')) {      if (Date.now() > deadline) throw new Error('Databases sheet did not close');      await pause(300);    }  }  async databases(expected: Database[]) {    await this.id('bar-database');    const until = Date.now() + 180_000;    let screen: Element[] = [];    let missing: string[] = [];    do {      screen = this.see(); missing = missingDatabases(expected, screen);      // A copy still coming down says so on the sheet; that is a wait, not yet a verdict.      if (!missing.length && !downloading(screen)) break;      // Reopening asks the model to refresh, without replacing the phone's replica.      await this.closeDatabases(); await pause(2000); await this.id('bar-database');    } while (Date.now() < until);    this.shot('databases');    this.report.check(!missing.length, `${this.phase} every server database listed`, missing.join(', '));    this.report.check(!screenFailures(screen).length, `${this.phase} Databases has no error sentence`, screenFailures(screen).join('; '));    return !missing.length;  }  async pick(database: Database) {    const title = database.name ?? database.id;    const cap = this.see().find(e => e.role === 'AXButton' && e.id === `database-${database.id}`);    if (!cap) throw new Error('database cap is absent');    this.tap(cap);    await pause(800);    await this.wait(e => e.id === 'bar-database');    const screen = this.see();    const heading = screen.find(e => e.id === 'board-name');    this.report.check(!!heading && !titleFailure(heading.label) && heading.label === title, `${this.phase} database ${title} opens`, heading?.label ?? 'no database heading');    this.report.check(!screenFailures(screen).length, `${this.phase} database ${title} reads`, screenFailures(screen).join('; '));  }  /**   * Every tool of the shown database, as the Tools screen lists them (Home   * shows the person's arrangement, the Tools screen all of them): each a   * button `board-tool-<key>`, collected while scrolling until nothing new.   */  async cards(): Promise<{ key: string; label: string }[]> {    this.open('tools');    await this.wait(e => e.id.startsWith('board-tool-'));    const seen = new Map<string, string>();    for (let n = 0, still = 0; n < 30 && still < 2; n++) {      const before = seen.size;      for (const e of this.see()) if (e.role === 'AXButton' && e.id.startsWith('board-tool-')) seen.set(e.id.slice('board-tool-'.length), e.label);      still = seen.size === before ? still + 1 : 0;      this.swipe(); await pause(250);    }    return [...seen].map(([key, label]) => ({ key, label }));  }  /** Open a tool from the Tools screen, scrolling down to it. */  async tool(key: string) {    this.open('tools');    await this.wait(e => e.id.startsWith('board-tool-'));    // The Tools screen keeps where it was scrolled: look back up it first, then down.    const card = (e: Element) => e.role === 'AXButton' && e.id === `board-tool-${key}` && e.frame.y > 0.06 && e.frame.y + e.frame.height < 0.91;    for (let n = 0; n < 32; n++) {      let found = this.see().find(card);      if (found) {        // A tap while the screen still settles from a swipe only stops the scroll        // (the cut on 437333472 tapped Todos just after scrolling back up): let it settle, read it again.        if (n > 0) { await pause(800); found = this.see().find(card) ?? found; }        this.tap(found);        // A slow tool is still opening a second later; a tap that opened nothing is said by name.        const until = Date.now() + 15_000 * loadFactor();        let again = Date.now() + 5_000 * loadFactor();        do {          await pause(500);          const screen = this.see();          if (!screen.some(e => e.id.startsWith('board-tool-'))) return;          // One more tap, said as a NOTE, before a dead card is called dead.          if (again && Date.now() > again) {            again = 0;            this.report.line(`NOTE ${this.phase} tool-${key}: the first tap did not open it; tapped again`);            this.tap(screen.find(card) ?? found);          }        } while (Date.now() < until);        throw new Error(`tapping board-tool-${key} never left the Tools screen`);      }      this.swipe(n >= 8); await pause(250);    }    throw new Error(`the Tools screen never showed board-tool-${key}`);  }  /** Open `<scheme>://<path>`, answering the system's "Open in …?" prompt when it asks. */  open(path: string) {    this.call('open-url', {url: `${this.app.scheme}://${path.replace(/^\//, '')}`});    const open = this.see().find(e => e.role === 'AXButton' && e.label === 'Open');    if (open) this.tap(open);  }  async home() {    await this.closeDatabases();    // The production deep link clears the navigation stack, preserving the selected database.    this.open('home');    await this.wait(e => e.id === 'bar-database');  }  async listAndRow(tool: string, tables: Fixtures['tables'], fixtures: Fixtures) {    const screen = this.see();    const errors = screenFailures(screen);    if (errors.length) throw new Error(errors.join('; '));    const table = tables.find(t => screen.some(e => e.id === `list-${t.id}-search` || e.id === `list-${t.id}-menu` || e.id === `list-${t.id}-new`));    if (!table) throw new Error('tool did not open a records list');    this.report.check(true, `${tool} list ${table.id} opens`);    // A list of only past records (Meetings) shows them behind "Earlier".    const earlier = screen.find(e => e.id === `list-${table.id}-earlier`);    if (earlier) { this.tap(earlier); await pause(1000); }    let row: Element;    try { row = await this.wait(e => e.id.startsWith(`${table.id}-`) && e.id !== `${table.id}-earlier` && e.role === 'AXButton', 15_000); }    catch { throw new Error(`MISSING first accessible ${table.id} row: generator gap or list rendering defect`); }    const rowId = row.id.slice(table.id.length + 1);    this.report.check(!titleFailure(row.label), `${tool} first row has a title`, titleFailure(row.label) ?? '');    this.tap(row);    // A record page names its own table, which need not be the list's (a project's memory section's rows open memory pages).    // A list row is `<table>-<id>`; the Reader's table is `page`, so its page's ids also start `page-page-`.    const isRow = (id: string) => id.startsWith(`${table.id}-`) && !id.startsWith(`page-${table.id}-`);    const isHeading = (e: Element) => e.id === `page-${table.id}-heading` || !!table.title && e.id === `page-${table.id}-${table.title}` || recordHeading(e.id);    // A conversation page (an email thread, a session) opens at its newest end, its heading above: scroll up to it.    await this.wait(e => e.id.startsWith('page-') && !isRow(e.id));    const heading = await this.heading(isHeading);    this.report.check(!titleFailure(heading.label), `${tool} first page has a title`, titleFailure(heading.label) ?? '');    const page = this.see();    this.report.check(!screenFailures(page).length, `${tool} first page reads`, screenFailures(page).join('; '));    if (table.id === 'thread') {      const texts = fixtures.messages.filter(m => m.thread_id === rowId).map(m => m.body);      const message = await this.wait(e => texts.some(t => e.label.includes(t)), 30_000);      this.report.check(!!message, 'Chats conversation shows seeded message text');    }    this.shot(tool.replace(/[^a-zA-Z0-9-]/g, '-'));  }  async chatCase(fixture: Fixtures['chatCases'][number]) {    await this.home();    this.call('open-url', {url: `${this.app.scheme}://messages/${encodeURIComponent(fixture.id)}`});    await this.wait(e => e.id === 'page-thread-menu');    const heading = await this.heading(e => e.id === 'page-thread-heading');    this.report.check(!titleFailure(heading.label), `${fixture.shape} page has a title`, titleFailure(heading.label) ?? '');    const errors = screenFailures(this.see());    this.report.check(!errors.length, `${fixture.shape} page reads`, errors.join('; '));    this.shot(fixture.shape.replaceAll(' ', '-'));  }}async function main() {  const [run, headless, app, port, source, before, ...rest] = process.argv.slice(2);  if (!run || !headless || !app || !port || Number(port) <= 9800 || !source || !before || rest.length && rest.join(' ') !== '--only update') throw new Error('usage: release-walk.ts run headless app port-above-9800 source-checkout build-to-update-from [--only update]');  const only = rest.length ? 'update' : null;  const report = new Report(run);  const devices = JSON.parse(command('xcrun', ['simctl', 'list', 'devices', 'available', '-j'])) as {devices: Record<string, {deviceTypeIdentifier?: string; name: string}[]>};  const runtime = Object.keys(devices.devices).filter(k => k.includes('iOS')).sort().reverse().find(k => devices.devices[k]!.some(d => d.name.startsWith('iPhone') && d.deviceTypeIdentifier));  const model = runtime ? devices.devices[runtime]!.find(d => d.name.startsWith('iPhone') && d.deviceTypeIdentifier) : undefined;  if (!runtime || !model?.deviceTypeIdentifier) throw new Error('no iPhone simulator runtime');  const deviceType = model.deviceTypeIdentifier;  let activeDevice: string | null = null;  const interrupted = () => {    report.check(false, 'run interrupted');    if (activeDevice) { try { disposeSimulator(activeDevice); } catch (error) { report.check(false, 'interrupted simulator cleanup', error); } }    process.exit(1);  };  process.once('SIGINT', interrupted); process.once('SIGTERM', interrupted);  // THE TWO FRESH PHONES, on the household release-walk.sh founded and serves.  const freshPhones = async () => {  const data = join(run, 'household');  const origin = `http://127.0.0.1:${port}`;  const request = deviceRequester(data, origin);  const fixtures = JSON.parse(readFileSync(join(run, 'fixtures.json'), 'utf8')) as Fixtures;  writeFileSync(join(run, 'fixtures.json'), JSON.stringify(fixtures, null, 2));  for (const [shape, present] of Object.entries(fixtures.shapes)) report.check(present, `generator shape: ${shape}`, present ? '' : 'MISSING from synthetic generator at this SHA');  let databases = (await request('GET', '/v1/me/databases')).databases as Database[];  if (databases.filter(d => d.kind !== 'personal').length < 3) {    report.line('MISSING generator project databases: creating three from its project names through the signed production API');    for (const project of fixtures.projects.slice(0, 3)) await request('POST', `/v1/databases?database=${fixtures.personal}`, {name: project.name});    databases = (await request('GET', '/v1/me/databases')).databases as Database[];  }  report.check(databases.filter(d => d.kind !== 'personal').length >= 3, 'household has at least three project databases');  writeFileSync(join(run, 'server-databases.json'), JSON.stringify(databases, null, 2));  // The board walk's databases: the personal one, and the business one release-walk.sh founded beside it.  const business = String((JSON.parse(readFileSync(join(run, 'business.json'), 'utf8').trim().split('\n').pop()!) as Json).workspaceId);  const setter = join(run, 'setter');  report.line('NOTE unknown family: Cotton Dev-only trigger (developer.wearThemeRow) — walked by walk:board, not by the REAL gate');  for (const phase of ['first', 'later']) {    // THE BOARD SETUP, only now: it rearranges the Home tool cards phase first    // walks, so it waits for that phone to be done — and lands before the later    // phone joins, which then downloads it with its first copy.    let board = false;    if (phase === 'later') {      try {        await joinSetter(headless, data, origin, setter, join(run, 'setter-join.log'));        boardSetup(headless, setter, run, fixtures.personal, business, report, source);        board = true;      } catch (error) { report.check(false, 'board setup', error); }    }    // Create, never erase or reuse somebody else's simulator. Later is created only AFTER phase one.    const udid = command('xcrun', ['simctl', 'create', `release-walk-${basename(run)}-${phase}`, deviceType, runtime]).trim();    activeDevice = udid;    appendFileSync(join(run, 'simulators.txt'), `${phase} ${udid}\n`);    const phone = new Phone(udid, phase, report);    const type = phase === 'later' ? largestTypeBeforeLaunch(udid, run, report) : null;    try {      await phone.join(headless, data, app, origin, { beforeLaunch: type?.beforeLaunch });      report.check(true, `${phase} fresh REAL phone joins by pair and approve`);      databases = (await request('GET', '/v1/me/databases')).databases as Database[];      await phone.databases(databases);      if (phase === 'first') {        for (const database of databases) {          try {            await phone.pick(database);            if (database.kind === 'personal') {              const cards = await phone.cards();              report.check(cards.length > 1, 'personal database has tool cards');              for (const key of fixtures.expectedTools) report.check(cards.some(c => c.key === key), `${key} tool card exists`);              report.check(cards.some(c => c.key === 'messages'), 'Chats tool is present in the walk');              writeFileSync(join(run, 'tool-cards.json'), JSON.stringify(cards, null, 2));              // The Tools card is the screen being walked, not a tool of its own.              for (const card of cards.filter(c => c.key !== 'tools')) {                const name = `tool-${card.key}`;                try {                  await phone.tool(card.key);                  await pause(1000);                  const subtables = phone.see().filter(e => e.id.startsWith('tool-table-'));                  if (subtables.length) {                    for (const subtable of subtables) {                      phone.tap(await phone.findScrolling(e => e.id === subtable.id));                      await phone.listAndRow(`${name}/${subtable.id}`, fixtures.tables, fixtures);                      await phone.label('Back'); await phone.label('Back');                    }                  } else await phone.listAndRow(name, fixtures.tables, fixtures);                } catch (error) { report.check(false, name, error); phone.shot(`${name}-failed`); }              }              // A group sorts first in the generator. Exercise the untitled DM and              // empty/media cases explicitly so their regressions cannot hide behind it.              for (const fixture of fixtures.chatCases) {                try { await phone.chatCase(fixture); }                catch (error) { report.check(false, fixture.shape, error); phone.shot(`${fixture.shape.replaceAll(' ', '-')}-failed`); }              }            }          } catch (error) { report.check(false, `database ${database.name ?? database.id}`, error); }          await phone.home(); await phone.id('bar-database');        }      }      if (phase === 'later' && board) {        await phone.closeDatabases();        const walked = (['personal', 'business'] as const).map(kind => ({ kind, database: databases.find(d => d.id === (kind === 'personal' ? fixtures.personal : business)) }));        report.check(walked.every(w => w.database), 'board walk: the server lists the personal and business databases', walked.filter(w => !w.database).map(w => w.kind).join(', '));        await walkBoardScreens(phone, udid, REAL_APP.bundleId, walked.filter((w): w is { kind: typeof w.kind; database: Database } => !!w.database), report, type!.launched);        feedbackChecks(headless, setter, run, fixtures.personal, report, source);      }    } catch (error) { report.check(false, `${phase} phone`, error); try { phone.shot('failed'); } catch { /* AX failure is already red. */ } }    finally {      type?.restore();      // Screenshots and trees stay; only this run's newly created device is deleted.      try { disposeSimulator(udid); } catch (error) { report.check(false, `${phase} simulator cleanup`, error); }      activeDevice = null;    }  }  };  if (!only) await freshPhones();  // THE UPDATE CASE, last, each phone on its own household and simulator: a phone on the build before the newest  // schema bump holds unsent changes, the Mac moves up, the phone updates — with the Mac serving, then with it away (update-walk.ts).  const [, was = '?', now = '?'] = readFileSync(join(run, 'update-from'), 'utf8').trim().split(' ');  for (const [phase, mac] of [['update', 'serving'], ['update-away', 'away']] as const) {    const udid = command('xcrun', ['simctl', 'create', `release-walk-${basename(run)}-${phase}`, deviceType, runtime]).trim();    activeDevice = udid;    appendFileSync(join(run, 'simulators.txt'), `${phase} ${udid}\n`);    const phone = new Phone(udid, phase, report);    try { await walkUpdate(phone, run, { kind: 'install', before: buildIn(before), after: { headless, app }, step: `${was} to ${now}` }, mac, report); }    catch (error) { report.check(false, `${phase} phone`, error); try { phone.shot('failed'); } catch { /* AX failure is already red. */ } }    finally {      try { disposeSimulator(udid); } catch (error) { report.check(false, `${phase} simulator cleanup`, error); }      activeDevice = null;    }  }  // Only the whole walk gates a cut; the update case alone says so in its verdict.  const walked = only ? 'the update case ONLY — not the gate' : 'two fresh REAL phones and two updated across a schema bump';  const summary = `${report.failures ? 'RED' : 'GREEN'} ${readFileSync(join(run, 'sha'), 'utf8').trim()} ${report.passed} passed, ${report.failures} failed; ${walked}; evidence ${run}`;  report.line(summary); writeFileSync(join(run, 'summary.txt'), summary + '\n');  process.exitCode = report.failures ? 1 : 0;}if (process.argv[1] === fileURLToPath(import.meta.url)) main().catch(error => { console.error(`FAIL setup: ${flat(error)}`); process.exitCode = 1; });