Cotton code
608 lines · 29.4 KB · TypeScriptRaw
/** * The app registry, `apps/registry.json`: one row per app this tree builds, the * one source every reader derives from (7 Nov 2026). * * The rules an app's PHASE drives live here, as functions other scripts call: * `walksPerJob`, `walksBeforeCut`, `isCut`, `inMatrix`. The cut path is bash and * Python, so `scripts/lib/registry.py` is this module's twin for the little the * cut needs (flavours, a flavour's identity, `is_cut`); the * twins are held equal by the registry test. * * The registry is edited by hand and by lanes only; nothing writes a cut into * it. The last cut of each app is READ (`pnpm apps:cuts`): from the Mac's kept * cut records (`~/prod-release/*\/cut.txt`) and, with `--asc`, from App Store * Connect. * * Derived from it: the Fastfile's FLAVORS table (generated in place between its * markers by `pnpm apps:gen`), phone-cut.sh's flavour list and bundle, and the * phone-cut identity check. Checked against it: project.yml's businessFlavours. */import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";import { join } from "node:path";import Ajv from "ajv";import { parse } from "yaml";/** * planned → provisioned → development → production, and parked beside them. * planned: a row and nothing at Apple yet. provisioned: its bundle ids, match * profiles, Fastfile rows and flavour scaffold made by `pnpm app:provision`, * with no App Store record. development: on TestFlight in development mode * (its records exist; the second pass of `app:provision`). production: live * data. parked: never cut. Only development and production are ever cut. */export type Phase = "planned" | "provisioned" | "development" | "production" | "parked";/** The phases in the order an app moves through them; parked stands outside. */export const PHASE_ORDER: readonly Phase[] = ["planned", "provisioned", "development", "production"];export type Platform = "ios" | "android";export interface IosVariant {  /** The Fastfile FLAVORS key a lane is asked for; null for an app no lane cuts (Loom). */  flavour: string | null;  bundleId: string;  /** The App Store Connect record's name, which Apple may have refused as the display name. */  storeName: string;  ascAppId: string | null;  testflightGroups: string[];  coreFlavour: "real" | "dev" | null;  dsyms: string | null;}/** A DeckWalk test that is this app's own, with the env knobs its gate needs (`WALK_MUSIC_WHOLE=1`). */export interface Step {  test: string;  env: Record<string, string>;}export interface App {  slug: string;  /** The store name: what App Store Connect, Play and the app's own words say. */  name: string;  /** What the home screen says under the icon (CFBundleDisplayName) when it is not the store name: Books, not Cotton Books, because the icon already says Cotton (owner, 9 Nov 2026). */  label?: string;  kit: string | null;  phase: Phase;  /** A parked app another took over; `identity`: its bundle ids, store records and signing went too, so it builds nothing. */  retired?: { into: string; identity?: boolean };  /** One of the few apps the owner is testing now; a release tick cuts only active apps. */  active: boolean;  platforms: Platform[];  icon: string;  /** `appGroup: false` names an app with no App Group at all (Loom: its own project, no extensions, no shared container); every other app takes group.<bundle id>. */  ios: { scheme: string; target: string; share: boolean; provider?: boolean; notifications?: boolean; widgets?: boolean; healthkit?: boolean; appGroup?: false; live: IosVariant; dev: IosVariant | null } | null;  /** `signing`: each side's installed signing certificates, SHA-256 colon hex (public), for the open host's assetlinks.json (pnpm -s passkey:associations). */  android: { package: string; devPackage: string | null; project: string; signing?: { live: string[]; dev: string[] } } | null;  walk: {    /** The synthetic number slot the walk signs in with: what the app's number ends in on each Mac (the standing-simulator table). */    phoneSlot: number | null;    /** Hosts the shared shell walk; exactly one app does. */    shellHost: boolean;    steps: Step[];    /** What the one whole walk (`testWalkWhole`) needs of this app beyond its kit; every key optional. */    whole?: Whole;    /** The app's Android walk on the box (pnpm android:walk): walker steps as data, the Android walk's Step. */    android?: { steps: Record<string, unknown>[] };  };}/** * The generic whole walk's knobs for one app (apps/registry.schema.json says each). Views are the kit's view ids; * a step the app has no part in is named in `notApplicable` with its reason and walks as a PASS saying it. */export interface Whole {  rows?: number;  held?: string;  opened?: string;  relaunch?: string;  largest?: string[];  empty?: string[];  says?: Record<string, string[]>;  opens?: string[];  choose?: Record<string, string>;  leave?: Record<string, string>;  seed?: { door: string; line: string };  notApplicable?: Record<string, string>;}export interface Registry {  $schema?: string;  apps: App[];}export const REGISTRY_PATH = "apps/registry.json";export const SCHEMA_PATH = "apps/registry.schema.json";export function readRegistry(root: string): Registry {  return JSON.parse(readFileSync(join(root, REGISTRY_PATH), "utf8")) as Registry;}/** The one spelling of the file: what `JSON.stringify(…, null, 2)` writes, and what the cut's Python writes. */export function formatRegistry(registry: Registry): string {  return `${JSON.stringify(registry, null, 2)}\n`;}// ── the rules the phase drives ─────────────────────────────────────────────export type Device = "standing-sim" | "fresh-sim" | "real-device";export interface Walk {  /** own: the app's DeckWalk tests; shell: the shared shell walk; whole: every step; fresh-install: a first launch; upgrade: over the last cut. */  walk: "own" | "shell" | "whole" | "fresh-install" | "upgrade";  device: Device;  steps?: Step[];}/** The walks a code job touching this app runs: its own steps on the standing simulator, plus the shell walk on its host. */export function walksPerJob(app: App): Walk[] {  if (!inMatrix(app)) return [];  const walks: Walk[] = [];  if (app.walk.steps.length) walks.push({ walk: "own", device: "standing-sim", steps: app.walk.steps.map((s) => ({ test: s.test, env: { ...s.env } })) });  if (app.walk.shellHost) walks.push({ walk: "shell", device: "standing-sim" });  return walks;}/** What is walked before a build of this app ships. development: whole + fresh install; production: whole + upgrade + a real device. */export function walksBeforeCut(app: App): Walk[] {  switch (app.phase) {    case "development":      return [        { walk: "whole", device: "standing-sim" },        { walk: "fresh-install", device: "fresh-sim" },      ];    case "production":      return [        { walk: "whole", device: "standing-sim" },        { walk: "upgrade", device: "standing-sim" },        { walk: "whole", device: "real-device" },      ];    case "planned":    case "provisioned":    case "parked":      return [];  }}/** Only an app with its App Store records is cut: development or production. A parked, planned or provisioned app never is. */export function isCut(app: App): boolean {  return app.phase === "development" || app.phase === "production";}/** * The iPhone apps people sign in to: every app cut to phones (development or production, never parked or planned) * with an iPhone flavour a lane cuts (not Loom). Each is signed with `webcredentials:<its sign-in host>` and named in * that host's apple-app-site-association, live and dev (scripts/ios-spec-gate.ts, pnpm -s passkey:associations). */export function signsInOnIphone(app: Pick<App, "phase" | "ios">): boolean {  return isCut(app as App) && Boolean(app.ios?.live.flavour);}/** The Android apps people sign in to: every app cut to phones with an Android package (assetlinks.json names them). */export function signsInOnAndroid(app: Pick<App, "phase" | "android">): boolean {  return isCut(app as App) && Boolean(app.android);}/** Whether the per-push walk matrix carries this app: a parked app and a planned one (nothing built yet) are not carried. */export function inMatrix(app: App): boolean {  return app.phase !== "parked" && app.phase !== "planned";}// ── the whole walk: the app's row and its kit's catalogue ──────────────────/** The kit as the whole walk reads it: its tool, the fan's views as the core deals them (the default first, then manifest order), the view lists are kept on, the account acts. */export interface WalkCatalogue {  tool: string;  /** Every view the fan holds, in the manifest's order: a partitioned view is one record's deck, never a tile. */  views: { id: string; label: string; table: string }[];  /** The first view whose table keeps lists (`groups`), or null when the kit keeps none. */  groups: string | null;  /** The card the account acts (Sign in, Back up now, Sign out) are held on: the Account card the kit deals left of its first view (`aside`); null when the kit deals none. */  account: string | null;  /** Plus's doors on the first view, from its table's `create`: a files door raises the system's picker; signedOut is the line an act door says before sign-in. */  doors: { label: string; files: boolean; signedOut: string | null }[];  /** The first view's table's own empty title, which its empty deck says; null when the table names none. */  empty: string | null;}interface ViewFile {  id: string;  label: string;  partition?: string;  is_default?: boolean;  read?: { table?: string };}interface TableFile {  groups?: unknown;  empty?: { title?: string };  create?: { doors?: { label: string; files?: unknown; act?: { signed_out?: string } }[] };  tool?: { key?: string; views?: ViewFile[] };}interface KitFile {  tools?: string[];  tables?: string[];  folds?: string[];  aside?: string[];}interface ManifestFile {  id: string;  name?: string;  tables?: string[];  views?: ViewFile[];}/** The catalogue of an app's kit in `crates/cotton-core/kits`, read from its kit.json, its tools' manifests (the first is the tool it opens on, where its account acts stand) and its tables. */export function kitCatalogue(root: string, kit: string): WalkCatalogue {  const kits = join(root, "crates/cotton-core/kits");  const file = JSON.parse(readFileSync(join(kits, kit, "kit.json"), "utf8")) as KitFile;  const tools = file.tools ?? [];  const [tool] = tools;  if (!tool?.includes("/")) throw new Error(`kit ${kit} is no app kit (its kit.json names its tools by id alone): the whole walk walks an app's first tool`);  const table = (home: string, id: string): TableFile => {    const path = join(kits, home, "tables", `${id}.json`);    return id && existsSync(path) ? (JSON.parse(readFileSync(path, "utf8")) as TableFile) : {};  };  const manifestOf = (named: string): ManifestFile & { home: string } => {    const [home, id] = named.split("/") as [string, string];    return { ...(JSON.parse(readFileSync(join(kits, home, "tools", id, "manifest.json"), "utf8")) as ManifestFile), home };  };  // RULE (AppKit::views_of): a tool's views are its home table's where the table heads it with views of its own, else its manifest's.  const viewsOf = (manifest: ManifestFile & { home: string }): ViewFile[] => {    const dir = join(kits, manifest.home, "tables");    for (const name of existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".json")).sort() : []) {      const heads = table(manifest.home, name.replace(/\.json$/, "")).tool;      if (heads?.views?.length && (heads.key ?? name.replace(/\.json$/, "")) === manifest.id) return heads.views;    }    return manifest.views ?? [];  };  const first = manifestOf(tool);  // RULE (AppKit::fold, owner 11 Nov 2026): the fan is one tier of views: the first tool's own, then every other  // tool the kit lists, then the ones it folds, none of them the default. A listed tool that declares no view is one  // view of its home table under its own name; a listed tool's view whose id is taken is `<tool>__<id>`; a folded  // tool's view whose id is taken stays the first tool's.  const laid: ViewFile[] = [...viewsOf(first)];  for (const named of [...tools.slice(1), ...(file.folds ?? [])]) {    const other = manifestOf(named);    const listed = tools.includes(named);    const views = viewsOf(other).map((v) => ({ ...v }));    if (listed && !views.some((v) => !v.partition) && other.tables?.[0]) views.push({ id: other.id, label: other.name ?? other.id, read: { table: other.tables[0] } });    for (const next of views) {      next.is_default = false;      if (laid.some((held) => held.id === next.id)) {        if (!listed) continue;        next.id = `${other.id}__${next.id}`;      }      laid.push(next);    }  }  // RULE: a views tier deals the default view first, then the rest in manifest order (shell_fan.rs),  // and no view over a table the kit leaves to another app (AppKit::deals_view: Messages' Agents is Developer's).  const shell = JSON.parse(readFileSync(join(kits, "shell", "kit.json"), "utf8")) as KitFile;  const kept = new Set([...(file.tables ?? []), ...(shell.tables ?? [])].map((t) => t.split("/").pop()!));  const dealt = laid.filter((v) => !v.partition && (!v.read?.table || kept.has(v.read.table)));  const views = [...dealt.filter((v) => v.is_default), ...dealt.filter((v) => !v.is_default)].map((v) => ({ id: v.id, label: v.label, table: v.read?.table ?? "" }));  const keepsLists = (id: string) => table(first.home, id).groups != null;  const opening = table(first.home, views[0]?.table ?? "");  return {    tool: first.id,    views,    groups: views.find((v) => v.table && keepsLists(v.table))?.id ?? null,    account: file.aside?.includes("account") ? "account" : null,    doors: (opening.create?.doors ?? []).map((d) => ({ label: d.label, files: d.files != null, signedOut: d.act?.signed_out ?? null })),    empty: opening.empty?.title ?? null,  };}/** What walk-deck.sh hands the whole walk as WALK_APP_ROW: the app's registry row with its kit's catalogue beside it. */export function wholeRow(root: string, slug: string, registry: Registry = readRegistry(root)): App & { catalogue: WalkCatalogue } {  const app = registry.apps.find((a) => a.slug === slug);  if (!app) throw new Error(`no app ${slug} in ${REGISTRY_PATH}`);  if (!app.kit) throw new Error(`${slug} ships no kit, so it has no whole walk`);  return { ...app, catalogue: kitCatalogue(root, app.kit) };}/** The view ids an app's `walk.whole` names that its kit's fan does not hold. */export function wholeStrays(whole: Whole, catalogue: WalkCatalogue): string[] {  const named = [whole.held, whole.opened, whole.relaunch, ...(whole.largest ?? []), ...(whole.empty ?? []), ...Object.keys(whole.says ?? {})].filter((v): v is string => !!v);  return named.filter((id) => !catalogue.views.some((v) => v.id === id));}// ── flavours: the iOS identities a lane is asked for ───────────────────────export interface Flavour {  flavour: string;  app: App;  variant: "live" | "dev";  identity: IosVariant;  appGroup: string;  /** Xcode extension target (share extension, passkey provider) → its bundle id. */  extensions: Record<string, string>;}export function flavours(registry: Registry): Flavour[] {  const out: Flavour[] = [];  for (const app of registry.apps) {    if (!app.ios) continue;    for (const variant of ["live", "dev"] as const) {      const identity = app.ios[variant];      if (!identity?.flavour) continue;      out.push({        flavour: identity.flavour,        app,        variant,        identity,        appGroup: `group.${identity.bundleId}`,        extensions: {          ...(app.ios.share ? { [`${app.ios.target}ShareExtension`]: `${identity.bundleId}.share-extension` } : {}),          ...(app.ios.provider ? { [`${app.ios.target}Provider`]: `${identity.bundleId}.provider` } : {}),          ...(app.ios.notifications ? { [`${app.ios.target}Notifications`]: `${identity.bundleId}.notifications` } : {}),          ...(app.ios.widgets ? { [`${app.ios.target}Widgets`]: `${identity.bundleId}.widgets` } : {}),        },      });    }  }  return out;}export function flavourNamed(registry: Registry, name: string): Flavour | undefined {  return flavours(registry).find((f) => f.flavour === name);}// ── the Fastfile's FLAVORS, generated ──────────────────────────────────────export const FASTFILE_BEGIN = "# BEGIN FLAVORS — generated from apps/registry.json by `pnpm apps:gen`; edit the registry, never this block";export const FASTFILE_END = "# END FLAVORS";function ruby(value: string): string {  if (/["\\#]/.test(value)) throw new Error(`registry value ${value} cannot be written as a plain Ruby string`);  return `"${value}"`;}export function fastfileFlavors(registry: Registry): string {  const rows = flavours(registry).map((f) => {    const { identity, app } = f;    const ext = Object.entries(f.extensions);    return [      `  ${ruby(f.flavour)} => {`,      `    name: ${ruby(identity.storeName)},`,      `    bundle_id: ${ruby(identity.bundleId)},`,      `    app_group: ${ruby(f.appGroup)},`,      `    asc_app_id: ${identity.ascAppId ? ruby(identity.ascAppId) : "nil"},`,      `    dsyms: ${ruby(identity.dsyms!)},`,      `    scheme: ${ruby(app.ios!.scheme)}, target: ${ruby(app.ios!.target)}, core_flavor: ${ruby(identity.coreFlavour!)},`,      ext.length        ? `    extensions: {\n${ext.map(([t, id]) => `      ${ruby(t)} => ${ruby(id)},`).join("\n")}\n    }.freeze,`        : "    extensions: {}.freeze,",      "  }.freeze,",    ].join("\n");  });  return [FASTFILE_BEGIN, "FLAVORS = {", ...rows, "}.freeze", FASTFILE_END].join("\n");}/** The Fastfile with its FLAVORS block replaced by the registry's. */export function withFlavors(fastfile: string, registry: Registry): string {  const start = fastfile.indexOf(FASTFILE_BEGIN);  const end = fastfile.indexOf(FASTFILE_END);  if (start < 0 || end < start) throw new Error(`the Fastfile has no "${FASTFILE_BEGIN}" … "${FASTFILE_END}" block`);  return fastfile.slice(0, start) + fastfileFlavors(registry) + fastfile.slice(end + FASTFILE_END.length);}// ── the check: the file against its schema and the tree ────────────────────interface BusinessFlavour {  target: string;  appId: string;  displayName: string;  appIcon: string;  icons: string;  manifest: string;  dev?: { appId: string; displayName: string; appIcon: string };}/** * The registry against its schema and the tree. The release machinery's own * checks (the Fastfile's FLAVORS, the standing simulators' numbers) are * `releaseCheck` in registry-release.ts, beside that machinery. */export function check(root: string, registry: Registry = readRegistry(root)): string[] {  const problems: string[] = [];  const ajv = new Ajv({ allErrors: true });  const validate = ajv.compile(JSON.parse(readFileSync(join(root, SCHEMA_PATH), "utf8")));  if (!validate(registry)) {    for (const e of validate.errors ?? []) problems.push(`schema: ${e.dataPath || "(root)"} ${e.message}`);    return problems;  }  const raw = readFileSync(join(root, REGISTRY_PATH), "utf8");  if (raw !== formatRegistry(registry)) problems.push(`${REGISTRY_PATH} is not in its one spelling (JSON.stringify, two spaces, a final newline): run \`pnpm apps:gen\``);  const once = (what: string, values: string[]) => {    const seen = new Set<string>();    for (const v of values) {      if (seen.has(v)) problems.push(`${what} ${v} is written twice`);      seen.add(v);    }  };  once("slug", registry.apps.map((a) => a.slug));  once("flavour", flavours(registry).map((f) => f.flavour));  once("bundle id", registry.apps.flatMap((a) => [a.ios?.live.bundleId, a.ios?.dev?.bundleId].filter((x): x is string => !!x)));  once("android package", registry.apps.flatMap((a) => [a.android?.package, a.android?.devPackage].filter((x): x is string => !!x)));  const hosts = registry.apps.filter((a) => a.walk.shellHost).map((a) => a.slug);  if (hosts.length !== 1) problems.push(`exactly one app hosts the shell walk; ${hosts.length ? hosts.join(", ") : "none"} do`);  const kits = new Set(readdirSync(join(root, "crates/cotton-core/kits")));  for (const app of registry.apps) {    const at = `${app.slug}:`;    if (app.retired) {      const into = registry.apps.find((a) => a.slug === app.retired!.into);      if (!into || into.retired) problems.push(`${at} retired into ${app.retired.into}, which is no standing app`);      if (app.phase !== "parked") problems.push(`${at} is retired, so its phase is parked, not ${app.phase}`);      if (app.retired.identity && (app.platforms.length || app.ios || app.android)) problems.push(`${at} gave its identity to ${app.retired.into}, so it holds no ios or android row and lists no platform`);    }    if (app.platforms.length === 0 && !app.retired?.identity) problems.push(`${at} lists no platform; only a row whose identity was retired into another builds nothing`);    if (app.kit !== null && !kits.has(app.kit)) problems.push(`${at} kit ${app.kit} is not in crates/cotton-core/kits`);    // A planned row is declared before its scaffold: its icon comes with `pnpm app:provision`.    if (app.phase !== "planned" && !existsSync(join(root, app.icon))) problems.push(`${at} icon ${app.icon} does not exist`);    for (const p of ["ios", "android"] as const) {      if (app.platforms.includes(p) !== (app[p] !== null)) problems.push(`${at} platforms says ${p} ${app.platforms.includes(p) ? "is" : "is not"} built, its ${p} row says otherwise`);    }    if (app.android && !existsSync(join(root, app.android.project))) problems.push(`${at} android project ${app.android.project} does not exist`);    const generic = app.walk.steps.some((s) => s.test === "testWalkWhole");    if (app.walk.whole && !generic) problems.push(`${at} walk.whole is set but no step walks testWalkWhole`);    if (generic && app.kit === null) problems.push(`${at} walks testWalkWhole but ships no kit`);    if (generic && app.kit !== null && kits.has(app.kit)) {      for (const id of wholeStrays(app.walk.whole ?? {}, kitCatalogue(root, app.kit))) problems.push(`${at} walk.whole names view ${id}, which kit ${app.kit}'s fan does not hold`);    }    for (const v of [app.ios?.live, app.ios?.dev]) {      if (v?.flavour && (!v.coreFlavour || !v.dsyms)) problems.push(`${at} flavour ${v.flavour} names no coreFlavour or dsyms`);    }  }  // One app to a phone slot, and the standing simulators' numbers end in it.  once("phone slot", registry.apps.flatMap((a) => (a.walk.phoneSlot === null ? [] : [String(a.walk.phoneSlot)])));  // Every flavour folder has a row.  const flavourDir = join(root, "apps/cotton/App/Flavours");  const slugs = new Set(registry.apps.map((a) => a.slug));  for (const name of readdirSync(flavourDir)) {    if (existsSync(join(flavourDir, name, "flavour.json")) && !slugs.has(name)) problems.push(`apps/cotton/App/Flavours/${name}/flavour.json has no registry row`);  }  // project.yml's businessFlavours: one entry per flavoured app, the same identity.  const spec = parse(readFileSync(join(root, "apps/cotton/project.yml"), "utf8")) as { businessFlavours: Record<string, BusinessFlavour> };  const business = spec.businessFlavours ?? {};  const flavoured = registry.apps.filter((a) => a.ios && existsSync(join(flavourDir, a.slug, "flavour.json")));  for (const app of flavoured) {    const b = business[app.slug];    const at = `apps/cotton/project.yml businessFlavours.${app.slug}`;    if (!b) {      problems.push(`${at} is missing`);      continue;    }    const ios = app.ios!;    if (b.target !== ios.target) problems.push(`${at}.target is ${b.target}, the registry says ${ios.target}`);    if (b.appId !== ios.live.bundleId) problems.push(`${at}.appId is ${b.appId}, the registry says ${ios.live.bundleId}`);    const label = app.label ?? app.name;    if (b.displayName !== label) problems.push(`${at}.displayName is ${b.displayName}, the registry says ${label}`);    if ((b.dev?.appId ?? null) !== (ios.dev?.bundleId ?? null)) problems.push(`${at}.dev.appId is ${b.dev?.appId ?? "absent"}, the registry says ${ios.dev?.bundleId ?? "none"}`);    if (`${b.icons}/${b.appIcon}.appiconset` !== app.icon.replace(/^apps\/cotton\//, "")) problems.push(`${at} icon is ${b.icons}/${b.appIcon}, the registry says ${app.icon}`);  }  for (const name of Object.keys(business)) if (!flavoured.some((a) => a.slug === name)) problems.push(`apps/cotton/project.yml businessFlavours.${name} has no registry row`);  return problems;}// ── DeckWalk: a test's body and the knobs its gate needs ───────────────────/** The source of `func <test>()` in DeckWalk.swift, up to the next test, or null. */export function deckWalkBody(source: string, test: string): string | null {  const start = source.indexOf(`func ${test}(`);  if (start < 0) return null;  const next = source.indexOf("\n    func test", start + 1);  return source.slice(start, next < 0 ? undefined : next);}/** The env knobs a test's guards demand: `environment["X"] == "1"`, or `let pass = environment["X"], [...]`. */export function gateKnobs(body: string): string[] {  const knobs = new Set<string>();  for (const guard of body.match(/\bguard\b[\s\S]*?\belse\s*\{/g) ?? []) {    for (const m of guard.matchAll(/environment\["(WALK_[A-Z0-9_]+)"\]\s*==\s*"1"/g)) knobs.add(m[1]!);    for (const m of guard.matchAll(/let \w+ = environment\["(WALK_[A-Z0-9_]+)"\],\s*\[/g)) knobs.add(m[1]!);  }  return [...knobs];}// ── the last cut of each app, read: never written into the registry ───────export interface CutRecord {  flavour: string;  sha: string;  build: string;  at: string;  dir: string;}/** Every uploaded cut a Mac kept: `<release>/*\/cut.txt` with `uploaded=yes` (phone-cut.sh's record). */export function readCuts(release: string): CutRecord[] {  if (!existsSync(release)) return [];  const cuts: CutRecord[] = [];  for (const name of readdirSync(release)) {    const file = join(release, name, "cut.txt");    if (!existsSync(file) || !statSync(file).isFile()) continue;    const cut = parseCut(name, readFileSync(file, "utf8"));    if (cut) cuts.push(cut);  }  return cuts;}/** One kept cut record (`cut.txt` in the folder `dir`), or null when it is not an uploaded cut. */export function parseCut(dir: string, text: string): CutRecord | null {  const fields = Object.fromEntries(    text.split("\n").flatMap((line) => {      const m = /^(sha|flavor|build|uploaded|at)=(.*)$/.exec(line);      return m ? [[m[1]!, m[2]!]] : [];    }),  );  if (fields.uploaded !== "yes" || !fields.sha || !fields.flavor) return null;  return { flavour: fields.flavor, sha: fields.sha, build: fields.build ?? "?", at: fields.at ?? "", dir };}/** One Mac's kept cuts, or null when it did not answer (its cuts are then unknown). */export interface MacCuts { mac: string; cuts: CutRecord[] | null }/** A listing of `~/prod-release/*\/cut.txt` as readEveryMacCut prints it (`#cut\t<dir>` per record, `#end` last); null when it was cut short. */export function parseCutListing(text: string): CutRecord[] | null {  if (!text.includes("#end")) return null;  const cuts: CutRecord[] = [];  for (const section of text.split("#cut\t").slice(1)) {    const newline = section.indexOf("\n");    const cut = parseCut(section.slice(0, newline).trim(), section.slice(newline + 1));    if (cut) cuts.push(cut);  }  return cuts;}/** The newest App Store Connect build of a flavour, as `asc:builds` reads it. */export interface AscLatest {  buildNumber: string;  uploadedDate: string | null;}/** One line per flavour: its app, the newest kept cut (sha, build, when) and, when asked, ASC's newest build. */export function cutsTable(registry: Registry, cuts: CutRecord[], asc?: Record<string, AscLatest | null>): string {  const rows = flavours(registry).map((f) => {    const newest = cuts.filter((c) => c.flavour === f.flavour).sort((a, b) => b.at.localeCompare(a.at))[0];    const row = [f.app.slug, f.flavour, f.app.phase, f.app.active ? "active" : "", newest?.sha.slice(0, 9) ?? "-", newest?.build ?? "-", newest?.at ?? "-"];    if (asc) {      const latest = asc[f.flavour];      row.push(latest ? `${latest.buildNumber} ${latest.uploadedDate ?? ""}`.trim() : "-");    }    return row;  });  const head = ["app", "flavour", "phase", "active", "cut sha", "build", "uploaded", ...(asc ? ["asc newest"] : [])];  return columns(head, rows);}function columns(head: string[], rows: string[][]): string {  const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i]!.length)));  return [head, ...rows].map((r) => r.map((c, i) => c.padEnd(widths[i]!)).join("  ").trimEnd()).join("\n");}// ── the table `pnpm apps:list` prints ──────────────────────────────────────export function table(registry: Registry): string {  const rows = registry.apps.map((a) => [    a.slug,    a.name,    a.phase,    a.active ? "active" : "",    a.kit ?? "-",    a.platforms.join("+"),    [a.ios?.live.flavour, a.ios?.dev?.flavour].filter(Boolean).join(",") || "-",    a.ios?.live.bundleId ?? a.android?.package ?? "-",    a.walk.shellHost ? "shell" : "",    String(a.walk.steps.length),    a.walk.phoneSlot === null ? "-" : String(a.walk.phoneSlot),  ]);  return columns(["app", "name", "phase", "active", "kit", "platforms", "flavours", "bundle", "host", "steps", "slot"], rows);}