Cotton code
351 lines · 20.1 KB · TypeScriptRaw
/** * THE BOARD WALK, shared: the day-3 setup and screens (design note "board and * theme") that both `pnpm walk:board` (Cotton Dev, `walk-board.ts`) and the * production gate `pnpm release:walk` (REAL, `release-walk.ts` phase `later`) * run. One driver, so the gate cannot drift from the walk that closed the build. * * WHY METHODS GO THROUGH A JOINED SETTER. The walks' other server acts are * signed `/v1` routes, and no route writes a home arrangement, a board or a * theme — those are app methods, answered by a device's core over its own * copy (`cotton_ffi::dispatch`). So a second device, `setter`, joins the * served household beside the phone (`cotton-headless join`, approved at the * server), and `cotton-headless call --data-dir setter` runs each method there * and syncs — the write reaches the server, and the phone, as a phone's own * would. A method this build lacks is refused by the CORE as `unknown_method`, * and the step FAILS with a sentence naming it — never a skip. * * release-walk.ts imports this module and this module imports its runtime * helpers back: the cycle is safe because neither touches the other's exports * at module top level, only inside functions. */import { spawn, spawnSync } from 'node:child_process';import { appendFileSync, closeSync, mkdirSync, openSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import type { Element } from './lib/describe-screen';import { command, flat, pause, screenFailures, type Database, type Json, type Phone, type Report } from './release-walk';const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');/** One screen of the day-3 row: what it is, its deep link, and what proves it opened. */export interface BoardScreen {  name: string;  /** `{row}` is the first row the list screen before it showed. */  path: string;  proof?: { anyId?: string[]; idPrefix?: string; goneId?: string };}/** THE DAY-3 ROW, as data: walked once in each database, in this order. */export const BOARD_SCREENS: readonly BoardScreen[] = [  { name: 'Home', path: '/home', proof: { anyId: ['bar-search', 'bar-database'] } },  { name: 'Tools', path: '/tools' },  { name: 'database page', path: '/database' },  // A list is proven by a ROW (`todo-<id>`), not its search field: the field draws while the rows still load.  { name: 'a list', path: '/todos', proof: { idPrefix: 'todo-' } },  { name: 'a record page', path: '/todos/todo/{row}', proof: { anyId: ['page-todo-title'] } },  { name: 'This phone', path: '/device', proof: { anyId: ['page-device-name'] } },  { name: 'a Work screen', path: '/projects', proof: { goneId: 'bar-search' } },  { name: 'Connections', path: '/connections' },];/** Who does a setup step: the shell, the phone driver, or the core (a named method, and the lane that owes it). */export interface SetupStep { name: string; by: 'shell' | 'phone' | 'core'; how: string; method?: string; lane?: string }/** THE DAY-3 SETUP, as data, in the order it runs. */export const BOARD_SETUP: readonly SetupStep[] = [  { name: 'fresh install', by: 'shell', how: 'erase the walk simulator (ios-walk-sim.sh --may-erase), then reinstall Cotton Dev' },  { name: 'large seed', by: 'shell', how: 'cotton-headless seed --size large' },  // POST /v1/databases takes {name} or {id} and no toolkit, so the business  // database is founded by `add-database`, which installs its own toolkit  // (`SECOND_DATABASE_TOOLKIT`, family) — not yoga-studio or tech-team.  { name: 'second database', by: 'shell', how: 'cotton-headless add-database --database Studio' },  { name: 'board grid columns 4', by: 'core', how: "the personal database's home board, its tools part face grid, columns 4", method: 'definitions.saveBoard', lane: 'board' },  { name: 'business database on plain', by: 'core', how: "the business database's theme row 'database', family plain", method: 'definitions.saveTheme', lane: 'theme' },  { name: 'largest Dynamic Type', by: 'phone', how: 'xcrun simctl ui content_size accessibility-extra-extra-extra-large before launch, restored after' },];/** The shipped home board with its tools part as a grid of four columns; its id and every other part kept. */export function gridBoard(board: { id: string; parts: Json[] }): { id: string; parts: Json[] } {  if (!board.parts.some(p => p.kind === 'tools')) throw new Error(`board ${board.id} has no tools part`);  return { ...board, parts: board.parts.map(p => p.kind === 'tools' ? { ...p, face: 'grid', columns: 4 } : p) };}/** The database's own theme row: the shipped plain theme's shape, under the id `database`. */export function plainTheme(theme: Json): Json {  if (theme.family !== 'plain') throw new Error('the plain theme definition is not family plain');  return { ...theme, id: 'database' };}/** A `cotton-headless call` that failed, said as a sentence: the core's unknown_method names the lane that owes it. */export function methodRefusal(step: Pick<SetupStep, 'method' | 'lane'>, stderr: string): string {  if (/unknown_method/.test(stderr)) return `${step.method} is not on this build — the ${step.lane} lane has not landed it`;  if (/unknown command: call/.test(stderr)) return `this cotton-headless has no call verb, so ${step.method} could not be asked — rebuild it from this checkout`;  return `${step.method} was refused: ${flat(stderr).replace(/^cotton-headless:\s*/, '')}`;}/** Every Feedback row whose text says the app met an unknown board part or theme family. */export function unknownFeedback(answer: unknown): string[] {  // `read.myReports` answers `{reports}`; the row's words are matched whole, so  // whichever field the board and theme lanes file them under is read.  const rows = (answer as { reports?: unknown })?.reports;  if (!Array.isArray(rows)) return [];  return rows    .filter(row => /unknown (part|family)|passed over|not drawn|cannot draw/i.test(JSON.stringify(row)))    .map(row => {      const said = typeof row === 'object' && row ? (row as Json).text ?? (row as Json).body ?? (row as Json).title : row;      return flat(typeof said === 'string' ? said : JSON.stringify(row));    });}/** The system's "Open in …?" prompt's Open button, when the prompt is up: a screen judged under it is not the app's. */export function openPrompt(screen: Element[]): Element | undefined {  if (!screen.some(e => e.label.startsWith('Open in'))) return undefined;  return screen.find(e => e.role === 'AXButton' && e.label === 'Open');}/** Dynamic Type sizes `simctl ui content_size` accepts, smallest first. */export const CONTENT_SIZES = [  'extra-small', 'small', 'medium', 'large', 'extra-large', 'extra-extra-large', 'extra-extra-extra-large',  'accessibility-medium', 'accessibility-large', 'accessibility-extra-large', 'accessibility-extra-extra-large',  'accessibility-extra-extra-extra-large',] as const;export const LARGEST_TYPE = CONTENT_SIZES[CONTENT_SIZES.length - 1];/** The size `xcrun simctl ui <udid> content_size` printed, or null when it printed none we know (then nothing is restored). */export function readContentSize(output: string): string | null {  const word = output.trim().split(/\s+/).pop() ?? '';  return (CONTENT_SIZES as readonly string[]).includes(word) ? word : null;}/** The simctl arguments that put a device's text size back; none when the previous size was never read. */export function contentSizeRestore(udid: string, previous: string | null): string[] | null {  return previous && previous !== LARGEST_TYPE ? ['simctl', 'ui', udid, 'content_size', previous] : null;}/** True while launchctl on the simulator lists the app's process. *//** A screen saying a read missed its deadline (the app's Try again). */export const readTimedOut = (elements: Element[]) => elements.some(e => /did not answer in time/.test(e.label));export function isAlive(launchctl: string, bundleId: string): boolean {  return launchctl.includes(`UIKitApplication:${bundleId}`);}/** The deep link for a screen in a database, with `{row}` filled. */export function screenUrlPath(screen: BoardScreen, database: string, row: string | null): string {  if (screen.path.includes('{row}') && !row) throw new Error(`${screen.name} needs a row, and the list before it showed none`);  return `${screen.path.replace('{row}', encodeURIComponent(row ?? ''))}?database=${encodeURIComponent(database)}`;}/** Whether a screen's proof is on it. */export function proven(screen: BoardScreen, elements: Element[]): boolean {  const proof = screen.proof;  if (!proof) return true;  if (proof.anyId && !elements.some(e => proof.anyId!.includes(e.id))) return false;  if (proof.idPrefix && !elements.some(e => e.id.startsWith(proof.idPrefix!))) return false;  if (proof.goneId && elements.some(e => e.id === proof.goneId)) return false;  return true;}/** The first todo row's id on a list screen (`todo-<id>`, as release-walk reads rows). */export function firstRow(elements: Element[], table = 'todo'): string | null {  const row = elements.find(e => e.role === 'AXButton' && e.id.startsWith(`${table}-`) && !e.id.startsWith(`list-${table}-`));  return row ? row.id.slice(table.length + 1) : null;}const REPORTS = join(homedir(), 'Library/Logs/DiagnosticReports');export function crashesSince(since: number): string[] {  try {    return readdirSync(REPORTS).filter(f => /^Cotton-.*\.ips$/.test(f)).map(f => join(REPORTS, f)).filter(f => statSync(f).mtimeMs > since);  } catch { return []; }}export type CoreAnswer = { ok: true; answer: unknown } | { ok: false; stderr: string };/** One app method in `database`, through the setter — a device joined to the served household, so the write reaches the server as a phone's does. */export function core(headless: string, setter: string, run: string, method: string, request: Json, database: string): CoreAnswer {  const out = spawnSync(headless, ['call', method, '--args', JSON.stringify(request), '--database', database, '--data-dir', setter], { encoding: 'utf8', timeout: 600_000, maxBuffer: 64 * 1024 * 1024 });  appendFileSync(join(run, 'core-calls.log'), `$ call ${method} in ${database} ${JSON.stringify(request)}\n${out.stdout ?? ''}${out.stderr ?? ''}\n`);  if (out.status !== 0) return { ok: false, stderr: out.stderr || String(out.error ?? `exit ${out.status}`) };  try { return { ok: true, answer: JSON.parse(out.stdout.trim().split('\n').pop() ?? 'null') }; } catch { return { ok: true, answer: out.stdout }; }}/** * Join the SETTER to the household served at `origin` and approve it at the * server's data directory: `join` blocks until approved, so it runs beside * this process while its `Pairing ID:` line is read from `log`. Throws with * the log's path when any step does not happen. */export async function joinSetter(headless: string, data: string, origin: string, setter: string, log: string): Promise<void> {  mkdirSync(setter, { mode: 0o700 });  const out = openSync(log, 'a');  const joining = spawn(headless, ['join', origin, '--name', 'walk-setter', '--data-dir', setter], { stdio: ['ignore', out, out] });  closeSync(out);  let code: number | null | undefined;  const exited = new Promise<number | null>(resolve => joining.on('exit', c => { code = c; resolve(c); }));  joining.on('error', () => { code ??= -1; });  try {    let pairing = '';    for (let i = 0; i < 60 && !pairing; i++) {      pairing = /^Pairing ID: (\S+)/m.exec(readFileSync(log, 'utf8'))?.[1] ?? '';      if (pairing) break;      // A refusal is the server's own line (on this Mac, a setter carries the      // serving Mac's machine: "this Mac already serves; re-key from the app").      if (code !== undefined) throw new Error(`the setter's join ended before asking: ${readFileSync(log, 'utf8').trim().split('\n').pop() ?? ''} (${log})`);      await pause(1000);    }    if (!pairing) throw new Error(`the setter's join asked nothing within 60 seconds: ${log}`);    const approved = spawnSync(headless, ['approve', pairing, '--data-dir', data], { encoding: 'utf8', timeout: 60_000 });    appendFileSync(log, `${approved.stdout ?? ''}${approved.stderr ?? ''}`);    if (approved.status !== 0) throw new Error(`the setter was not approved: ${log}`);    const status = await Promise.race([exited, pause(180_000).then(() => 'timeout' as const)]);    if (status !== 0) throw new Error(`the setter did not join (${status === 'timeout' ? 'still waiting after 180 seconds' : `exit ${status}`}): ${log}`);  } finally {    if (code === undefined) joining.kill();  }}/** * The day-3 core setup through the setter, in BOARD_SETUP's order: the * four-column grid in `personal` (Home's arrangement is set by MCP only, never * by an app method), the plain theme in * `business`. The definitions are read from `root`, the checkout walked (the * release walk builds from its own worktree of the cut commit). */export function boardSetup(headless: string, setter: string, run: string, personal: string, business: string, report: Report, root = ROOT) {  const definitions = join(root, 'crates/cotton-core/kits/shell');  const requests: Record<string, [Json, string]> = {    'definitions.saveBoard': [{ definition: gridBoard(JSON.parse(readFileSync(join(definitions, 'boards/home.json'), 'utf8'))) }, personal],    'definitions.saveTheme': [{ definition: plainTheme(JSON.parse(readFileSync(join(definitions, 'themes/plain.json'), 'utf8'))) }, business],  };  for (const step of BOARD_SETUP.filter(s => s.by === 'core')) {    const [request, database] = requests[step.method!]!;    const answer = core(headless, setter, run, step.method!, request, database);    report.check(answer.ok, `setup ${step.name} (${step.method})`, answer.ok ? '' : methodRefusal(step, answer.stderr));  }}/** * The largest Dynamic Type, set on `udid` between install and launch (Phone.join's * `beforeLaunch`), and its `restore` for a `finally`. `launched()` is when the * app was launched: a crash report newer than it is this walk's. */export function largestTypeBeforeLaunch(udid: string, run: string, report: Report) {  let previous: string | null = null;  let launched = Date.now();  return {    beforeLaunch: () => {      previous = readContentSize(command('xcrun', ['simctl', 'ui', udid, 'content_size']));      writeFileSync(join(run, 'content-size.prev'), `${previous ?? ''}\n`);      command('xcrun', ['simctl', 'ui', udid, 'content_size', LARGEST_TYPE]);      const now = readContentSize(command('xcrun', ['simctl', 'ui', udid, 'content_size']));      report.check(now === LARGEST_TYPE, 'setup largest Dynamic Type', now === LARGEST_TYPE ? '' : `the simulator says ${now ?? 'nothing'}`);      launched = Date.now();    },    restore: () => {      const args = contentSizeRestore(udid, previous);      if (args) try { command('xcrun', args); } catch (error) { report.check(false, 'Dynamic Type restored', error); }    },    launched: () => launched,  };}/** Deep-link `screen` in `database`, answer the "Open in" prompt, and wait up to 30 s for its proof; the elements last read, and why none were. */export async function arrive(phone: Phone, screen: BoardScreen, database: string, row: string | null): Promise<{ elements: Element[]; blank: string }> {  phone.open(screenUrlPath(screen, database, row));  await pause(1500);  let elements: Element[] = [];  let blank = '';  const until = Date.now() + 30_000;  do {    try { elements = phone.see(); blank = ''; } catch (error) { blank = flat(error); elements = []; }    // The system asks "Open in “Cotton …”?" a moment after the link; the app sees nothing until it is answered.    const asked = openPrompt(elements);    if (asked) { phone.tap(asked); await pause(1500); continue; }    if (elements.length && proven(screen, elements)) break;    await pause(700);  } while (Date.now() < until);  return { elements, blank };}/** * Walk every BOARD_SCREENS screen in each database, in order: the list's first * row feeds the record page, each screen is shot as * `<phase>-<kind>-NN-<Screen>.png` and judged (crash, alive, blank, an error * sentence, its proof). True when the app died — every later screen would be * the same failure, so the first one says it and the walk stops. */export async function walkBoardScreens(phone: Phone, udid: string, bundleId: string, databases: { kind: 'personal' | 'business'; database: Database }[], report: Report, launched: () => number): Promise<boolean> {  let dead = false;  for (const { kind, database } of databases) {    if (dead) break;    let row: string | null = null;    for (const [n, screen] of BOARD_SCREENS.entries()) {      if (dead) break;      const name = `${kind} ${screen.name}`;      const shot = `${kind}-${String(n + 1).padStart(2, '0')}-${screen.name.replace(/[^a-zA-Z0-9]+/g, '-')}`;      try {        let { elements, blank } = await arrive(phone, screen, database.id, row);        // A read past its deadline (SettingsReadDeadline: six seconds for the Mac) is the app's        // Try again, not a defect: under a Mac's load it is read once more, said as a NOTE.        if (readTimedOut(elements)) {          report.line(`NOTE ${name}: a read did not answer in time; opened again`);          await pause(5_000);          ({ elements, blank } = await arrive(phone, screen, database.id, row));        }        phone.shot(shot);        if (screen.path === '/todos') row = firstRow(elements);        const crashes = crashesSince(launched());        const alive = isAlive(command('xcrun', ['simctl', 'spawn', udid, 'launchctl', 'list']), bundleId);        const failures = screenFailures(elements);        const reason = crashes.length ? `the app crashed — ${crashes.join(', ')}`          : !alive ? 'the app is gone with no crash report'          : openPrompt(elements) ? 'the system\'s "Open in" prompt never let the deep link through'          : !elements.length ? `blank screen: ${blank || 'no accessibility elements'}`          : failures.length ? failures.join('; ')          : !proven(screen, elements) ? `did not open (proof ${JSON.stringify(screen.proof)} absent)` : '';        report.check(!reason, `${name} opens and reads`, reason);        dead = crashes.length > 0 || !alive;      } catch (error) {        report.check(false, name, error);        try { phone.shot(`${shot}-failed`); } catch { /* already red */ }        dead = crashesSince(launched()).length > 0;      }    }  }  // A Feedback row the app wrote on the way must reach the server before it stops.  await pause(20_000);  return dead;}/** * The methods that file the Feedback lines the walk reads, each with the lane * that owes it (the unknown family's is `definitions.theme` itself, met by * walk:board's own step). One missing from the walked build is a named FAIL: * an empty Feedback list proves nothing when nothing could have written to it. */export const FEEDBACK_WRITERS: readonly { method: string; lane: string; says: string }[] = [  { method: 'definitions.passedOver', lane: 'board', says: 'an unknown board part' },];/** The writers the core of this checkout does not answer. */export function missingWriters(methodsRs: string): typeof FEEDBACK_WRITERS[number][] {  return FEEDBACK_WRITERS.filter(w => !methodsRs.includes(`"${w.method}"`));}/** Feedback after the screens: every writer is on the walked build (`root`), and no row says an unknown part or family. */export function feedbackChecks(headless: string, setter: string, run: string, personal: string, report: Report, root = ROOT) {  const methodsRs = readFileSync(join(root, 'crates/cotton-ffi/src/methods.rs'), 'utf8');  for (const writer of FEEDBACK_WRITERS) {    const missing = missingWriters(methodsRs).includes(writer);    report.check(!missing, `Feedback can say ${writer.says} (${writer.method})`, missing ? methodRefusal(writer, 'unknown_method') : '');  }  // Feedback is the person's (Spec 9.5): every database's app files into the  // personal one, so one read sees both databases' lines.  const answer = core(headless, setter, run, 'read.myReports', {}, personal);  if (!answer.ok) {    report.check(false, 'Feedback reads', methodRefusal({ method: 'read.myReports', lane: 'feedback' }, answer.stderr));  } else {    const unknown = unknownFeedback(answer.answer);    report.check(!unknown.length, 'Feedback has no unknown part or family', unknown.join(' | '));  }}