Cotton code
902 lines · 64.0 KB · TypeScriptRaw
import { existsSync, readdirSync, readFileSync } from "node:fs";import { join } from "node:path";import { describe, expect, it } from "vitest";import { parse } from "yaml";import { foundsPersonal, registryApp, registryApps } from "./helpers/app-registry";import {  COTTON_MANIFEST,  FAMILY_APP,  FAMILY_EXTENSIONS,  LAUNCH_GROUND,  LAUNCH_OBJECT,  LAUNCH_STORYBOARD,  LAUNCH_SURFACE,  launchStoryboard,  PROVIDER_SUFFIX,  NOTIFICATIONS_SUFFIX,  WIDGETS_SUFFIX,  manifestDatabaseRefusal,  signInTargets,  ASSOCIATED_DOMAINS,  PASSKEY_ENTITLEMENTS_DIR,  PASSKEY_HOST_KEY,  withBusinessFlavours,  type Written,  withoutTargets,  type BusinessFlavour,  exportRefusal,  NO_CONTACTS,  NO_CAMERA,  NO_PHOTOS,  NO_PHOTO_WRITES,  devHost,  DEV_HOST_TOKEN,  MANIFESTS_DIR,} from "../ios-spec-gate";import { expandSettings, targetSettings, type SpecShape } from "../lib/xcode-settings";import { signsInOnIphone } from "../lib/registry";/** * A business flavour is a whole app beside Cotton on the same phone: its own * bundle ids, app group, label, URL scheme and icon, its own manifest, and * nothing of Cotton's. `project.yml` declares it once (`businessFlavours`) and * `scripts/ios-spec-gate.ts` writes the four targets when the project is * generated. These guards resolve the generated targets the way Xcode does, * because a business app that resolved even one of Cotton Dev's identifiers * would share its container — a second app reading and writing the first's * data. */const ROOT = join(__dirname, "..", "..");const IOS_DIR = join(ROOT, "apps", "cotton");const SPEC_PATH = join(IOS_DIR, "project.yml");const KITS = join(ROOT, "crates", "cotton-core", "kits");/** `FaceGround.tile`'s cases, by the ground's id: the grounds with a painted tile. */function groundTiles(): Record<string, string> {  const source = readFileSync(join(ROOT, "apps", "loom", "Sources", "CottonFaces", "Face.swift"), "utf8");  const body = source.slice(source.indexOf("public var tile: String?"));  return Object.fromEntries([...body.slice(0, body.indexOf("\n    }\n")).matchAll(/case \.(\w+): "([\w-]+)"/g)].map((m) => [m[1], m[2]]));}type Spec = SpecShape & {  targets: Record<string, Record<string, any>>;  schemes: Record<string, Record<string, any>>;  businessFlavours: Record<string, BusinessFlavour>;};/** * Cotton's own identities, phone and Mac, both flavours, and their app groups: * a business app is never one of them nor under one (Cotton Development is * `com.cottondb.development`, beside them, not inside). */const COTTON_IDENTITIES = [  "com.cottondb.cotton",  "com.cottondb.cotton.dev",  "group.com.cottondb.cotton",  "group.com.cottondb.cotton.dev",  "com.decemberfm.cottondb.mac",  "com.decemberfm.cottondb.mac.dev",];/** Cotton's own apps over the owner's personal object, by their names. */// RULE (owner, 9 Nov 2026): the store name says Cotton (the registry's storeName); the// home screen says the plain word for an app whose plain word collides with none of// Apple's own apps. Todos is the first; Music and Books keep Cotton for now.// The names are the registry's; a family app is one with a kit of its own over the personal object.const COTTONS_FAMILY: Record<string, string> = Object.fromEntries(  registryApps().filter((a) => a.kit && a.kit !== "personal" && foundsPersonal(a)).map((a) => [a.slug, a.name]),);/** A flavour declared before its App Store record exists: the cut does not build it yet. */const notCutYet = (name: string) => !registryApp(name).ios?.live?.ascAppId;const declared = (): Spec => parse(readFileSync(SPEC_PATH, "utf8")) as Spec;const generated = (): Spec => withBusinessFlavours(declared() as any) as unknown as Spec;/** A kit's tools as its kit.json lists them (`crates/cotton-core/kits/<kit>/kit.json`). */function toolsOf(kit: string): string[] {  const listed = JSON.parse(readFileSync(join(KITS, kit, "kit.json"), "utf8")).tools as string[];  return listed.map((entry) => entry.split("/").pop()!);}/** The kit's tools (the personal kit's, `crates/cotton-core/kits/personal/tools/<id>`): no tool is built in (72nd amendment). */function kitToolIds(): string[] {  return toolsOf("personal");}/** The Disk tool, shipped inside the CI ledger package rather than in a kit. */function ledgerToolId(): string {  return JSON.parse(readFileSync(join(ROOT, "crates", "cotton-client", "src", "ci", "ledger_package", "manifest.json"), "utf8")).id as string;}/** * The business kits' tools Cotton ships as files (yoga, kitchen), by their * tool's id: each kit's OWN tools. A tool a kit lists from another kit * (`personal/books` in the books kit) is that kit's, not a package. */function packageToolIds(): string[] {  return readdirSync(KITS)    .filter((kit) => kit !== "personal" && existsSync(join(KITS, kit, "kit.json")))    .flatMap((kit) => (JSON.parse(readFileSync(join(KITS, kit, "kit.json"), "utf8")).tools as string[]).filter((entry) => !entry.includes("/")));}describe("Cotton's own manifest", () => {  // RULE: Cotton is one app over one database (owner, 19 Oct 2026): its bundle carries a manifest naming Personal alone, single, no Home of its own (the shipped one draws). Its `tools` is the genesis set: every database it founds is born with those packages (architect, 22 Oct 2026; `cotton_core::genesis::GenesisTools`).  it("names Personal alone and the shipped Home", () => {    const sources = declared().targets[FAMILY_APP].sources.map((s: any) => s.path ?? s);    expect(sources).toContain(COTTON_MANIFEST);    const manifest = JSON.parse(readFileSync(join(IOS_DIR, COTTON_MANIFEST), "utf8"));    expect(manifest).toMatchObject({ flavour: "cotton", name: "Cotton", databases: "single", database: "personal" });    expect(manifest).not.toHaveProperty("home");    // RULE: Assistant approval and external connections belong to Cotton's Personal and project apps, never a business app. Documents held by either database stay reachable from its fan (architect's development walk, 19 Oct 2026).    for (const path of [COTTON_MANIFEST, "Tests/Fixtures/Flavours/development.json"]) {      const cotton = JSON.parse(readFileSync(join(IOS_DIR, path), "utf8"));      expect(cotton.tools).toEqual(expect.arrayContaining(["assistants", "connections", "documents"]));    }    // RULE: Rigby is a phone-only app with no server and no upload: every tool runs on the phone over the person's own data and nothing leaves (owner's memory, rigby-is-a-phone-only-app…). So it names only kit tools, keeps Documents, and carries neither assistant approval nor external connections — the exact nine are `cotton_core::kit_tests::rigby_names_exactly_its_nine_kit_tools`.    const rigby = JSON.parse(readFileSync(join(IOS_DIR, "Tests/Fixtures/Flavours/rigby.json"), "utf8"));    expect(kitToolIds()).toEqual(expect.arrayContaining(rigby.tools));    expect(rigby.tools).toContain("documents");    expect(rigby.tools).not.toContain("assistants");    expect(rigby.tools).not.toContain("connections");    for (const flavour of Object.values(declared().businessFlavours ?? {})) {      const business = JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8"));      if (business.genesis !== "none") continue;      expect(business.tools).not.toContain("assistants");      expect(business.tools).not.toContain("connections");    }  });});describe("one app, one database", () => {  const manifests = (): [string, any][] => [    [COTTON_MANIFEST, JSON.parse(readFileSync(join(IOS_DIR, COTTON_MANIFEST), "utf8"))],    ...Object.values(declared().businessFlavours ?? {}).map(      (flavour) => [flavour.manifest, JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8"))] as [string, any],    ),  ];  // RULE: a flavour manifest that names neither personal nor its business object refuses to build (owner's 62nd–64th rulings: the app opens only the database its manifest names, and the join screen signs in only at its host). Generation is where it refuses — `ios-spec-gate.ts` throws — so a manifest that forgot its database never becomes an app that opens every database it is handed, or Personal in Cotton Project.  it("refuses to generate a flavour whose manifest names neither personal nor a business object", () => {    for (const [path, manifest] of manifests()) expect(manifestDatabaseRefusal(path, manifest), path).toBeNull();    expect(manifestDatabaseRefusal("x", {})).toMatch(/names no database/);    expect(manifestDatabaseRefusal("x", { database: { id: "db", host: "https://unit.example" } })).toMatch(/"personal" or a business object/);    expect(manifestDatabaseRefusal("x", { business: { server: "unit.example", slug: "unit" } })).toMatch(/no https server/);    expect(manifestDatabaseRefusal("x", { business: { server: "https://unit.example" } })).toMatch(/no slug/);    expect(manifestDatabaseRefusal("x", { business: { server: "https://unit.example", slug: "unit" } })).toBeNull();    expect(generated()).toBeDefined();  });  // RULE: the development flavour is Cotton Project — its label says Project — and no business app carries the word Cotton in its name or label, because a business's customer never reads Cotton (owner, 20 Oct 2026; lane phonewalk, 19 Oct 2026). Cotton's own family of apps over the owner's object says Cotton in the store and in the app (manifest name): Cotton Books and Cotton Music (owner, 4 Nov 2026), Cotton Cinemas (5 Nov 2026), Cotton Money (6 Nov 2026), Cotton Keys (8 Nov 2026); under its icon on the home screen each says only its short name, Books or Music (owner, 9 Nov 2026), because the icon already says Cotton. Apple refuses a bundle whose display name an App Store app already carries (ITMS-90129, Books 2 on 9 Nov 2026: Books and Music are Apple's own apps), so a colliding short name ends in a full stop, Books., and its Dev build moves the stop to the end, Books Dev. (owner, 9 Nov 2026).  it("calls the development flavour Cotton Project and no business Cotton", () => {    const flavours = declared().businessFlavours ?? {};    for (const [name, flavour] of Object.entries(flavours)) {      const manifest = JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8"));      if (name === "development") {        expect(flavour.displayName).toContain("Project");        expect(manifest.name).toContain("Project");      } else if (name in COTTONS_FAMILY) {        expect(manifest.genesis, "a Cotton app founds Personal").toBe("personal");        expect(manifest.name).toBe(COTTONS_FAMILY[name]);        const short = COTTONS_FAMILY[name].replace(/^Cotton /, "");        const stop = flavour.displayName.endsWith(".") ? "." : "";        expect(flavour.displayName, "the home screen says the short name, with a full stop where Apple holds the bare word").toBe(`${short}${stop}`);        expect(flavour.dev?.displayName, "the dev build says the short name and Dev, the stop last").toBe(`${short} Dev${stop}`);      } else {        expect(flavour.displayName, name).not.toMatch(/cotton/i);        expect(manifest.name, name).not.toMatch(/cotton/i);      }    }  });});describe("business flavours", () => {  const flavours = Object.entries(declared().businessFlavours ?? {});  it("declares days", () => {    expect(flavours.map(([name]) => name)).toContain("days");  });  for (const [name, flavour] of flavours) {    describe(name, () => {      // RULE: a flavour that takes no shares (`share: false`, Cotton Money) is the app alone.      // RULE: the passkey app (`provider: true`, Cotton Keys) carries its passkey provider (8 Nov 2026).      // RULE: the chat app (`notifications: true`, Cotton Messages) carries its chat notification extension (13 Nov 2026).      // RULE: the meetings app (`widgets: true`, Cotton Meetings) carries its widget extension: the recording's Live Activity and its control (17 Nov 2026).      const family = [        flavour.target,        ...(flavour.share === false ? [] : FAMILY_EXTENSIONS.map((suffix) => flavour.target + suffix)),        ...(flavour.provider ? [flavour.target + PROVIDER_SUFFIX] : []),        ...(flavour.notifications ? [flavour.target + NOTIFICATIONS_SUFFIX] : []),        ...(flavour.widgets ? [flavour.target + WIDGETS_SUFFIX] : []),      ];      it("generates the app, its share extension unless it takes no shares, its passkey provider if it is the passkey app, its chat notification extension if it carries chat, and a scheme that builds the app", () => {        expect(family.filter((one) => !one.endsWith(PROVIDER_SUFFIX) && !one.endsWith(NOTIFICATIONS_SUFFIX) && !one.endsWith(WIDGETS_SUFFIX))).toEqual(flavour.share === false ? [flavour.target] : [flavour.target, `${flavour.target}ShareExtension`]);        if (!flavour.provider) expect(generated().targets[`${flavour.target}${PROVIDER_SUFFIX}`]).toBeUndefined();        if (!flavour.notifications) expect(generated().targets[`${flavour.target}${NOTIFICATIONS_SUFFIX}`]).toBeUndefined();        if (!flavour.widgets) expect(generated().targets[`${flavour.target}${WIDGETS_SUFFIX}`]).toBeUndefined();        if (flavour.share === false) expect(generated().targets[`${flavour.target}ShareExtension`]).toBeUndefined();        const spec = generated();        for (const target of family) expect(spec.targets[target], target).toBeDefined();        expect(spec.schemes[name].build).toEqual({ targets: { [flavour.target]: "all" } });        expect(spec.schemes[name].test).toBeUndefined();        expect(spec).not.toHaveProperty("businessFlavours");        const embedded = (spec.targets[flavour.target].dependencies as { target?: string }[])          .map((one) => one.target)          .filter(Boolean);        expect(embedded.sort()).toEqual(family.slice(1).sort());      });      // RULE: a business app's permission prompts are said in the business's      // name, never Cotton's: a clone of Cotton's Info.plist asked Sharmila's      // customers "Cotton uses the camera…" (lane phonewalk, 19 Oct 2026). Each      // target writes its own plist, because two writers of one generated plist      // is last-writer-wins and the business's words would vanish.      it("says every permission prompt in its manifest's name, in a plist of its own", () => {        const spec = generated();        const manifest = JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8")) as { name: string };        const paths = new Set<string>();        for (const target of family) {          const info = spec.targets[target].info as { path: string; properties: Record<string, unknown> } | undefined;          if (!info) continue;          expect(info.path, target).toMatch(new RegExp(`^App/Flavours/${name}/`));          paths.add(info.path);          const prompts = Object.entries(info.properties ?? {}).filter(([key]) => key.endsWith("UsageDescription"));          for (const [key, value] of prompts) {            const said = String(value).replaceAll(manifest.name, "");            expect(said, `${target} ${key}`).not.toMatch(/\bCotton\b/);            // The store name (Cotton Words) or the name under the icon (Words), which iOS shows above the prompt.            expect([manifest.name, flavour.displayName].some((one) => String(value).includes(one)), `${target} ${key}: ${value}`).toBe(true);          }        }        expect(paths.size, "one plist per target").toBe(family.filter((t) => spec.targets[t].info).length);        expect(spec.targets[FAMILY_APP].info.path).toBe("App/Cotton/Info.plist");      });      // Cotton's plist lives in a source folder the clone keeps; unexcluded, it      // is copied in beside the clone's own and the build fails on "Multiple      // commands produce Info.plist" (lane nancywalk, 20 Oct 2026).      it("leaves Cotton's plist out of every clone's sources", () => {        const spec = generated();        for (const target of family) {          const cotton = spec.targets[FAMILY_APP + target.slice(flavour.target.length)];          const cottons = (cotton?.info as { path?: string } | undefined)?.path;          if (!cottons || !spec.targets[target].info) continue;          for (const one of spec.targets[target].sources ?? []) {            const source = typeof one === "string" ? { path: one } : one;            if (!cottons.startsWith(`${source.path}/`)) continue;            expect((source as { excludes?: string[] }).excludes ?? [], target).toContain(cottons.slice(source.path.length + 1));          }        }      });      // Cotton Dev and the real app both, because the business app's identity      // must not move with `COTTON_FLAVOR` — and must never be either of Cotton's.      // A two-app family (`dev`, Cotton Books) is its dev identity under dev      // and its real one under real, and neither side is ever the other's.      for (const flavor of ["dev", "real"]) {        it(`resolves only its own identity under COTTON_FLAVOR=${flavor}`, () => {          const spec = generated();          const side = flavor === "dev" && flavour.dev ? flavour.dev : flavour;          const other = flavour.dev ? (flavor === "dev" ? flavour.appId : flavour.dev.appId) : null;          for (const target of family) {            const settings = targetSettings(spec, target, "Release", { COTTON_FLAVOR: flavor });            const x = (template: unknown) => expandSettings(String(template), settings);            const own = spec.targets[target];            const bundleId = x(settings.PRODUCT_BUNDLE_IDENTIFIER);            expect(bundleId === side.appId || bundleId.startsWith(`${side.appId}.`), target).toBe(true);            if (other) expect(bundleId === other || (bundleId.startsWith(`${other}.`) && !bundleId.startsWith(`${side.appId}`)), `${target} is the other side's`).toBe(false);            expect(x("$(COTTON_APP_GROUP)"), target).toBe(`group.${side.appId}`);            // RULE: every app of Cotton's family shares one keychain group per flavour, so one founding or approval serves them all; a business app keeps its own (e2e rulings R9, 16 Nov 2026).            expect(x("$(COTTON_KEYCHAIN_GROUP)"), target).toBe(              flavour.dev ? (flavor === "dev" ? "com.cottondb.vault.dev" : "com.cottondb.vault") : `${flavour.appId}.keys`,            );            const info = own.info.properties;            expect(x(info.CFBundleDisplayName), target).toBe(side.displayName);            expect(x(info.CottonURLScheme), target).toBe(side.urlScheme);            for (const value of [bundleId, x("$(COTTON_APP_GROUP)")]) {              for (const cotton of COTTON_IDENTITIES) {                expect(value === cotton || value.startsWith(`${cotton}.`), `${value} is under ${cotton}`).toBe(false);              }            }          }          const app = targetSettings(spec, flavour.target, "Release", { COTTON_FLAVOR: flavor });          expect(expandSettings(String(app.ASSETCATALOG_COMPILER_APPICON_NAME), app)).toBe(            side.appIcon,          );          const schemes = (spec.targets[flavour.target].info.properties.CFBundleURLTypes as { CFBundleURLSchemes: string[] }[])            .flatMap((t) => t.CFBundleURLSchemes)            .map((s) => expandSettings(s, app));          expect(schemes).toEqual([side.urlScheme]);        });      }      it("leaves Cotton's own family as it was", () => {        const before = declared();        const after = generated();        // Cotton's app carries its manifest filled in (MANIFESTS_DIR), in its own manifest's place; nothing else changes.        const asDeclared = (target: string, spec: { targets: Record<string, { sources?: unknown[] }> }) => {          const one = spec.targets[target];          if (target !== FAMILY_APP || !one?.sources) return one;          return {            ...one,            sources: one.sources.map((s: any) => ((typeof s === "string" ? s : s.path) === `${MANIFESTS_DIR}/${FAMILY_APP}/flavour.json` ? { ...s, path: COTTON_MANIFEST } : s)),          };        };        for (const target of [FAMILY_APP, ...FAMILY_EXTENSIONS.map((suffix) => FAMILY_APP + suffix)]) {          expect(asDeclared(target, after as never), target).toEqual(before.targets[target]);        }        expect(after.schemes["tinmen-cotton"]).toEqual(before.schemes["tinmen-cotton"]);      });      it("carries its icon set and a manifest that names it, one database rule and only tools the fan knows", () => {        for (const icon of [flavour.appIcon, ...(flavour.dev ? [flavour.dev.appIcon] : [])]) {          expect(existsSync(join(IOS_DIR, flavour.icons, `${icon}.appiconset`, "Contents.json")), icon).toBe(true);        }        expect(flavour.manifest.endsWith("/flavour.json")).toBe(true);        const manifest = JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8"));        // RULE: business installs join their database without founding Personal; Development, Rigby (Cotton's manifest under its own identity) Cotton Books, Cotton Music and Cotton Cinemas (the books, music and cinemas kits over the owner's personal object) found Personal.        expect(manifest.genesis).toBe(foundsPersonal(registryApp(name)) ? "personal" : "none");        // One app, one database, by data: every flavour names personal or its business object.        expect(manifestDatabaseRefusal(flavour.manifest, manifest)).toBeNull();        // RULE: Rigby is one database ever (`only`: no new, no join, no Databases screen); every other flavour shows one at a time.        expect(manifest.databases).toBe(name === "rigby" ? "only" : "single");        expect(manifest.flavour).toBe(name);        // The label under the icon never says Cotton; the app's own name may (assets/design/shared/DECISIONS.md "Names", 21 Nov 2026).        expect(manifest.name).toBe(name in COTTONS_FAMILY ? COTTONS_FAMILY[name] : name === "development" ? registryApp(name).name : flavour.displayName);        expect(["single", "many", "only"]).toContain(manifest.databases);        // Every id is a shipped key: a kit tool (the kit ships everything        // built for Personal, owner 26 Oct 2026), a        // business package or the ledger's; the fan keeps only what the        // database holds. Only a business flavour's tools are applied (at its        // database's creation); a flavour that founds Personal declares none.        const known = [...kitToolIds(), ...packageToolIds(), ledgerToolId()];        // RULE (5 Nov 2026): one source only — a flavour names its kit (Books, Music: the kit names its tools) or a tools list, never both.        if (manifest.kit !== undefined) {          expect(manifest.tools, `${name} names a kit, and its kit names the tools`).toBeUndefined();          expect(existsSync(join(KITS, manifest.kit, "kit.json")), `${manifest.kit} is a shipped kit`).toBe(true);        } else expect(manifest.tools.length).toBeGreaterThan(0);        for (const tool of manifest.genesis === "none" ? manifest.tools : []) {          expect(known, `${tool} is a shipped tool`).toContain(tool);        }        // RULE: a business that runs a shipped package (yoga, kitchen) names the object it runs against — the business Worker's https address and its slug — or the phone's shell has nothing to draw (the Worker, 24 Oct 2026). No relay customer endpoint is left beside it.        if ((manifest.tools ?? []).some((tool: string) => packageToolIds().includes(tool))) {          expect(manifest.business, `${name} names its business object`).toBeDefined();          expect(Object.keys(manifest.business).sort()).toEqual(["server", "slug"]);          expect(new URL(manifest.business.server).protocol).toBe("https:");          expect(manifest.business.slug).toMatch(/^[a-z0-9-]+$/);          expect(manifest.customers, `${name} still names a relay customer endpoint`).toBeUndefined();          // RULE: a shipped manifest names no synthetic business (architect, 19 Oct 2026): a build that pointed at          // a synthetic object or web face would sign real people into invented data.          for (const field of [manifest.business.server, manifest.business.slug, manifest.web?.database ?? ""]) {            expect(field, `${name} points at a synthetic business`).not.toMatch(/synthetic/i);          }        }        const sources = generated().targets[flavour.target].sources.map((s: any) => (typeof s === "string" ? s : s.path));        // The bundle carries the manifest with the dev host filled in (config/dev-server.json), not the source with its token.        expect(sources).toEqual(expect.arrayContaining([flavour.icons, `${MANIFESTS_DIR}/${flavour.target}/flavour.json`]));        expect(sources).not.toContain(flavour.manifest);        expect(generated().targets[FAMILY_APP].sources.map((s: any) => s.path ?? s)).not.toContain(flavour.manifest);        expect(sources, "a clone never carries Cotton's own manifest").not.toContain(COTTON_MANIFEST);      });      it("is a flavour the cut builds: the Fastfile names its scheme, target and every bundle the spec makes", () => {        // RULE: a flavour whose App Store record the registry does not hold yet        // (no live ascAppId) is not cut yet — the record is the coordinator's        // to make (4 Nov 2026); the Fastfile row comes with it.        if (notCutYet(name)) return;        const fastfile = readFileSync(join(ROOT, "fastlane", "Fastfile"), "utf8");        const block = fastfile.match(new RegExp(`^  "${name}" => \\{\\n([\\s\\S]*?)^  \\}\\.freeze`, "m"))?.[1];        expect(block, `FLAVORS has no ${name}`).toBeDefined();        expect(block).toContain(`bundle_id: "${flavour.appId}"`);        expect(block).toContain(`app_group: "group.${flavour.appId}"`);        expect(block).toContain(`scheme: "${name}", target: "${flavour.target}"`);        const suffixes: Record<string, string> = { ShareExtension: "share-extension" };        for (const suffix of flavour.share === false ? [] : FAMILY_EXTENSIONS) {          expect(block).toMatch(new RegExp(`"${flavour.target}${suffix}"\\s*=> "${flavour.appId}\\.${suffixes[suffix]}"`));        }        // phone-cut.sh takes its flavours from the app registry, which names this one.        const registry = JSON.parse(readFileSync(join(ROOT, "apps", "registry.json"), "utf8"));        expect(registry.apps.find((a: { slug: string }) => a.slug === name)?.ios?.live?.flavour, `apps/registry.json has no ${name} flavour`).toBe(name);      });      // RULE (owner, 15 Nov 2026): Messages' chats lie on the shell's paper and it still launches on its icon's pegboard      // with the object on it. Build 5 launched bare: `ground` was the one switch for both, and taking the pegboard      // from under the chats took the launch storyboard out of the app. `launch` names the launch's ground alone.      if (name === "messages") {        // Since 22 Nov 2026 (owner): Comms launches flat, its Quote mark on its own colour; the pegboard is retired.        it("launches flat on its own colour though it stands on paper", () => {          const manifest = JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8"));          expect(manifest.ground).toBeUndefined();          expect(manifest.launch).toBeUndefined();          expect(manifest.flat).toEqual({ light: "#FAF7F2", dark: "#1A1714" });          const properties = (generated().targets[flavour.target].info as { properties: Record<string, unknown> }).properties;          expect(properties.UILaunchStoryboardName).toBe(LAUNCH_STORYBOARD);          expect(properties.UILaunchScreen).toBeUndefined();        });      }      it("launches on the ground its manifest names, or on Cotton's paper when it names none", () => {        const manifest = JSON.parse(readFileSync(join(IOS_DIR, flavour.manifest), "utf8"));        const target = generated().targets[flavour.target];        const properties = (target.info as { properties: Record<string, unknown> }).properties;        // The ground it launches on: the one it stands on, or the one it names for the launch alone (`launch`).        const ground = manifest.launch ?? manifest.ground;        if (ground === undefined && manifest.flat === undefined) {          expect(properties.UILaunchScreen).toEqual(generated().targets[FAMILY_APP].info?.properties.UILaunchScreen);          expect(properties.UILaunchStoryboardName).toBeUndefined();          return;        }        if (manifest.flat !== undefined) {          // RULE (17 Nov 2026): a flat app (Cotton Story) launches on its flat colour, light or dark as the phone is, with          // its word mark in the middle and no painted ground: a launch storyboard beside its manifest, in its resources,          // its colour set holding a dark appearance, and every picture it draws in the flavour's catalogue.          expect(properties.UILaunchScreen).toBeUndefined();          expect(properties.UILaunchStoryboardName).toBe(LAUNCH_STORYBOARD);          const drawn = readFileSync(join(IOS_DIR, launchStoryboard(flavour)), "utf8");          expect(drawn).toContain(`<color key="backgroundColor" name="${LAUNCH_GROUND}"/>`);          expect(drawn).not.toContain(`image="${LAUNCH_SURFACE}"`);          const colour = JSON.parse(readFileSync(join(IOS_DIR, flavour.icons, `${LAUNCH_GROUND}.colorset`, "Contents.json"), "utf8"));          expect(colour.colors.some((one: { appearances?: { value: string }[] }) => one.appearances?.some((look) => look.value === "dark"))).toBe(true);          if (drawn.includes(`image="${LAUNCH_OBJECT}"`)) {            expect(existsSync(join(IOS_DIR, flavour.icons, `${LAUNCH_OBJECT}.imageset`, "Contents.json")), `${flavour.icons} has ${LAUNCH_OBJECT}`).toBe(true);          }          return;        }        // RULE (13 Nov 2026): an app on its own ground launches on that ground as the app lays it, full bleed (its painted        // tile repeated, its lamp), its icon's object cut out in the middle: a launch storyboard beside its manifest, in its        // resources, and every picture it draws in the flavour's catalogue.        expect(groundTiles(), `${ground} is a FaceGround with a painted tile`).toHaveProperty(ground);        expect(properties.UILaunchScreen).toBeUndefined();        expect(properties.UILaunchStoryboardName).toBe(LAUNCH_STORYBOARD);        const storyboard = launchStoryboard(flavour);        expect((target.sources ?? []).some((one: string | { path: string; buildPhase?: string }) => typeof one !== "string" && one.path === storyboard && one.buildPhase === "resources")).toBe(true);        const drawn = readFileSync(join(IOS_DIR, storyboard), "utf8");        expect(drawn).toContain(`<color key="backgroundColor" name="${LAUNCH_GROUND}"/>`);        expect(drawn).toContain(`image="${LAUNCH_SURFACE}"`);        if (drawn.includes(`image="${LAUNCH_OBJECT}"`)) {          expect(existsSync(join(IOS_DIR, flavour.icons, `${LAUNCH_OBJECT}.imageset`, "Contents.json")), `${flavour.icons} has ${LAUNCH_OBJECT}`).toBe(true);        }        const surface = JSON.parse(readFileSync(join(IOS_DIR, flavour.icons, `${LAUNCH_SURFACE}.imageset`, "Contents.json"), "utf8"));        expect(surface.images[0].scale, "the ground is laid at three pixels a point, as FaceGroundSurface lays it").toBe("3x");        // The launch screen ignores an image view's content mode, so each picture's view is exactly its own size.        const size = drawn.match(/<image name="LaunchSurface" width="([\d.]+)" height="([\d.]+)"\/>/);        expect(size && Number(size[1]) >= 440 && Number(size[2]) >= 956, "the ground covers the largest phone's screen").toBe(true);        expect(drawn, "the ground is drawn at its own size, never scaled").toContain(`<constraint firstAttribute="width" constant="${size![1]}"`);        expect(drawn, "the ground is pinned to the screen's top left corner").toMatch(/firstItem="Lgt-pi-c01" firstAttribute="top" secondItem="Lgr-oo-t01" secondAttribute="top" constant="0"/);      });      it("carries only the Info.plist keys its own flavour declares", () => {        const properties = (generated().targets[flavour.target].info as { properties: Record<string, unknown> }).properties;        if (name === "rigby") {          // RULE: Rigby opens a `.cottonpkg` — an exported zip type and a document type naming it, opened as a copy.          const exported = properties.UTExportedTypeDeclarations as { UTTypeIdentifier: string; UTTypeConformsTo: string[]; UTTypeTagSpecification: Record<string, string[]> }[];          expect(exported.map((one) => one.UTTypeIdentifier)).toEqual(["com.decemberfm.cotton.package"]);          expect(exported[0].UTTypeConformsTo).toContain("public.zip-archive");          expect(exported[0].UTTypeTagSpecification["public.filename-extension"]).toEqual(["cottonpkg"]);          const documents = properties.CFBundleDocumentTypes as { LSItemContentTypes: string[] }[];          expect(documents.flatMap((one) => one.LSItemContentTypes)).toEqual(["com.decemberfm.cotton.package"]);          expect(properties.LSSupportsOpeningDocumentsInPlace).toBe(false);        } else if (name === "books") {          // RULE: Cotton Books reads EPUB and PDF — two document types, ranked Alternate, opened as a copy, and no type of its own.          expect(properties.UTExportedTypeDeclarations).toBeUndefined();          const documents = properties.CFBundleDocumentTypes as { LSItemContentTypes: string[]; LSHandlerRank: string }[];          expect(documents.flatMap((one) => one.LSItemContentTypes)).toEqual(["org.idpf.epub-container", "com.adobe.pdf"]);          expect(documents.map((one) => one.LSHandlerRank)).toEqual(["Alternate", "Alternate"]);          expect(properties.LSSupportsOpeningDocumentsInPlace).toBe(false);        } else if (name === "music") {          // RULE: Cotton Music plays the common audio types — one document type each, ranked Alternate, opened as a copy, and no type of its own. It keeps Cotton's background modes, `audio` among them, so a song plays on with the screen locked, and Cotton's Ogg import; FLAC is iOS's own type.          expect(properties.UTExportedTypeDeclarations).toBeUndefined();          const documents = properties.CFBundleDocumentTypes as { LSItemContentTypes: string[]; LSHandlerRank: string; CFBundleTypeRole: string }[];          expect(documents.flatMap((one) => one.LSItemContentTypes)).toEqual([            "public.mp3",            "public.mpeg-4-audio",            "org.xiph.flac",            "com.microsoft.waveform-audio",            "public.aiff-audio",            "org.xiph.ogg",            "public.audio",          ]);          for (const one of documents) {            expect(one.LSHandlerRank).toBe("Alternate");            expect(one.CFBundleTypeRole).toBe("Viewer");          }          expect(properties.LSSupportsOpeningDocumentsInPlace).toBe(false);          expect(properties.UIBackgroundModes).toEqual(expect.arrayContaining(["audio", "remote-notification", "fetch", "processing"]));          const imported = (properties.UTImportedTypeDeclarations as { UTTypeIdentifier: string }[]).map((one) => one.UTTypeIdentifier);          expect(imported).toEqual(expect.arrayContaining(["org.xiph.ogg", "org.xiph.opus"]));        } else if (name === "cinemas") {          // RULE: Cotton Cinemas plays MP4, QuickTime, AVI and Matroska — one document type each, ranked Alternate, opened as a copy, and no type of its own. iOS declares no Matroska type, so it imports one (a movie, `.mkv`, `video/x-matroska`) beside Cotton's Ogg and Opus. Its background modes are Cotton's without `audio`: a film does not play on with the phone locked (5 Nov 2026).          expect(properties.UTExportedTypeDeclarations).toBeUndefined();          const documents = properties.CFBundleDocumentTypes as { LSItemContentTypes: string[]; LSHandlerRank: string; CFBundleTypeRole: string }[];          expect(documents.flatMap((one) => one.LSItemContentTypes)).toEqual(["public.mpeg-4", "com.apple.quicktime-movie", "public.avi", "org.matroska.mkv"]);          for (const one of documents) {            expect(one.LSHandlerRank).toBe("Alternate");            expect(one.CFBundleTypeRole).toBe("Viewer");          }          expect(properties.LSSupportsOpeningDocumentsInPlace).toBe(false);          expect(properties.UIBackgroundModes).toEqual(["remote-notification", "fetch", "processing"]);          const imported = properties.UTImportedTypeDeclarations as { UTTypeIdentifier: string; UTTypeConformsTo: string[]; UTTypeTagSpecification: Record<string, string[]> }[];          expect(imported.map((one) => one.UTTypeIdentifier)).toEqual(["org.matroska.mkv", "org.xiph.ogg", "org.xiph.opus"]);          const mkv = imported[0];          expect(mkv.UTTypeConformsTo).toEqual(["public.movie"]);          expect(mkv.UTTypeTagSpecification["public.filename-extension"]).toEqual(["mkv"]);          expect(mkv.UTTypeTagSpecification["public.mime-type"]).toEqual(["video/x-matroska"]);          // RULE (cinemas-airplay, 18 Nov 2026): a sealed film plays to an AirPlay TV from the phone's Wi-Fi address, so the Local Network ask says so in the kit's own line, and plain http reaches a private address alone (Cotton's `NSAllowsLocalNetworking`), nothing wider.          const lines = JSON.parse(readFileSync(join(ROOT, "crates/cotton-core/kits/shell/lines/cinemas.json"), "utf8")) as { player: Record<string, string> };          expect(properties.NSLocalNetworkUsageDescription).toBe(lines.player.local_network);          expect(properties.NSAppTransportSecurity).toEqual({ NSAllowsLocalNetworking: true });        } else if (name === "story") {          // RULE: Cotton Story opens a script file — Fountain, Final Draft, a printed PDF or plain text (de959bdda: Open in takes .fdx and .pdf) — as one document type, ranked Alternate, opened as a copy, and no type of its own; it imports Fountain (`.fountain`, as plain text) and Final Draft (`.fdx`, as XML), which iOS does not declare. It is no longer pinned light: its Look's paper decides each appearance (owner, 23 Nov 2026; story DECISIONS "Look"), so iOS follows the phone's.          expect(properties.UTExportedTypeDeclarations).toBeUndefined();          const documents = properties.CFBundleDocumentTypes as { LSItemContentTypes: string[]; LSHandlerRank: string; CFBundleTypeRole: string }[];          expect(documents.flatMap((one) => one.LSItemContentTypes)).toEqual(["io.fountain.screenplay", "com.finaldraft.fdx", "com.adobe.pdf", "public.plain-text"]);          expect(documents.map((one) => one.LSHandlerRank)).toEqual(["Alternate"]);          expect(properties.LSSupportsOpeningDocumentsInPlace).toBe(false);          const imported = properties.UTImportedTypeDeclarations as { UTTypeIdentifier: string; UTTypeConformsTo: string[]; UTTypeTagSpecification: Record<string, string[]> }[];          const fountain = imported.find((one) => one.UTTypeIdentifier === "io.fountain.screenplay");          expect(fountain?.UTTypeConformsTo).toEqual(["public.plain-text"]);          expect(fountain?.UTTypeTagSpecification["public.filename-extension"]).toEqual(["fountain"]);          const fdx = imported.find((one) => one.UTTypeIdentifier === "com.finaldraft.fdx");          expect(fdx?.UTTypeConformsTo).toEqual(["public.xml"]);          expect(fdx?.UTTypeTagSpecification["public.filename-extension"]).toEqual(["fdx"]);          expect(properties.UIUserInterfaceStyle).toBe("Automatic");          // Listen reads the script aloud and goes on with the screen off (wireframes 6); nothing else runs in the background (launch-ios, 22 Nov 2026).          expect(properties.UIBackgroundModes).toEqual(["audio"]);        } else if (name === "messages") {          // RULE (owner, 23 Nov 2026; chat CONTRACT "Recordings", Import): an audio file opened into Comms becomes a recording, so Comms takes any audio as one document type, ranked Alternate, opened as a copy, and no type of its own.          expect(properties.UTExportedTypeDeclarations).toBeUndefined();          const documents = properties.CFBundleDocumentTypes as { LSItemContentTypes: string[]; LSHandlerRank: string }[];          expect(documents.flatMap((one) => one.LSItemContentTypes)).toEqual(["public.audio"]);          expect(documents.map((one) => one.LSHandlerRank)).toEqual(["Alternate"]);          expect(properties.LSSupportsOpeningDocumentsInPlace).toBe(false);        } else {          expect(properties.UTExportedTypeDeclarations).toBeUndefined();          expect(properties.CFBundleDocumentTypes).toBeUndefined();        }        expect(generated().targets[FAMILY_APP].info?.properties.CFBundleDocumentTypes, "Cotton's own app declares none").toBeUndefined();        // RULE: Cotton's own app imports Matroska as Cotton Cinemas does: Films' Add files names        // `org.matroska.mkv`, and undeclared it is a type no file has, so an MKV stood greyed in        // Cotton's picker (the 361 walk, 5 Nov 2026).        const own = generated().targets[FAMILY_APP].info?.properties.UTImportedTypeDeclarations as { UTTypeIdentifier: string; UTTypeConformsTo: string[] }[];        expect(own.find((one) => one.UTTypeIdentifier === "org.matroska.mkv")?.UTTypeConformsTo).toEqual(["public.movie"]);        // RULE: Cotton imports OPML, as XML, for Podcasts' Bring subscriptions in: Apple declares        // no OPML type, and undeclared `org.opml.opml` greys every list in the door's picker (7 Nov 2026).        expect(own.find((one) => one.UTTypeIdentifier === "org.opml.opml")?.UTTypeConformsTo).toEqual(["public.xml"]);      });      // RULE: a flavour's share sheet takes what its drain files: Cotton Books      // an EPUB, a PDF or a Goodreads CSV, Cotton Music audio files, a      // folder of them or an album ZIP, Cotton Cinemas films or a folder of them, by a      // predicate; every other family keeps Cotton's six rules.      it("carries its own share rule, or Cotton's", () => {        const spec = generated();        const rule = (target: string) => spec.targets[target].info.properties.NSExtension.NSExtensionAttributes.NSExtensionActivationRule;        if (flavour.share === false) {          // RULE: Cotton Money takes no shares: an assistant writes its rows over MCP, and its kit holds no table a shared file becomes (6 Nov 2026). Cotton Keys takes none either: a passkey is made by a site asking the provider extension, never by a shared file (8 Nov 2026). Cotton Todos takes none: a todo is written on the card or by an assistant over MCP (9 Nov 2026). Cotton Notes takes none, as Todos (11 Nov 2026). Cotton People takes none, as Notes (11 Nov 2026). Cotton Messages takes none and imports nothing until its tables are sealed (11 Nov 2026). Cotton Email takes none and imports nothing until its tables are sealed (11 Nov 2026). Cotton Calendar takes none, as Notes (11 Nov 2026). Cotton Developer takes none: its memories, machines and artifacts are written by an assistant over MCP (11 Nov 2026).          expect(registryApp(name).ios?.share, `${name}: the registry says it takes no shares`).toBe(false);          expect(spec.targets[`${flavour.target}ShareExtension`]).toBeUndefined();          expect(flavour.shareRule).toBeUndefined();          return;        }        if (flavour.shareRule === undefined) {          expect(rule(`${flavour.target}ShareExtension`)).toEqual(rule("CottonShareExtension"));          return;        }        const said = String(rule(`${flavour.target}ShareExtension`));        const admits: Record<string, string[]> = {          books: ["org.idpf.epub-container", "com.adobe.pdf", "public.comma-separated-values-text"],          music: ["public.audio", "public.folder", "public.zip-archive"],          cinemas: ["public.movie", "public.folder"],          // RULE: Cotton Downloads takes what becomes a download: a link, text (a magnet is text) or a .torrent.          downloads: ["public.url", "public.plain-text", "org.bittorrent.torrent"],          // RULE: Cotton Podcasts takes another podcast app's subscription list, one OPML file (or the XML it is), brought in by import_opml (12 Nov 2026).          podcasts: ["org.opml.opml", "public.xml"],          // RULE: Cotton Pages takes a link: a web address, or text that holds one (12 Nov 2026).          pages: ["public.url", "public.plain-text"],        };        expect(admits[name], `${name} has a share rule this guard does not name`).toBeDefined();        const named = [...said.matchAll(/UTI-CONFORMS-TO "([^"]+)"/g)].map((match) => match[1]);        expect(named.sort()).toEqual([...admits[name]].sort());        if (name !== "downloads" && name !== "pages") expect(said).not.toMatch(name === "cinemas" ? /public\.(image|url|plain-text)/ : /public\.(image|movie|url|plain-text)/);        // Cotton Music and Cotton Cinemas take one file or many, every one        // theirs or a folder.        if (name === "music" || name === "cinemas") expect(said).toContain("@count == $item.attachments.@count");        expect(rule("CottonShareExtension"), "Cotton's own rule is untouched").toHaveProperty("NSExtensionActivationSupportsFileWithMaxCount", 20);      });      it("drops a gated-off extension from its family too", () => {        const spec = withBusinessFlavours(withoutTargets(declared() as any, ["CottonShareExtension"]) as any) as unknown as Spec;        expect(spec.targets[`${flavour.target}ShareExtension`]).toBeUndefined();        const deps = (spec.targets[flavour.target].dependencies as { target?: string }[]).map((one) => one.target);        expect(deps).not.toContain(`${flavour.target}ShareExtension`);      });    });  }});/** * RULE (19 Nov 2026; coordinator, the same day): every app people sign in to on an iPhone — every * app cut to phones (development or production) with a flavour a lane cuts — is signed with * `webcredentials:<its sign-in host>`, the live host for the live app and the dev host for the dev one, in an * entitlements file the gate writes from the app's own, so a Cotton account passkey works in it. A parked or planned * app, and Loom (no flavour, no sign-in), carry no associated domain, so their profiles need none until they are cut. */// RULE (launch-ios, 22 Nov 2026; App Review 5.1.1(ii), 2.5.4; assets/design/LAUNCH.md section 4): Words, Days and Story,// the first apps for the App Store, ask only for what each uses, in its own words: no prompt, background mode,// background task or Bonjour service of Cotton's beyond those. Each carries its own privacy manifest, and each says// it uses standard encryption beyond the exempt kinds (the core seals with its own X25519, AES-256-GCM, Ed25519).describe("an app that asks only for what it uses", () => {  const own: Record<string, { prompts: string[]; modes?: string[]; tasks?: string[] }> = {    notes: { prompts: ["NSCameraUsageDescription", "NSFaceIDUsageDescription", "NSMicrophoneUsageDescription", "NSPhotoLibraryAddUsageDescription", "NSSpeechRecognitionUsageDescription"] },    // Days syncs in the background so an event from another device alerts with Days closed (24 Nov 2026).    days: { prompts: ["NSCameraUsageDescription", "NSFaceIDUsageDescription", "NSMicrophoneUsageDescription", "NSSpeechRecognitionUsageDescription"],      modes: ["fetch", "processing"], tasks: ["com.cottondb.catchup.refresh", "com.cottondb.catchup.processing"] },    story: { prompts: ["NSCameraUsageDescription", "NSFaceIDUsageDescription", "NSMicrophoneUsageDescription", "NSPhotoLibraryAddUsageDescription", "NSSpeechRecognitionUsageDescription"], modes: ["audio"] },  };  it("albums: the face model goes in by its pinned hash as the app's last phase, and no model is committed", () => {    const flavour = declared().businessFlavours!.albums;    const target = generated().targets[flavour.target];    const phases = (target.postBuildScripts ?? []) as { name: string; script: string }[];    expect(phases.at(-1)?.name).toBe("Face model");    expect(phases.at(-1)?.script).toContain("scripts/albums-face-model.sh");    expect((flavour.resources ?? []).some((folder: string) => folder.includes("FaceModels"))).toBe(false);    const pin = JSON.parse(readFileSync(join(IOS_DIR, "App/Flavours/albums/face-model.json"), "utf8"));    expect(pin.sha256).toMatch(/^[0-9a-f]{64}$/);    expect(pin.model).toMatch(/^hyperface-50k/);    expect(existsSync(join(IOS_DIR, "App/Flavours/albums/FaceModels"))).toBe(false);    // No other app carries the phase.    for (const [other, one] of Object.entries(declared().businessFlavours!)) {      if (other === "albums") continue;      const scripts = (generated().targets[one.target].postBuildScripts ?? []) as { name: string }[];      expect(scripts.some((phase) => phase.name === "Face model"), other).toBe(false);    }  });  // ALBUMS PHOTOLIB (coordinator, 27 Nov 2026): Albums' PhotoKit library sat in the shared CottonUI package, so every app  // referenced PHPhotoLibrary and Sites' archive was refused (ITMS-90683). The package names no Photos class the purpose  // check reads; the app target names one only inside a condition that keeps it out of apps without photo strings.  it("albums: PhotoKit is compiled only into Albums, never into the shared package", () => {    const PHOTOS = /\bPHPhotoLibrary\b|\bPHAssetCreationRequest\b|\bPHAsset\b|\bPHImageManager\b|\bPHCachingImageManager\b|\bPHAssetResource\b|\bPHFetchOptions\b|\bPHAssetCollection\b/;    const swiftFiles = (dir: string): string[] =>      readdirSync(dir, { withFileTypes: true }).flatMap((one) =>        one.isDirectory() ? swiftFiles(join(dir, one.name)) : one.name.endsWith(".swift") ? [join(dir, one.name)] : [],      );    for (const file of swiftFiles(join(IOS_DIR, "Sources"))) {      const named = readFileSync(file, "utf8").split("\n").filter((line) => PHOTOS.test(line) && !line.trim().startsWith("//") && !line.trim().startsWith("///"));      expect(named, file.slice(IOS_DIR.length)).toEqual([]);    }    for (const file of swiftFiles(join(IOS_DIR, "App"))) {      const open: string[] = [];      readFileSync(file, "utf8").split("\n").forEach((line, i) => {        const t = line.trim();        if (t.startsWith("#if")) open.push(t);        else if (t.startsWith("#endif")) open.pop();        else if (PHOTOS.test(line) && !t.startsWith("//")) {          const kept = open.some((cond) => cond.includes("COTTON_ALBUMS") || cond.includes(`!${NO_PHOTOS}`));          expect(kept, `${file.slice(IOS_DIR.length)}:${i + 1} ${t}`).toBe(true);        }      });    }    // Only Albums is built with COTTON_ALBUMS.    for (const [name, one] of Object.entries(declared().businessFlavours!)) {      const conditions = String((generated().targets[one.target].settings as { base: Record<string, unknown> }).base.SWIFT_ACTIVE_COMPILATION_CONDITIONS ?? "");      expect(conditions.split(" ").includes("COTTON_ALBUMS"), name).toBe(name === "albums");    }  });  // ALBUMS KEEP (owner, 28 Nov 2026: photo backup into Cotton is the real direction; Keep is in his real Albums build).  // AlbumsKeeper.allowed is a Dev build's always and the real app's by one constant (realFlavourKeeps, now true); every  // way in (keep, start, resume) asks it first, and the band is drawn only when it says. Keep only reads photos.  it("albums: the real build keeps (uploads) only when one constant says so, and every way in asks it", () => {    const keep = readFileSync(join(IOS_DIR, "Sources/CottonUI/Albums/AlbumsKeep.swift"), "utf8");    // Off the Dev build it answers one constant alone, a literal the cut can be chosen by.    const allowed = /static var allowed: Bool \{\s*#if COTTON_DEV\s*return true\s*#else\s*return realFlavourKeeps\s*#endif\s*\}/;    expect(keep, "AlbumsKeeper.allowed: COTTON_DEV, else realFlavourKeeps").toMatch(allowed);    // Owner, 28 Nov: Keep is in his real Albums build.    expect(keep, "the real Albums build keeps (owner, 28 Nov)").toMatch(/static let realFlavourKeeps = true\n/);    for (const way of ["func keep(", "func start()", "func resume()"]) {      const at = keep.indexOf(way);      expect(at, way).toBeGreaterThan(-1);      const body = keep.slice(at, keep.indexOf("\n    }\n", at));      expect(body.split("\n").slice(1, 3).join("\n"), `${way} asks AlbumsKeeper.allowed first`).toContain("guard Self.allowed");    }    const screens = readdirSync(join(IOS_DIR, "Sources/CottonUI/Albums")).filter((f) => f.endsWith(".swift"));    for (const file of screens) {      readFileSync(join(IOS_DIR, "Sources/CottonUI/Albums", file), "utf8").split("\n").forEach((line, i, lines) => {        if (!line.includes("AlbumsKeepBand(model:")) return;        expect(lines.slice(Math.max(0, i - 2), i + 1).join("\n"), `${file}:${i + 1}`).toContain("AlbumsKeeper.allowed");      });    }  });  // ALBUMS LOOK-ONLY (owner, 27 Nov 2026): the first Albums build can look but never change his library. No call to  // PHPhotoLibrary.performChanges may be reachable: the shared package names no photo-changing API at all, the app  // target's writers sit inside COTTON_NO_PHOTO_WRITES, and Albums is built with it.  it("albums: the look-only build cannot reach any call that changes the photo library", () => {    const CHANGES = /performChanges|deleteAssets|ChangeRequest/;    const swiftFiles = (dir: string): string[] =>      readdirSync(dir, { withFileTypes: true }).flatMap((one) =>        one.isDirectory() ? swiftFiles(join(dir, one.name)) : one.name.endsWith(".swift") ? [join(dir, one.name)] : [],      );    // The package the screens and the pass live in: none at all, so a look-only app cannot get one through it.    for (const file of swiftFiles(join(IOS_DIR, "Sources"))) {      const lines = readFileSync(file, "utf8").split("\n");      const named = lines.filter((line) => CHANGES.test(line) && !line.trim().startsWith("//"));      expect(named, file.slice(IOS_DIR.length)).toEqual([]);    }    // The app target: every line that names one sits inside `#if ... !COTTON_NO_PHOTO_WRITES`.    for (const file of swiftFiles(join(IOS_DIR, "App"))) {      const lines = readFileSync(file, "utf8").split("\n");      const open: string[] = [];      lines.forEach((line, i) => {        const t = line.trim();        if (t.startsWith("#if")) open.push(t);        else if (t.startsWith("#endif")) open.pop();        else if (CHANGES.test(line) && !t.startsWith("//")) {          expect(open.some((cond) => cond.includes(`!${NO_PHOTO_WRITES}`)), `${file.slice(IOS_DIR.length)}:${i + 1} ${t}`).toBe(true);        }      });    }    // Albums is built with the condition and asks only to read photos, in plain words.    const flavour = declared().businessFlavours!.albums;    expect(flavour.photoWrites).toBe(false);    const target = generated().targets[flavour.target];    const conditions = String((target.settings as { base: Record<string, unknown> }).base.SWIFT_ACTIVE_COMPILATION_CONDITIONS ?? "");    expect(conditions.split(" ")).toContain(NO_PHOTO_WRITES);    const properties = (target.info as { properties: Record<string, unknown> }).properties;    expect(properties.NSPhotoLibraryAddUsageDescription).toBeUndefined();    expect(String(properties.NSPhotoLibraryUsageDescription).replace(/\s+/g, " ")).toBe(      "Albums looks through your photos on this phone to group them. Only albums you choose to keep are uploaded.",    );    // No other app loses its writers.    for (const [other, one] of Object.entries(declared().businessFlavours!)) {      if (other === "albums") continue;      const theirs = String((generated().targets[one.target].settings as { base: Record<string, unknown> }).base.SWIFT_ACTIVE_COMPILATION_CONDITIONS ?? "");      expect(theirs.split(" ").includes(NO_PHOTO_WRITES), other).toBe(false);    }  });  for (const [name, want] of Object.entries(own)) {    it(`${name}: its own prompts and modes, its privacy manifest, and export compliance said`, () => {      const flavour = declared().businessFlavours![name];      expect(flavour.ownPermissions).toBe(true);      const target = generated().targets[flavour.target];      const properties = (target.info as { properties: Record<string, unknown> }).properties;      expect(Object.keys(properties).filter((key) => key.endsWith("UsageDescription")).sort()).toEqual(want.prompts);      expect(properties.UIBackgroundModes).toEqual(want.modes);      expect(properties.BGTaskSchedulerPermittedIdentifiers).toEqual(want.tasks);      expect(properties.NSBonjourServices).toBeUndefined();      // No contacts string, no Contacts code (ITMS-90683): the app's own address book is compiled out.      const conditions = String((target.settings as { base: Record<string, unknown> }).base.SWIFT_ACTIVE_COMPILATION_CONDITIONS ?? "");      expect(conditions.split(" ")).toContain(NO_CONTACTS);      // Camera and photo code only where the app says why (Days says neither).      expect(conditions.split(" ").includes(NO_CAMERA)).toBe(!want.prompts.includes("NSCameraUsageDescription"));      expect(conditions.split(" ").includes(NO_PHOTOS)).toBe(!want.prompts.some((key) => key.startsWith("NSPhotoLibrary")));      expect(conditions.startsWith("$(inherited)")).toBe(true);      // Neither export key (90592; false is kept off so all four are answered alike): pnpm phone:cut answers each build after its upload.      expect(properties.ITSAppUsesNonExemptEncryption).toBeUndefined();      expect(properties.ITSEncryptionExportComplianceCode).toBeUndefined();      for (const [key, value] of Object.entries(properties).filter(([key]) => key.endsWith("UsageDescription"))) {        expect(String(value), key).toMatch(new RegExp(`^${flavour.displayName} `));        expect(String(value), key).not.toMatch(/meeting|Camera tool|assistant|vault|password/i);      }      const manifest = `App/Flavours/${name}/PrivacyInfo.xcprivacy`;      expect(flavour.privacyManifest).toBe(manifest);      expect((target.sources ?? []).map((one: string | { path: string }) => (typeof one === "string" ? one : one.path))).toContain(manifest);      const text = readFileSync(join(IOS_DIR, manifest), "utf8");      expect(text).toMatch(/<key>NSPrivacyTracking<\/key>\s*<false\/>/);      for (const reason of ["CA92.1", "1C8F.1", "C617.1"]) expect(text).toContain(reason);    });  }});describe("the passkey domain on every app people sign in to", () => {  const active = signInTargets();  const written: Written[] = [];  const spec = withBusinessFlavours(declared() as any, active, written) as unknown as Spec;  const LIVE_HOST = "cottondb.com";  // The dev Worker's host is a setting (config/dev-server.json), which the gate fills into each bundled manifest.  const DEV_HOST = devHost();  // RULE: Every flavour.json names its dev side as https://{dev-host}; the bundle carries a copy with config/dev-server.json's host filled in, and the tree names no dev address.  it("bundles each manifest with the dev host filled in, and the tree's manifests name the token alone", () => {    for (const target of active) {      const manifest = written.find((one) => one.path === `${MANIFESTS_DIR}/${target}/flavour.json`);      expect(manifest, `${target} has no bundled manifest`).toBeTruthy();      expect(manifest!.text).not.toContain(DEV_HOST_TOKEN);      expect(manifest!.text).toContain(`https://${DEV_HOST}`);      const sources = spec.targets[target].sources as ({ path: string } | string)[];      expect(sources.some((one) => (typeof one === "string" ? one : one.path) === `${MANIFESTS_DIR}/${target}/flavour.json`), target).toBe(true);    }    const cotton = written.find((one) => one.path === `${MANIFESTS_DIR}/Cotton/flavour.json`);    expect(cotton?.text).toContain(`https://${DEV_HOST}`);    expect(readFileSync(join(IOS_DIR, "App/CottonManifest/flavour.json"), "utf8")).toContain(`"https://${DEV_HOST_TOKEN}"`);  });  it("is on every iPhone app cut to phones, the coordinator's eight among them, and on no parked or planned app nor Loom", () => {    const targets = registryApps().filter((a) => signsInOnIphone(a as never)).map((a) => (a.ios as unknown as { target: string }).target);    expect([...active].sort()).toEqual([...targets].sort());    for (const target of ["CottonNotes", "CottonMessages", "CottonStory", "CottonMeetings", "CottonKeys", "CottonBooks", "CottonCinemas", "CottonDownloads"]) {      expect(active.has(target), target).toBe(true);    }    for (const app of registryApps().filter((a) => a.phase === "parked" || a.phase === "planned")) {      expect(active.has((app.ios as unknown as { target?: string } | null)?.target ?? ""), app.slug).toBe(false);    }  });  it("signs each of them with its own entitlements plus webcredentials, for the host its flavour signs in at", () => {    for (const target of active) {      const path = `${PASSKEY_ENTITLEMENTS_DIR}/${target}.entitlements`;      const file = written.find((one) => one.path === path);      expect(file, `${target} has no passkey entitlements written`).toBeTruthy();      expect(file!.text).toContain(`<key>${ASSOCIATED_DOMAINS}</key>`);      expect(file!.text).toContain("<string>webcredentials:$(COTTON_SIGNIN_HOST)</string>");      // The base entitlements stay whole: the app group, the keychain group, the push environment.      expect(file!.text).toContain("$(COTTON_APP_GROUP)");      expect(file!.text).toContain("$(AppIdentifierPrefix)$(COTTON_KEYCHAIN_GROUP)");      expect(file!.text).toContain("<key>aps-environment</key>");      for (const [flavor, host] of [["real", LIVE_HOST], ["dev", DEV_HOST]] as const) {        const settings = targetSettings(spec as any, target, "Release", { COTTON_FLAVOR: flavor });        expect(settings.CODE_SIGN_ENTITLEMENTS, target).toBe(path);        expect(expandSettings("$(COTTON_SIGNIN_HOST)", settings), `${target} ${flavor}`).toBe(host);      }      // Said in the Info.plist too, by the key the app reads (the app cannot read its own entitlements).      expect(spec.targets[target].info.properties[PASSKEY_HOST_KEY], target).toBe("$(COTTON_SIGNIN_HOST)");      const swift = readFileSync(join(IOS_DIR, "Sources", "CottonKit", "PasskeyPlatform.swift"), "utf8");      expect(swift).toContain(`public static let hostKey = "${PASSKEY_HOST_KEY}"`);    }  });  it("is on no other app, and on no extension", () => {    for (const [name, target] of Object.entries(spec.targets)) {      if (active.has(name)) continue;      const path = target.settings?.base?.CODE_SIGN_ENTITLEMENTS;      if (typeof path !== "string") continue;      expect(path.startsWith(PASSKEY_ENTITLEMENTS_DIR), name).toBe(false);      expect(target.info?.properties?.[PASSKEY_HOST_KEY], name).toBeUndefined();      expect(readFileSync(join(IOS_DIR, path), "utf8"), name).not.toContain(ASSOCIATED_DOMAINS);    }  });  it("refuses a sign-in app that project.yml declares no flavour for", () => {    expect(() => withBusinessFlavours(declared() as any, new Set(["CottonNowhere"]), [])).toThrow(/CottonNowhere/);  });});describe("a flavour's own resources", () => {  // RULE: Cotton Vault's faces (Inter and JetBrains Mono, SIL OFL, with their licences) ship in Cotton Keys alone, copied whole as the VaultFonts folder; no other app carries them (SHAPES "Decided" 9, 20 Nov 2026).  it("puts VaultFonts in the Keys and Health apps alone", () => {    const spec = generated();    const carries = (target: string) =>      ((spec.targets[target] as { sources?: unknown[] }).sources ?? []).some(        (one) => typeof one === "object" && one !== null && (one as { path?: string; type?: string }).path === "App/Flavours/keys/VaultFonts" && (one as { type?: string }).type === "folder",      );    const keys = declared().businessFlavours?.keys;    expect(keys?.target).toBe("CottonKeys");    expect(carries("CottonKeys")).toBe(true);    // Cotton Health draws in Vault's faces too (project.yml, health's resources).    expect(carries("CottonHealth")).toBe(true);    for (const target of Object.keys(spec.targets).filter((one) => one !== "CottonKeys" && one !== "CottonHealth")) expect(carries(target), target).toBe(false);    for (const face of ["Inter-Regular", "Inter-Medium", "Inter-SemiBold", "Inter-Bold", "JetBrainsMono-Regular", "JetBrainsMono-SemiBold"]) {      expect(existsSync(join(IOS_DIR, "App/Flavours/keys/VaultFonts", `${face}.ttf`)), face).toBe(true);    }    expect(existsSync(join(IOS_DIR, "App/Flavours/keys/VaultFonts/OFL-Inter.txt"))).toBe(true);    expect(existsSync(join(IOS_DIR, "App/Flavours/keys/VaultFonts/OFL-JetBrainsMono.txt"))).toBe(true);  });});// RULE (App Store upload refused, altool 90592, 22 Nov 2026): an app's plist never says it uses non-exempt encryption// without the compliance code Apple issues for it; with neither key, App Store Connect asks for each build.describe("export compliance keys an upload accepts", () => {  it("refuses true with no code and false, and takes none or true with a code", () => {    expect(exportRefusal({ ITSAppUsesNonExemptEncryption: true })).toMatch(/90592/);    expect(exportRefusal({ ITSAppUsesNonExemptEncryption: true, ITSEncryptionExportComplianceCode: "" })).toMatch(/90592/);    expect(exportRefusal({})).toBeNull();    expect(exportRefusal({ ITSAppUsesNonExemptEncryption: false })).toMatch(/phone:cut/);    expect(exportRefusal({ ITSAppUsesNonExemptEncryption: true, ITSEncryptionExportComplianceCode: "abc-123" })).toBeNull();  });});