/** * THE RELEASE WALK'S UPDATE CASE: a phone holds unsent changes, the Mac moves * to a higher schema, the phone updates. * * The owner's phone, 10 Oct 2026: three changes it had not sent, a Mac already * on the next schema, an update — and "Something went wrong" with one button, * Try again, that drew the same screen for good. The phone's copy was older * than the app could read and held work the app would not throw away, so * nothing moved and nothing could be pressed that changed that. * * The case, on a household of its own: * 1. the build BEFORE the newest schema bump (release-walk-before.sh) founds * a household and serves it; its app joins on a fresh simulator; * 2. the server stops, and the phone makes UNSENT todos it cannot send; * 3. the walked commit's server serves the same household — the Mac moved up; * 4. the walked commit's app is installed OVER the phone's data and opened; * 5. the walk goes forward as a person would: it presses what the screen * offers, sending before discarding, until Home. * * It fails on a screen with no way forward (every action on it brought it * back, or it offers nothing and never changes), on a phone that forgot its * household, on a crash, and on Home reached with the changes on neither side * — unless the phone asked and the walk, with sending exhausted, discarded. * * TWICE, for where the Mac is when the updated app opens: SERVING (the phone * sends first and reaches Home) and AWAY (the phone cannot send, so it must * list the changes and offer to send or discard them; the Mac then returns, * the walk presses send, and Home follows). * * AND STAGED TWO WAYS. The gate (`pnpm release:walk`, the REAL app) makes the * step real: two builds, the older app's own copy. Cotton Dev has a hook for * one build (`developer.stampStaleCopy`, the device page's "Mark this copy as * an older build's"): the copy is stamped one schema lower and the app * relaunched — `pnpm walk:update`, minutes instead of a second build. The * real app refuses the hook by name, so the gate never leans on it. */ import { spawn, type ChildProcess } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { createServer, type AddressInfo } from 'node:net'; import { join } from 'node:path'; import { crashesSince, isAlive } from './board-walk'; import { type Element } from './lib/describe-screen'; import { command, flat, loadFactor, pause, screenFailures, type Json, type Phone, type Report } from './release-walk'; /** How many changes the phone holds unsent across the update. */ export const UNSENT = 3; /** The todos' titles: this run's own, so a seeded todo is never mistaken for one. */ export function unsentTitles(run: string): string[] { const tag = run.replace(/[^a-zA-Z0-9]/g, '').slice(-6) || 'walk'; return Array.from({ length: UNSENT }, (_, n) => `Unsent ${n + 1} of ${UNSENT} ${tag}`); } /** Which of the phone's changes the Mac's database does not hold. */ export function missingOnTheMac(titles: string[], onTheMac: string[]): string[] { return titles.filter(t => !onTheMac.includes(t)); } /** Buttons pressed so far, by the screen they were pressed on. */ export type Tried = Map>; export type Step = | { kind: 'home' } /** Nothing to press: the app is working (a copy coming down), or drawing. */ | { kind: 'wait' } | { kind: 'press'; button: Element; sends: boolean; discards: boolean } | { kind: 'stuck'; why: string }; const words = (e: Element) => (e.label || e.value).replace(/\s+/g, ' ').trim(); /** Leaves the household (the stalled wait's "join again"): never a way forward for a phone holding changes. */ const leaves = (e: Element) => /\b(join|pair|sign out)\b/i.test(words(e)) || /-join$/.test(e.id); /** What a person can press to go on: a button that says what it does, and keeps the household. */ const actions = (screen: Element[]) => screen.filter(e => e.role === 'AXButton' && words(e) && !leaves(e)); const key = (e: Element) => e.id || words(e); const sends = (e: Element) => /\b(send|sync)\b/i.test(words(e)); /** Throws work away: tried last, and said. */ const discards = (e: Element) => /\b(discard|delete|erase|reset|remove|start (?:over|again|fresh))\b/i.test(words(e)); /** * A screen as what it says and offers, wherever it is drawn: the same sentence * with another count ("attempt 2", "4 MB so far") is the same screen. */ export function signature(screen: Element[]): string { return screen.filter(e => words(e) && ['AXButton', 'AXStaticText', 'AXHeading'].includes(e.role)) .map(e => `${e.role}:${e.id}:${words(e).replace(/\d+/g, '#')}`).sort().join('|'); } /** * What to do on the screen the updated phone shows. `tried` remembers every * button pressed on every screen, so a screen met again offers only what has * not been pressed on it — and one with nothing left is the dead end. */ export function nextStep(screen: Element[], tried: Tried): Step { if (screen.some(e => e.id === 'bar-database')) return { kind: 'home' }; const said = screen.filter(e => e.role !== 'AXButton').map(words).filter(Boolean).join(' · ').slice(0, 300); // First run again is not a way forward: the phone's household, and its changes, are gone. if (screen.some(e => e.id === 'join-screen' || e.role === 'AXButton' && e.label === 'Join my database')) { return { kind: 'stuck', why: 'the updated phone forgot its household: it asks to join again' }; } const offered = actions(screen); if (!offered.length) return { kind: 'wait' }; const at = signature(screen); const pressed = tried.get(at) ?? new Set(); tried.set(at, pressed); const left = offered.filter(b => !pressed.has(key(b))); if (!left.length) { return { kind: 'stuck', why: `no way forward: ${offered.map(b => `"${words(b)}"`).join(', ')} brought the same screen back — ${said || 'a screen with no words'}` }; } const order = (b: Element) => sends(b) ? 0 : discards(b) ? 2 : 1; const button = [...left].sort((a, b) => order(a) - order(b))[0]!; pressed.add(key(button)); return { kind: 'press', button, sends: sends(button), discards: discards(button) }; } /** The system's own question over the app (notifications, "Open in …?"): answered, never judged. */ export function systemPrompt(screen: Element[]): Element | undefined { return 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')))); } /** The titles of this walk's todos in the Mac's own file for `database`, read beside the serving process. */ export function todosOnTheMac(data: string, database: string): string[] { const files = join(data, 'files'); const shard = readdirSync(files).find(s => existsSync(join(files, s, database, 'life.db'))); if (!shard) throw new Error(`the household holds no file for ${database}`); const out = command('sqlite3', ['-readonly', '-json', join(files, shard, database, 'life.db'), "SELECT title FROM cotton_todos WHERE title LIKE 'Unsent %'"]); return out.trim() ? (JSON.parse(out) as { title: string }[]).map(r => r.title) : []; } const tail = (file: string) => { try { return flat(readFileSync(file, 'utf8').trim().split('\n').slice(-4).join(' ')); } catch { return ''; } }; function freePort(): Promise { return new Promise((resolve, reject) => { const probe = createServer(); probe.once('error', reject); probe.listen(0, '127.0.0.1', () => { const { port } = probe.address() as AddressInfo; // Above 9800, as release-walk.sh reserves its own: never a port a real Cotton serves on. probe.close(() => port > 9800 ? resolve(port) : reject(new Error(`the free port ${port} is not above 9800`))); }); }); } /** `headless serve` over `data`, returned once its status says it bound `port`. This process's own child: stopped by its handle, never by name. */ async function serve(headless: string, data: string, origin: string, port: number, log: string): Promise { const out = openSync(log, 'a'); const child = spawn(headless, ['serve', '--data-dir', data, '--name', 'release-walk-update', '--address', origin], { stdio: ['ignore', out, out] }); closeSync(out); const until = Date.now() + 180_000 * loadFactor(); while (Date.now() < until) { if (child.exitCode !== null || child.signalCode) throw new Error(`the server ended before serving — ${tail(log)}`); try { if ((JSON.parse(command(headless, ['status', '--json', '--data-dir', data])) as Json).boundPort === port) return child; } catch { /* Not serving yet. */ } await pause(1000); } child.kill(); throw new Error(`the server did not bind ${port} in time — ${tail(log)}`); } async function stopServer(child: ChildProcess): Promise { if (child.exitCode !== null || child.signalCode) return; const gone = new Promise(resolve => child.once('exit', () => resolve(true))); child.kill('SIGTERM'); if (await Promise.race([gone, pause(30_000).then(() => false as const)])) return; child.kill('SIGKILL'); await gone; } /** A build of release-walk.sh's `build_at`: its headless server and its simulator app. */ export interface Build { headless: string; app: string } export const buildIn = (dir: string): Build => ({ headless: join(dir, 'cotton-headless'), app: join(dir, 'derived/Build/Products/Debug-iphonesimulator/Cotton.app') }); /** How the phone comes to hold another build's copy. */ export type Stage = /** A real update: `before`'s app writes the copy, `after`'s server and app meet it. `step` says the schemas ("92 to 93"). */ | { kind: 'install'; before: Build; after: Build; step: string } /** Cotton Dev's hook: one build, its copy stamped one schema lower from the device page. */ | { kind: 'stamp'; build: Build }; /** Where the Mac is when the updated app opens. */ export type Mac = 'serving' | 'away'; /** The device page's developer act, as the developer lines name it. */ export const STAMP_ACT = { id: 'dev_stale_copy', label: 'Mark this copy as an older build\'s', confirm: 'Mark' } as const; /** Cotton Dev only: the phone's copy stamped as an older build's, through the device page. */ async function stampStaleCopy(phone: Phone, report: Report) { phone.open('device'); await phone.wait(e => e.id === 'page-device-name'); const act = (e: Element) => e.role === 'AXButton' && (e.id.endsWith(`action-${STAMP_ACT.id}`) || e.label === STAMP_ACT.label); let button: Element; try { button = await phone.findScrolling(act); } catch { // Not drawn on the page itself: the page's menu holds its acts. await phone.id('page-device-menu'); button = await phone.wait(act, 10_000); } phone.tap(button); phone.tap(await phone.wait(e => e.role === 'AXButton' && e.label === STAMP_ACT.confirm, 10_000)); try { report.line(`NOTE ${phone.phase}: the phone says — ${flat((await phone.wait(e => /Marked as schema \d+/.test(e.label), 10_000)).label)}`); } catch { report.line(`NOTE ${phone.phase}: the stamp's answer was not on the screen to quote`); } } /** * THE UPDATE, driven on `phone` (a simulator the caller owns), in a household * of its own under `run`. Every verdict is a `report.check` named for the * phone's phase; a step that cannot run at all throws, and the caller says so. */ export async function walkUpdate(phone: Phone, run: string, stage: Stage, mac: Mac, report: Report): Promise { const at = phone.phase; const first = stage.kind === 'install' ? stage.before : stage.build; const last = stage.kind === 'install' ? stage.after : stage.build; const data = join(run, `${at}-household`); mkdirSync(data, { mode: 0o700 }); const port = await freePort(); const origin = `http://127.0.0.1:${port}`; writeFileSync(join(data, 'env'), `PORT=${port}\nCOTTON_ADMIN_TOKEN=${randomBytes(32).toString('hex')}\n`, { mode: 0o600 }); const seeded = command(first.headless, ['seed', '--data-dir', data, '--size', 'small', '--seed', '41', '--name', `walk-${at}`], 600_000); writeFileSync(join(run, `${at}-seed.json`), seeded); const personal = String((JSON.parse(seeded.trim().split('\n').pop()!) as Json).workspaceId); const titles = unsentTitles(run); let server: ChildProcess | null = null; // The walk may be ended from outside mid-case: its server goes with it. const orphan = () => { server?.kill(); }; process.once('exit', orphan); const log = join(run, `${at}-server.log`); /** The Mac, back on the build the updated phone meets: for a real update, moving its household up. */ const macReturns = async (): Promise => { const name = stage.kind === 'install' ? `${at}: the Mac moves its household up (schema ${stage.step})` : `${at}: the Mac serves again`; try { server = await serve(last.headless, data, origin, port, log); report.check(true, name, stage.kind === 'install' ? /Shape move: v\d+ → v\d+/.exec(readFileSync(log, 'utf8'))?.[0] ?? '' : ''); } catch (error) { report.check(false, name, error); return false; } const already = todosOnTheMac(data, personal).filter(t => titles.includes(t)); report.check(!already.length, `${at}: the ${UNSENT} changes are unsent — the Mac holds none of them`, already.join(', ')); return true; }; try { server = await serve(first.headless, data, origin, port, join(run, `${at}-server-before.log`)); await phone.join(first.headless, data, first.app, origin, { owner: 'Update Walker' }); report.check(true, `${at}: a phone joins${stage.kind === 'install' ? ' on the build before the schema bump' : ''}`); // A write is the outbox's once this app has heard the Mac's time; one quiet exchange after the first copy makes sure. await pause(5000 * loadFactor()); // THE MAC GOES AWAY, and the phone keeps working: three todos it cannot send. await stopServer(server); server = null; for (const title of titles) { await phone.home(); phone.open('todos?new=1'); // A blank todo page opens with the cursor in its title; Return commits it. await phone.wait(e => e.id.startsWith('page-todo-')); await pause(800); phone.call('keyboard', { text: title }); phone.call('keyboard', { key: 'enter' }); await phone.wait(e => (e.label + ' ' + e.value).includes(title) && e.id !== 'page-todo-editor-title', 20_000); } report.check(true, `${at}: the phone makes ${UNSENT} changes with no Mac to send them to`); await phone.home(); try { phone.open('device'); const says = await phone.wait(e => e.id === 'page-device-unsent', 15_000); report.line(`NOTE ${at}: the phone says of its sync — ${flat(says.label || says.value)}`); } catch { report.line(`NOTE ${at}: This phone showed no sync line to quote`); } phone.shot('unsent'); if (stage.kind === 'stamp') { await stampStaleCopy(phone, report); phone.shot('stamped'); } command('xcrun', ['simctl', 'terminate', phone.udid, phone.app.bundleId]); if (mac === 'serving' && !await macReturns()) return; // THE UPDATE: the walked commit's app over the phone's data. An uninstall would walk a fresh phone instead. if (stage.kind === 'install') command('xcrun', ['simctl', 'install', phone.udid, stage.after.app], 300_000); const launched = Date.now(); phone.call('launch-app', { bundleId: phone.app.bundleId }); // FORWARD, as a person would go: press what the screen offers until Home. const tried: Tried = new Map(); const bound = 300_000 * loadFactor(); const until = Date.now() + bound; let screen: Element[] = []; let arrived = false, discarded = false, sent = false, presses = 0, why = ''; while (Date.now() < until) { try { screen = phone.see(); } catch (error) { why = `blank screen: ${flat(error)}`; await pause(1000); continue; } why = ''; const asked = systemPrompt(screen); if (asked) { phone.tap(asked); await pause(800); continue; } const step = nextStep(screen, tried); if (step.kind === 'home') { arrived = true; break; } if (step.kind === 'stuck') { why = step.why; break; } if (step.kind === 'wait') { await pause(1500); continue; } if (++presses > 12) { why = 'twelve presses, and still not Home'; break; } phone.shot(`before-press-${presses}`); report.line(`NOTE ${at}: pressed "${flat(step.button.label)}"${step.discards ? ' — which discards' : ''}`); phone.tap(step.button); sent ||= step.sends; discarded ||= step.discards; await pause(3000); } if (!arrived && !why) { const said = screen.map(e => e.label).filter(Boolean).join(' · ').slice(0, 300); why = `no way forward: for ${Math.round(bound / 60_000)} minutes the screen offered nothing more and never became Home — ${said}`; } phone.shot('after-update'); const crashes = crashesSince(launched); report.check(!crashes.length, `${at}: the updated app does not crash`, crashes.join(', ')); report.check(isAlive(command('xcrun', ['simctl', 'spawn', phone.udid, 'launchctl', 'list']), phone.app.bundleId), `${at}: the updated app is still running`); report.check(arrived, `${at}: the updated phone has a way forward to Home`, why); if (!arrived) return; report.line(`NOTE ${at}: Home after ${presses} press${presses === 1 ? '' : 'es'} beyond the update itself`); report.check(!screenFailures(screen).length, `${at}: Home has no error sentence`, screenFailures(screen).join('; ')); // Home with the Mac never back: the server is read as it was left, stopped. if (!server && !await macReturns()) return; // HOME ALONE PROVES NOTHING: the changes are on the Mac, or the phone asked and they were discarded. let missing = titles; const sendBy = Date.now() + 120_000 * loadFactor(); do { missing = missingOnTheMac(titles, todosOnTheMac(data, personal)); if (!missing.length) break; await pause(3000); } while (!discarded && Date.now() < sendBy); if (discarded) report.line(`NOTE ${at}: the phone asked, and the walk discarded — ${missing.length} of ${UNSENT} changes are not on the Mac`); report.check(!missing.length || discarded, `${at}: no change is lost without the phone asking`, missing.join(', ')); report.check(!(sent && discarded && missing.length), `${at}: sending, where the phone offers it, sends`, 'the walk pressed send, then had to discard'); } finally { process.off('exit', orphan); if (server) await stopServer(server); } }